Search code examples
vimmacroskeymapping

VIM mapping not fully repeating


I've added the following lines to my vimrc in order to quickly comment lines of code:

augroup cmnts
    autocmd FileType c, cpp, javascript nnoremap <buffer> <leader>c 
I//<esc>j
    autocmd FileType python nnoremap <buffer> <leader>c I#<esc>j
augroup END

My expectation was that when I repeat the mapping with a number, that number of lines would be commented, but instead it just adds the comment character multiple times.

For example in Python, When I type Hc Hc Hc (H is my leader key) it comments three lines, but when I type 3Hc I get ### at the start of my current line.


Solution

  • To take counts you'll switch to use :normal Ex command. This would look like the below for ruby/python:

    nnoremap <leader>c :normal I# <CR>
    

    Also, vim knows the comment string for most languages and file types. So, you don't have to explicitly tell what to use as a comment string for every language, instead, use something like below:

    nnoremap <leader>c :call CommentLine()<CR>
    function! CommentLine()
        let comment_character = split(&commentstring, '%s')
        exec 'normal I' . comment_character[0] . ' '
    endfunction