"""Turn the thesis LaTeX into a pandoc-friendly single file with resolved numbering.""" import re, sys, os ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) DX = os.path.dirname(os.path.abspath(__file__)) aux = open(f"{DX}/aux/thesis.aux").read() LBL = {m.group(1): m.group(2) for m in re.finditer(r"\\newlabel\{([^}@]+)\}\{\{([^}]*)\}", aux)} KIND = {"ch": ("Chapter", "Chapters"), "sec": ("Section", "Sections"), "fig": ("Figure", "Figures"), "tab": ("Table", "Tables"), "eq": ("Eq.", "Eqs."), "alg": ("Algorithm", "Algorithms"), "lst": ("Listing", "Listings"), "def": ("Definition", "Definitions"), "thm": ("Theorem", "Theorems"), "prop": ("Proposition", "Propositions"), "app": ("Appendix", "Appendices")} def num(label): n = LBL[label] return f"({n})" if label.startswith("eq:") else n def cref(m): labels = [l.strip() for l in m.group(2).split(",")] kinds = {l.split(":")[0] for l in labels} if len(kinds) == 1: k = KIND[labels[0].split(":")[0]] nums = [num(l) for l in labels] name = k[0] if len(nums) == 1 else k[1] return name + "\u00a0" + (nums[0] if len(nums) == 1 else ", ".join(nums[:-1]) + " and " + nums[-1]) return " and ".join(KIND[l.split(":")[0]][0] + "\u00a0" + num(l) for l in labels) def resolve_refs(s): s = re.sub(r"\\([cC])ref\{([^}]*)\}", cref, s) s = re.sub(r"\\ref\{([^}]*)\}", lambda m: LBL[m.group(1)], s) return s def snippet_source(): """Preamble + tikz/algorithm snippets with refs resolved (for image rendering).""" pre = open(f"{ROOT}/thesis.tex").read() pre = pre[:pre.index(r"\begin{document}")] body = [r"\pagestyle{empty}"] for ch in ["04_problem", "05_method", "06_implementation"]: s = open(f"{ROOT}/chapters/{ch}.tex").read() for m in re.finditer(r"(\\resizebox\{\\textwidth\}\{!\}\{)?\\begin\{tikzpicture\}.*?\\end\{tikzpicture\}\}?" r"|\\begin\{algorithm\}\[t\].*?\\end\{algorithm\}", s, re.S): sn = resolve_refs(m.group(0)) if sn.startswith(r"\begin{algorithm}"): sn = sn.replace(r"\begin{algorithm}[t]", r"\begin{algorithm}[H]") body.append(r"\begin{minipage}{\textwidth}" + sn + r"\end{minipage}\clearpage") else: body.append(r"\begin{center}" + sn + r"\end{center}\clearpage") return pre + "\\begin{document}\n" + "\n".join(body) + "\n\\end{document}\n" # ------------------------------------------------------------------ main document TIKZ = iter(["fig_placements", "fig_typegraph", "fig_architecture"]) ALG = iter(["alg1", "alg2", "alg3"]) def read_all(): main = open(f"{ROOT}/thesis.tex").read() order = re.findall(r"\\input\{(chapters/[^}]+)\}", main) parts = [] for p in order: if p.endswith("09_appendix"): parts.append("\\APPENDIX\n") parts.append(open(f"{ROOT}/{p}.tex").read()) return "\n".join(parts) def inline_tables(s): def rep(m): return open(f"{ROOT}/{m.group(1)}").read() return re.sub(r"\\csname @@input\\endcsname (tables/\S+\.tex)", rep, s) def strip_comments(s): return re.sub(r"(?