3

In git when patching you have to count:

  • The "leave alone" lines
  • The "remove" lines
  • The "add" lines
  • The "leave alone" + "add" lines

I've found ways to count all of these...

  • %s/^ / /n "leave alone"
  • %s/^-/ /n "remove"
  • %s/^+/ /n "add"
  • %s/^ \|^+/ /n "add" + "leave alone"

Now what I'd like to do is display these counts in a new split buffer, so that my patching can go well.

Is there any way to display the resulting counts in an split buffer Window, either above or below the patch one using Vim Script?

  • Okay so everybody loves this question...how about an answer?!?!? – leeand00 Apr 30 '16 at 12:47
2

I don't know git so I'm not sure it will work in your case, but maybe you could try the following code:

command! -range=% CountGit let b:winview = winsaveview() | <line1>,<line2>call s:count_git()
function! s:count_git() abort range
    let counts = repeat([0], 4)
    let patterns = ['^ ', '^-', '^+', '^ \|^+']
    for i in range(4)
        exe a:firstline ',' a:lastline 'g/' . patterns[i] . '/let counts[' i '] += 1'
    endfor
    lefta new
    sil! 0put =['leave alone: ', 'remove: ', 'add: ', 'add + leave alone: ']
    sil! 4put =counts
    sil! 1,4g/^/5m.|-j!
    $d_
    sil! %!column -t -s:
    if !bufexists('Counts') | file Counts | endif
    setl noma bt=nofile noswf nobl bh=wipe
    wincmd p
    call winrestview(b:winview) | unlet b:winview
endfunction

It defines a custom command :CountGit which calls the s:count_git() function.

The function initializes the lists counts and patterns.

counts should contain the number of occurrences of the lines you're interested in, while patterns contains the description of the latter.

The for loop executes a global command for each pattern which increments a number inside counts for each occurrence of the pattern.

  • 0put =... paste some description text (leave alone:, remove:...).
  • 4put =... paste the number of occurrences after the 4th line.
  • 1,4g/^/5m.|-j! join the 2 blocks of text (description + counts).
  • sil! %!column -t -s: align the counts (remove this line if you don't have the shell column utility)

The command accepts a range (which by default is %) so you could for example select only a part of the buffer and type :'<,'>CountGit to search for the patterns only inside the visual selection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.