12

If one searches in less by typing /search term and jumping to search results with n and N the view of the text jumps so that the occurrence of the search term is at top of the terminal. Displaying the half of text before and after the occurrence is much more useful and I'd like to know how to achieve it.

phk
  • 5,953
  • 7
  • 42
  • 71

1 Answers1

13

Use the -j option. For instance, if you use less -j3, the match will be displayed on the 3rd line. To do what you want, i.e. display the match at the center of the terminal:

less -j$((LINES/2))

or since less 397, one can specify a percentage within the screen:

less -j.5

Note: To do that permanently, i.e. for all invocations, you can put this -jn option in the LESS environment variable.

This also affects commands to go to line N, e.g. line N will appear on the 3rd line of the terminal with -j3. A minor drawback is that one can get spurious empty lines before the beginning of the file, e.g. with the key <. EDIT: I've written a patch to avoid this problem; see this message of my bug report for additional details. This patch allows one to avoid these empty lines only when going to the special line 0, which is the default for keys g and <. Thus it should be sufficient in practice.

vinc17
  • 12,174
  • Great! Works in man with LESS variable, e.g. LESS="-j3" man <program>, BTW. – Kalle Richter Oct 01 '14 at 11:25
  • @vinc17 By the way, I tried to do it permanently by putting -j.5 in my .lessrc file but it doesn't work that way. OTOH, it work by setting the LESS=-j.5. Why it doesn't work in the .lessrc method? – Utku Nov 19 '15 at 15:00
  • @Utku The less(1) man page does not mention a .lessrc file. – vinc17 Nov 27 '15 at 02:19
  • This option (as any other) can also be set in a running session by typing -j and a number (Less will request the number with prompt Target line:). – ruvim Sep 01 '17 at 12:46
  • Is there any way to solve the "spurious empty lines before the beginning of the file" problem? – AleXoundOS Nov 15 '20 at 18:42
  • 1
    @AleXoundOS I've just written a patch to avoid this spurious empty lines problem. It is available in my Debian bug report at https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=763631#10 – vinc17 Nov 17 '20 at 01:17
  • 1
    @AleXoundOS I've written a new patch, which avoids the issue with long lines. It works only when going to the special line 0, which is the default for keys g and <, so that it should be sufficient in practice. See my edited answer above. I've also created a pull request upstream: https://github.com/gwsw/less/pull/94 (and https://github.com/gwsw/less/issues/93 is the associated bug). – vinc17 Nov 17 '20 at 23:43