user1642311
user1642311

Reputation: 21

VIM key map doesn't work as expected

I've got following key map:

nmap <F9> :s/^/\/\*! /<cr>:s/$/ !\*\//<cr>j

It is intended to comment line in C style. When I hit <F9> it works fine. But when I try preceed it with number(to comment specified amount of lines) it misses closing bracket */ on every line except the last one. It looks like:

/*! foo1;
/*! foo2;
/*! foo3; !*/

I've got similar key map to uncomment:

nmap  <F10>   :s/^\/\*! //e<cr>:s/ !\*\/$//e<cr>j

and situation is analogous(doesn't remove closing bracket).

EDIT:

Ha! I found solution.

Upvotes: 2

Views: 321

Answers (2)

Kris Jenkins
Kris Jenkins

Reputation: 4210

Hmmm...tricky. This is something to do with the first substitute command being converted to the range :.,.+n, but the second one only acting on the final line. I'm not quite sure why that's happening, but converting to a single substitution solves the problem. So, collapsing into one call and then tidying up a little, this works:

nnoremap <F9> :s!.*!/* & */!<CR>j

(Note the use of ! instead of / as a pattern separator. You can use :s with (almost) any character. / is just the default. If your pattern uses a lot of /s, it's sensible to use something else and save yourself some escapes.)

Upvotes: 2

Zsolt Botykai
Zsolt Botykai

Reputation: 51693

Actually vim keymaps usually does not support lineranges. But there are some workarounds:

  1. set up a visual selection (of lines) and change your mapping to: nmap <F9> :'<,'>s/^/\/\*! /<cr>:'<,'>s/$/ !\*\//<cr>j (and note that you can issue more ex commands on one line so you can "shorten" it to nmap <F9> :'<,'>s/^/\/\*! /|'<,'>s/$/ !\*\//<cr>j
  2. but I would recommend using a plugin for this: NERD commenter is really capable...

Upvotes: 2

Related Questions