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