kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

git.kak (40517B)


      1 declare-option -docstring "name of the client in which documentation is to be displayed" \
      2     str docsclient
      3 
      4 declare-option -docstring "git diff added character" \
      5     str git_diff_add_char "▊"
      6 
      7 declare-option -docstring "git diff modified character" \
      8     str git_diff_mod_char "▊"
      9 
     10 declare-option -docstring "git diff deleted character" \
     11     str git_diff_del_char "_"
     12 
     13 declare-option -docstring "git diff top deleted character" \
     14     str git_diff_top_char "‾"
     15 
     16 hook -group git-log-highlight global WinSetOption filetype=git-log %{
     17     add-highlighter window/git-log group
     18     add-highlighter window/git-log/ regex '^([*|\\ /_.-])*' 0:keyword
     19     add-highlighter window/git-log/ regex '^( ?[*|\\ /_.-])*\h{,3}(commit )?(\b[0-9a-f]{4,40}\b)' 2:keyword 3:comment
     20     add-highlighter window/git-log/ regex '^( ?[*|\\ /_.-])*\h{,3}([a-zA-Z_-]+:) (.*?)$' 2:variable 3:value
     21     hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/git-log }
     22 }
     23 
     24 hook global WinSetOption filetype=diff %{
     25     try %{
     26         execute-keys -draft %{/^diff --git\b<ret>}
     27         evaluate-commands %sh{
     28             if [ -n "$(git ls-files -- "${kak_buffile}")" ]; then
     29                 echo fail
     30             fi
     31         }
     32         set-option buffer filetype git-diff
     33     }
     34 }
     35 
     36 hook -group git-diff-highlight global WinSetOption filetype=(git-diff|git-log) %{
     37     require-module diff
     38     add-highlighter %exp{window/%val{hook_param_capture_1}-ref-diff} ref diff
     39     hook -once -always window WinSetOption filetype=.* %exp{
     40         remove-highlighter window/%val{hook_param_capture_1}-ref-diff
     41     }
     42 }
     43 
     44 hook global WinSetOption filetype=(?:git-diff|git-log) %{
     45     map buffer normal <ret> %exp{:git-diff-goto-source # %val{hook_param}<ret>} -docstring 'Jump to source from git diff'
     46     hook -once -always window WinSetOption filetype=.* %exp{
     47         unmap buffer normal <ret> %%{:git-diff-goto-source # %val{hook_param}<ret>}
     48     }
     49 }
     50 
     51 hook -group git-status-highlight global WinSetOption filetype=git-status %{
     52     add-highlighter window/git-status group
     53     add-highlighter window/git-status/ regex '^## ' 0:comment
     54     add-highlighter window/git-status/ regex '^## (\S*[^\s\.@])' 1:green
     55     add-highlighter window/git-status/ regex '^## (\S*[^\s\.@])(\.\.+)(\S*[^\s\.@])' 1:green 2:comment 3:red
     56     add-highlighter window/git-status/ regex '^(##) (No commits yet on) (\S*[^\s\.@])' 1:comment 2:Default 3:green
     57     add-highlighter window/git-status/ regex '^## \S+ \[\N*ahead (\d+)\N*\]' 1:green
     58     add-highlighter window/git-status/ regex '^## \S+ \[\N*behind (\d+)\N*\]' 1:red
     59     add-highlighter window/git-status/ regex '^(?:([Aa])|([Cc])|([Dd!?])|([MUmu])|([Rr])|([Tt]))[ !\?ACDMRTUacdmrtu]\h' 1:green 2:blue 3:red 4:yellow 5:cyan 6:cyan
     60     add-highlighter window/git-status/ regex '^[ !\?ACDMRTUacdmrtu](?:([Aa])|([Cc])|([Dd!?])|([MUmu])|([Rr])|([Tt]))\h' 1:green 2:blue 3:red 4:yellow 5:cyan 6:cyan
     61     add-highlighter window/git-status/ regex '^R[ !\?ACDMRTUacdmrtu] \N+( -> )' 1:cyan
     62     add-highlighter window/git-status/ regex '^\h+(?:((?:both )?modified:)|(added:|new file:)|(deleted(?: by \w+)?:)|(renamed:)|(copied:))(?:.*?)$' 1:yellow 2:green 3:red 4:cyan 5:blue 6:magenta
     63 
     64     hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/git-status }
     65 }
     66 
     67 hook -group git-show-branch-highlight global WinSetOption filetype=git-show-branch %{
     68     add-highlighter window/git-show-branch group
     69     add-highlighter window/git-show-branch/ regex '(\*)|(\+)|(!)' 1:red 2:green 3:green
     70     add-highlighter window/git-show-branch/ regex '(!\D+\{0\}\])|(!\D+\{1\}\])|(!\D+\{2\}\])|(!\D+\{3\}\])' 1:red 2:green 3:yellow 4:blue
     71     add-highlighter window/git-show-branch/ regex '(\B\+\D+\{0\}\])|(\B\+\D+\{1\}\])|(\B\+\D+\{2\}\])|(\B\+\D+\{3\}\])|(\B\+\D+\{1\}\^\])' 1:red 2:green 3:yellow 4:blue 5:magenta
     72 
     73     hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/git-show-branch}
     74 }
     75 
     76 declare-option -hidden line-specs git_blame_flags
     77 declare-option -hidden line-specs git_blame_index
     78 declare-option -hidden str git_blame
     79 declare-option -hidden str git_blob
     80 declare-option -hidden line-specs git_diff_flags
     81 declare-option -hidden str-list git_hunk_list
     82 
     83 define-command -params 1.. \
     84     -docstring %{
     85         git [<arguments>]: git wrapping helper
     86         All the optional arguments are forwarded to the git utility
     87         Available commands:
     88             add
     89             apply      - run "patch git apply [<arguments>]"; if buffile is
     90                          tracked, use the changes to selected lines instead
     91             blame      - toggle blame annotations
     92             blame-jump - show the commit that added the line at cursor
     93             checkout
     94             commit
     95             diff
     96             edit
     97             grep
     98             hide-diff
     99             init
    100             log
    101             next-hunk
    102             prev-hunk
    103             reset
    104             rm
    105             show
    106             show-branch
    107             show-diff
    108             status
    109             update-diff
    110     } -shell-script-candidates %{
    111     if [ $kak_token_to_complete -eq 0 ]; then
    112         printf %s\\n \
    113             add \
    114             apply \
    115             blame \
    116             blame-jump \
    117             checkout \
    118             commit \
    119             diff \
    120             edit \
    121             grep \
    122             hide-diff \
    123             init \
    124             log \
    125             next-hunk \
    126             prev-hunk \
    127             reset \
    128             rm \
    129             show \
    130             show-branch \
    131             show-diff \
    132             status \
    133             update-diff \
    134         ;
    135     else
    136         # Quote POSIX extended regular expressions, see SPEC_CHAR/QUOTED_CHAR in
    137         # https://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap09.html#tag_09_05_01
    138         sed_quote_ext_re() {
    139             # SED uses BREs by default, and matching in a group the ERE SPEC_CHAR
    140             sed -e 's/[\^\.\[\$\\()|\*+?{]/\\&/g' "$@"
    141             # to balance kakoune %<lbrace>: }
    142         }
    143         suggest_refs() {
    144             # Ten most recent refs
    145             git for-each-ref --format='%(refname:short)' --sort=-comitterdate --count=10
    146             # Commits, using name to match instead of hash (in the absence of having subject
    147             # as a comment for completion).
    148             git log -100 --format='%s' | sed_quote_ext_re -e 's|.*|@^{/&}|g'
    149         }
    150         case "$1" in
    151             commit) printf -- "--amend\n--no-edit\n--all\n--reset-author\n--fixup\n--squash\n"; git ls-files -m ;;
    152             add) git ls-files -dmo --exclude-standard ;;
    153             apply) printf -- "--reverse\n--cached\n--index\n--3way\n" ;;
    154             grep|edit) git ls-files -c --recurse-submodules ;;
    155             diff) printf -- "--cached\n----merge-base\n--stat\n--word-diff\n"; suggest_refs ;;
    156             show) printf -- "--patch\n--stat\n--remerge-diff\n"; suggest_refs ;;
    157             log) printf -- "--patch\n--stat\n--remerge-diff\n--walk-reflogs\n--grep\n"; suggest_refs ;;
    158         esac
    159     fi
    160   } \
    161   git %{ evaluate-commands %sh{
    162     cd_bufdir() {
    163         dirname_buffer="${kak_buffile%/*}"
    164         if [ "${dirname_buffer}" = "${kak_buffile}" ]; then
    165             printf 'fail git: cannot operate on scratch buffer: %s\n' "${kak_buffile}"
    166             return 1
    167         fi
    168         cd "${dirname_buffer}" 2>/dev/null || {
    169             printf 'fail git: unable to change the current working directory to: %s\n' "${dirname_buffer}"
    170             return 1
    171         }
    172     }
    173     kakquote() {
    174         printf "%s" "$1" | sed "s/'/''/g; 1s/^/'/; \$s/\$/'/"
    175     }
    176 
    177     show_git_cmd_output() {
    178         local filetype
    179 
    180         case "$1" in
    181            diff) filetype=git-diff ;;
    182            show) filetype=git-log ;;
    183            show-branch) filetype=git-show-branch ;;
    184            log)  filetype=git-log ;;
    185            status)  filetype=git-status ;;
    186            *) return 1 ;;
    187         esac
    188         output=$(mktemp -d "${TMPDIR:-/tmp}"/kak-git.XXXXXXXX)/fifo
    189         mkfifo ${output}
    190         ( trap - INT QUIT; git "$@" > ${output} 2>&1 & ) > /dev/null 2>&1 < /dev/null
    191 
    192         printf %s "evaluate-commands -try-client '$kak_opt_docsclient' '
    193                   edit! -fifo ${output} *git*
    194                   set-option buffer filetype ${filetype}
    195                   $(hide_blame)
    196                   set-option buffer git_blob %{}
    197                   hook -always -once buffer BufCloseFifo .* ''
    198                       nop %sh{ rm -r $(dirname ${output}) }
    199                       $(printf %s "${on_close_fifo}" | sed "s/'/''''/g")
    200                   ''
    201         '"
    202     }
    203 
    204     hide_blame() {
    205         printf %s "
    206             set-option buffer git_blame_flags $kak_timestamp
    207             set-option buffer git_blame_index $kak_timestamp
    208             set-option buffer git_blame %{}
    209             try %{ remove-highlighter window/git-blame }
    210             unmap window normal <ret> %{:git blame-jump<ret>}
    211         "
    212     }
    213 
    214     diff_buffer_against_rev() {
    215         if ! command -v diff >/dev/null; then
    216             echo >${kak_command_fifo} "fail diff: command not found"
    217         fi
    218         rev=$1 # empty means index
    219         shift
    220         buffile_relative=${kak_buffile#"$(git rev-parse --show-toplevel)/"}
    221         echo >${kak_command_fifo} "evaluate-commands -no-hooks write ${kak_response_fifo}"
    222         git show "$rev:${buffile_relative}" |
    223             diff - ${kak_response_fifo} "$@" |
    224             awk -v buffile_relative="$buffile_relative" '
    225                 NR == 1 { print "--- a/" buffile_relative }
    226                 NR == 2 { print "+++ b/" buffile_relative }
    227                 NR > 2
    228             '
    229     }
    230 
    231     blame_toggle() {
    232         echo >${kak_command_fifo} "try %{
    233             add-highlighter window/git-blame flag-lines Information git_blame_flags
    234             echo -to-file ${kak_response_fifo}
    235         } catch %{
    236             echo -to-file ${kak_response_fifo} 'hide_blame; exit'
    237         }"
    238         eval $(cat ${kak_response_fifo})
    239         if [ -z "${kak_opt_git_blob}" ] && {
    240             [ "${kak_opt_filetype}" = git-diff ] || [ "${kak_opt_filetype}" = git-log ]
    241         } then {
    242             echo 'try %{ remove-highlighter window/git-blame }'
    243             printf >${kak_command_fifo} %s '
    244                 evaluate-commands -client '${kak_client}' -draft %{
    245                     try %{
    246                         execute-keys <a-l><semicolon><a-?>^commit<ret><a-semicolon>
    247                     } catch %{
    248                         # Missing commit line, assume it is an uncommitted change.
    249                         execute-keys <a-l><semicolon>Gg<a-semicolon>
    250                     }
    251                     require-module diff
    252                     try %{
    253                         diff-parse BEGIN %{
    254                             $directory = qx(git rev-parse --show-toplevel);
    255                             chomp $directory;
    256                         } END %{
    257                             my $filename = $other_file;
    258                             my $line = $other_file_line;
    259                             if (not defined $commit) {
    260                                 $commit = "HEAD";
    261                                 if ($diff_line_text =~ m{^\+}) {
    262                                     print "echo -to-file '${kak_response_fifo}' -quoting shell "
    263                                         . "%{git blame: blame from HEAD does not work on added lines}";
    264                                     exit;
    265                                 }
    266                             } elsif ($diff_line_text =~ m{^[-]}) {
    267                                 $commit = "$commit~";
    268                             } else {
    269                                 $filename = $file;
    270                                 $line = $file_line;
    271                             }
    272                             $line = $line or 1;
    273                             my $filename_relative = substr($filename, length "$directory/");
    274                             printf "echo -to-file '${kak_response_fifo}' -quoting shell %s %s %s %d %d",
    275                                $commit, quote($filename), quote($filename_relative),
    276                                $line, ('${kak_cursor_column}' - 1);
    277                         }
    278                     } catch %{
    279                         echo -to-file '${kak_response_fifo}' -quoting shell -- %val{error}
    280                     }
    281                 }
    282             '
    283             n=$#
    284             eval set -- "$(cat ${kak_response_fifo})" "$@"
    285             if [ $# -eq $((n+1)) ]; then
    286                 echo fail -- "$(kakquote "$1")"
    287                 exit
    288             fi
    289             commit=$1
    290             file_absolute=$2
    291             file_relative=$3
    292             cursor_line=$4
    293             cursor_column=$5
    294             shift 5
    295             # Log commit and file name because they are only echoed briefly
    296             # and not shown elsewhere (we don't have a :messages buffer).
    297             message="Blaming $file_relative as of $(git rev-parse --short $commit)"
    298             echo "echo -debug -- $(kakquote "$message")"
    299             on_close_fifo="
    300                 execute-keys -client ${kak_client} ${cursor_line}g<a-h>${cursor_column}lh
    301                 evaluate-commands -client ${kak_client} %{
    302                     set-option buffer git_blob $(kakquote "$commit:$file_absolute")
    303                     git blame $(for arg; do kakquote "$arg"; printf " "; done)
    304                     echo -markup -- $(kakquote "{Information}{\\}$message. Press <ret> to jump to blamed commit")
    305                     hook -once window NormalIdle .* %{ execute-keys vv }
    306                 }
    307             " show_git_cmd_output show "$commit:$file_relative"
    308             exit
    309         } fi
    310         if [ -n "${kak_opt_git_blob}" ]; then {
    311             set -- "$@" "${kak_opt_git_blob%%:*}" -- "${kak_opt_git_blob#*:}"
    312             blame_stdin=/dev/null
    313         } else {
    314             if ! error=$(cd_bufdir); then
    315                 echo 'remove-highlighter window/git-blame'
    316                 printf %s\\n "$error"
    317                 exit
    318             fi
    319             set -- "$@" --contents - -- "${kak_buffile}" # use stdin to work around git bug
    320             blame_stdin=$(mktemp "${TMPDIR:-/tmp}"/kak-git.XXXXXX)
    321             echo >${kak_command_fifo} "
    322                 evaluate-commands -no-hooks write -force ${blame_stdin}
    323                 echo -to-file ${kak_response_fifo}
    324             "
    325             : <${kak_response_fifo}
    326         } fi
    327         echo 'map window normal <ret> %{:git blame-jump<ret>}'
    328         echo 'echo -markup {Information}Press <ret> to jump to blamed commit'
    329         (
    330             trap - INT QUIT
    331             printf %s "evaluate-commands -client '$kak_client' %{
    332                       set-option buffer=$kak_bufname git_blame_flags '$kak_timestamp'
    333                       set-option buffer=$kak_bufname git_blame_index '$kak_timestamp'
    334                       set-option buffer=$kak_bufname git_blame ''
    335                   }" | kak -p ${kak_session}
    336             if ! stderr=$({ git blame --incremental "$@" <${blame_stdin} | perl -wne '
    337                   BEGIN {
    338                   use POSIX qw(strftime);
    339                   sub quote {
    340                       my $SQ = "'\''";
    341                       my $token = shift;
    342                       $token =~ s/$SQ/$SQ$SQ/g;
    343                       return "$SQ$token$SQ";
    344                   }
    345                   sub send_flags {
    346                       my $is_last_call = shift;
    347                       if (not defined $line) {
    348                           if ($is_last_call) { exit 1; }
    349                           return;
    350                       }
    351                       my $text = substr($sha,0,7) . " " . $dates{$sha} . " " . $authors{$sha};
    352                       s/\\/\\\\/g, s/\|/\\|/g, s/~/~~/g for $text;
    353                       for ( my $i = 0; $i < $count; $i++ ) {
    354                           $flags .= " %~" . ($line+$i) . "|$text~";
    355                       }
    356                       $now = time();
    357                       # Send roughly one update per second, to avoid creating too many kak processes.
    358                       if (!$is_last_call && defined $last_sent && $now - $last_sent < 1) {
    359                           return
    360                       }
    361                       open CMD, "|-", "kak -p $ENV{kak_session}";
    362                       print CMD "set-option -add buffer=$ENV{kak_bufname} git_blame_flags $flags;";
    363                       print CMD "set-option -add buffer=$ENV{kak_bufname} git_blame_index $index;";
    364                       print CMD "set-option -add buffer=$ENV{kak_bufname} git_blame " . quote $raw_blame;
    365                       close(CMD);
    366                       $flags = "";
    367                       $index = "";
    368                       $raw_blame = "";
    369                       $last_sent = $now;
    370                   }
    371                   }
    372                   $raw_blame .= $_;
    373                   chomp;
    374                   if (m/^([0-9a-f]+) ([0-9]+) ([0-9]+) ([0-9]+)/) {
    375                       send_flags(0);
    376                       $sha = $1;
    377                       $line = $3;
    378                       $count = $4;
    379                       for ( my $i = 0; $i < $count; $i++ ) {
    380                           $index .= " " . ($line+$i) . "|$.,$i";
    381                       }
    382                   }
    383                   if (m/^author /) {
    384                       $authors{$sha} = substr($_,7);
    385                       $authors{$sha} = "Not Committed Yet" if $authors{$sha} eq "External file (--contents)";
    386                   }
    387                   if (m/^author-time ([0-9]*)/) { $author_time = $1; }
    388                   if (m/^author-tz ([+-])(\d\d)/) {
    389                       my $sign = $1 eq "+" ? "-" : "+";
    390                       local $ENV{"TZ"} = "UTC${sign}$2";
    391                       $dates{$sha} = strftime("%F %T", localtime $author_time);
    392                   }
    393                   END { send_flags(1); }'
    394             } 2>&1); then
    395                 escape2() { printf %s "$*" | sed "s/'/''''/g"; }
    396                 echo "evaluate-commands -client ${kak_client} '
    397                     evaluate-commands -draft %{
    398                         buffer %{${kak_buffile}}
    399                         git hide-blame
    400                     }
    401                     echo -debug failed to run git blame
    402                     echo -debug git stderr: <<<
    403                     echo -debug ''$(escape2 "$stderr")>>>''
    404                     echo -markup %{{Error}failed to run git blame, see *debug* buffer}
    405                 '" | kak -p ${kak_session}
    406             fi
    407             if [ ${blame_stdin} != /dev/null ]; then
    408                 rm ${blame_stdin}
    409             fi
    410         ) > /dev/null 2>&1 < /dev/null &
    411     }
    412 
    413     run_git_cmd() {
    414         if git "${@}" > /dev/null 2>&1; then
    415           printf %s "echo -markup '{Information}git $1 succeeded'"
    416         else
    417           printf 'fail git %s failed\n' "$1"
    418         fi
    419     }
    420 
    421     update_diff() {
    422         (
    423             cd_bufdir || exit
    424             diff_buffer_against_rev "" -U0 | perl -e '
    425             use utf8;
    426             $flags = $ENV{"kak_timestamp"};
    427             $add_char = $ENV{"kak_opt_git_diff_add_char"};
    428             $del_char = $ENV{"kak_opt_git_diff_del_char"};
    429             $top_char = $ENV{"kak_opt_git_diff_top_char"};
    430             $mod_char = $ENV{"kak_opt_git_diff_mod_char"};
    431             foreach $line (<STDIN>) {
    432                 if ($line =~ /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))?/) {
    433                     $from_line = $1;
    434                     $from_count = ($2 eq "" ? 1 : $2);
    435                     $to_line = $3;
    436                     $to_count = ($4 eq "" ? 1 : $4);
    437 
    438                     if ($from_count == 0 and $to_count > 0) {
    439                         for $i (0..$to_count - 1) {
    440                             $line = $to_line + $i;
    441                             $flags .= " $line|\{green\}$add_char";
    442                         }
    443                     }
    444                     elsif ($from_count > 0 and $to_count == 0) {
    445                         if ($to_line == 0) {
    446                             $flags .= " 1|\{red\}$top_char";
    447                         } else {
    448                             $flags .= " $to_line|\{red\}$del_char";
    449                         }
    450                     }
    451                     elsif ($from_count > 0 and $from_count == $to_count) {
    452                         for $i (0..$to_count - 1) {
    453                             $line = $to_line + $i;
    454                             $flags .= " $line|\{blue\}$mod_char";
    455                         }
    456                     }
    457                     elsif ($from_count > 0 and $from_count < $to_count) {
    458                         for $i (0..$from_count - 1) {
    459                             $line = $to_line + $i;
    460                             $flags .= " $line|\{blue\}$mod_char";
    461                         }
    462                         for $i ($from_count..$to_count - 1) {
    463                             $line = $to_line + $i;
    464                             $flags .= " $line|\{green\}$add_char";
    465                         }
    466                     }
    467                     elsif ($to_count > 0 and $from_count > $to_count) {
    468                         for $i (0..$to_count - 2) {
    469                             $line = $to_line + $i;
    470                             $flags .= " $line|\{blue\}$mod_char";
    471                         }
    472                         $last = $to_line + $to_count - 1;
    473                         $flags .= " $last|\{blue+u\}$mod_char";
    474                     }
    475                 }
    476             }
    477             print "set-option buffer git_diff_flags $flags\n"
    478         ' )
    479     }
    480 
    481     jump_hunk() {
    482         direction=$1
    483         set -- ${kak_opt_git_diff_flags}
    484         shift
    485 
    486         if [ $# -lt 1 ]; then
    487             echo "fail 'no git hunks found, try \":git show-diff\" first'"
    488             exit
    489         fi
    490 
    491         # Update hunk list if required
    492         if [ "$kak_timestamp" != "${kak_opt_git_hunk_list%% *}" ]; then
    493             hunks=$kak_timestamp
    494 
    495             prev_line="-1"
    496             for line in "$@"; do
    497                 line="${line%%|*}"
    498                 if [ "$((line - prev_line))" -gt 1 ]; then
    499                     hunks="$hunks.1,$prev_line.1 $line"
    500                 fi
    501                 prev_line="$line"
    502             done
    503             hunks="$hunks.1,$prev_line.1"
    504             echo "set-option buffer git_hunk_list $hunks"
    505             hunks=${hunks#* }
    506         else
    507             hunks=${kak_opt_git_hunk_list#* }
    508         fi
    509 
    510         prev_hunk=""
    511         next_hunk=""
    512         for hunk in ${hunks}; do
    513             if   [ "${hunk%%.*}" -lt "$kak_cursor_line" ]; then
    514                 prev_hunk=$hunk
    515             elif [ "${hunk%%.*}" -gt "$kak_cursor_line" ]; then
    516                 next_hunk=$hunk
    517                 break
    518             fi
    519         done
    520 
    521         wrapped=false
    522         if [ "$direction" = "next" ]; then
    523             if [ -z "$next_hunk" ]; then
    524                 next_hunk=${hunks%% *}
    525                 wrapped=true
    526             fi
    527             if [ -n "$next_hunk" ]; then
    528                 echo "select $next_hunk"
    529                 echo 'execute-keys x'
    530             fi
    531         elif [ "$direction" = "prev" ]; then
    532             if [ -z "$prev_hunk" ]; then
    533                 wrapped=true
    534                 prev_hunk=${hunks##* }
    535             fi
    536             if [ -n "$prev_hunk" ]; then
    537                 echo "select $prev_hunk"
    538                 echo 'execute-keys x'
    539             fi
    540         fi
    541 
    542         if [ "$wrapped" = true ]; then
    543             echo "echo -markup '{Information}git hunk search wrapped around buffer'"
    544         fi
    545     }
    546 
    547     commit() {
    548         if ! fifo_dir="$(mktemp -d "${TMPDIR:-/tmp}/kak-git-commit-XXXXXX")" ||
    549            ! mkfifo "${fifo_dir}/response_fifo"
    550         then
    551             echo "fail %{failed to run git commit (see *debug* buffer)}"
    552             [ -n "${fifo_dir}" ] && rmdir "${fifo_dir}"
    553             exit 1
    554         fi
    555         {
    556             trap 'rm -r "${fifo_dir}"' EXIT
    557             export GIT_EDITOR="$(git rev-parse --sq-quote \
    558                 "${KAKOUNE_POSIX_SHELL:-/bin/sh}" \
    559                 "${kak_runtime}/rc/tools/blocking-editor-in-client" \
    560                 "${fifo_dir}" "${kak_session}" "${kak_client}")"
    561             failed=false
    562             if err="$(git commit "$@" 2>&1)"; then
    563                 cmd="eval -try-client ${kak_client} %{
    564                     echo -markup '{Information}Commit succeeded'
    565                 }"
    566             elif [ -f "${fifo_dir}/cancelled" ]; then
    567                 cmd="eval -try-client ${kak_client} %{
    568                     echo -markup '{Information}Commit cancelled'
    569                 }"
    570             else
    571                 failed=true
    572                 cmd="eval -try-client ${kak_client} %{
    573                     try %{
    574                         edit! -fifo $(kakquote "${fifo_dir}/response_fifo") '*git-commit*'
    575                     }
    576                     echo -markup '{Error}Commit failed'
    577                 }"
    578             fi
    579             printf %s "${cmd}" | kak -p "${kak_session}"
    580             if [ ${failed} = true ]; then
    581                 printf %s "$err" >"${fifo_dir}/response_fifo"
    582             fi
    583         } 2>/dev/null 1>&2 </dev/null &
    584     }
    585 
    586     blame_jump() {
    587         if [ -z "${kak_client}" ]; then
    588             echo fail git blame-jump: no client in context
    589             exit
    590         fi
    591         echo >${kak_command_fifo} "echo -to-file ${kak_response_fifo} -- %opt{git_blame}"
    592         blame_info=$(cat < ${kak_response_fifo})
    593         blame_index=
    594         cursor_column=${kak_cursor_column}
    595         cursor_line=${kak_cursor_line}
    596         if [ -n "$blame_info" ]; then {
    597             echo >${kak_command_fifo} "
    598                 update-option buffer git_blame_index
    599                 echo -to-file ${kak_response_fifo} -- %opt{git_blame_index}
    600             "
    601             blame_index=$(cat < ${kak_response_fifo})
    602         } elif [ "${kak_opt_filetype}" = git-diff ] || [ "${kak_opt_filetype}" = git-log ]; then {
    603             printf >${kak_command_fifo} %s '
    604                 evaluate-commands -draft %{
    605                     try %{
    606                         execute-keys <a-l><semicolon><a-?>^commit<ret><a-semicolon>
    607                     } catch %{
    608                         # Missing commit line, assume it is an uncommitted change.
    609                         execute-keys <a-l><semicolon><a-?>\A<ret><a-semicolon>
    610                     }
    611                     require-module diff
    612                     try %{
    613                         diff-parse BEGIN %{
    614                             $version = "-";
    615                             $directory = qx(git rev-parse --show-toplevel);
    616                             chomp $directory;
    617                         } END %{
    618                             if ($diff_line_text !~ m{^[ -]}) {
    619                                 print quote "git blame-jump: recursive blame only works on context or deleted lines";
    620                                 exit 1;
    621                             }
    622                             if (not defined $commit) {
    623                                 $commit = "HEAD";
    624                             } else {
    625                                 $commit = "$commit~";
    626                             }
    627                             printf "echo -to-file '${kak_response_fifo}' -quoting shell %s %s %d %d",
    628                                     $commit, quote($file), $file_line, ('$cursor_column' - 1);
    629                         }
    630                     } catch %{
    631                         echo -to-file '${kak_response_fifo}' -quoting shell -- %val{error}
    632                     }
    633                 }
    634             '
    635             eval set -- "$(cat ${kak_response_fifo})"
    636             if [ $# -eq 1 ]; then
    637                 echo fail -- "$(kakquote "$1")"
    638                 exit
    639             fi
    640             starting_commit=$1
    641             file=$2
    642             cursor_line=$3
    643             cursor_column=$4
    644             blame_info=$(git blame --porcelain "$starting_commit" -L"$cursor_line,$cursor_line" -- "$file")
    645             if [ $? -ne 0 ]; then
    646                 echo 'echo -markup %{{Error}failed to run git blame, see *debug* buffer}'
    647                 exit
    648             fi
    649         } else {
    650             if [ -n "${kak_opt_git_blob}" ]; then {
    651                 set -- "${kak_opt_git_blob%%:*}" -- "${kak_opt_git_blob#*:}"
    652                 blame_stdin=/dev/null
    653             } else {
    654                 set -- --contents - -- "${kak_buffile}" # use stdin to work around git bug
    655                 blame_stdin=${kak_response_fifo}
    656                 echo >${kak_command_fifo} "evaluate-commands -no-hooks write ${kak_response_fifo}"
    657             } fi
    658             if ! blame_info=$(
    659                 git blame --porcelain -L"$cursor_line,$cursor_line" "$@" <${blame_stdin})
    660             then
    661                 echo 'echo -markup %{{Error}failed to run git blame, see *debug* buffer}'
    662                 exit
    663             fi
    664         } fi
    665         eval "$(printf '%s\n---\n%s' "$blame_index" "$blame_info" |
    666                 client=${kak_opt_docsclient:-$kak_client} \
    667                 cursor_line=$cursor_line cursor_column=$cursor_column \
    668                 perl -wne '
    669             BEGIN {
    670                 use POSIX qw(strftime);
    671                 our $SQ = "'\''";
    672                 sub escape {
    673                    return shift =~ s/$SQ/$SQ$SQ/gr
    674                 }
    675                 sub quote {
    676                     my $token = escape shift;
    677                     return "$SQ$token$SQ";
    678                 }
    679                 sub shellquote {
    680                     my $token = shift;
    681                     $token =~ s/$SQ/$SQ\\$SQ$SQ/g;
    682                     return "$SQ$token$SQ";
    683                 }
    684                 sub perlquote {
    685                     my $token = shift;
    686                     $token =~ s/\\/\\\\/g;
    687                     $token =~ s/$SQ/\\$SQ/g;
    688                     return "$SQ$token$SQ";
    689                 }
    690                 $target = $ENV{"cursor_line"};
    691                 $state = "index";
    692             }
    693             chomp;
    694             if ($state eq "index") {
    695                 if ($_ eq "---") {
    696                     $state = "blame";
    697                     next;
    698                 }
    699                 @blame_index = split;
    700                 next unless @blame_index;
    701                 shift @blame_index;
    702                 foreach (@blame_index) {
    703                     $_ =~ m{(\d+)\|(\d+),(\d+)} or die "bad blame index flag: $_";
    704                     my $buffer_line = $1;
    705                     if ($buffer_line == $target) {
    706                         $target_in_blame = $2;
    707                         $target_offset = $3;
    708                         last;
    709                     }
    710                 }
    711                 defined $target_in_blame and next, or last;
    712             }
    713             if (m/^([0-9a-f]+) ([0-9]+) ([0-9]+) ([0-9]+)/) {
    714                 if ($done) {
    715                     last;
    716                 }
    717                 $sha = $1;
    718                 $old_line = $2;
    719                 $new_line = $3;
    720                 $count = $4;
    721                 if (defined $target_in_blame) {
    722                     if ($target_in_blame == $. - 2) {
    723                         $old_line += $target_offset;
    724                         $done = 1;
    725                     }
    726                 } else {
    727                     if ($new_line <= $target and $target < $new_line + $count) {
    728                         $old_line += $target - $new_line;
    729                         $done = 1;
    730                     }
    731                 }
    732             }
    733             if (m/^filename /) { $old_filenames{$sha} = substr($_,9) }
    734             if (m/^author /) { $authors{$sha} = substr($_,7) }
    735             if (m/^author-time ([0-9]*)/) { $author_time = $1; }
    736             if (m/^author-tz ([+-])(\d\d)/) {
    737                 my $sign = $1 eq "+" ? "-" : "+";
    738                 local $ENV{"TZ"} = "UTC${sign}$2";
    739                 $dates{$sha} = strftime("%F", localtime $author_time);
    740             }
    741             if (m/^summary /) { $summaries{$sha} = substr($_,8) }
    742             END {
    743                 if (@blame_index and not defined $target_in_blame) {
    744                     print "echo fail git blame-jump: line has no blame information;";
    745                     exit;
    746                 }
    747                 if (not defined $sha) {
    748                     print "echo fail git blame-jump: missing blame info";
    749                     exit;
    750                 }
    751                 if (not $done) {
    752                     print "echo \"fail git blame-jump: line not found in annotations (blame still loading?)\"";
    753                     exit;
    754                 }
    755                 $info = "{Information}{\\}";
    756                 if ($sha =~ m{^0+$}) {
    757                     $old_filename = $ENV{"kak_buffile"};
    758                     $old_filename = substr $old_filename, length($ENV{"PWD"}) + 1;
    759                     $show_diff = "diff HEAD";
    760                     $info .= "Not committed yet";
    761                 } else {
    762                     $old_filename = $old_filenames{$sha};
    763                     $author = $authors{$sha};
    764                     $date = $dates{$sha};
    765                     $summary = $summaries{$sha};
    766                     $show_diff = "show $sha";
    767                     $info .= "$date $author \"$summary\"";
    768                 }
    769                 $on_close_fifo = "
    770                     evaluate-commands -draft $SQ
    771                         execute-keys <percent>
    772                         require-module diff
    773                         diff-parse BEGIN %{
    774                             \$in_file = " . escape(perlquote($old_filename)) . ";
    775                             \$in_file_line = $old_line;
    776                         } END $SQ$SQ
    777                             print \"execute-keys -client $ENV{client} \${diff_line}g<a-h>$ENV{cursor_column}l;\";
    778                             printf \"evaluate-commands -client $ENV{client} $SQ$SQ$SQ$SQ
    779                                 hook -once window NormalIdle .* $SQ$SQ$SQ$SQ$SQ$SQ$SQ$SQ
    780                                     execute-keys vv
    781                                     echo -markup -- %s
    782                                 $SQ$SQ$SQ$SQ$SQ$SQ$SQ$SQ
    783                             $SQ$SQ$SQ$SQ ;\"," . escape(escape(perlquote(escape(escape(quote($info)))))) . ";
    784                         $SQ$SQ
    785                     $SQ
    786                 ";
    787                 printf "on_close_fifo=%s show_git_cmd_output %s",
    788                     shellquote($on_close_fifo), $show_diff;
    789             }
    790         ')"
    791     }
    792 
    793     apply_selections() {
    794         if [ -z "$(cd_bufdir >/dev/null 2>&1 && git ls-files -- ":(literal)${kak_buffile}")" ]; then {
    795             enquoted="$(printf '"%s" ' "$@")"
    796             echo "require-module patch"
    797             echo "patch git apply $enquoted"
    798             return
    799         } fi
    800         base_rev=HEAD
    801         index_only=false
    802         index=false
    803         reverse=false
    804         for arg; do
    805             case "$arg" in
    806                 (--cached) index_only=true ; base_rev= ;;
    807                 (--index) index=true ;;
    808                 (--reverse|-R) reverse=true ;;
    809             esac
    810         done
    811         if ! $reverse && ! $index_only; then
    812             echo "fail %{git apply on buffer contents doesn't make sense without --reverse or --cached}"
    813             exit
    814         fi
    815         cd_bufdir || exit
    816         num_inserted=0
    817         num_deleted=0
    818         for selection_desc in $kak_selections_desc; do {
    819             IFS=' .,' read anchor_line _ cursor_line _ <<-EOF
    820                 $selection_desc
    821 		EOF
    822             if [ $anchor_line -lt $cursor_line ]; then
    823                 min_line=$anchor_line
    824                 max_line=$cursor_line
    825             else
    826                 min_line=$cursor_line
    827                 max_line=$anchor_line
    828             fi
    829             intended_diff='diff_buffer_against_rev "$base_rev" -u'
    830             if $index; then {
    831                 git update-index --refresh "${kak_buffile}" >/dev/null
    832                 intended_diff='git diff --no-ext-diff HEAD -- ":(literal)${kak_buffile}"'
    833             } elif $index_only && $reverse; then {
    834                 diff=$(eval "$intended_diff")
    835                 if [ -n "$diff" ]; then {
    836                     # Convert from buffile lines to index lines.
    837                     for line in min_line max_line; do {
    838                         if ! index_line_or_error_message=$(
    839                             eval file_line=\$$line
    840                             printf %s "$diff" |
    841                                 perl "${kak_runtime}/rc/filetype/diff-parse.pl" \
    842                                     BEGIN '
    843                                         $in_file = ""; # no need to check filename, there is only one
    844                                         $in_file_line = '"$file_line"';
    845                                     ' END '
    846                                         $other_file_line++ if $diff_line_text =~ m{^\+};
    847                                         $other_file_line += $in_file_line - $file_line;
    848                                         print "$other_file_line\n";
    849                                     '
    850                         ); then
    851                             echo fail "git apply: $index_line_or_error_message"
    852                             exit
    853                         fi
    854                         eval $line=$index_line_or_error_message
    855                     } done
    856                 } fi
    857                 intended_diff='git diff --no-ext-diff --cached -- ":(literal)${kak_buffile}"'
    858             } fi
    859             diff=$(eval "$intended_diff" |
    860                     perl "${kak_runtime}"/rc/tools/patch-range.pl -line-numbers-from-new-file \
    861                         $min_line $max_line sh -c cat -- "$@" # forward any --reverse arg
    862                    printf .) # avoid stripping newline
    863             diff=${diff%.}
    864             if ! printf %s "$diff" | git apply "$@"; then
    865                 printf >&2 "git apply: error running:\n\$ git apply %s << EOF\n" "$*"
    866                 printf >&2 %s "$diff"
    867                 printf >&2 'EOF\n'
    868                 echo "fail 'git apply: failed to apply selections, see *debug* buffer'"
    869                 exit
    870             fi
    871             count() {
    872                 printf %s "$diff" | awk '
    873                     BEGIN { n = 0 }
    874                     /^@@/,/^$/ { if ($0 ~ /^'"$1"'/) { n++ } }
    875                     END { print n }'
    876             }
    877             num_inserted=$(( $num_inserted + $(count +) ))
    878             num_deleted=$(( $num_deleted + $(count -) ))
    879         } done
    880         if ! $index_only && ! $kak_modified; then
    881             echo edit!
    882             echo git update-diff
    883         else
    884             update_diff
    885         fi
    886         msg=
    887         case $index_only,$reverse,$index in
    888             (true,false,*) msg=Staged ;;
    889             (true,true,*) msg=Unstaged ;;
    890             (false,true,false) msg=Reverted ;;
    891             (false,true,true) msg='Unstaged and reverted' ;;
    892         esac
    893         case $num_inserted,$num_deleted in
    894             (*,0) msg="$msg $num_inserted inserted line(s)";;
    895             (0,*) msg="$msg $num_deleted deleted line(s)";;
    896             (*,*) msg="$msg $num_inserted inserted and $num_deleted deleted lines";;
    897         esac
    898         echo "echo -markup '{Information}{\\}$msg'"
    899     }
    900 
    901     case "$1" in
    902         apply)
    903             shift
    904             apply_selections "$@"
    905             ;;
    906         show|show-branch|log|diff|status)
    907             show_git_cmd_output "$@"
    908             ;;
    909         blame)
    910             shift
    911             blame_toggle "$@"
    912             ;;
    913         blame-jump)
    914             blame_jump
    915             ;;
    916         hide-blame)
    917             hide_blame
    918             ;;
    919         show-diff)
    920             echo 'try %{ add-highlighter window/git-diff flag-lines Default git_diff_flags }'
    921             update_diff
    922             ;;
    923         hide-diff)
    924             echo 'try %{ remove-highlighter window/git-diff }'
    925             ;;
    926         update-diff) update_diff ;;
    927         next-hunk) jump_hunk next ;;
    928         prev-hunk) jump_hunk prev ;;
    929         commit)
    930             shift
    931             commit "$@"
    932             ;;
    933         init)
    934             shift
    935             git init "$@" > /dev/null 2>&1
    936             ;;
    937         add|rm)
    938             cmd="$1"
    939             shift
    940             run_git_cmd $cmd "${@:-"${kak_buffile}"}"
    941             ;;
    942         reset|checkout)
    943             run_git_cmd "$@"
    944             ;;
    945         grep)
    946             shift
    947             enquoted="$(printf '"%s" ' "$@")"
    948             printf %s "try %{
    949                 set-option current grepcmd 'git grep -n --column'
    950                 grep $enquoted
    951                 set-option current grepcmd '$kak_opt_grepcmd'
    952             }"
    953             ;;
    954         edit)
    955             shift
    956             enquoted="$(printf '"%s" ' "$@")"
    957             printf %s "edit -existing -- $enquoted"
    958             ;;
    959         *)
    960             printf "fail unknown git command '%s'\n" "$1"
    961             exit
    962             ;;
    963     esac
    964 }}
    965 
    966 # Works within :git diff and :git show
    967 define-command git-diff-goto-source \
    968     -docstring 'Navigate to source by pressing the enter key in hunks when git diff is displayed. Works within :git diff and :git show' %{
    969     require-module diff
    970     diff-jump %sh{ git rev-parse --show-toplevel }
    971 }