#!/usr/bin/env python3 """Turn docs/basic-manual.md into LaTeX for XeLaTeX (docs/build-manual.sh runs it). The Markdown stays the only source. It is read with python-markdown (tables and fenced code), and the HTML that gives is walked and written out as LaTeX: ## headings become numbered chapters (their "N." prefix must count up from 1, since the text refers to "section N"), ### headings unnumbered sections in the contents, tables booktabs tables that can break across pages, and code blocks framed verbatim text. md2tex.py basic-manual.md basic-manual.tex """ import html.parser import re import sys import markdown # ------------------------------------------------------------- HTML to a tree class Node: def __init__(self, tag, attrs=None, parent=None): self.tag, self.attrs, self.parent, self.kids = tag, dict(attrs or []), parent, [] def text(self): return "".join(k if isinstance(k, str) else k.text() for k in self.kids) class TreeBuilder(html.parser.HTMLParser): VOID = {"br", "hr", "img"} def __init__(self): super().__init__(convert_charrefs=True) self.root = self.cur = Node("root") def handle_starttag(self, tag, attrs): n = Node(tag, attrs, self.cur) self.cur.kids.append(n) if tag not in self.VOID: self.cur = n def handle_endtag(self, tag): n = self.cur while n is not self.root and n.tag != tag: n = n.parent if n is not self.root: self.cur = n.parent def handle_data(self, data): self.cur.kids.append(data) # ------------------------------------------------------------------ escaping SPECIAL = { "\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "$": r"\$", "&": r"\&", "#": r"\#", "%": r"\%", "_": r"\_", "~": r"\textasciitilde{}", "^": r"\textasciicircum{}", } def esc(s): return "".join(SPECIAL.get(c, c) for c in s) def esc_code(s): """Inline code: escaped, in a font where -- and '' are not ligatures, with break points after punctuation so long expressions can wrap.""" out = [] for c in s: if c in SPECIAL: out.append(SPECIAL[c]) elif c == "-": out.append("-{}") elif c in "'`\"<>": out.append("\\char`\\%s{}" % c) elif c == " ": out.append("\\ ") else: out.append(c) if c in ",;:/=+(": out.append(r"\allowbreak{}") return "".join(out) class Quotes: """Straight double quotes in running text become curly, alternately.""" def __init__(self): self.open = True def __call__(self, s): out = [] for c in s: if c == '"': out.append("“" if self.open else "”") self.open = not self.open else: out.append(c) return "".join(out) # -------------------------------------------------------------- the converter class Converter: def __init__(self, codeblocks): self.codeblocks = codeblocks self.quotes = Quotes() # inline content def inline(self, node): out = [] for k in node.kids: if isinstance(k, str): out.append(self.text(k)) elif k.tag == "code": out.append(r"\code{%s}" % esc_code(k.text())) elif k.tag == "strong": out.append(r"\textbf{%s}" % self.inline(k)) elif k.tag == "em": out.append(r"\emph{%s}" % self.inline(k)) elif k.tag == "br": out.append(r"\\") elif k.tag == "a": out.append(r"\href{%s}{%s}" % (esc(k.attrs.get("href", "")), self.inline(k))) elif k.tag in ("p", "ul", "ol", "pre", "table"): out.append(self.block(k)) else: out.append(self.inline(k)) return "".join(out) def text(self, s): # a code block that sat inside a list item comes through as a marker parts = re.split(r"@@CODE(\d+)@@", s) out = [] for i, p in enumerate(parts): if i % 2: out.append("\n" + self.verbatim(self.codeblocks[int(p)]) + "\n") else: out.append(esc(self.quotes(re.sub(r"\s+", " ", p)))) return "".join(out) # blocks def verbatim(self, code): code = code.rstrip("\n") return "\\begin{codebox}\n\\begin{Verbatim}\n%s\n\\end{Verbatim}\n\\end{codebox}" % code def heading(self, node, level): title = node.text().strip() if level == 2: m = re.match(r"(\d+)\.\s+(.*)", title) if not m: sys.exit("md2tex: ## heading without a number: %r" % title) self.chapter += 1 if int(m.group(1)) != self.chapter: sys.exit("md2tex: ## %s is out of order (expected %d)" % (title, self.chapter)) return "\\chapter{%s}\n" % self.inline_title(m.group(2)) t = self.inline_title(title) return "\\section*{%s}\\addcontentsline{toc}{section}{%s}\n" % (t, t) def inline_title(self, s): return esc(self.quotes(s)) def table(self, node): rows = [] for tr in self.find(node, "tr"): cells = [c for c in tr.kids if not isinstance(c, str) and c.tag in ("th", "td")] rows.append((cells[0].tag == "th" if cells else False, cells)) if not rows: return "" ncol = max(len(c) for _, c in rows) lens = [0] * ncol for _, cells in rows: for i, c in enumerate(cells): lens[i] = max(lens[i], len(c.text().strip())) total = sum(lens) or 1 wide = total > 70 spec = [] for n in lens: if not wide or n <= 22: spec.append(r">{\raggedright\arraybackslash}l" if n <= 22 or not wide else "L") else: spec.append("L") if wide and "L" not in spec: spec[-1] = "L" head, body = [], [] for is_head, cells in rows: if is_head: if any(c.text().strip() for c in cells): head.append(" & ".join(r"\thead{%s}" % self.inline(c).strip() for c in cells)) else: body.append(" & ".join(self.inline(c).strip() for c in cells)) env = "xltabular" if wide else "longtable" width = "{\\linewidth}" if wide else "" out = ["\\begin{%s}%s{%s}" % (env, width, "".join(spec))] if head: hrow = r"\rowcolor{gray10}" + head[0] + r" \\ \toprow" out += [hrow, r"\endfirsthead", hrow, r"\endhead"] else: out += [r"\toprow"] out.append(r"\endlastfoot") out += [b + r" \\ \rowrule" for b in body] out.append("\\end{%s}" % env) return "\n".join(out) + "\n" def find(self, node, tag): for k in node.kids: if isinstance(k, str): continue if k.tag == tag: yield k else: yield from self.find(k, tag) def block(self, node): t = node.tag if t == "h1": return "" if t in ("h2", "h3"): return self.heading(node, int(t[1])) if t == "p": return self.inline(node).strip() + "\n\n" if t == "pre": return self.verbatim(node.text()) + "\n\n" if t in ("ul", "ol"): env = "itemize" if t == "ul" else "enumerate" items = [r"\item " + self.inline(li).strip() for li in node.kids if not isinstance(li, str) and li.tag == "li"] return "\\begin{%s}\n%s\n\\end{%s}\n\n" % (env, "\n".join(items), env) if t == "table": return self.table(node) if t == "hr": return "\\bigskip\\hrule\\bigskip\n" return self.inline(node) def convert(self, root): self.chapter = 0 title = subtitle = "" kids = [k for k in root.kids if not isinstance(k, str) or k.strip()] if kids and not isinstance(kids[0], str) and kids[0].tag == "h1": title = kids.pop(0).text().strip() if kids and not isinstance(kids[0], str) and kids[0].tag == "p" \ and len(kids[0].kids) == 1 and not isinstance(kids[0].kids[0], str) \ and kids[0].kids[0].tag == "em": subtitle = self.inline(kids.pop(0).kids[0]) body = "".join(self.block(k) if not isinstance(k, str) else self.text(k) for k in kids) return title, subtitle, body PREAMBLE = r"""\documentclass[a4paper,10pt,chapterprefix=false,headings=small, parskip=half-,toc=flat,numbers=noenddot]{scrreprt} % ---- type: IBM Plex throughout \usepackage{fontspec} \defaultfontfeatures{Path=/usr/share/fonts/truetype/ibm-plex/,Extension=.ttf} \setmainfont{IBMPlexSans}[UprightFont=*-Regular,BoldFont=*-SemiBold, ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic] \setsansfont{IBMPlexSans}[UprightFont=*-Regular,BoldFont=*-SemiBold, ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic] \setmonofont{IBMPlexMono}[UprightFont=*-Regular,BoldFont=*-SemiBold, ItalicFont=*-Italic,BoldItalicFont=*-SemiBoldItalic,Scale=0.92] \newfontfamily\plexlight{IBMPlexSans}[UprightFont=*-Light,ItalicFont=*-LightItalic] \newfontfamily\plexthin{IBMPlexSans}[UprightFont=*-ExtraLight] \newfontfamily\plexmed{IBMPlexSans}[UprightFont=*-Medium] \newfontfamily\plexmono{IBMPlexMono}[UprightFont=*-Regular,BoldFont=*-Medium] \newfontfamily\plexmonolabel{IBMPlexMono}[UprightFont=*-Medium,LetterSpace=14] \usepackage{newunicodechar} \newunicodechar{ⁿ}{\textsuperscript{\textit{n}}} % ---- colour: Carbon greys and one blue \usepackage[table]{xcolor} \definecolor{blue60}{HTML}{0F62FE} \definecolor{blue70}{HTML}{0043CE} \definecolor{gray100}{HTML}{161616} \definecolor{gray90}{HTML}{262626} \definecolor{gray80}{HTML}{393939} \definecolor{gray70}{HTML}{525252} \definecolor{gray50}{HTML}{8D8D8D} \definecolor{gray30}{HTML}{C6C6C6} \definecolor{gray20}{HTML}{E0E0E0} \definecolor{gray10}{HTML}{F4F4F4} \color{gray100} % ---- page \usepackage[a4paper,top=28mm,bottom=26mm,inner=26mm,outer=26mm,headsep=10mm, footskip=12mm]{geometry} \usepackage{microtype} \usepackage{ragged2e} \setlength{\RaggedRightRightskip}{0pt plus 4em} \AtBeginDocument{\RaggedRight} \usepackage{tikz} \newcommand{\twodig}[1]{\ifnum#1<10 0\fi\number#1} \renewcommand{\thechapter}{\twodig{\value{chapter}}} % ---- tables: grey header band, hairlines between rows \usepackage{booktabs,longtable,xltabular,array} \newcolumntype{L}{>{\raggedright\arraybackslash}X} \setlength{\LTpre}{8pt}\setlength{\LTpost}{10pt}\setlength{\LTleft}{0pt}\setlength{\LTright}{\fill} \setlength{\aboverulesep}{0pt}\setlength{\belowrulesep}{0pt} \setlength{\tabcolsep}{7pt} \renewcommand{\arraystretch}{1.55} \arrayrulecolor{gray20} \newcommand{\thead}[1]{\leavevmode{\plexmed\footnotesize\color{gray100}#1}} \newcommand{\rowrule}{\arrayrulecolor{gray20}\specialrule{0.4pt}{0pt}{0pt}} \newcommand{\toprow}{\arrayrulecolor{gray100}\specialrule{0.8pt}{0pt}{0pt}\arrayrulecolor{gray20}} % ---- code \usepackage{fancyvrb} \fvset{fontsize=\small,formatcom=\color{gray100}} \usepackage[most]{tcolorbox} \newtcolorbox{codebox}{breakable,enhanced,sharp corners,boxrule=0pt, colback=gray10,frame hidden,borderline west={2pt}{0pt}{blue60}, left=10pt,right=8pt,top=5pt,bottom=3pt,before skip=8pt,after skip=10pt} \newcommand{\code}[1]{\leavevmode{\plexmono\color{gray80}#1}} % ---- lists: small blue squares \usepackage{enumitem} \setlist{itemsep=3pt,topsep=4pt,parsep=0pt,leftmargin=1.4em} \setlist[itemize]{label={\color{blue60}\rule[0.22em]{0.38em}{0.38em}}} \setlist[enumerate]{label={\plexmono\color{blue60}0\arabic*}, leftmargin=2em} % ---- headings \setkomafont{disposition}{\normalfont\color{gray100}} \setkomafont{section}{\plexmed\large} \RedeclareSectionCommand[beforeskip=-1.6\baselineskip,afterskip=0.35\baselineskip]{section} \RedeclareSectionCommand[beforeskip=0pt,afterskip=2.2\baselineskip]{chapter} \renewcommand*{\chapterformat}{\thechapter} \renewcommand*{\chapterlinesformat}[3]{% \parbox[b]{\linewidth}{% {\plexmonolabel\scriptsize\color{blue60}% \ifx\relax#2\relax BASYS 3 RISC-V BASIC\else SECTION\ #2\fi\par} \vspace{3mm}{\color{gray100}\rule{\linewidth}{0.8pt}}\par\vspace{9mm} \begin{minipage}[t]{0.17\linewidth} {\plexthin\fontsize{40}{40}\selectfont\color{blue60}#2} \end{minipage}% \begin{minipage}[t]{0.83\linewidth} {\plexlight\fontsize{30}{34}\selectfont\color{gray100}#3\par} \end{minipage}}} % ---- running heads: mono caps, quiet \usepackage[automark]{scrlayer-scrpage} \clearpairofpagestyles \renewcommand*{\chaptermarkformat}{\thechapter\enskip/\enskip} \ihead{\plexmonolabel\fontsize{6.5}{8}\selectfont\color{gray50}BASYS 3 RISC-V BASIC} \ohead{\plexmonolabel\fontsize{6.5}{8}\selectfont\color{gray50}\MakeUppercase{\leftmark}} \ofoot*{\plexmono\footnotesize\color{gray100}\thepage} \ifoot*{\color{blue60}\rule[0.2em]{6mm}{1.2pt}} \setkomafont{pageheadfoot}{\normalfont} \setkomafont{pagenumber}{\normalfont} % ---- contents \DeclareTOCStyleEntry[beforeskip=1.1em,entryformat=\plexmed,pagenumberformat=\plexmono, linefill=\hfill,numwidth=2.4em,entrynumberformat=\tocnum]{tocline}{chapter} \DeclareTOCStyleEntry[indent=2.4em,numwidth=0pt,linefill=\hfill, entryformat=\color{gray70},pagenumberformat=\plexmono\color{gray70}]{tocline}{section} \newcommand{\tocnum}[1]{{\plexmono\color{blue60}#1}} \usepackage[hidelinks,unicode]{hyperref} \usepackage{bookmark} \raggedbottom \widowpenalty=10000\clubpenalty=10000 """ TITLE = r"""\hypersetup{pdftitle={%(title)s}} \begin{document} \begin{titlepage} \begin{tikzpicture}[remember picture,overlay] \fill[gray100] (current page.south west) rectangle (current page.north east); \begin{scope}[shift={(current page.south west)}] \foreach \x in {0,1,...,21} \draw[gray90,line width=0.3pt] (\x,0) -- (\x,29.7); \foreach \y in {0,1,...,29} \draw[gray90,line width=0.3pt] (0,\y) -- (21,\y); \fill[blue60] (2,21) rectangle (3,22); \draw[gray80,line width=0.4pt] (2,6) -- (19,6); \node[anchor=north west,inner sep=0,text width=16cm] at (2,20.2) {\plexlight\fontsize{46}{50}\selectfont\color{white}%(titlewords)s}; \node[anchor=north west,inner sep=0,text width=14cm] at (2,15.7) {\plexlight\large\color{gray30}%(subtitle)s}; \node[anchor=north west,inner sep=0] at (2,24.6) {\plexmonolabel\scriptsize\color{blue60}REFERENCE MANUAL}; \node[anchor=north west,inner sep=0,text width=17cm] at (2,5.3) {\plexmonolabel\scriptsize\color{gray50}RV32IMF\quad/\quad 100 MHZ\quad/\quad VT220\quad/\quad 320\texttimes240 \& 640\texttimes480\quad/\quad DIGILENT BASYS 3}; \node[anchor=north west,inner sep=0] at (2,3.6) {\plexmono\footnotesize\color{gray30}barant.com/opensource/basys3}; \node[anchor=north west,inner sep=0] at (2,3.0) {\plexmono\footnotesize\color{gray50}git.barant.com/barant/Basys3RiscV}; \end{scope} \end{tikzpicture} \end{titlepage} \pagenumbering{roman} \tableofcontents \cleardoublepage \pagenumbering{arabic} """ def main(src, dst): md = open(src, encoding="utf-8").read() # Code fences indented inside a list item: python-markdown would turn # them into inline code, so take them out and put a marker in their place. codeblocks = [] def take(m): indent = m.group(1) body = "\n".join(l[len(indent):] if l.startswith(indent) else l for l in m.group(2).split("\n")) codeblocks.append(body) return "%s@@CODE%d@@" % (indent, len(codeblocks) - 1) md = re.sub(r"^( +)```[^\n]*\n(.*?)\n\1```[ \t]*$", take, md, flags=re.S | re.M) htm = markdown.markdown(md, extensions=["tables", "fenced_code"]) tb = TreeBuilder() tb.feed(htm) title, subtitle, body = Converter(codeblocks).convert(tb.root) with open(dst, "w", encoding="utf-8") as f: f.write(PREAMBLE) f.write(TITLE % {"title": esc(title), "subtitle": subtitle, "titlewords": " ".join(r"\mbox{%s}" % esc(w) for w in title.split())}) f.write(body) f.write("\n\\end{document}\n") if __name__ == "__main__": main(sys.argv[1], sys.argv[2])