Move Cursor Right When Typing ')' and Character Under Cursor is ')'

巧了我就是萌 提交于 2021-02-11 14:20:01

问题


I'm trying to use a combination of vim settings in .vimrc and vim functions to make the cursor move to the right when I type ')' IF there is already a ')'. What I've tried so far is adding the following to my .vimrc file:

inoremap ) <Esc>:source PATH/TO/Function.vim<Enter>

Where Function.vim is something like

if getline('.')[col('.')] == ')'
    " move cursor two spaces right and re-enter insert mode
else
    " move cursor one space right, enter insert mode, type ')'
endif

What commands can I use to manipulate the cursor from a .vim script file? Should I be using a different method entirely? Thanks in advance!


回答1:


You could use this:

inoremap <expr> ) getline('.')[col('.')-1]==')' ? '<c-g>U<right>' : ')'

The <expr> tag tells vim to map ) to the result of the right-hand side expression. Here, if the symbol under the cursor is a (, it will be <right>, else it will print a ).




回答2:


I'm quite sure this is a duplicate.

It's all about cursor position. A minus 1 offset is required as cursor position starts at 1 while string indices start at 0. And also :imap-<expr> to make it simple as there is no cursor teleportation, and also i_CTRL-G_U to make the mapping reoable. In the end, this is what all bracketing plugins do, here is mine.

inoremap <silent><expr> ) getline('.')[col('.')-1] == ')' ? '<c-g>U<right>' : ')'

PS: you certainly don't want to source a file here. It would be quite overkill and in some unfortunate conditions extremely slow.



来源:https://stackoverflow.com/questions/62615872/move-cursor-right-when-typing-and-character-under-cursor-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!