Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have the following handy abbreviation in VIM:

iab for for<Space>(<Space>{{<Esc>kA<Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>

This nicely replaces for with the following text:

for (  ) {

}

However, I would like this abbreviation to work only in code, not in comments or in single- or double- quoted strings. How might this constraint be accomplished? Thanks!

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

First of all, your abbreviation doesn't insert what you say it does in your example; it behaves rather oddly for me even though I do have Eatchar() defined. My best guess is that it's triggering other abbreviations/mappings, and I will assume I should leave it alone.

My solution is to tie into the syntax engine, which means it will only work if you have syntax highlighting enabled. Try this:

iab <buffer> <expr> for <SID>CodeInsert("for", "for<Space>(<Space>{{<Esc>kA<Left><Left><Left><Left><C-R>=Eatchar('\s')<CR>")

function! s:CodeInsert(abbr,str)
    let syn = synIDattr(synIDtrans(synID(line('.'), col('.') - 1, 1)), 'name')
    if syn ==? 'comment' || syn ==? 'constant'
        return a:abbr
    else
        return a:str
    endif
endfunction
share|improve this answer
    
Thank you! I will play around with this solution and see what I can get working. –  dotancohen Oct 14 '12 at 22:51
    
You are right, I have other imappings as well, such as {{. In any case, your solution works perfect. Thank you! –  dotancohen Oct 15 '12 at 16:06
    
I was able to read about synIDattr and the other bits in the help, but when reading the help page h ==? it looks like I was getting the help text for ==. What is the ==? operator? Thanks. –  dotancohen Oct 15 '12 at 16:10
    
See :help expr-==? (or :help expr4) –  Heptite Oct 15 '12 at 18:07
    
Thanks. I've got some reading to do! –  dotancohen Oct 15 '12 at 18:23
show 3 more comments

You could use autocmd to prevent the abbreviation from working in Python files:

if has("autocmd")
  autocmd FileType php,c,java iab for for<Space>...<CR>
endif

I don't think it's possible to prevent it from working just inside particular text section like double or single quoted strings.

share|improve this answer
    
Thanks. The Python bit is very secondary, I've removed it from the question as I see that it is distracting from the real issue. In any case I've upvoted. Thanks. –  dotancohen Oct 14 '12 at 15:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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