首页 > 解决方案 > 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.

标签: vimmacroskeymapping

解决方案


要进行计数,您将切换到使用:normal Ex命令。对于 ruby​​/python,这将如下所示:

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

此外,vim 知道大多数语言和文件类型的注释字符串。因此,您不必明确告诉每种语言使用什么作为注释字符串,而是使用如下内容:

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

推荐阅读