简体   繁体   中英

What's wrong with this Vim mapping?

Inside a function I use to initialise some TeX related settings I have the following mapping defined:

vmap <buffer> ucm :s/^\% //<CR>:nohlsearch<CR>

I expected it to allow me to easily uncomment visually selected lines. The analogous:

vmap <buffer> cm :s/^/\% /<CR>:nohlsearch<CR>

does a pretty nice job in commenting. Also analogous mappings for other languages, which use a #, and not a % work just fine. Those last ones look like this:

vmap <buffer> cm :s/^/# /<CR>:nohlsearch<CR>
vmap <buffer> ucm :s/^# //<CR>:nohlsearch<CR>

A sequence of V 10 j cm V 10 k ucm is supposed to leave the code intact.

So now: What am I doing wrong?

You are adding unecessary stuff.

:s/^/% <CR>

and

:s/^% /<CR>

should work for commenting and uncommenting respectively.

The third / is used to add options such as /c for "confirm" or /g for "global". If you don't use those options you don't need this / at all.

In your "uncomment" substitution you are escaping % but % in itself has no special meaning for Vim's regex flavour. Not only Vim is certainly not going to match it if it's escaped but \\%<something> is used for a bunch of atoms like \\%d . So your pattern fails because Vim stumbles upon your \\% expecting the rest of the atom and getting "nothing".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM