I'd like less to quit immediately if the entire file can be displayed within one screen. For this, I'd use the -F option:

-F or --quit-if-one-screen

    Causes less to automatically exit if the entire file can be
    displayed on the first screen.

The gotcha: when the file is longer than one screen long, I'd like to be able to use the alternate screen. As such, I don't want to pass -X:

-X or --no-init

    Disables sending the termcap initialization and deinitialization
    strings to the terminal. This is sometimes desirable if the
    deinitialization string does something unnecessary, like
    clearing the screen.

Note that if you set -F without -X, doing less some-short-file produces no visible output, because it appears only in the alternate screen, which goes away as soon as less exits, which is immediately.

Why I want this: I have tmux bindings set up such that I can scroll with the mousewheel when in alternate screen mode (ie. in less and in things which use it as a pager: git, ack, ag, man etc).

Wondering if I have to replace less with some wrapper script or function which checks the screen height and conditionally decides whether to invoke less -FX or less, or whether such a thing would be too tricky to implement when reading from a pipe (in which case it might have to do something simpler, like default to less).


The question appears to contain all of the relevant information. A simple wrapper script would look something like this:

if [ -t 0 && $# = 1 ]
    want=$(wc -l "$1" |sed -e 's/[[:space:]].*//')
    have=$(stty -a |grep -E " rows [[:digit:]]" | sed -e 's/^.* rows //' -e 's/;.*//')
    if [ $want -le $have ]
        less -FX "$1"
        less "$1"
    less "$1"

which checks if the standard input is a terminal, and if so, counts the number of lines in the file, comparing it to the number on the screen. Handling options would complicate things of course.

Someone might post a more concise script; this works in a quick test here.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.