File: nn.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2025 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 # Notes
  27 #
  28 # String-slicing was a major source of inefficiencies in this script, making
  29 # it viable only for small inputs; it's not clear what the stdlib offers to
  30 # loop over sub-strings without copying data, which is really needed in this
  31 # case.
  32 #
  33 # String-slicing seems to be amortized in more recent versions of Python.
  34 #
  35 # In the end the code has become much uglier by using explicit index-pairs,
  36 # which are used/updated all over to avoid copying sub-strings.
  37 
  38 
  39 from io import SEEK_CUR
  40 from sys import argv, exit, stderr, stdin, stdout
  41 
  42 
  43 info = '''
  44 nn [option...] [filepaths/URIs...]
  45 
  46 
  47 Nice Numbers restyles all runs of 4+ digits by alternating ANSI-styles
  48 every 3-digit group, so long numbers become easier to read at a glance.
  49 
  50 All (optional) leading options start with either single or double-dash,
  51 and most of them change the style/color used. Some of the options are,
  52 shown in their single-dash form:
  53 
  54     -h          show this help message
  55     -help       show this help message
  56 
  57     -b          use a blue color
  58     -blue       use a blue color
  59     -bold       bold-style digits
  60     -g          use a green color
  61     -gray       use a gray color (default)
  62     -green      use a green color
  63     -hi         use a highlighting/inverse style
  64     -highlight  use a highlighting/inverse style
  65     -hilite     use a highlighting/inverse style
  66     -inverse    use a highlighting/inverse style
  67     -m          use a magenta color
  68     -magenta    use a magenta color
  69     -o          use an orange color
  70     -orange     use an orange color
  71     -p          use a purple color
  72     -purple     use a purple color
  73     -r          use a red color
  74     -red        use a red color
  75     -u          underline digits
  76     -underline  underline digits
  77 '''
  78 
  79 # handle standard help cmd-line options, quitting right away in that case
  80 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'):
  81     print(info.strip())
  82     exit(0)
  83 
  84 
  85 # names_aliases normalizes lookup keys for table names2styles
  86 names_aliases = {
  87     'b': 'blue',
  88     'g': 'green',
  89     'm': 'magenta',
  90     'o': 'orange',
  91     'p': 'purple',
  92     'r': 'red',
  93     'u': 'underline',
  94 
  95     'bb': 'blueback',
  96     'bg': 'greenback',
  97     'bm': 'magentaback',
  98     'bo': 'orangeback',
  99     'bp': 'purpleback',
 100     'br': 'redback',
 101 
 102     'gb': 'greenback',
 103     'mb': 'magentaback',
 104     'ob': 'orangeback',
 105     'pb': 'purpleback',
 106     'rb': 'redback',
 107 
 108     'hi': 'inverse',
 109     'inv': 'inverse',
 110 
 111     'flip': 'inverse',
 112     'swap': 'inverse',
 113 
 114     'reset': 'plain',
 115     'highlight': 'inverse',
 116     'hilite': 'inverse',
 117     'invert': 'inverse',
 118     'inverted': 'inverse',
 119     'swapped': 'inverse',
 120 
 121     'under': 'underline',
 122 
 123     'bgblue': 'blueback',
 124     'bggray': 'grayback',
 125     'bggreen': 'greenback',
 126     'bgmagenta': 'magentaback',
 127     'bgorange': 'orangeback',
 128     'bgpurple': 'purpleback',
 129     'bgred': 'redback',
 130 
 131     'bluebg': 'blueback',
 132     'graybg': 'grayback',
 133     'greenbg': 'greenback',
 134     'magentabg': 'magentaback',
 135     'orangebg': 'orangeback',
 136     'purplebg': 'purpleback',
 137     'redbg': 'redback',
 138 
 139     'backblue': 'blueback',
 140     'backgray': 'grayback',
 141     'backgreen': 'greenback',
 142     'backmagenta': 'magentaback',
 143     'backorange': 'orangeback',
 144     'backpurple': 'purpleback',
 145     'backred': 'redback',
 146 }
 147 
 148 # names2styles matches color/style names to their ANSI-style strings
 149 names2styles = {
 150     'blue': '\x1b[38;2;0;95;215m',
 151     'bold': '\x1b[1m',
 152     'gray': '\x1b[38;2;168;168;168m',
 153     'green': '\x1b[38;2;0;135;95m',
 154     'inverse': '\x1b[7m',
 155     'magenta': '\x1b[38;2;215;0;255m',
 156     'orange': '\x1b[38;2;215;95;0m',
 157     'plain': '\x1b[0m',
 158     'purple': '\x1b[38;2;135;95;255m',
 159     'red': '\x1b[38;2;204;0;0m',
 160     'underline': '\x1b[4m',
 161 
 162     'blueback': '\x1b[48;2;0;95;215m\x1b[38;2;238;238;238m',
 163     'grayback': '\x1b[48;2;168;168;168m\x1b[38;2;238;238;238m',
 164     'greenback': '\x1b[48;2;0;135;95m\x1b[38;2;238;238;238m',
 165     'magentaback': '\x1b[48;2;215;0;255m\x1b[38;2;238;238;238m',
 166     'orangeback': '\x1b[48;2;215;95;0m\x1b[38;2;238;238;238m',
 167     'purpleback': '\x1b[48;2;135;95;255m\x1b[38;2;238;238;238m',
 168     'redback': '\x1b[48;2;204;0;0m\x1b[38;2;238;238;238m',
 169 }
 170 
 171 
 172 def restyle_line(w, line: str, style: str) -> None:
 173     'Alternate styles for runs of digits in the string given.'
 174 
 175     start = 0
 176     end = len(line)
 177     if end > 1 and line[end - 2] == '\r' and line[end - 1] == '\n':
 178         end -= 2
 179     elif end > 0 and line[end - 1] == '\n':
 180         end -= 1
 181 
 182     while True:
 183         # see if line is over
 184         if start >= end:
 185             w.write('\n')
 186             return
 187 
 188         # find where the next run of digits starts, if present
 189         i = -1
 190         for j in range(start, end):
 191             if line[j].isdigit():
 192                 i = j
 193                 break
 194 
 195         # check if rest of the line has no more digits
 196         if i < 0:
 197             w.write(line[start:end])
 198             w.write('\n')
 199             return
 200 
 201         # some ANSI-style sequences use 4-digit numbers, which are long
 202         # enough for this script to mangle
 203         is_ansi = i >= 2 and line[i-2] == '\x1b' and line[i-1] == '['
 204 
 205         # emit line up to right before the next run of digits starts
 206         w.write(line[start:i])
 207         start = i
 208 
 209         # find where/if the current run of digits ends
 210         i = -1
 211         for j in range(start, end):
 212             if not line[j].isdigit():
 213                 i = j
 214                 break
 215 
 216         # check if rest of the line has only digits in it
 217         if i < 0:
 218             if not is_ansi:
 219                 restyle_digits(w, line, start, end, style)
 220             else:
 221                 w.write(line[start:end])
 222             w.write('\n')
 223             return
 224 
 225         # emit digits using alternate styling, and advance past them
 226         if not is_ansi:
 227             restyle_digits(w, line, start, i, style)
 228         else:
 229             w.write(line[start:i])
 230         start = i
 231 
 232 
 233 def restyle_digits(w, digits: str, start: int, end: int, style: str) -> None:
 234     'Alternate styles on 3-item chunks from the string given.'
 235 
 236     diff = end - start
 237 
 238     # it's overall quicker to just emit short-enough digit-runs verbatim
 239     if diff < 4:
 240         w.write(digits[start:end])
 241         return
 242 
 243     # emit leading chunk of digits, which is the only one which
 244     # can have fewer than 3 items
 245     lead = diff % 3
 246     w.write(digits[start:start + lead])
 247 
 248     # the rest of the sub-string now has a multiple of 3 items left
 249     start += lead
 250 
 251     # start by styling the next digit-group only if there was a
 252     # non-empty leading group at the start of the full digit-run
 253     use_style = lead > 0
 254 
 255     # alternate styles until the string is over
 256     while start < end:
 257         # the digits left are always a multiple of 3
 258         stop = start + 3
 259 
 260         if use_style:
 261             w.write(style)
 262             w.write(digits[start:stop])
 263             w.write('\x1b[0m')
 264         else:
 265             w.write(digits[start:stop])
 266 
 267         # switch style and advance to the next 3-digit chunk
 268         use_style = not use_style
 269         start = stop
 270 
 271 
 272 def seems_url(s: str) -> bool:
 273     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
 274     return any(s.startswith(p) for p in protocols)
 275 
 276 
 277 def handle_lines(w, src, style: str, live: bool) -> None:
 278     for line in src:
 279         restyle_line(w, line, style)
 280         if live:
 281             w.flush()
 282 
 283 
 284 args = argv[1:]
 285 style = names2styles['gray']
 286 
 287 # handle leading style/color option, if present
 288 if len(args) > 0 and args[0].startswith('-'):
 289     s = args[0].lstrip('-')
 290     if s in names_aliases:
 291         s = names_aliases[s]
 292 
 293     if s in names2styles:
 294         style = names2styles[s]
 295         args = args[1:]
 296 
 297 if any(seems_url(e) for e in args):
 298     from io import TextIOWrapper
 299     from urllib.request import urlopen
 300 
 301 try:
 302     if args.count('-') > 1:
 303         msg = 'reading from `-` (standard input) more than once not allowed'
 304         raise ValueError(msg)
 305 
 306     try:
 307         stdout.seek(0, SEEK_CUR)
 308         live = False
 309     except:
 310         live = True
 311 
 312     for path in args:
 313         if path == '-':
 314             handle_lines(stdout, stdin, style, live)
 315             continue
 316 
 317         if seems_url(path):
 318             with urlopen(path) as inp:
 319                 with TextIOWrapper(inp, encoding='utf-8') as txt:
 320                     handle_lines(stdout, txt, style, live)
 321             continue
 322 
 323         with open(path, encoding='utf-8') as inp:
 324             handle_lines(stdout, inp, style, live)
 325 
 326     if len(args) == 0:
 327         handle_lines(stdout, stdin, style, live)
 328 except BrokenPipeError:
 329     # quit quietly, instead of showing a confusing error message
 330     stderr.close()
 331     exit(0)
 332 except KeyboardInterrupt:
 333     exit(2)
 334 except Exception as e:
 335     print(str(e), file=stderr)
 336     exit(1)