automan.bash 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/bin/bash
  2. #------------------------------------------------------------------------------
  3. # Alternative to the 'man' command, meant to automatically reflow the manual
  4. # pages on terminal resize.
  5. #
  6. # TODO:
  7. # - Options should be implemented via an env var to avoid slowing the code
  8. # - Implement caching
  9. # Caching should store previously rendered output for specific terminal
  10. # widths. This would allow to skip some recompilations.
  11. # - Check if less has the --save-marks option
  12. # - Restore previous position in manual
  13. # - Print menu for man pages when no arguments are passed?
  14. # - Flag to exit on file not found
  15. # - Flag to allow for LESSOPEN
  16. #-----------------------------------------------------------------------------
  17. usage() {
  18. cat <<-USAGE
  19. Usage: automan [PAGES]
  20. Wrapper for man that automatically reflows text on terminal resize.
  21. USAGE
  22. return $1
  23. }
  24. declare -r base_dir='/tmp/autoless'
  25. declare -a pages_arr
  26. declare -a less_args=(-L)
  27. [[ $1 == '--restore' ]] && less_args+=(+\'\') && shift
  28. mkdir $base_dir 2>/dev/null
  29. # WARNING: be careful when moving this line as COLUMNS is only set after an
  30. # external command is called
  31. columns=$COLUMNS
  32. # Cleaunp
  33. trap "rm -rf $base_dir" EXIT
  34. # Treat arguments as potential pages
  35. for page in "$@" ; do
  36. # Find the path to the page and format its name
  37. page=$(man -w $page)
  38. (($? != 0)) && continue # Skip missing pages
  39. page_base=$(basename $page)
  40. page_path=$base_dir/${page_base/bz2/txt}
  41. pages_arr+=($page_path)
  42. # Prepare man pages to be output
  43. # The '-rLL' and '-rLT' make the output fit to terminal window
  44. bzcat $page |\
  45. groff -spte -mandoc -Tutf8 -rLL=$((COLUMNS-1))n -rLT=$((COLUMNS-1))n \
  46. >${page_path} 2>/dev/null
  47. done
  48. # Pass the formated pages path to a less job
  49. less ${less_args[@]} "${pages_arr[@]}" &
  50. # Sends SIGTERM to 'less' and restarts this script to force a redraw
  51. trap '
  52. (:;:) # pseudo-command used to force bash to set COLUMNS
  53. if (($columns != $COLUMNS)) ; then
  54. kill $!
  55. exec $(basename $0) --restore $@
  56. fi
  57. ' WINCH
  58. # Alternative to 'wait' (which was causing weird issues).
  59. # Keep running while the 'less' process is alive.
  60. while ps -o pid= $! >/dev/null ; do : ; done