Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

How to autocomplete per conditions in vim?

When coding in vim, I add autocomplete for "{(' in vimrc as below:

inoremap " ""<ESC>i
inoremap ' ''<ESC>i
inoremap { {<Cr>}<Esc>O
inoremap ( ()<ESC>i

But I find it's quite annoying to add an additional semicolon ; manually in the end of a function call or expression.
Example 1: print("hello world"); => autocomplete should be ); when input (
Example 2: if (true) or while (true) => autocomplete should be only ) when input (

When inputting a single (, how to autocomplete correctly for both example 1 and example 2? My focus here is whether there are some easy ways to add if/else for key mapping.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It could be a pretty challenging task to handle all the options properly. But if all you ask is just a simple and very incomplete example code then, perhaps, this small snippet could be of some help:

inoremap <expr>( Paren()

function! Paren() abort
    return printf("()%s<Left>",
         search('v(if|while)s*%#', 'bn', line('.')) ? "" : ";<Left>")
endfunction

The idea is to match the current line (just before the cursor) against regex. Depending on the result, we build an expression to be inserted.

See :h search(), :h :map-expression etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...