File: plain.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright (c) 2026 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the "Software"), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath plain.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bufio"
  36     "bytes"
  37     "errors"
  38     "io"
  39     "os"
  40 )
  41 
  42 const info = `
  43 plain [options...] [file...]
  44 
  45 
  46 Turn potentially ANSI-styled plain-text into actual plain-text.
  47 
  48 Input is assumed to be UTF-8, and all CRLF byte-pairs are turned into line
  49 feeds.
  50 
  51 All (optional) leading options start with either single or double-dash:
  52 
  53     -h, -help    show this help message
  54 `
  55 
  56 func main() {
  57     buffered := false
  58     args := os.Args[1:]
  59 
  60     if len(args) > 0 {
  61         switch args[0] {
  62         case `-b`, `--b`, `-buffered`, `--buffered`:
  63             buffered = true
  64             args = args[1:]
  65 
  66         case `-h`, `--h`, `-help`, `--help`:
  67             os.Stdout.WriteString(info[1:])
  68             return
  69         }
  70     }
  71 
  72     if len(args) > 0 && args[0] == `--` {
  73         args = args[1:]
  74     }
  75 
  76     liveLines := !buffered
  77     if !buffered {
  78         if _, err := os.Stdout.Seek(0, io.SeekCurrent); err == nil {
  79             liveLines = false
  80         }
  81     }
  82 
  83     if err := run(os.Stdout, args, liveLines); err != nil && err != io.EOF {
  84         os.Stderr.WriteString(err.Error())
  85         os.Stderr.WriteString("\n")
  86         os.Exit(1)
  87         return
  88     }
  89 }
  90 
  91 func run(w io.Writer, args []string, live bool) error {
  92     bw := bufio.NewWriter(w)
  93     defer bw.Flush()
  94 
  95     if len(args) == 0 {
  96         return plain(bw, os.Stdin, live)
  97     }
  98 
  99     for _, name := range args {
 100         if err := handleFile(bw, name, live); err != nil {
 101             return err
 102         }
 103     }
 104     return nil
 105 }
 106 
 107 func handleFile(w *bufio.Writer, name string, live bool) error {
 108     if name == `` || name == `-` {
 109         return plain(w, os.Stdin, live)
 110     }
 111 
 112     f, err := os.Open(name)
 113     if err != nil {
 114         return errors.New(`can't read from file named "` + name + `"`)
 115     }
 116     defer f.Close()
 117 
 118     return plain(w, f, live)
 119 }
 120 
 121 // indexEscapeSequence finds the first ANSI-style escape-sequence, which is
 122 // the multi-byte sequences starting with ESC[; the result is a pair of slice
 123 // indices which can be independently negative when either the start/end of
 124 // a sequence isn't found; given their fairly-common use, even the hyperlink
 125 // ESC]8 sequences are supported
 126 func indexEscapeSequence(s []byte) (int, int) {
 127     var prev byte
 128 
 129     for i, b := range s {
 130         if prev == '\x1b' && b == '[' {
 131             j := indexLetter(s[i+1:])
 132             if j < 0 {
 133                 return i, -1
 134             }
 135             return i - 1, i + 1 + j + 1
 136         }
 137 
 138         if prev == '\x1b' && b == ']' && i+1 < len(s) && s[i+1] == '8' {
 139             j := indexPair(s[i+1:], '\x1b', '\\')
 140             if j < 0 {
 141                 return i, -1
 142             }
 143             return i - 1, i + 1 + j + 2
 144         }
 145 
 146         prev = b
 147     }
 148 
 149     return -1, -1
 150 }
 151 
 152 func indexLetter(s []byte) int {
 153     for i, b := range s {
 154         upper := b &^ 32
 155         if 'A' <= upper && upper <= 'Z' {
 156             return i
 157         }
 158     }
 159 
 160     return -1
 161 }
 162 
 163 func indexPair(s []byte, x byte, y byte) int {
 164     var prev byte
 165 
 166     for i, b := range s {
 167         if prev == x && b == y && i > 0 {
 168             return i
 169         }
 170         prev = b
 171     }
 172 
 173     return -1
 174 }
 175 
 176 func plain(w *bufio.Writer, r io.Reader, live bool) error {
 177     const gb = 1024 * 1024 * 1024
 178     sc := bufio.NewScanner(r)
 179     sc.Buffer(nil, 8*gb)
 180 
 181     for i := 0; sc.Scan(); i++ {
 182         s := sc.Bytes()
 183         if i == 0 && bytes.HasPrefix(s, []byte{0xef, 0xbb, 0xbf}) {
 184             s = s[3:]
 185         }
 186 
 187         for line := s; len(line) > 0; {
 188             i, j := indexEscapeSequence(line)
 189             if i < 0 {
 190                 w.Write(line)
 191                 break
 192             }
 193             if j < 0 {
 194                 j = len(line)
 195             }
 196 
 197             if i > 0 {
 198                 w.Write(line[:i])
 199             }
 200 
 201             line = line[j:]
 202         }
 203 
 204         if w.WriteByte('\n') != nil {
 205             return io.EOF
 206         }
 207 
 208         if !live {
 209             continue
 210         }
 211 
 212         if err := w.Flush(); err != nil {
 213             return io.EOF
 214         }
 215     }
 216 
 217     return sc.Err()
 218 }