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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With