colorize.plugin.zsh 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # easier alias to use the plugin
  2. alias ccat='colorize_via_pygmentize'
  3. alias cless='colorize_via_pygmentize_less'
  4. colorize_via_pygmentize() {
  5. local available_tools=("chroma" "pygmentize")
  6. if [ -z $ZSH_COLORIZE_TOOL ]; then
  7. if (( $+commands[pygmentize] )); then
  8. ZSH_COLORIZE_TOOL="pygmentize"
  9. elif (( $+commands[chroma] )); then
  10. ZSH_COLORIZE_TOOL="chroma"
  11. else
  12. echo "Neither 'pygments' nor 'chroma' is installed!"
  13. return 1
  14. fi
  15. fi
  16. if [[ ${available_tools[(Ie)$ZSH_COLORIZE_TOOL]} -eq 0 ]]; then
  17. echo "ZSH_COLORIZE_TOOL '$ZSH_COLORIZE_TOOL' not recognized. Available options are 'pygmentize' and 'chroma'."
  18. return 1
  19. elif (( $+commands["$ZSH_COLORIZE_TOOL"] )); then
  20. echo "Package '$ZSH_COLORIZE_TOOL' is not installed!"
  21. return 1
  22. fi
  23. # If the environment variable ZSH_COLORIZE_STYLE
  24. # is set, use that theme instead. Otherwise,
  25. # use the default.
  26. if [ -z $ZSH_COLORIZE_STYLE ]; then
  27. if [[ $ZSH_COLORIZE_TOOL == "pygmentize" ]]; then
  28. ZSH_COLORIZE_STYLE="default"
  29. else
  30. # Choosing 'emacs' to match pygmentize's default as per:
  31. # https://github.com/pygments/pygments/blob/master/pygments/styles/default.py#L19
  32. ZSH_COLORIZE_STYLE="emacs"
  33. fi
  34. fi
  35. # pygmentize stdin if no arguments passed
  36. if [ $# -eq 0 ]; then
  37. if [[ $ZSH_COLORIZE_TOOL == "pygmentize" ]]; then
  38. pygmentize -O style="$ZSH_COLORIZE_STYLE" -g
  39. else
  40. chroma --style="$ZSH_COLORIZE_STYLE"
  41. fi
  42. return $?
  43. fi
  44. # guess lexer from file extension, or
  45. # guess it from file contents if unsuccessful
  46. local FNAME lexer
  47. for FNAME in "$@"
  48. do
  49. if [[ $ZSH_COLORIZE_TOOL == "pygmentize" ]]; then
  50. lexer=$(pygmentize -N "$FNAME")
  51. if [[ $lexer != text ]]; then
  52. pygmentize -O style="$ZSH_COLORIZE_STYLE" -l "$lexer" "$FNAME"
  53. else
  54. pygmentize -O style="$ZSH_COLORIZE_STYLE" -g "$FNAME"
  55. fi
  56. else
  57. chroma --style="$ZSH_COLORIZE_STYLE" "$FNAME"
  58. fi
  59. done
  60. }
  61. colorize_via_pygmentize_less() (
  62. # this function is a subshell so tmp_files can be shared to cleanup function
  63. declare -a tmp_files
  64. cleanup () {
  65. [[ ${#tmp_files} -gt 0 ]] && rm -f "${tmp_files[@]}"
  66. exit
  67. }
  68. trap 'cleanup' EXIT HUP TERM INT
  69. while (( $# != 0 )); do #TODO: filter out less opts
  70. tmp_file="$(mktemp -t "tmp.colorize.XXXX.$(sed 's/\//./g' <<< "$1")")"
  71. tmp_files+=("$tmp_file")
  72. colorize_via_pygmentize "$1" > "$tmp_file"
  73. shift 1
  74. done
  75. less -f "${tmp_files[@]}"
  76. )