Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - Command Line - previous and next command key mapping

When opening the command line and pressing the up arrow or down arrow keys, it shows the commands there were typed the last time. Is there a way to map this behaviour? For example when I press ctrl p, I want vim to show me my previous command (make vim act as if I pressed the up arrow). The same thing for ctrl n for the next command.

How can I make this happen?

like image 299
DasOhmoff San Avatar asked Jan 25 '23 07:01

DasOhmoff San


1 Answers

The CTRL-P and CTRL-N keystrokes already do what you want, they search your command history. See :help c_CTRL-P, which explains how it will "recall older command-line from history."

The way CTRL-P and CTRL-N work differs slightly from the up and down arrow, in that the arrows will only go through the items in history that start with the characters you typed. So :e, space, up arrow will go to the last command you used to open a file for editing. See :help c_<Up> for details.

You can remap them so that they do the same as their counterpart, by using the cnoremap command, which creates mappings for keystrokes typed while in the Vim command-line.

For example, to make CTRL-P and CTRL-N behave the same as the arrows (complete respecting the prefix), you can use the following commands to create a (somewhat naive) mapping:

cnoremap <C-P> <Up>
cnoremap <C-N> <Down>

The shortcoming of this approach is that CTRL-P and CTRL-N behave differently on a wildmenu, so a more complete mapping would be:

cnoremap <expr> <C-P> wildmenumode() ? "\<C-P>" : "\<Up>"
cnoremap <expr> <C-N> wildmenumode() ? "\<C-N>" : "\<Down>"

That will preserve the original behavior of CTRL-P and CTRL-N in the wildmenu.

like image 140
filbranden Avatar answered Jan 28 '23 04:01

filbranden