0

I have this mapping to surround a Word with jQuery id selector $("#...") and it works fine using a command:

command! JqId normal viwo^[i#^[ysiW"ysiW)i$^[E
nnoremap <Leader>jqid :JqId<CR>

But I cannot make it works only with the mapping, it inserts the $ sign, but the vim-surround commands do nothing:

nnoremap <silent> <Leader>jqid viwo^[i#^[ysiW"ysiW)i$^[E

I also tried this (for testing purposes) and it doesn't work either:

nnoremap <silent> <Leader>jqid ysiW"

Any hint? Thanks!

statox
  • 49,782
  • 19
  • 148
  • 225
raul.vila
  • 113
  • 4

2 Answers2

2

EDIT:

Your mapping doesn't work because you are in a rare case where you want to use nmap instead of nnoremap: You want to use in a mapping an already defined mapping. Using nnoremap you said to Vim "use the default behavior of ysiW"" instead of "use the behavior defined by a plugin"


If I understand your mapping correctly you want to be able to transform

foo

into

$("#foo")

Vim surround is useful when you need to provide a different character to surround your word, here you know that you will always use it with the same characters so you could just use built-in motions. For example something like this:

nnoremap <yourkey> bi$("#<Esc>ea")

This mapping will work if you are not on the first character of the word it would need a bit of work to be more robust but what I want to say with this answer is don't use a plugin if you don't actually need it.

statox
  • 49,782
  • 19
  • 148
  • 225
  • Thank statox, you undertand perfectly. I think the "first character issue" can be fixed with viwo (idea from reddit).

    But I would also like to know the problem of executing the original mapping without the command (with the command it works). So I think I'm not understanding something about the basics of executing stuff through mappings.

    – raul.vila Feb 20 '18 at 08:00
  • @raul.vila See my edit :) – statox Feb 20 '18 at 08:09
  • Thanks! It was that. I thought the recursivity worked in reverse (to allow other mappings to invoke the one which is being defined). Now I know :D. – raul.vila Feb 20 '18 at 08:14
  • @raul.vila For the next time you have an issue with a mapping you might be interested in this generic answer I made some times ago. – statox Feb 20 '18 at 08:35
0

Alternatively you can setup a customized "surrounding".

let g:surround_{char2nr('i')} = "$(\"#\r\")"

Now you can use the "i" surrounding with all your surrounding operators, ys, insert mode <c-s> / <c-g>s, visual mode (S), etc.

For more help see:

:h surround-customizing
:h curly-braces-names
:h :let
:h char2nr()
Peter Rincker
  • 15,854
  • 1
  • 36
  • 45
  • Thanks for the workaround, it make sense if I'm using vim-surround. But the "nore" option was what I was really missing. – raul.vila Feb 20 '18 at 16:22