-->

Vim smart insert semicolon

2019-03-12 05:19发布

问题:

Is there a Vim plugin that can handle smart semicolon insertion, like the one in Eclipse?

Example (pipe character is insertion cursor):

foobar(|)

I type a semicolon:

foobar();|

Similarly:

foobar("blah|")

I type a semicolon:

foobar("blah");|

If I want a semicolon at the original cursor position, I press backspace after the smart re-position:

foobar("hello|")
foobar("hello");|
foobar("hello;|")

回答1:

I use this mapping:

inoremap <leader>; <C-o>A;

It's not ; because I use semicolons often and in more than one context.

  • <C-o> is used to input a single normal mode command.
  • A; means "add a ; at the end of the line".


回答2:

I want to do the same thing, I works on it whole night, tons of code, but at last, I got a simple solution.

inoremap ;<cr> <end>;<cr>

and if I am in a brace, I want to add a semicolon or a dot at the end, like this

foo({
  |
})

I press ;;<cr> or ..<cr> to do this

inoremap ;<cr> <end>;<cr>
inoremap .<cr> <end>.
inoremap ;;<cr> <down><end>;<cr>
inoremap ..<cr> <down><end>.


回答3:

You should try Cosco.vim plugin.



回答4:

I use the following function and a mapping to insert a semicolon to the end of the line and to delete the remaning spaces:

imap <leader>. <C-R>=Semicolonfun()<CR>
fun! Semicolonfun() "{{{
  call setline(line('.'), substitute(getline('.'), '\s*$', ';', ''))
  return "\<End>"
endfunction "}}}

So if you have something like:

log.warning("you miss the |identifier")

Pressing . or ,. if you remap the leader, you get the following:

log.warning("you miss the identifier");|


回答5:

inoremap <expr> ;<cr> getline('.')[-1:] == ';' ? '\<Nop>' : '<End>;<CR>'

The code above will check if there is ; at the end of the line.

If ; not exists, then it will add ; otherwise do nothing.



回答6:

" ftplugin/c/c_snippet.vim
inoremap <expr> <buffer> ; getline('.')[col('.')-1:-1]=~')$' ? '<right>;' : ';'

This version shall not pose problems with for if your snippets engine expands it into

for (...|) {
   <+code+>
}<++>

If the open bracket is on a newline, it will mess things up.

You could easily change the regex to '"\=)\+$' to answer your initial question.

inoremap <expr> <buffer> ; getline('.')[col('.')-1:-1]=~'"\=)\+$' ? '<end>;' : ';'

However, I don't think it's a good idea. In that case, the mapping for <bs>will be:

inoremap <expr> <buffer> <bs> getline('.')[:col('.')-2] =~ '.*")\+;$' ? '<bs><c-o>F";' : '<bs>'


标签: vim semicolon