#!/usr/bin/env bash # Originally written by https://github.com/deyloop/dot # Formats Markdown tables so that they are readable in text form # Parses the table in order to print the formatted form. # # Supposed to be used as an UNIX filter, where the unformatted table # should be sent to `stdin` and the formatted output will be sent to # `stdout`. # If a parsing error occures, prints the unformatted table unchanged, # and exits with code 42 # # In order to debug, look at `__fail` # Does all the parsing in pure bash, in a single process. Printing uses # a few subshells as that was convenient. # TODO: support escaping pipe characters # TODO: skipping to just tables when whole markdown document is passed # TODO: allow filename to be passed as argument #------------------------------------------------------------------------- # The Parsing Grammar used: # # table -> newline headingrow delimrow tablebody # # headingrow -> pipe? headings pipe? newline # headings -> content pipe headingsB # headingsB -> content / content pipe headingsB # content -> [^pipe]* # # delimrow -> pipe? delims pipe? newline # delims -> delim pipe delimsB # delimsB -> delim / delim pipe delimsB # delim -> noalign / leftalign / centeralign / rightalign # noalign -> dash dash dashes # leftalign -> colon dash dashes # centeralign -> colon dashes colon # rightalign -> dash dashes colon # # tablebody -> nothing / tablerow tablebody # tablerow -> pipe? body pipe? newline # body -> content pipe bodyB # bodyB -> content / content pipe bodyB # # dashes -> dash / dash dashes # pipe -> '|' # dash -> '-' # colon -> ':' #------------------------------------------------------------------------- fmttable() { local in=/dev/stdin local buf buf="$(<"$in")" buf+=$'\n' local i=0 local c local -a contents local col=0 local row=0 local totalcols=0 local -a colwidths local -a colaligns # parsing _parse_table # print the headings printf "|" for (( x=0; x