Giant blob of minor changes
[dotfiles/.git] / scripts / onelineserver / ansi2html.sh
1 #!/bin/sh
2
3 # Convert ANSI (terminal) colours and attributes to HTML
4
5 # Licence: LGPLv2
6 # Author:
7 #    http://www.pixelbeat.org/docs/terminal_colours/
8 # Examples:
9 #    ls -l --color=always | ansi2html.sh > ls.html
10 #    git show --color | ansi2html.sh > last_change.html
11 #    Generally one can use the `script` util to capture full terminal output.
12 # Changes:
13 #    V0.1, 24 Apr 2008, Initial release
14 #    V0.2, 01 Jan 2009, Phil Harnish <philharnish@gmail.com>
15 #                         Support `git diff --color` output by
16 #                         matching ANSI codes that specify only
17 #                         bold or background colour.
18 #                       P@draigBrady.com
19 #                         Support `ls --color` output by stripping
20 #                         redundant leading 0s from ANSI codes.
21 #                         Support `grep --color=always` by stripping
22 #                         unhandled ANSI codes (specifically ^[[K).
23 #    V0.3, 20 Mar 2009, http://eexpress.blog.ubuntu.org.cn/
24 #                         Remove cat -v usage which mangled non ascii input.
25 #                         Cleanup regular expressions used.
26 #                         Support other attributes like reverse, ...
27 #                       P@draigBrady.com
28 #                         Correctly nest <span> tags (even across lines).
29 #                         Add a command line option to use a dark background.
30 #                         Strip more terminal control codes.
31 #    V0.4, 17 Sep 2009, P@draigBrady.com
32 #                         Handle codes with combined attributes and color.
33 #                         Handle isolated <bold> attributes with css.
34 #                         Strip more terminal control codes.
35 #    V0.26, 16 Nov 2019
36 #      http://github.com/pixelb/scripts/commits/master/scripts/ansi2html.sh
37
38 gawk --version >/dev/null || exit 1
39
40 if [ "$1" = "--version" ]; then
41     printf '0.26\n' && exit
42 fi
43
44 usage()
45 {
46 printf '%s\n' \
47 'This utility converts ANSI codes in data passed to stdin
48 It has 4 optional parameters:
49 --bg=dark --palette=linux|solarized|tango|xterm --css-only|--body-only
50 E.g.: ls -l --color=always | ansi2html.sh --bg=dark > ls.html' >&2
51     exit
52 }
53
54 if [ "$1" = "--help" ]; then
55     usage
56 fi
57
58 processArg()
59 {
60     [ "$1" = "--bg=dark" ] && { dark_bg=yes; return; }
61     [ "$1" = "--css-only" ] && { css_only=yes; return; }
62     [ "$1" = "--body-only" ] && { body_only=yes; return; }
63     if [ "$1" = "--palette=solarized" ]; then
64        # See http://ethanschoonover.com/solarized
65        P0=073642;  P1=D30102;  P2=859900;  P3=B58900;
66        P4=268BD2;  P5=D33682;  P6=2AA198;  P7=EEE8D5;
67        P8=002B36;  P9=CB4B16; P10=586E75; P11=657B83;
68       P12=839496; P13=6C71C4; P14=93A1A1; P15=FDF6E3;
69       return;
70     elif [ "$1" = "--palette=solarized-xterm" ]; then
71        # Above mapped onto the xterm 256 color palette
72        P0=262626;  P1=AF0000;  P2=5F8700;  P3=AF8700;
73        P4=0087FF;  P5=AF005F;  P6=00AFAF;  P7=E4E4E4;
74        P8=1C1C1C;  P9=D75F00; P10=585858; P11=626262;
75       P12=808080; P13=5F5FAF; P14=8A8A8A; P15=FFFFD7;
76       return;
77     elif [ "$1" = "--palette=tango" ]; then
78        # Gnome default
79        P0=000000;  P1=CC0000;  P2=4E9A06;  P3=C4A000;
80        P4=3465A4;  P5=75507B;  P6=06989A;  P7=D3D7CF;
81        P8=555753;  P9=EF2929; P10=8AE234; P11=FCE94F;
82       P12=729FCF; P13=AD7FA8; P14=34E2E2; P15=EEEEEC;
83       return;
84     elif [ "$1" = "--palette=xterm" ]; then
85        P0=000000;  P1=CD0000;  P2=00CD00;  P3=CDCD00;
86        P4=0000EE;  P5=CD00CD;  P6=00CDCD;  P7=E5E5E5;
87        P8=7F7F7F;  P9=FF0000; P10=00FF00; P11=FFFF00;
88       P12=5C5CFF; P13=FF00FF; P14=00FFFF; P15=FFFFFF;
89       return;
90     else # linux console
91        P0=000000;  P1=AA0000;  P2=00AA00;  P3=AA5500;
92        P4=0000AA;  P5=AA00AA;  P6=00AAAA;  P7=AAAAAA;
93        P8=555555;  P9=FF5555; P10=55FF55; P11=FFFF55;
94       P12=5555FF; P13=FF55FF; P14=55FFFF; P15=FFFFFF;
95       [ "$1" = "--palette=linux" ] && return;
96     fi
97 }
98
99 processArg #defaults
100 for var in "$@"; do processArg $var; done
101 [ "$css_only" ] && [ "$body_only" ] && usage
102
103 # Mac OSX's GNU sed is installed as gsed
104 # use e.g. homebrew 'gnu-sed' to get it
105 if ! sed --version >/dev/null 2>&1; then
106   if gsed --version >/dev/null 2>&1; then
107     alias sed=gsed
108   else
109     echo "Error, can't find an acceptable GNU sed." >&2
110     exit 1
111   fi
112 fi
113
114 [ "$css_only" ] || [ "$body_only" ] || printf '%s' "<html>
115 <head>
116 <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
117 <style type=\"text/css\">
118 pre { white-space: pre-wrap; }
119 "
120 [ "$body_only" ] || printf ".ef0,.f0 { color: #$P0; } .eb0,.b0 { background-color: #$P0; }
121 .ef1,.f1 { color: #$P1; } .eb1,.b1 { background-color: #$P1; }
122 .ef2,.f2 { color: #$P2; } .eb2,.b2 { background-color: #$P2; }
123 .ef3,.f3 { color: #$P3; } .eb3,.b3 { background-color: #$P3; }
124 .ef4,.f4 { color: #$P4; } .eb4,.b4 { background-color: #$P4; }
125 .ef5,.f5 { color: #$P5; } .eb5,.b5 { background-color: #$P5; }
126 .ef6,.f6 { color: #$P6; } .eb6,.b6 { background-color: #$P6; }
127 .ef7,.f7 { color: #$P7; } .eb7,.b7 { background-color: #$P7; }
128 .ef8, .f0 > .bold,.bold > .f0 { color: #$P8; font-weight: normal; }
129 .ef9, .f1 > .bold,.bold > .f1 { color: #$P9; font-weight: normal; }
130 .ef10,.f2 > .bold,.bold > .f2 { color: #$P10; font-weight: normal; }
131 .ef11,.f3 > .bold,.bold > .f3 { color: #$P11; font-weight: normal; }
132 .ef12,.f4 > .bold,.bold > .f4 { color: #$P12; font-weight: normal; }
133 .ef13,.f5 > .bold,.bold > .f5 { color: #$P13; font-weight: normal; }
134 .ef14,.f6 > .bold,.bold > .f6 { color: #$P14; font-weight: normal; }
135 .ef15,.f7 > .bold,.bold > .f7 { color: #$P15; font-weight: normal; }
136 .eb8  { background-color: #$P8; }
137 .eb9  { background-color: #$P9; }
138 .eb10 { background-color: #$P10; }
139 .eb11 { background-color: #$P11; }
140 .eb12 { background-color: #$P12; }
141 .eb13 { background-color: #$P13; }
142 .eb14 { background-color: #$P14; }
143 .eb15 { background-color: #$P15; }
144 "
145 # The default xterm 256 colour palette
146 for red in 0 1 2 3 4 5 ; do
147   for green in 0 1 2 3 4 5 ; do
148     for blue in 0 1 2 3 4 5 ; do
149       c=$((16 + ($red * 36) + ($green * 6) + $blue))
150       r=$((($red * 40 + 55) * ($red > 0)))
151       g=$((($green * 40 + 55) * ($green > 0)))
152       b=$((($blue * 40 + 55) * ($blue > 0)))
153       [ "$body_only" ] || printf ".ef%d { color: #%2.2x%2.2x%2.2x; } " $c $r $g $b
154       [ "$body_only" ] || printf ".eb%d { background-color: #%2.2x%2.2x%2.2x; }\n" $c $r $g $b
155     done
156   done
157 done
158 for gray in $(seq 0 23); do
159   c=$(($gray+232))
160   l=$(($gray*10 + 8))
161   [ "$body_only" ] || printf ".ef%d { color: #%2.2x%2.2x%2.2x; } " $c $l $l $l
162   [ "$body_only" ] || printf ".eb%d { background-color: #%2.2x%2.2x%2.2x; }\n" $c $l $l $l
163 done
164
165 [ "$body_only" ] || printf '%s' '
166 .f9 { color: '`[ "$dark_bg" ] && printf "#$P7;" || printf "#$P0;"`' }
167 .b9 { background-color: #'`[ "$dark_bg" ] && printf $P0 || printf $P15`'; }
168 .f9 > .bold,.bold > .f9, body.f9 > pre > .bold {
169   /* Bold is heavy black on white, or bright white
170      depending on the default background */
171   color: '`[ "$dark_bg" ] && printf "#$P15;" || printf "#$P0;"`'
172   font-weight: '`[ "$dark_bg" ] && printf 'normal;' || printf 'bold;'`'
173 }
174 .reverse {
175   /* CSS does not support swapping fg and bg colours unfortunately,
176      so just hardcode something that will look OK on all backgrounds. */
177   '"color: #$P0; background-color: #$P7;"'
178 }
179 .underline { text-decoration: underline; }
180 .line-through { text-decoration: line-through; }
181 .blink { text-decoration: blink; }
182
183 /* Avoid pixels between adjacent span elements.
184    Note this only works for lines less than 80 chars
185    where we close span elements on the same line.
186 span { display: inline-block; }
187 */
188 '
189 [ "$body_only" ] || [ "$css_only" ] && printf '%s\n' \
190 'To use the css generated from --css-only, do: '\
191 '<head><link rel="stylesheet" type="text/css" href="style.css"></head>' >&2
192 [ "$css_only" ] && exit
193 [ "$body_only" ] || printf '%s' '</style>
194 </head>
195
196 <body class="f9 b9">
197 <pre>
198 '
199 [ "$body_only" ] && printf '%s\n' 'Be sure to use <body class="f9 b9"> and <pre>' >&2
200
201 p='\x1b\['        #shortcut to match escape codes
202
203 # Handle various xterm control sequences.
204 # See /usr/share/doc/xterm-*/ctlseqs.txt
205 sed "
206 # escape ampersand and quote
207 s#&#\&amp;#g; s#\"#\&quot;#g;
208 s#\x1b[^\x1b]*\x1b\\\##g  # strip anything between \e and ST
209 s#\x1b][0-9]*;[^\a]*\a##g # strip any OSC (xterm title etc.)
210
211 s#\r\$## # strip trailing \r
212
213 # strip other non SGR escape sequences
214 s#[\x07]##g
215 s#\x1b[]>=\][0-9;]*##g
216 s#\x1bP+.\{5\}##g
217 # Mark cursor positioning codes \"Jr;c;
218 s#${p}\([0-9]\{1,2\}\)G#\"J;\1;#g
219 s#${p}\([0-9]\{1,2\}\);\([0-9]\{1,2\}\)H#\"J\1;\2;#g
220
221 # Mark clear as \"Cn where n=1 is screen and n=0 is to end-of-line
222 s#${p}H#\"C1;#g
223 s#${p}K#\"C0;#g
224 # Mark Cursor move columns as \"Mn where n is +ve for right, -ve for left
225 s#${p}C#\"M1;#g
226 s#${p}\([0-9]\{1,\}\)C#\"M\1;#g
227 s#${p}\([0-9]\{1,\}\)D#\"M-\1;#g
228 s#${p}\([0-9]\{1,\}\)P#\"X\1;#g
229
230 s#${p}[0-9;?]*[^0-9;?m]##g
231
232 " |
233
234 # Normalize the input before transformation
235 sed "
236 # escape HTML (ampersand and quote done above)
237 s#>#\&gt;#g; s#<#\&lt;#g;
238
239 # handle truecolor
240 s#${p}38;2;\([0-9]\{1,3\}\);\([0-9]\{1,3\}\);\([0-9]\{1,3\}\)m#\
241 <span style=\"color:rgb(\1\,\2\,\3\)\">#g
242 s#${p}48;2;\([0-9]\{1,3\}\);\([0-9]\{1,3\}\);\([0-9]\{1,3\}\)m#\
243 <span style=\"background-color:rgb(\1\,\2\,\3\)\">#g
244
245 # normalize SGR codes a little
246
247 # split 256 colors out and mark so that they're not
248 # recognised by the following 'split combined' line
249 :e
250 s#${p}\([0-9;]\{1,\}\);\([34]8;5;[0-9]\{1,3\}\)m#${p}\1m${p}¬\2m#g; t e
251 s#${p}\([34]8;5;[0-9]\{1,3\}\)m#${p}¬\1m#g;
252
253 :c
254 s#${p}\([0-9]\{1,\}\);\([0-9;]\{1,\}\)m#${p}\1m${p}\2m#g; t c   # split combined
255 s#${p}0\([0-7]\)#${p}\1#g                                 #strip leading 0
256 s#${p}1m\(\(${p}[4579]m\)*\)#\1${p}1m#g                   #bold last (with clr)
257 s#${p}m#${p}0m#g                                          #add leading 0 to norm
258
259 # undo any 256 color marking
260 s#${p}¬\([34]8;5;[0-9]\{1,3\}\)m#${p}\1m#g;
261
262 # map 16 color codes to color + bold
263 s#${p}9\([0-7]\)m#${p}3\1m${p}1m#g;
264 s#${p}10\([0-7]\)m#${p}4\1m${p}1m#g;
265
266 # change 'reset' code to \"R
267 s#${p}0m#\"R;#g
268 " |
269
270 # Convert SGR sequences to HTML
271 sed "
272 # common combinations to minimise html (optional)
273 :f
274 s#${p}3[0-7]m${p}3\([0-7]\)m#${p}3\1m#g; t f
275 :b
276 s#${p}4[0-7]m${p}4\([0-7]\)m#${p}4\1m#g; t b
277 s#${p}3\([0-7]\)m${p}4\([0-7]\)m#<span class=\"f\1 b\2\">#g
278 s#${p}4\([0-7]\)m${p}3\([0-7]\)m#<span class=\"f\2 b\1\">#g
279
280 s#${p}1m#<span class=\"bold\">#g
281 s#${p}4m#<span class=\"underline\">#g
282 s#${p}5m#<span class=\"blink\">#g
283 s#${p}7m#<span class=\"reverse\">#g
284 s#${p}9m#<span class=\"line-through\">#g
285 s#${p}3\([0-9]\)m#<span class=\"f\1\">#g
286 s#${p}4\([0-9]\)m#<span class=\"b\1\">#g
287
288 s#${p}38;5;\([0-9]\{1,3\}\)m#<span class=\"ef\1\">#g
289 s#${p}48;5;\([0-9]\{1,3\}\)m#<span class=\"eb\1\">#g
290
291 s#${p}[0-9;]*m##g # strip unhandled codes
292 " |
293
294 # Convert alternative character set and handle cursor movement codes
295 # Note we convert here, as if we do at start we have to worry about avoiding
296 # conversion of SGR codes etc., whereas doing here we only have to
297 # avoid conversions of stuff between &...; or <...>
298 #
299 # Note we could use sed to do this based around:
300 #   sed 'y/abcdefghijklmnopqrstuvwxyz{}`~/▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π£◆·/'
301 # However that would be very awkward as we need to only conv some input.
302 # The basic scheme that we do in the awk script below is:
303 #  1. enable transliterate once "T1; is seen
304 #  2. disable once "T0; is seen (may be on diff line)
305 #  3. never transliterate between &; or <> chars
306 #  4. track x,y movements and active display mode at each position
307 #  5. buffer line/screen and dump when required
308 sed "
309 # change 'smacs' and 'rmacs' to \"T1 and \"T0 to simplify matching.
310 s#\x1b(0#\"T1;#g;
311 s#\x0E#\"T1;#g;
312
313 s#\x1b(B#\"T0;#g
314 s#\x0F#\"T0;#g
315 " |
316 (
317 gawk '
318 function dump_line(l,del,c,blanks,ret) {
319   for(c=1;c<maxX;c++) {
320     if ((c SUBSEP l) in attr || alength(cur)) {
321       ret = ret blanks fixas(cur,attr[c,l])
322       if(del) delete attr[c,l]
323       blanks=""
324     }
325     if ((c SUBSEP l) in dump) {
326       ret=ret blanks dump[c,l]
327       if(del) delete dump[c,l]
328       blanks=""
329     } else blanks=blanks " "
330   }
331   if(alength(cur)) ret=ret blanks
332   return ret
333 }
334
335 function dump_screen(l,ret) {
336   for(l=1;l<=maxY;l++)
337     ret=ret dump_line(l,0) "\n"
338   return ret fixas(cur, "")
339 }
340
341 function atos(a,i,ret) {
342   for(i=1;i<=alength(a);i++) if(i in a) ret=ret a[i]
343   return ret
344 }
345
346 function alength(a, i, k) {
347     k = 0
348     for(i in a) k++
349     return k
350 }
351
352 function fixas(a,s,spc,i,attr,rm,ret) {
353   spc=alength(a)
354   l=split(s,attr,">")
355   for(i=1;i<=spc;i++) {
356     rm=rm?rm:(a[i]!=attr[i]">")
357     if(rm) {
358       ret=ret "</span>"
359       delete a[i];
360     }
361   }
362   for(i=1;i<l;i++) {
363     attr[i]=attr[i]">"
364     if(a[i]!=attr[i]) {
365       a[i]=attr[i]
366       ret = ret attr[i]
367     }
368   }
369   return ret
370 }
371
372 function encode(string,start,end,i,ret,pos,sc,buf) {
373    if(!end) end=length(string);
374    if(!start) start=1;
375    state=3
376    for(i=1;i<=length(string);i++) {
377      c=substr(string,i,1)
378      if(state==2) {
379        sc=sc c
380        if(c==";") {
381           c=sc
382           state=last_mode
383        } else continue
384      } else {
385        if(c=="\r") { x=1; continue }
386        if(c=="<") {
387          # Change attributes - store current active
388          # attributes in span array
389          split(substr(string,i),cord,">");
390          i+=length(cord[1])
391          span[++spc]=cord[1] ">"
392          continue
393        }
394        else if(c=="&") {
395          # All goes to single position till we see a semicolon
396          sc=c
397          state=2
398          continue
399        }
400        else if(c=="\b") {
401           # backspace move insertion point back 1
402           if(spc) attr[x,y]=atos(span)
403           x=x>1?x-1:1
404           continue
405        }
406        else if(c=="\"") {
407           split(substr(string,i+2),cord,";")
408           cc=substr(string,i+1,1);
409           if(cc=="T") {
410               # Transliterate on/off
411               if(cord[1]==1&&state==3) last_mode=state=4
412               if(cord[1]==0&&state==4) last_mode=state=3
413           }
414           else if(cc=="C") {
415               # Clear
416               if(cord[1]+0) {
417                 # Screen - if Recording dump screen
418                 if(dumpStatus==dsActive) ret=ret dump_screen()
419                 dumpStatus=dsActive
420                 delete dump
421                 delete attr
422                 x=y=1
423               } else {
424                 # To end of line
425                 for(pos=x;pos<maxX;pos++) {
426                   dump[pos,y]=" "
427                   if (!spc) delete attr[pos,y]
428                   else attr[pos,y]=atos(span)
429                 }
430               }
431           }
432           else if(cc=="J") {
433               # Jump to x,y
434               i+=length(cord[2])+1
435               # If line is higher - dump previous screen
436               if(dumpStatus==dsActive&&cord[1]<y) {
437                 ret=ret dump_screen();
438                 dumpStatus=dsNew;
439               }
440               x=cord[2]
441               if(length(cord[1]) && y!=cord[1]){
442                 y=cord[1]
443                 if(y>maxY) maxY=y
444                 # Change y - start recording
445                 dumpStatus=dumpStatus?dumpStatus:dsReset
446               }
447           }
448           else if(cc=="M") {
449               # Move left/right on current line
450               x+=cord[1]
451           }
452           else if(cc=="X") {
453               # delete on right
454               for(pos=x;pos<=maxX;pos++) {
455                 nx=pos+cord[1]
456                 if(nx<maxX) {
457                   if((nx SUBSEP y) in attr) attr[pos,y] = attr[nx,y]
458                   else delete attr[pos,y]
459                   if((nx SUBSEP y) in dump) dump[pos,y] = dump[nx,y]
460                   else delete dump[pos,y]
461                 } else if(spc) {
462                   attr[pos,y]=atos(span)
463                   dump[pos,y]=" "
464                 }
465               }
466           }
467           else if(cc=="R") {
468               # Reset attributes
469               while(spc) delete span[spc--]
470           }
471           i+=length(cord[1])+2
472           continue
473        }
474        else if(state==4&&i>=start&&i<=end&&c in Trans) c=Trans[c]
475      }
476      if(dumpStatus==dsReset) {
477        delete dump
478        delete attr
479        ret=ret"\n"
480        dumpStatus=dsActive
481      }
482      if(dumpStatus==dsNew) {
483        # After moving/clearing we are now ready to write
484        # somthing to the screen so start recording now
485        ret=ret"\n"
486        dumpStatus=dsActive
487      }
488      if(dumpStatus==dsActive||dumpStatus==dsOff) {
489        dump[x,y] = c
490        if(!spc) delete attr[x,y]
491        else attr[x,y] = atos(span)
492        if(++x>maxX) maxX=x;
493      }
494     }
495     # End of line if dumping increment y and set x back to first col
496     x=1
497     if(!dumpStatus) return ret dump_line(y,1);
498     else if(++y>maxY) maxY=y;
499     return ret
500 }
501 BEGIN{
502   OFS=FS
503   # dump screen status
504   dsOff=0    # Not dumping screen contents just write output direct
505   dsNew=1    # Just after move/clear waiting for activity to start recording
506   dsReset=2  # Screen cleared build new empty buffer and record
507   dsActive=3 # Currently recording
508   F="abcdefghijklmnopqrstuvwxyz{}`~"
509   T="▒␉␌␍␊°±␤␋┘┐┌└┼⎺⎻─⎼⎽├┤┴┬│≤≥π£◆·"
510   maxX=80
511   delete cur;
512   x=y=1
513   for(i=1;i<=length(F);i++)Trans[substr(F,i,1)]=substr(T,i,1);
514 }
515
516 { $0=encode($0) }
517 1
518 END {
519   if(dumpStatus) {
520     print dump_screen();
521   }
522 }'
523 )
524
525 [ "$body_only" ] || printf '</pre>
526 </body>
527 </html>\n'