def add_color_macros(tex: str, after_macros: Optional[str] = None) -> str: documentclass_extractor = DocumentclassExtractor() documentclass = documentclass_extractor.parse(tex) if documentclass is not None: begin_document_extractor = BeginDocumentExtractor() begin_document = begin_document_extractor.parse(tex) if begin_document is not None: return ( tex[: begin_document.start] + "\n" + COLOR_MACROS_BASE_MACROS + "\n" + COLOR_MACROS_LATEX_IMPORTS + "\n" + tex[begin_document.start : begin_document.end] + "\n" # These main color macros should be included *after* "\begin{document}". This is # because AutoTeX will sometimes add a "\RequirePackage{hyperref}" statement right # before "\begin{document}" in the moments before compiling the TeX. If we instead # put the color macros are put above "\begin{document}", what happens is that # hyperref reverts the hyperref macros that we had redefined to enable coloring. + COLOR_MACROS + ("\n" + after_macros if after_macros else "") + tex[begin_document.end :] ) return ( TEX_COLOR_MACROS + ("\n" + after_macros if after_macros else "") + "\n\n" + tex )
def test_extract_begindocument(): extractor = BeginDocumentExtractor() tex = "\\RequirePackage[hyperindex]{hyperref}\n\\begin{document}" begindocument = extractor.parse(tex) assert begindocument.start == 38 assert begindocument.end == 54