colorize.plugin.zsh 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. if ! (( $+commands[pygmentize] )); then
  6. echo "package 'Pygments' is not installed!"
  7. return 1
  8. fi
  9. # If the environment varianle ZSH_COLORIZE_STYLE
  10. # is set, use that theme instead. Otherwise,
  11. # use the default.
  12. if [ -z $ZSH_COLORIZE_STYLE ]; then
  13. ZSH_COLORIZE_STYLE="default"
  14. fi
  15. # pygmentize stdin if no arguments passed
  16. if [ $# -eq 0 ]; then
  17. pygmentize -O style="$ZSH_COLORIZE_STYLE" -g
  18. return $?
  19. fi
  20. # guess lexer from file extension, or
  21. # guess it from file contents if unsuccessful
  22. local FNAME lexer
  23. for FNAME in "$@"
  24. do
  25. lexer=$(pygmentize -N "$FNAME")
  26. if [[ $lexer != text ]]; then
  27. pygmentize -O style="$ZSH_COLORIZE_STYLE" -l "$lexer" "$FNAME"
  28. else
  29. pygmentize -O style="$ZSH_COLORIZE_STYLE" -g "$FNAME"
  30. fi
  31. done
  32. }
  33. colorize_via_pygmentize_less() (
  34. # this function is a subshell so tmp_files can be shared to cleanup function
  35. declare -a tmp_files
  36. cleanup () {
  37. [[ ${#tmp_files} -gt 0 ]] && rm -f "${tmp_files[@]}"
  38. exit
  39. }
  40. trap 'cleanup' EXIT HUP TERM INT
  41. while (( $# != 0 )); do #TODO: filter out less opts
  42. tmp_file="$(mktemp -t "tmp.colorize.XXXX.$(sed 's/\//./g' <<< "$1")")"
  43. tmp_files+=("$tmp_file")
  44. colorize_via_pygmentize "$1" > "$tmp_file"
  45. shift 1
  46. done
  47. less -f "${tmp_files[@]}"
  48. )