Less Command – Prevent Matching Line from Being Top Line

lesspagerscrollingsearch

Very often happens that I do

$ man someprogram

to inspect the manual for some program. Often I also want to search for something in there, and I simply hit / and write whatever I want to search for.

Unfortunately, whatever the match is, it is brought to the top line of the screen, therefore most of the times I need to scroll up manually a few times to actually see some context for that matching line.

How can I set less such that it leaves some offset lines between the top line and the matching line?

Best Answer

You want the -j option. See under "OPTIONS" in the man page:

-jn or --jump-target=n

Specifies a line on the screen where the "target" line is to be positioned. The target line is the line specified by any command to search for a pattern, jump to a line number, jump to a file percentage or jump to a tag.

The screen line may be specified by a number: the top line on the screen is 1, the next is 2, and so on. The number may be negative to specify a line relative to the bottom of the screen: the bottom line on the screen is -1, the second to the bottom is -2, and so on.

Alternately, the screen line may be specified as a fraction of the height of the screen, starting with a decimal point: .5 is in the middle of the screen, .3 is three tenths down from the first line, and so on. If the line is specified as a fraction, the actual line number is recalculated if the terminal window is resized, so that the target line remains at the specified fraction of the screen height.

If any form of the -j option is used, repeated forward searches (invoked with "n" or "N") begin at the line immediately after the target line, and repeated backward searches begin at the target line, unless changed by -a or -A. For example, if "-j4" is used, the target line is the fourth line on the screen, so forward searches begin at the fifth line on the screen. However nonrepeated searches (invoked with "/" or "?") always begin at the start or end of the current screen respectively.

Note: you can configure the option using lesskey, use an environment variable like LESS=-j5 man someprogram or just type -j5 while in less.

Related Question