Search code examples
vimkeymapping

Vim key mapping for visual mode


I'm trying to create a mapping for Visual Mode where I press F7 and the selected code will be wrapped with /* and / respectively. I want / and */ to be on a line by themselves.

I have this in my vimrc:

autocmd BufNewFile,BufRead *.c,*.js xmap <F7> I <ENTER> <ESC> k I /* <ESC> gv A */ <ENTER> <ESC>

since I want this mapping to only be valid for C and js files. It works ALMOST as I want it. The only issue is instead a of the code being on a newline after /*, there'll be an empty line after the code and before the closing */.

I don't really understand why, since executing each action manually does what I want.

The result of pressing F7 should turn this code:

for (size_t a = 0; a<5; a++) {
    printf("%d\n", somearray[a]);
 }

into this

  /*
    for (size_t a = 0; a<5; a++) {
            printf("%d\n", somearray[a]);
         }
 */

while as it stands, it'll end up like this for some reason:

/*for (size_t a = 0; a<5; a++) {
        printf("%d\n", somearray[a]);
     }
---newline---
*/

Solution

  • It works now.

    autocmd BufNewFile,BufRead *.c,*.js xmap <F7> I<CR><ESC>kI /*<ESC> gv A*/ <CR> <ESC>