16

I have this in my .zshrc file

export MANLESS=""
export LESS="--RAW-CONTROL-CHARS"
export LESS_TERMCAP_mb=$(tput bold; tput setaf 5)
export LESS_TERMCAP_md=$(tput bold; tput setaf 1)
export LESS_TERMCAP_so=$(tput setaf 1; tput setab 3)
export LESS_TERMCAP_se=$(tput rmso; tput sgr0)
export LESS_TERMCAP_us=$(tput setaf 3)
export LESS_TERMCAP_ue=$(tput sgr0)

When I use man as: man zshexpn, I have nicely colored sections:

enter image description here

When I use man as: man zshexpn | less '+/PROCESS SUBSTITUTION', on same part of the manual page, it is no longer colored:

enter image description here

How can I get colored output in second case, same as first case?

2 Answers 2

17

I’m assuming you’re using man on a mainstream Linux distribution. man there (and on other systems) defaults to removing formatting if its output isn’t a terminal; since you’re manually piping to less, that’s what’s happening here.

You can override this by setting MAN_KEEP_FORMATTING to a non-empty value:

MAN_KEEP_FORMATTING=1 man zshexpn | less '+/PROCESS SUBSTITUTION'

If you want this behaviour to be the default, export MAN_KEEP_FORMATTING along with your other settings; bear in mind that this will affect all man invocations, which will have side-effects when the output doesn’t end up being processed by a terminal (e.g. if you want to grep the output).

2
  • I have discovered a problem with exporting MAN_KEEP_FORMATTING=1. When I do man zshexpn | grep -n 'FILENAME GENERATION', grep finds only one match, whereas without the option grep finds 2 matches. Aug 15 at 12:20
  • @400theCat Yeah, that's kinda expected and the main reason man (and many other programs) disable generating terminal escape sequences when not writing to a terminal. You would have to design your regex to silently skip any terminal escape codes (which would make it really complex) or pipe through another intermediate step to strip out all escape sequences. It's probably much easier to just define a shell function for the man something | less combination which will internally set MAN_KEEP_FORMATTING.
    – TooTea
    Aug 16 at 9:16
10

Instead of piping through less with extra options, pass those extra options in the LESS variable.

LESS="$LESS +/PROCESS SUBSTITUTION" man zshexpn

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.