/* The MIT License (MIT) Copyright (c) 2026 pacman64 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* To compile a smaller-sized command-line app, you can use the `go` command as follows: go build -ldflags "-s -w" -trimpath coma.go */ package main import ( "bufio" "io" "os" "regexp" ) const info = ` coma [options...] [regexes/style pairs...] COlor MAtches ANSI-styles matching regular expressions along lines read from the standard input. The regular-expression mode used is "re2", which is a superset of the commonly-used "extended-mode". Regexes always avoid matching any ANSI-style sequences, to avoid messing those up. Also, multiple matches in a line never overlap: at each step along a line, the earliest-starting match among the regexes always wins, as the order regexes are given among the arguments never matters. The options are, available both in single and double-dash versions -h show this help message -help show this help message -i match regexes case-insensitively -ins match regexes case-insensitively ` var styleAliases = map[string]string{ `b`: `blue`, `g`: `green`, `m`: `magenta`, `o`: `orange`, `p`: `purple`, `r`: `red`, `u`: `underline`, `bb`: `blueback`, `bg`: `greenback`, `bm`: `magentaback`, `bo`: `orangeback`, `bp`: `purpleback`, `br`: `redback`, `gb`: `greenback`, `mb`: `magentaback`, `ob`: `orangeback`, `pb`: `purpleback`, `rb`: `redback`, `hi`: `inverse`, `inv`: `inverse`, `mag`: `magenta`, `du`: `doubleunderline`, `flip`: `inverse`, `swap`: `inverse`, `reset`: `plain`, `highlight`: `inverse`, `hilite`: `inverse`, `invert`: `inverse`, `inverted`: `inverse`, `swapped`: `inverse`, `dunderline`: `doubleunderline`, `dunderlined`: `doubleunderline`, `strikethrough`: `strike`, `strikethru`: `strike`, `struck`: `strike`, `underlined`: `underline`, `bblue`: `blueback`, `bgray`: `grayback`, `bgreen`: `greenback`, `bmagenta`: `magentaback`, `borange`: `orangeback`, `bpurple`: `purpleback`, `bred`: `redback`, `bgblue`: `blueback`, `bggray`: `grayback`, `bggreen`: `greenback`, `bgmag`: `magentaback`, `bgmagenta`: `magentaback`, `bgorange`: `orangeback`, `bgpurple`: `purpleback`, `bgred`: `redback`, `bluebg`: `blueback`, `graybg`: `grayback`, `greenbg`: `greenback`, `magbg`: `magentaback`, `magentabg`: `magentaback`, `orangebg`: `orangeback`, `purplebg`: `purpleback`, `redbg`: `redback`, `backblue`: `blueback`, `backgray`: `grayback`, `backgreen`: `greenback`, `backmag`: `magentaback`, `backmagenta`: `magentaback`, `backorange`: `orangeback`, `backpurple`: `purpleback`, `backred`: `redback`, } var styles = map[string]string{ `blue`: "\x1b[38;2;0;95;215m", `bold`: "\x1b[1m", `doubleunderline`: "\x1b[21m", `gray`: "\x1b[38;2;168;168;168m", `green`: "\x1b[38;2;0;135;95m", `inverse`: "\x1b[7m", `magenta`: "\x1b[38;2;215;0;255m", `orange`: "\x1b[38;2;215;95;0m", `plain`: "\x1b[0m", `purple`: "\x1b[38;2;135;95;255m", `red`: "\x1b[38;2;204;0;0m", `strike`: "\x1b[9m", `underline`: "\x1b[4m", `blueback`: "\x1b[48;2;0;95;215m\x1b[38;2;238;238;238m", `grayback`: "\x1b[48;2;168;168;168m\x1b[38;2;238;238;238m", `greenback`: "\x1b[48;2;0;135;95m\x1b[38;2;238;238;238m", `magentaback`: "\x1b[48;2;215;0;255m\x1b[38;2;238;238;238m", `orangeback`: "\x1b[48;2;215;95;0m\x1b[38;2;238;238;238m", `purpleback`: "\x1b[48;2;135;95;255m\x1b[38;2;238;238;238m", `redback`: "\x1b[48;2;204;0;0m\x1b[38;2;238;238;238m", } type patternStylePair struct { expr *regexp.Regexp style string } func main() { buffered := false insensitive := false args := os.Args[1:] out: for len(args) > 0 { switch args[0] { case `-b`, `--b`, `-buffered`, `--buffered`: buffered = true args = args[1:] continue case `-h`, `--h`, `-help`, `--help`: os.Stdout.WriteString(info[1:]) return case `-i`, `--i`, `-ins`, `--ins`: insensitive = true args = args[1:] continue default: break out } } if len(args) > 0 && args[0] == `--` { args = args[1:] } if len(args)%2 != 0 { const msg = "you forgot the style-name for/after the last regex\n" os.Stderr.WriteString(msg) os.Exit(1) } nerr := 0 pairs := make([]patternStylePair, 0, len(args)/2) for len(args) >= 2 { src := args[0] sname := args[1] var err error var exp *regexp.Regexp if insensitive { exp, err = regexp.Compile(`(?i)` + src) } else { exp, err = regexp.Compile(src) } if err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") nerr++ } if alias, ok := styleAliases[sname]; ok { sname = alias } style, ok := styles[sname] if !ok { os.Stderr.WriteString("no style named `") os.Stderr.WriteString(args[1]) os.Stderr.WriteString("`\n") nerr++ } pairs = append(pairs, patternStylePair{expr: exp, style: style}) args = args[2:] } if nerr > 0 { os.Exit(1) } liveLines := !buffered if !buffered { if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil { liveLines = false } } sc := bufio.NewScanner(os.Stdin) sc.Buffer(nil, 8*1024*1024*1024) bw := bufio.NewWriter(os.Stdout) defer bw.Flush() for i := 0; sc.Scan(); i++ { s := sc.Bytes() if i == 0 && len(s) > 2 && s[0] == 0xef && s[1] == 0xbb && s[2] == 0xbf { s = s[3:] } handleLine(bw, s, pairs) if err := bw.WriteByte('\n'); err != nil { return } if !liveLines { continue } if err := bw.Flush(); err != nil { return } } } // indexEscapeSequence finds the first ANSI-style escape-sequence, which is // the multi-byte sequences starting with ESC[; the result is a pair of slice // indices which can be independently negative when either the start/end of // a sequence isn't found; given their fairly-common use, even the hyperlink // ESC]8 sequences are supported func indexEscapeSequence(s []byte) (int, int) { var prev byte for i, b := range s { if prev == '\x1b' && b == '[' { j := indexLetter(s[i+1:]) if j < 0 { return i, -1 } return i - 1, i + 1 + j + 1 } if prev == '\x1b' && b == ']' && i+1 < len(s) && s[i+1] == '8' { j := indexPair(s[i+1:], '\x1b', '\\') if j < 0 { return i, -1 } return i - 1, i + 1 + j + 2 } prev = b } return -1, -1 } func indexLetter(s []byte) int { for i, b := range s { upper := b &^ 32 if 'A' <= upper && upper <= 'Z' { return i } } return -1 } func indexPair(s []byte, x byte, y byte) int { var prev byte for i, b := range s { if prev == x && b == y { return i } prev = b } return -1 } func handleLine(w *bufio.Writer, s []byte, with []patternStylePair) { for len(s) > 0 { i, j := indexEscapeSequence(s) if i < 0 { handleLineChunk(w, s, with) return } handleLineChunk(w, s[:i], with) w.Write(s[i:j]) if j < 0 { break } s = s[j:] } } func handleLineChunk(w *bufio.Writer, s []byte, with []patternStylePair) { start := -1 end := -1 which := -1 for len(s) > 0 { start = -1 for i, pair := range with { span := pair.expr.FindIndex(s) // also ignore empty regex matches to avoid infinite outer loops, // as skipping empty slices isn't advancing at all, leaving the // string stuck to being empty-matched forever by the same regex if span == nil || span[0] == span[1] { continue } if span[0] < start || start < 0 { start = span[0] end = span[1] which = i } } if start < 0 { w.Write(s) return } w.Write(s[:start]) w.WriteString(with[which].style) w.Write(s[start:end]) w.WriteString("\x1b[0m") s = s[end:] } }