patch.kak (2826B)
1 define-command patch -params .. -docstring %{ 2 patch [<arguments>]: apply selections in diff to a file 3 4 Given some selections within a unified diff, apply the changed lines in 5 each selection by piping them to "patch <arguments> 1>&2" 6 (or "<arguments> 1>&2" if <arguments> starts with a non-option argument). 7 If successful, the in-buffer diff will be updated to reflect the applied 8 changes. 9 For selections that contain no newline, the entire enclosing diff hunk 10 is applied (unless the cursor is inside a diff header, in which case 11 the entire diff is applied). 12 To revert changes, <arguments> must contain "--reverse" or "-R". 13 } %{ 14 evaluate-commands -draft -itersel -save-regs aes|^ %{ 15 try %{ 16 execute-keys <a-k>\n<ret> 17 } catch %{ 18 # The selection contains no newline. 19 execute-keys -save-regs '' Z 20 execute-keys <a-l><semicolon><a-?>^diff<ret> 21 try %{ 22 execute-keys <a-k>^@@<ret> 23 # If the cursor is in a diff hunk, stage the entire hunk. 24 execute-keys z 25 execute-keys /.*?(?:(?=\n@@)|(?=\ndiff)|(?=\n\n)|\z)<ret>x<semicolon><a-?>^@@<ret> 26 } catch %{ 27 # If the cursor is in a diff header, stage the entire diff. 28 execute-keys <a-semicolon>?.*?(?:(?=\ndiff)|(?=\n\n)|\z)<ret> 29 } 30 } 31 # We want to apply only the selected lines. Remember them. 32 execute-keys <a-:> 33 set-register s %val{selection_desc} 34 # Select forward until the end of the last hunk. 35 execute-keys H?.*?(?:(?=\n@@)|(?=\ndiff)|(?=\n\n)|\z)<ret>x 36 # Select backward to the beginning of the first hunk's diff header. 37 execute-keys <a-semicolon><a-L><a-?>^diff<ret> 38 # Move cursor to the beginning so we know the diff's offset within the buffer. 39 execute-keys <a-:><a-semicolon> 40 set-register a %arg{@} 41 set-register e nop 42 set-register | %{ 43 # The selected range to apply. 44 IFS=' .,' read min_line _ max_line _ <<-EOF 45 $kak_reg_s 46 EOF 47 min_line=$((min_line - kak_cursor_line + 1)) 48 max_line=$((max_line - kak_cursor_line + 1)) 49 50 # Since registers are never empty, we get an empty arg even if 51 # there were no args. This does no harm because we pass it to 52 # a shell where it expands to nothing. 53 eval set -- "$kak_quoted_reg_a" 54 55 perl "${kak_runtime}"/rc/tools/patch-range.pl -print-remaining-diff $min_line $max_line "$@" ">&2" || 56 echo >$kak_command_fifo "set-register e fail 'patch: failed to apply selections, see *debug* buffer'" 57 } 58 execute-keys |<ret> 59 %reg{e} 60 } 61 } 62 63 provide-module patch %ยงยง