Search code examples
gitgit-diffless-unix

How do I pass options to less from git-diff?


I've got a fairly default setup for git on an OSX machine, but I'd like to add -j.5 to less, so that search matches happen in the middle of the screen.

I tried doing export LESS=-j.5, but that caused content like ESC[1mdiff --git a/app/images/bluecog-icon.png b/app/images/bluecog-icon.pngESC[m to appear, even though beforehand, echo $LESS gave an empty result. I looked up git help diff but it didn't have any mentions of "pager", or mentions of "less" that refer to the unix tool (as opposed to meaning the opposite of "greater").

Either modifying an environmental variable, or passing a parameter to git diff is acceptable. I know that I can just input -j.5 when I'm within git diff itself.


Solution

  • Git's setup is a bit peculiar:

    • The default pager is less (though this is a compile-time option).
    • You can configure a specific pager with core.pager. If you do this, you can add options here.
    • The less command itself reads the environment variable LESS first, then scans options.
    • If the environment variable LESS is set (to anything, including even the empty string), Git does not set it; but otherwise, Git sets it to FRX, even if the pager is not less.

    Hence, as noted in the git config documentation:

    ... If you want to selectively override Git's default setting for LESS, you can set core.pager to e.g. less -S. This will be passed to the shell by Git, which will translate the final command to LESS=FRX less -S. The environment does not set the S option but the command line does, instructing less to truncate long lines. Similarly, setting core.pager to less -+F will deactivate the F option specified by the environment from the command-line, deactivating the "quit if one screen" behavior of less. One can specifically activate some flags for particular commands: for example, setting pager.blame to less -S enables line truncation only for git blame.

    Hence, if you only want this for git diff, set pager.diff to less -j.5. If you want it for all Git commands, you can either set core.pager to less -j.5 or set the environment variable LESS to FRXj.5; both will have the same effect.