def testStringCommand(self): class figurename(Command): unicode = 'Figure' s = TeX() s.input(r'\figurename') s.ownerDocument.context['figurename'] = figurename output = [x for x in s] assert output[0].unicode == 'Figure', output
def testNewcommand(self): s = TeX() s.input(r'\newcommand\mycommand[2][optional]{\itshape{#1:#2}}\newcommand{ \foo }{{this is foo}}\mycommand[hi]{{\foo}!!!}') res = [x for x in s] text = [x for x in res if x.nodeType == Node.TEXT_NODE] expected = list('hi:this is foo!!!') assert text == expected, '%s != %s' % (text, expected)
def testLocalCatCodes(self): """ Make sure that category codes are local """ class code(Macro): args = 'self:nox' def parse(self, tex): self.ownerDocument.context.catcode('#',11) self.ownerDocument.context.catcode('&',11) self.ownerDocument.context.catcode('^',11) self.ownerDocument.context.catcode('_',11) self.ownerDocument.context.catcode('$',11) return Macro.parse(self, tex) s = TeX() s.input('\code{this # is $ some & nasty _ text}&_2') s.ownerDocument.context['code'] = code tokens = [x for x in s] tok = type(tokens[0]) cs = type(s.ownerDocument.createElement('code')) assert tok is cs, '"%s" != "%s"' % (tok, cs) assert not [x.catcode for x in tokens[0].attributes['self'] if x.catcode not in [10,11]], \ 'All codes should be 10 or 11: %s' % [x.code for x in tokens[0]] tok = type(tokens[-3]) cs = type(s.ownerDocument.createElement('active::&')) assert tok is cs, '"%s" != "%s"' % (tok, cs)
def testTabular(self): tex_input = r'\begin{tabular}{lll} \hline a & b & c \\[0.4in] 1 & 2 & 3 \end{tabular}' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that(source, is_(tex_input))
def testMath(self): tex_input = r'a $ x^{y_3} $ b' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that(source, is_(tex_input))
def testParentage(self): class myenv(Environment): pass class foo(Command): args = 'self' s = TeX() s.ownerDocument.context.importMacros(locals()) s.input(r'\begin{myenv}\foo{TEST}\end{myenv}') output = s.parse() myenv = output[0] assert myenv.nodeName == 'myenv', myenv.nodeName foo = output[0][0] assert foo.nodeName == 'foo', foo.nodeName children = output[0][0].childNodes fooself = output[0][0].attributes['self'] assert children is fooself # Check parents assert fooself[0].parentNode is fooself, fooself[0].parentNode assert foo.parentNode is myenv, foo.parentNode assert myenv.parentNode is output, myenv.parentNode assert output.parentNode is None, output.parentNode # Check owner document assert fooself[0].ownerDocument is output assert foo.ownerDocument is output assert myenv.ownerDocument is output assert output.ownerDocument is output
def testTokenArgument(self): s = TeX() s.input(r'\foo a ') arg = s.readArgument(type='Tok') assert arg == 'foo' arg = s.readArgument(type='Tok') assert arg == 'a'
def testTeXDimen(self): s = TeX() s.input(r'''\newcount\mycount\mycount=120 \newdimen\mydimen\mydimen=12sp \newskip\myglue\myglue=10sp plus1pt minus2pt''') s.parse() value = s.ownerDocument.context['mycount'].value assert value == count(120), value value = s.ownerDocument.context['mydimen'].value assert value == dimen('12sp'), value value = s.ownerDocument.context['myglue'].value assert value == glue('10sp', plus='1pt', minus='2pt'), value # Literal dimension s.input(r'3.5pt') arg = s.readArgument(type='Dimen') assert arg == dimen('3.5pt'), arg # Literal dimension, {...} aren't allowed s.input(r'{3.5pt}') arg = s.readArgument(type='Dimen') assert arg == dimen(0), arg # Set by other dimension s.input(r'\mydimen') arg = s.readArgument(type='Dimen') assert arg == dimen('12sp'), arg # Set by count s.input(r'\mycount') arg = s.readArgument(type='Dimen') assert arg == dimen('120sp'), arg assert ParameterCommand._enablelevel == 0
def testTeXNumber(self): s = TeX() s.input(r'''\newcount\mycount\mycount=120 \newdimen\mydimen\mydimen=12sp \newskip\myglue\myglue=10sp plus1pt minus2pt''') s.parse() value = s.ownerDocument.context['mycount'].value assert value == count(120), value value = s.ownerDocument.context['mydimen'].value assert value == dimen('12sp'), value value = s.ownerDocument.context['myglue'].value assert value == glue('10sp', plus='1pt', minus='2pt'), value # Literal number s.input('100') arg = s.readArgument(type='Number') assert arg == count('100'), arg # Set by other dimen s.input(r'\mycount') arg = s.readArgument(type='Number') assert arg == count('120'), arg # Multiply by other dimen s.input(r'3\mycount') arg = s.readArgument(type='Number') assert arg == count('360'), arg # No number s.input('{0}') arg = s.readArgument(type='Number') assert arg == count(0), arg assert ParameterCommand._enablelevel == 0
def testTabular(self): input = r'\begin{tabular}{lll} \hline a & b & c \\[0.4in] 1 & 2 & 3 \end{tabular}' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input == source, '"%s" != "%s"' % (input, source)
def testTeXDimen2(self): s = TeX() s.input(r'''\newcount\mycount\mycount=120 \newdimen\mydimen\mydimen=12sp \newskip\myglue\myglue=10sp plus1pt minus2pt''') s.parse() value = s.ownerDocument.context['mycount'].value assert value == count(120), value value = s.ownerDocument.context['mydimen'].value assert value == dimen('12sp'), value value = s.ownerDocument.context['myglue'].value assert value == glue('10sp', plus='1pt', minus='2pt'), value # Literal dimension s.input(r'3.5pt') arg = s.readArgument(type='Dimen') assert arg == dimen('3.5pt'), arg # Literal dimension, {...} aren't allowed s.input(r'{3.5pt}') arg = s.readArgument(type='Dimen') assert arg == dimen(0), arg # Set by other dimension s.input(r'\mydimen') arg = s.readArgument(type='Dimen') assert arg == dimen('12sp'), arg # Set by count s.input(r'\mycount') arg = s.readArgument(type='Dimen') assert arg == dimen('120sp'), arg assert ParameterCommand._enablelevel == 0
def parse_documentation_source(language): # Instantiate a TeX processor and parse the input text tex = TeX() tex.ownerDocument.config['files']['split-level'] = 0 #tex.ownerDocument.config['files']['filename'] = 'cxcore.rst' for f in ['CxCore', 'CvReference', 'HighGui']: preprocess_conditionals(f, '-' + language, {'C':language=='c', 'Python':language=='py', 'plastex':True}) if 1: tex.input("\\input{online-opencv-%s.tex}" % language) else: src0 = r''' \documentclass{book} \usepackage{myopencv} \begin{document}''' src1 = r''' \end{document} ''' lines = list(open("../CvReference.tex")) LINES = 80 tex.input(src0 + "".join(lines[:LINES]) + src1) return tex.parse()
def test_plugin_packages(tmpdir): tmpdir = Path(str(tmpdir)) (tmpdir/'my_plugin'/'Packages').mkdir(parents=True) (tmpdir/'my_plugin'/'__init__.py').touch() (tmpdir/'my_plugin'/'Packages'/'mypkg.py').write_text( r""" from plasTeX import Command class mycmd(Command): my_var = 'ok' """) sys.path.append(str(tmpdir)) doc = TeXDocument() doc.config['general'].data['plugins'].value = ['my_plugin'] tex = TeX(doc) tex.input(r""" \documentclass{article} \usepackage{mypkg} \begin{document} \mycmd \end{document} """) tex.parse() sys.path.pop() assert doc.getElementsByTagName('mycmd') node = doc.getElementsByTagName('mycmd')[0] assert node.my_var == 'ok'
def test_packages_dirs(tmpdir): tmpdir = Path(str(tmpdir)) (tmpdir / "mypkg.py").write_text( r""" from plasTeX import Command class mycmd(Command): my_var = 'ok' """) doc = TeXDocument() doc.config['general'].data['packages-dirs'].value = [str(tmpdir)] tex = TeX(doc) tex.input(r""" \documentclass{article} \usepackage{mypkg} \begin{document} \mycmd \end{document} """) tex.parse() assert doc.getElementsByTagName('mycmd') node = doc.getElementsByTagName('mycmd')[0] assert node.my_var == 'ok'
def testMath(self): tex_input = r'a $ x^{y_3} $ b' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input))
def test_proof_block_type(): """ Check proof environment ends up inside a blockType paragraph. This in particular makes HTML5 not wrap the resulting object in <p></p> tags. """ tex = TeX() tex.input(r''' \documentclass{article} \begin{document} a \begin{proof} b \end{proof} c \end{document} ''') doc = tex.parse() proof = doc.getElementsByTagName('proof')[0] if not proof.parentNode.blockType: print(doc.toXML()) assert False
def testLabelStar(self): s = TeX() s.input(r'\section{hi} text \section*{bye\label{two}}') output = s.parse() assert_that(output, has_length(2)) section = output[0] section_star = output[1] __traceback_info__ = (section, section.__dict__, section_star, section_star.__dict__, dict(type(section).__dict__)) assert_that( section, has_property( 'arguments', has_item( all_of(has_property('index', 0), has_property('name', '*modifier*'))))) assert_that(section, has_property('source', '\\section{hi} text \n\n')) assert_that(section, has_property('id', 'two')) assert_that(section, has_property('argSource', '{hi}')) assert_that(section_star, has_property('source', '\\section*{bye\\label{two}}')) assert_that(section_star, has_property('argSource', '*{bye\\label{two}}')) assert_that(section_star, has_property('id', is_not('two'))) assert_that(dict(section_star.__dict__), has_entry('@hasgenid', True))
def testMath(self): input = r'a $ x^{y_3} $ b' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input == source, '"%s" != "%s"' % (input, source)
def parse_documentation_source(language): # Instantiate a TeX processor and parse the input text tex = TeX() tex.ownerDocument.config["files"]["split-level"] = 0 master_f = open("../online-opencv.tex", "rt") out_master_f = open(("../online-opencv-%s.tex" % language), "wt") flist = [] for l in master_f.readlines(): outl = l if l.startswith("\\newcommand{\\targetlang}{}"): outl = l.replace("}", ("%s}" % language)) elif l.startswith("\\input{"): flist.append(re.findall(r"\{(.+)\}", l)[0]) outl = l.replace("}", ("-%s}" % language)) out_master_f.write(outl) master_f.close() out_master_f.close() index_f = open("index.rst.copy", "rt") index_lines = list(index_f.readlines()) index_f.close() out_index_f = open("index.rst", "wt") header_line = "OpenCV |version| %s Reference" % {"py": "Python", "c": "C", "cpp": "C++"}[language] index_lines = [header_line + "\n", "=" * len(header_line) + "\n", "\n"] + index_lines for l in index_lines: out_index_f.write(l) out_index_f.close() for f in flist: preprocess_conditionals( f, "-" + language, { "C": language == "c", "Python": language == "py", "Py": language == "py", "CPy": (language == "py" or language == "c"), "Cpp": language == "cpp", "plastex": True, }, ) if 1: tex.input("\\input{online-opencv-%s.tex}" % language) else: src0 = r""" \documentclass{book} \usepackage{myopencv} \begin{document}""" src1 = r""" \end{document} """ lines = list(open("../CvReference.tex")) LINES = 80 tex.input(src0 + "".join(lines[:LINES]) + src1) return tex.parse()
def test_combining(): input_data = r'\c{o}' tex = TeX() tex.input(input_data) node = tex.parse()[0] assert node.source == input_data assert node.str == 'o̧'
class WordPressLatexPost(WordPressPost): """Encapsulate a LaTeX Post to Wordpress """ def __init__(self, latex): """ Arguments: - `latex`: """ WordPressPost.__init__(self) self._tex = TeX() self._renderer = WPRenderer() self._tex.input(latex) self._document = self._tex.parse() # Before rendering, let's pass through and extract the images self.images = findImageNodes(self._document) def render(self): """Render this post """ # Have to encode the unicode string to print it correctly. self.description = self._renderer.render(self._document).encode('utf-8') self.title = self._document.userdata['title'].textContent.encode('utf-8') self.tags = self._document.userdata['tags'].textContent.encode('utf-8')
def test_empty_accent(): input_data = r'\~{}' tex = TeX() tex.input(input_data) node = tex.parse()[0] assert node.source == input_data assert node.str == '~'
def test_package_resource(tmpdir): config = defaultConfig() config['general'].data['packages-dirs'].value = [ str(Path(__file__).parent) ] addConfig(config) doc = TeXDocument(config=config) tex = TeX(doc) tex.input(""" \\documentclass{article} \\usepackage{examplePackage} \\begin{document} \\emph{Hello} \\end{document}""") doc = tex.parse() doc.userdata['working-dir'] = os.path.dirname(__file__) with tmpdir.as_cwd(): Renderer().render(doc) assert tmpdir.join('styles', 'test.css').isfile() assert tmpdir.join('js', 'test.js').isfile() assert 'class="em"' in tmpdir.join('index.html').read() assert doc.userdata['testing'] == 'test'
def testLocalCatCodes(self): """ Make sure that category codes are local """ class code(Macro): args = 'self:nox' def parse(self, tex): self.ownerDocument.context.catcode('#', 11) self.ownerDocument.context.catcode('&', 11) self.ownerDocument.context.catcode('^', 11) self.ownerDocument.context.catcode('_', 11) self.ownerDocument.context.catcode('$', 11) return Macro.parse(self, tex) s = TeX() s.input(r'\code{this # is $ some & nasty _ text}&_2') s.ownerDocument.context['code'] = code tokens = [x for x in s] tok = type(tokens[0]) cs = type(s.ownerDocument.createElement('code')) assert tok is cs, '"%s" != "%s"' % (tok, cs) assert not [x.catcode for x in tokens[0].attributes['self'] if x.catcode not in [10,11]], \ 'All codes should be 10 or 11: %s' % [x.code for x in tokens[0]] tok = type(tokens[-3]) cs = type(s.ownerDocument.createElement('active::&')) assert tok is cs, '"%s" != "%s"' % (tok, cs)
def test_cleveref(): tex = TeX() tex.input(r''' \documentclass{article} \usepackage{cleveref} \newtheorem{thm}{TheoRem} \begin{document} \section{Foo}\label{sec} \begin{figure} \caption{Test} \label{fig} \end{figure} \subsection{Bar}\label{subsec} \begin{thm} \label{thm} \end{thm} \begin{equation} x = y\label{eq} \end{equation} \Cref{sec}\Cref{fig}\Cref{subsec}\Cref{thm}\Cref{eq}\Cref{missing} \cref{sec}\cref{fig}\cref{subsec}\cref{thm}\cref{eq}\cref{missing} \end{document} ''') p = tex.parse() assert ["Section", "Figure", "Section", "TheoRem", "Equation", ""] == [x.refname() for x in p.getElementsByTagName("Cref")] assert ["section", "figure", "section", "theoRem", "eq.", ""] == [x.refname() for x in p.getElementsByTagName("cref")]
def test_middle_combining(): input_data = r'\t{op}' tex = TeX() tex.input(input_data) node = tex.parse()[0] assert node.source == input_data assert node.str == 'o͡p'
def testTabular(self): tex_input = r'\begin{tabular}{lll} \hline a & b & c \\[0.4in] 1 & 2 & 3 \end{tabular}' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input))
def testEquation(self): tex_input = r'\sqrt{\pi ^{3}}' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input))
def testIfDim(self): s = TeX() s.input( r'\ifdim -5 pt > 2in bye\else text\fi\ifdim 2mm = 2 mm one\else two\fi' ) output = ''.join([x for x in s]).strip() expected = 'textone' assert output == expected, '"%s" != "%s"' % (output, expected)
def testLabelStar(self): s = TeX() s.input(r'\section{hi} text \section*{bye\label{two}}') output = s.parse() one = output[0] two = output[-1] assert one.id == 'two', one.id assert two.id != 'two', two.id
def testXYMatrix3(self): input = r'\xymatrix{A \ar[r]^u_d \ar[rd]^u_d &B \ar[d]^u_d &C \ar[l]^u_d \ar[ld]^u_d\\&D}' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input.replace(" ", "") == source.replace( " ", ""), '"%s" != "%s"' % (input, source)
def testXYMatrix(self): input = r'\xymatrix{A \ar[d]^b \ar[r]^a &B\ar[d]^c\\ C \ar[r]^d &D}' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input.replace(" ", "") == source.replace( " ", ""), '"%s" != "%s"' % (input, source)
def testEquation(self): tex_input = r'\sqrt{\pi ^{3}}' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that(source, is_(tex_input))
def test_numberwithin(): s = TeX() s.input(DOC) output = s.parse() equations = output.getElementsByTagName('equation') assert equations[0].ref.textContent == '1.1' assert equations[1].ref.textContent == '2.1' assert equations[2].ref.textContent == '2.2'
def testDef(self): s = TeX() s.input( r'\def\mymacro#1#2;#3\endmacro{this #1 is #2 my #3 command}\mymacro{one}x;y\endmacro morestuff' ) output = [x for x in s] text = [x for x in output if x.nodeType == Node.TEXT_NODE] assert text == list('this one is x my y commandmorestuff'), text
def testSimpleNewEnvironment(self): s = TeX() s.input(r"\newenvironment{myenv}{\it}{}\begin{myenv}hi\end{myenv}") for key, value in list(self.macros.items()): s.ownerDocument.context[key] = value output = [x for x in s] assert type(output[2]) == s.ownerDocument.context["it"] assert output[-3:-1] == ["h", "i"]
def testXYMatrix2(self): input = r'\xymatrix{A \ar@{->>}[rd] \ar@{^{(}->}[r]&B \ar@{.>}[d]&C \ar@{_{(}->}[l]\ar@{->>}[ld]\\&D}' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input.replace(" ", "") == source.replace( " ", ""), '"%s" != "%s"' % (input, source)
def test_numberwithin(): s = TeX() s.input(DOC) output = s.parse() equations =output.getElementsByTagName('equation') assert equations[0].ref.textContent == '1.1' assert equations[1].ref.textContent == '2.1' assert equations[2].ref.textContent == '2.2'
def testSimpleNewEnvironment(self): s = TeX() s.input(r'\newenvironment{myenv}{\it}{}\begin{myenv}hi\end{myenv}') for key, value in self.macros.items(): s.ownerDocument.context[key] = value output = [x for x in s] assert type(output[2]) == s.ownerDocument.context['it'] assert output[-3:-1] == ['h', 'i']
def testLabel(self): s = TeX() s.input(r'\section{hi\label{one}} text \section{bye\label{two}}') output = s.parse() one = output[0] two = output[-1] assert one.id == 'one', one.id assert two.id == 'two', two.id
def testSimpleNewEnvironment(self): s = TeX() s.input(r'\newenvironment{myenv}{\it}{}\begin{myenv}hi\end{myenv}') for key, value in self.macros.items(): s.ownerDocument.context[key] = value output = [x for x in s] assert type(output[2]) == s.ownerDocument.context['it'] assert output[-3:-1] == ['h','i']
def testDef2(self): s = TeX() s.input(r"\def\row#1{(#1_1,\ldots,#1_n)}\row{{x'}}") output = [x for x in s] text = [x for x in output if x.nodeType == Node.TEXT_NODE] assert text == list("(x'_1,,x'_n)"), text assert output[0].nodeName == "def" assert output[6] == "_" assert output[9].nodeName == "ldots"
def testStringCommand(self): class figurename(Command): unicode = "Figure" s = TeX() s.input(r"\figurename") s.ownerDocument.context["figurename"] = figurename output = [x for x in s] assert output[0].unicode == "Figure", output
def testXTokenArgument(self): s = TeX() s.input(r'\newcommand{\foo}{\it}') [x for x in s] s.input(r'\foo a ') arg = s.readArgument(type='XTok') assert arg.nodeName == 'it', arg.nodeName arg = s.readArgument(type='XTok') assert arg == 'a', arg
def testSimpleNewCommand(self): s = TeX() s.input(r"\newcommand\mycommand{\it}\mycommand") for key, value in list(self.macros.items()): s.ownerDocument.context[key] = value output = [x for x in s] result = type(output[1]) expected = type(s.ownerDocument.createElement("it")) assert result == expected, '"%s" != "%s"' % (result, expected)
def latex2edx(): print "=============================================================================" print "Converting latex to XHTML using PlasTeX with custom edX macros" print "Source file: %s" % myglob.INPUT_TEX_FILENAME print "=============================================================================" # get the input latex file # latex_str = open(fn).read() latex_str = codecs.open(myglob.fn).read() latex_str = latex_str.replace('\r','\n') # convert from mac format for EOL # Instantiate a TeX processor and parse the input text tex = TeX() tex.ownerDocument.config['files']['split-level'] = -100 tex.ownerDocument.config['files']['filename'] = myglob.ofn tex.ownerDocument.config['general']['theme'] = 'plain' tex.input(latex_str) document = tex.parse() renderer = MyRenderer() renderer.imdir = myglob.imdir renderer.imurl = myglob.imurl renderer.imfnset = [] #Here's where the xhtml file myglob.ofn is written myglob.outxhtml.append(myglob.ofn) renderer.render(document) print "\n======================================== IMAGE FILES" print renderer.imfnset or "None" print "========================================" #-------------------- # read XHTML file in and extract course + problems (JMO removed course code) print "=============================================================================" print "Converting XHTML into edX problems" print "=============================================================================" xml = etree.parse(myglob.ofn) process_edXmacros(xml.getroot()) course = xml.find('.//course') # top-level entry for edX course - should only be one chapters = xml.findall('.//chapter') # get all chapters if course is not None: raise Exception("This version of latex2edx does not handle the course tag") if chapters: raise Exception("This version of latex2edx does not handle the chapter tag") for problem in xml.findall('.//problem'): problem_to_file(problem, myglob.problemdir) for html in xml.findall('.//html'): html_to_file(html, myglob.htmldir) return ({'htmlfiles':myglob.outhtml, 'problemfiles':myglob.outproblem, 'xhtmlfiles':myglob.outxhtml})
def testNewCommandWithArgs(self): s = TeX() s.input(r"\newcommand{\mycommand}[2]{#1:#2}\mycommand{foo}{bar}") for key, value in list(self.macros.items()): s.ownerDocument.context[key] = value output = [x for x in s] assert s.ownerDocument.context["mycommand"].definition == list("#1:#2") text = [x for x in output if x.nodeType == Node.TEXT_NODE] assert text == list("foo:bar"), text
def testVerbStar(self): intext = r' verbatim \tt text ' input = r'hi \verb*+%s+ bye' % intext s = TeX() s.input(input) output = s.parse() output.normalize() text = ''.join(output.childNodes[1].childNodes) assert intext == text, '"%s" != "%s"' % (intext, text)
def testVerbatim(self): intext = 'line one\nline two' input = 'hi \\begin{verbatim}\n%s\n\\end{verbatim} bye' % intext s = TeX() s.input(input) output = s.parse() output.normalize() text = ''.join(output.childNodes[1].childNodes).strip() assert intext == text, '"%s" != "%s"' % (intext, text)
def testDef2(self): s = TeX() s.input(r"\def\row#1{(#1_1,\ldots,#1_n)}\row{{x'}}") output = [x for x in s] text = [x for x in output if x.nodeType == Node.TEXT_NODE] assert text == list('(x\'_1,,x\'_n)'), text assert output[0].nodeName == 'def' assert output[6] == '_' assert output[9].nodeName == 'ldots'
def simpleparse(text): """Parse a simple LaTeX string. """ tex = TeX() if not isinstance(text, unicode): text = text.decode("utf-8") tex.input(text) doc = tex.parse() return process_unbr_spaces(doc.textContent)
def execute_mediawiki_parser(config): # data input_path = config["input_path"] output_path = config["output_path"] title = config["title"] collapse_level = int(config["collapse_level"]) # startin process process f = open(input_path, "r") # input text must be utf-8 encoded. text = f.read().decode("utf-8") ###preparser operations # reading theorems # the preparser result is a tuple of (tex, th_dict) pre_export_path = "" if config["print_preparsed_tex"]: pre_export_path = output_path + ".pre" preparser_result = preparse_tex(text, pre_export_path) # saving source after preparsing source = preparser_result[0] # tex object tex = TeX() tex.input(source) # parsing DOM document = tex.parse() # renderer creation rend = MediaWikiRenderer(config) # inserting theorem dictionary in renderer rend.init_theorems(preparser_result[1]) # inserting tikz images source in renderer rend.init_tikz_images(preparser_result[2], preparser_result[3]) # starting rendering rend.render(document) # after rendering work # collapsing pages rend.tree.collapseText(collapse_level) # fixing refs rend.tree.fixReferences() # create index if config["create_index"]: rend.tree.createIndex(collapse_level) # exporting export = rend.tree.exportPages(output_path + ".mw", (config["export_format"], config["username"], config["userid"])) # check if we have to export single pages if config["export_single_pages"]: # writing single pages rend.tree.export_singlePages( config["export_format"], output_path + "_pages", (config["username"], config["userid"]) ) # writing debug info d = open(output_path + ".debug", "w") # used_tags d.write("USED TAGS:\n") for key in sorted(rend.used_tags): d.write(key + ": " + str(rend.used_tags[key]) + "\n") d.close()