Skip to content

Instantly share code, notes, and snippets.

@alphapapa
Last active June 21, 2021 16:03
Show Gist options
  • Save alphapapa/3cba3ff196147ad42bac to your computer and use it in GitHub Desktop.
Save alphapapa/3cba3ff196147ad42bac to your computer and use it in GitHub Desktop.
Mangle man pages to show just the parts you need (suitable for aliasing to "man")
#!/bin/bash
less_command='| less $less_no_init -aiF -Ps"Manual page\: $man_page (?ltline %lt?L/%L.:byte %bB?s/%s..? (END):?pB %pB\%..)"'
# Get section
if [[ $1 =~ [0-9]+ ]]
then
section=$1
shift
fi
# Find the longest set of args that gets a man page
man_page=("$@")
while ! command man -w $(echo "${man_page[@]}" | tr " " "-") &>/dev/null
do
patterns+=( ${man_page[-1]} )
unset man_page[-1]
done
# For some reason, using an array substitution in the prompt string in
# less_command isn't working, so work around that by turning it into a
# plain string
man_page="${man_page[@]}"
# Build grep command
if [[ ${patterns[@]} ]]
then
grep_command="| grep -i -C4 --color=always -- ${patterns[@]}"
fi
command="command man $section $man_page $grep_command"
# Check screen and output sizes
tty_lines=$(tput lines)
output_lines=$(eval "$command" | wc -l)
# If output < screen size, use less with -X
[[ $output_lines -lt $tty_lines ]] && less_no_init="-X"
# Display the page
eval "$command $less_command"
#!/bin/bash
# Get section
if [[ $1 =~ [0-9]+ ]]
then
section=$1
shift
fi
# Find the longest set of args that gets a man page
args=("$@")
while ! command man -w $(echo "${args[@]}" | tr " " "-") &>/dev/null
do
patterns+=( ${args[-1]} )
unset args[-1]
done
# Build grep command
if [[ ${patterns[@]} ]]
then
grepCommand="| grep -i -C4 --color=always -- ${patterns[@]} | less -RFX"
else
grepCommand=" | less -RFX"
fi
# Do it
eval "command man $section ${args[@]} $grepCommand"
@alphapapa
Copy link
Author

@derimagia

You should throw this in a proper repo so people can contribute back, I can see it being useful to others. I would have liked to pull request that stuff in.

I think I will do that, thanks.

Wow, that Bash version is old! :)

In terms of the feature, I just found out about a neat less argument "less -X" that pretty much does that. It's actually my default MANPAGER - it essentially makes it so it doesn't clear/reset the screen when you man. (Try mangle less -X ;))

Yep, that's what I was referring to. I made it so mangle only does that if the output fits on the screen, otherwise it uses a normal pager that resets the terminal. I just posted the version that does that, it's up at the top above the previous version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment