Tip #1386: Make Vim completion popup menu work just like in an IDE
tip karma |
Rating 85/27, Viewed by 1339
|
created: |
|
November 13, 2006 13:09 |
|
complexity: |
|
intermediate |
author: |
|
Matt Zyzik |
|
as of Vim: |
|
|
In most IDEs, you normally type some code, press ctrl-space for a completion popup menu, type some more characters to select the menu item you want, then hit enter to insert that completion into the code. With Vim's initial popup menu settings, the behavior of the popup menu is a little less pleasant (for some people).
The first step to "improve" the menu behavior is to execute this command:
:set completeopt=longest,menuone
The above command will change the 'completeopt' option so that Vim's popup menu doesn't select the first completion item, but rather just inserts the longest common text of all matches; and the menu will come up even if there's only one match. (The "longest" setting is responsible for the former effect and the "menuone" is responsible for the latter.)
The next enhancement is the following mapping:
:inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
The above mapping will change the behavior of the "<enter>" key when the popup menu is visible. In that case the "<enter>" key will simply select the highlighted menu item, just as the "ctrl-y" key does.
** These two mappings are probably the most rare, yet most valuable: **
:inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
:inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
In the above mappings, the first will make "ctrl-n" work the way it normally does; however, when the menu appears, the "<down>" key will be simulated. What this accomplishes is it keeps a menu item always highlighted... this way you can keep typing characters to narrow the matches, and the nearest match will be selected so that you can hit enter at any time to insert it. In the above mappings, the second one is a little more exotic: it simulates "ctrl-x, ctrl-o" to bring up the omni completion menu, then it simulates "ctrl-n, ctrl-p" to remove the "longest" common text, and finally it simulates "<down>" again to keep a match highlighted.
Let this tip be a reminder that the possibilities in Vim are endless.
<<Disable the "Hit any key to close this window" message in remote editing |
Standard editing shotcuts >>
Additional Notes
|