0

When I am coding in c++, I want vim to expand ( into ()<++> and place the cursor in the parenthesis. I do this by putting the following line in one of the files loaded at startup:

inoremap (      ()<++><Left><Left><Left><Left><Left>

However, I would like this binding to be disabled in comments, like

// Inline comment where ( shouldn't become ()<++>

or

/* Comment block where ( shouldn't become ()<++>
*/

How can I do it?

2 Answers 2

1

You can make use of expression mappings. The basic idea is to test the current syntax and only expand, if it is not a comment. That is basically what all the plugins will be hiding from you: :inoremap <silent><expr> ( synIDattr(synIDtrans(synID(line('.'), col('.')-1, 'name')),'name')=~?"comment"?"(":"()<++><Left><Left><Left> <Left><Left>"

Which means, check that the current syntax item is not of type comment and in that case replace by your ()<++> item or else replace by themselves. Note, it is probably more easier to hide that functionality behind a function that does the necessary checks.

Note: to make undo and redo work properly, instead of using "<Left>" you should use "<C-G>U<Left>", which is a relative recent addition to Vim. Read the help at :h i_CTRL-G_U

1
  • Great! To the point and complete. Really helpful!
    – dPol
    Sep 30, 2015 at 19:23
0

[copy paste of the answer given on SO...]

Install lh-brackets it already detects the context to not expand anywhere. It also adds a placeholder after the closing brackets. If you directly install lh-cpp, the control statements will also be context aware.

(I must admit your request is quite surprising as nobody seems to use placeholders any more. And yet lh-brackets is the plugin that (re-)introduced this concept (idea stolen from Stephen Riehm's original bracketing macros). Then mu-template used a similar bracketing philosophy, and finally latex-suite did as well. BTW, lh-brackets should be compatible with an installed version of latex-suite)

NB: for the ones that absolutely want to define the mappings themselves, look at the Map*Context() functions from lh-brackets. The first version recognized comments and string contexts to not expand the key. The last version (Map4TheseContext()) permits to specify how the key should be expanded for a list of possible contexts.
The idea is to test the context with synIDattr(synID(line('.'),col('.')-1,1),'name'), then to interpret possible special character sequences like <esc>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.