/* 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 hima.go */ package main import ( "bufio" "io" "os" "regexp" ) const info = ` hima [options...] [regexes...] HIlight 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, -help show this help message -f, -filter filter out (ignore) lines with no matches -i, -ins match regexes case-insensitively ` const highlightStyle = "\x1b[7m" func main() { filter := false 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:] case `-f`, `--f`, `-filter`, `--filter`: filter = true args = args[1:] case `-h`, `--h`, `-help`, `--help`: os.Stdout.WriteString(info[1:]) return case `-i`, `--i`, `-ins`, `--ins`: insensitive = true args = args[1:] default: break out } } if len(args) > 0 && args[0] == `--` { args = args[1:] } exprs := make([]*regexp.Regexp, 0, len(args)) for _, s := range args { var err error var exp *regexp.Regexp if insensitive { exp, err = regexp.Compile(`(?i)` + s) } else { exp, err = regexp.Compile(s) } if err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") continue } exprs = append(exprs, exp) } // quit right away when given invalid regexes if len(exprs) < len(args) { os.Exit(1) } liveLines := !buffered if !buffered { if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil { liveLines = false } } if err := run(os.Stdout, os.Stdin, exprs, filter, liveLines); err != nil { os.Stderr.WriteString(err.Error()) os.Stderr.WriteString("\n") os.Exit(1) } } func run(w io.Writer, r io.Reader, exprs []*regexp.Regexp, filter, live bool) error { sc := bufio.NewScanner(r) sc.Buffer(nil, 8*1024*1024*1024) bw := bufio.NewWriter(w) 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:] } if filter && !matches(s, exprs) { continue } for len(s) > 0 { i, j := indexEscapeSequence(s) if i < 0 { handleChunk(bw, s, exprs) break } if j < 0 { j = len(s) } handleChunk(bw, s[:i], exprs) bw.Write(s[i:j]) s = s[j:] } if err := bw.WriteByte('\n'); err != nil { return nil } if !live { continue } if err := bw.Flush(); err != nil { return nil } } return sc.Err() } // matches finds out if any regex matches any substring around ANSI-sequences func matches(s []byte, exprs []*regexp.Regexp) bool { for len(s) > 0 { i, j := indexEscapeSequence(s) if i < 0 { for _, e := range exprs { if e.Match(s) { return true } } break } if j < 0 { j = len(s) } for _, e := range exprs { if e.Match(s[:i]) { return true } } s = s[j:] } return false } // 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 } // note: looking at the results of restoring ANSI-styles after style-resets // doesn't seem to be worth it, as a previous version used to do // handleChunk handles line-slices around any detected ANSI-style sequences, // or even whole lines, when no ANSI-styles are found in them func handleChunk(w *bufio.Writer, s []byte, with []*regexp.Regexp) { start := -1 end := -1 for len(s) > 0 { start = -1 for _, e := range with { span := e.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] } } if start < 0 { w.Write(s) return } w.Write(s[:start]) w.WriteString(highlightStyle) w.Write(s[start:end]) w.WriteString("\x1b[0m") s = s[end:] } }