← Back to Upcase

Help with a vim mapping?

I have found myself lately needing to change a bunch of Javascript code from . syntax to [] for property access. So, I wanted to make a mapping for this. Manually, I place my cursor on the . (in normal mode) and then type lysiw"ysa"]hx but I can’t get this to work in my vimrc. I’m sure there’s something I’m missing about how to define the mappings. So far, here’s what I tried:

nnoremap <leader>[ lysiw"ysa"]hx

It appears that the i for inner word dumps me to insert mode and the rest of the mapping gets plopped in as a string literal. Anyone able to point me in the right direction for making this mapping work?

I think the issue has to do with the use of nnoremap to define the mapping. nnoremap does not allowing mappings (like surround’s ysiw that you’re using) to work in the right hand side of the mapping. If you wanted to use this functionality you can map with nmap instead of nnoremap.

You could always use a macro, press qq to record to q then push the lysiw"ysa"]hx and then q again to stop recording. Goto the next period and press @q to recall it.

Thanks, @christoomey! Using nmap rather than nnoremap worked brilliantly.

IMHO, you don’t need a whole mapping here. Macros would serve the case:

qa        " start macros creation and save it under the `a` key
10@a      " run macros ten times

second line does exactly what you would expect from this commands in normal mode

This way you can perform some complex command, which you don’t actually need in the long term. Though macros won’t be persistent, unless you write it in the .vimrc.

Of course this is kinda ideal case, but I’m sure it is possible to make something for any pattern.