Search code examples
regexvimcommandmode

vim insert output from command mode and increase by one


I would like to make a map to automatically insert the number of matches of some regular expression. In my vimrc i mapped

map <C-A> :%s/^\[^\d*\]//gn<CR>

to find the number of footnotes in a document. I want to expand this map such that it inserts the number of matches+1 at the current curser position. So if there were 3 matches, it should insert 4.


Solution

  • This function does what you want:

    function! FootNotes()
        redir => number_of_matches
        silent %s/^\[^\d*\]//gn
        redir END
        return split(number_of_matches)[0] + 1
    endfunction
    inoremap <expr> <key> FootNotes()
    

    Relevant documentation:

    :help :redir
    :help split()
    :help <expr>