Some notes on computer stuff

Configuring keys in less

October 11, 2012
[less] [terminal] [keys]

Since I'm using Vim and terminal constantly the only right way of going through command-line history in my world is using Control-P (<c-p> or ^P; to go backwards) and Control-N (<c-n> or ^N to go forwards).

And I missed this key bindings while using less to view man pages or long output of commands (e.g. git log). As always the first thing to do in such case should be reading of man page of a tool. Here is what I've found there:

  1. Less has support of key bindings configuration file of binary format (~/.less by default)
  2. There is a special tool called lesskey, which generates ~/.less binary file from a text file (~/.lesskey by default)

If you want to know more about this stuff, just read man less and man lesskey. Below is an example of adding support of several shortcuts for less.

First of all one needs to create a file named ~/.lesskey (read man lesskey if you want to name it in another way) and put these lines in it:

\e abort
^P up
^N down

You should already know that less has some kind of modality and thus it has several modes. No surprise that one needs to specify target mode for key bingings, which is #line-edit in the example above. There should be no spaces after sharp symbol. Bellow that line tree more lines follow. The first one makes less leave line-edit mode if user presses Escape key (<esc>). The second one makes Control-P work as Arrow Up works by default, while the third line binds Control-N to Arrow Down action.

Here is where we need to use lesskey tool. Just run it and it will generate a ~/.less file of binary format from the contents of ~/.lesskey. Now try running less for something, type / (forward slash) to enter line-edit mode and press Control-N and Control-P to check if it works, well it should work now.