File: cbe.sh 1 #!/bin/sh 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2024 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 # cbe [options...] [files...] 27 # 28 # Color By (file) Extension makes all lines look different, using different 29 # ANSI-styles as it finds new trailing file-extensions. Since its list of 30 # styles is limited, these will start being reused, given enough unique 31 # extensions. 32 # 33 # Any ANSI-styles from the original input lines are ignored. 34 # 35 # The case-insensitive-comparison option is any of `-i`, `--i`, `-ins`, or 36 # `--ins`. The help option is `-h`, `--h`, `-help`, or `--help`. 37 38 39 # handle leading options 40 sensitive=1 41 case "$1" in 42 -h|--h|-help|--help) 43 awk '/^# +cbe/, /^$/ { gsub(/^# ?/, ""); print }' "$0" 44 exit 0 45 ;; 46 -i|--i|-ins|--ins) 47 sensitive=0 48 shift 49 ;; 50 esac 51 52 awk -v sensitive="${sensitive}" ' 53 BEGIN { 54 palette[n++] = "\x1b[38;5;26m" # blue 55 palette[n++] = "\x1b[38;5;166m" # orange 56 palette[n++] = "\x1b[38;5;99m" # purple 57 palette[n++] = "\x1b[38;5;38m" # cyan 58 palette[n++] = "\x1b[38;5;213m" # pink 59 palette[n++] = "\x1b[38;5;29m" # green 60 palette[n++] = "\x1b[31m" # red 61 palette[n++] = "\x1b[38;5;248m" # gray 62 palcount = length(palette) 63 n = 0 64 } 65 66 { 67 # ignore trailing carriage-returns, which may interfere with later regex 68 gsub(/\r$/, "") 69 # ignore notifications (code 9) and hyperlinks (code 8) 70 gsub(/\x1b\](8|9);[^\x07]*\x07/, "") 71 # ignore cursor-movers and style-changers 72 gsub(/\x1b\[([0-9]*[A-HJKST]|[0-9;]*m)/, "") 73 74 src = sensitive ? $0 : tolower($0) 75 match(src, /\.[A-Za-z][A-Za-z0-9_-]*$/) 76 ext = substr(src, RSTART, RLENGTH) 77 78 if (ext != "") { 79 style = ext2style[ext] 80 if (style == "") { 81 style = palette[n % palcount] 82 ext2style[ext] = style 83 n++ 84 } 85 printf "%s%s\x1b[0m\n", style, $0 86 } else { 87 print 88 } 89 }' "$@"