colorize.plugin.zsh 1.3 KB

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