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 testNumber(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, this will only parse the `1` s.input('100') arg = s.readArgument(type='number') assert arg == count(1), arg # Literal number s.input('{100}') arg = s.readArgument(type='number') assert arg == count(100), arg # Set by other number s.input(r'\mycount') arg = s.readArgument(type='number') assert arg == count(120), arg # Set by other number s.input(r'{\mycount}') arg = s.readArgument(type='number') assert arg == count(120), arg # Multiply by other number s.input(r'{5\mycount}') arg = s.readArgument(type='number') assert arg == count(600), arg # No number s.input('{a}') arg = s.readArgument(type='number') assert arg == count(0), arg # No number s.input('b') arg = s.readArgument(type='number') assert arg == count(0), arg # Coerced dimen s.input(r'{\mydimen}') arg = s.readArgument(type='number') assert arg == count(12), arg # Coerced glue s.input(r'{\myglue}') arg = s.readArgument(type='number') assert arg == count(10), 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 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 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 runPlastex(self, item): if not item.course.args.veryverbose: plasTeX.Logging.disableLogging() logger.debug("PlasTeX: " + str(item.source)) root_dir = self.get_root_dir() outPath = item.temp_path() outPaux = self.temp_path().resolve() inPath = root_dir / item.source wd = os.getcwd() plastex_config['files']['filename'] = item.plastex_filename_rules plastex_config['files']['split-level'] = item.splitlevel plastex_config['general']['renderer'] = 'chirun' plastex_config['document']['base-url'] = self.get_web_root() plastex_config['images']['vector-imager'] = 'none' plastex_config['images']['imager'] = 'none' self.document = TeXDocument(config=plastex_config) self.document.userdata['working-dir'] = '.' self.document.context.importMacros(vars(overrides)) f = open(str(Path(wd) / inPath)) TeX.processIfContent = _processIfContent tex = TeX(self.document, myfile=f) self.document.userdata['jobname'] = tex.jobname pauxname = os.path.join( self.document.userdata.get('working-dir', '.'), '%s.paux' % self.document.userdata.get('jobname', '')) for fname in glob.glob(str(outPaux / '*.paux')): if os.path.basename(fname) == pauxname: continue self.document.context.restore(fname, 'chirun') sys.excepthook = PlastexRunner.exception_handler tex.parse() f.close() os.chdir(str(outPath)) self.renderer = Renderer() self.renderer.loadTemplates(self.document) self.renderer.importDirectory( str(Path(wd) / self.theme.source / 'plastex')) self.renderer.vectorImager = VectorImager( self.document, self.renderer.vectorImageTypes) self.renderer.imager = Imager(self.document, self.renderer.imageTypes) self.renderer.render(self.document) os.chdir(wd) original_paux_path = item.temp_path() / item.base_file.with_suffix( '.paux') collated_paux_path = self.temp_path() / ( str(item.out_path).replace('/', '-') + '.paux') shutil.copyfile(str(original_paux_path), str(collated_paux_path))
def testListTypes(self): s = TeX() s.input(r'''\newcount\mycount\mycount=120 \newdimen\mydimen\mydimen=12sp \newskip\myglue\myglue=10sp plus1pt minus2pt''') s.parse() s.input(r'{1, \mycount, 3}') arg = s.readArgument(type='list', subtype='int') assert arg == [1, 120, 3], arg
def testDictTypes(self): s = TeX() s.input(r'''\newcount\mycount\mycount=120 \newdimen\mydimen\mydimen=12sp \newskip\myglue\myglue=10sp plus1pt minus2pt''') s.parse() s.input(r'{one=1, two={\mycount} , three={3}}') arg = s.readArgument(type='dict', expanded=True) keys = list(arg.keys()) keys.sort() assert keys == ['one', 'three', 'two']
def test_builtin_packages(): doc = TeXDocument() tex = TeX(doc) tex.input(r""" \documentclass{article} \usepackage{float} \begin{document} \floatstyle{ruled} \end{document} """) tex.parse() assert doc.getElementsByTagName('floatstyle')
def runPlastex(self, item): logger.debug("PlasTeX: " + str(item.source)) root_dir = self.get_root_dir() outPath = item.temp_path() outPaux = self.temp_path().resolve() inPath = root_dir / item.source wd = os.getcwd() plastex_config['files']['filename'] = item.out_file rname = plastex_config['general']['renderer'] = 'makecourse' plastex_config['document']['base-url'] = self.get_web_root() document = TeXDocument(config=plastex_config) document.userdata['working-dir'] = '.' tikzPath = self.config.get('tikz_template') if tikzPath: logger.debug('Using tikz template: ' + tikzPath) document.userdata['tikz-template'] = tikzPath document.context.importMacros(vars(macros)) document.context.importMacros(vars(overrides)) f = open(str(Path(wd) / inPath)) tex = TeX(document, myfile=f) document.userdata['jobname'] = tex.jobname pauxname = os.path.join( document.userdata.get('working-dir', '.'), '%s.paux' % document.userdata.get('jobname', '')) for fname in glob.glob(str(outPaux / '*.paux')): if os.path.basename(fname) == pauxname: continue document.context.restore(fname, 'makecourse') sys.excepthook = PlastexRunner.exception_handler tex.parse() f.close() os.chdir(str(outPath)) renderer = Renderer() renderer.loadTemplates(document) renderer.importDirectory(str(Path(wd) / self.theme.source / 'plastex')) renderer.render(document) os.chdir(wd) original_paux_path = item.temp_path() / item.base_file.with_suffix( '.paux') collated_paux_path = self.temp_path() / ( str(item.out_path).replace('/', '-') + '.paux') shutil.copyfile(str(original_paux_path), str(collated_paux_path))
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 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 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 testDisplayMath(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) # \begin{displaymath} ... \end{displaymath} is transformed # into \[ ...\] input2 = r'a \begin{displaymath} x^{y_3} \end{displaymath}b' s = TeX() s.input(input2) output = s.parse() source = normalize(output.source) assert input == source, '"%s" != "%s"' % (input, source)
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)
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_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 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 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 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 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 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 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_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 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̧'
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 testDisplayMath(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)) # \begin{displaymath} ... \end{displaymath} is transformed # into \[ ...\] tex_input2 = r'a \begin{displaymath} x^{y_3} \end{displaymath}b' s = TeX() s.input(tex_input2) output = s.parse() source = normalize(output.source) assert_that(source, is_(tex_input))
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 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 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 testDisplayMath(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)) # \begin{displaymath} ... \end{displaymath} is transformed # into \[ ...\] tex_input2 = r'a \begin{displaymath} x^{y_3} \end{displaymath}b' s = TeX() s.input(tex_input2) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input))
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 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 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 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 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 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 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 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 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()
def parseLaTeX(string): # PlasTeX bug - this variable doent get reinitialised MathShift.inEnv = [] # Instantiate a TeX processor and parse the input text tex = TeX() tex.disableLogging() # Parse the LaTeX tex.input(string) return tex.parse()
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] __traceback_info__ = one.__dict__ assert_that( one, has_property( 'id', 'one' ) ) __traceback_info__ = two.__dict__ assert_that( two, has_property( 'id', 'two' ) )
class Epub(object): ''' simple class to initialize with the name of a tex document. controls plastex command-line-type options through config dict. parse method parses and renders the doc resulting in *.epub file ''' def __init__(self, name): self.name = name self.filename = '%s.tex' % name self.config = config self.config['general']['renderer'] = 'Epub' self.config['general']['theme'] = 'default' def parse(self): self.doc = plasTeX.TeXDocument(config=self.config) self.tex = TeX(self.doc, file=self.filename) self.tex.parse() renderer = EpubRenderer() renderer.chapterName = self.name renderer.render(self.doc)
def testList(self): tex_input = r'\begin{enumerate} \item one \item two \item three \end{enumerate}' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input)) tex_input = r'\item one' item = output[0].firstChild source = normalize(item.source) assert_that( source, is_(tex_input))
def testSection(self): tex_input = r'\section{Heading 1} foo one \subsection{Heading 2} bar two' s = TeX() s.input(tex_input) output = s.parse() source = normalize(output.source) assert_that( source, is_(tex_input)) tex_input = r'\subsection{Heading 2} bar two' item = output[0].lastChild source = normalize(item.source)
def testList(self): input = r'\begin{enumerate} \item one \item two \item three \end{enumerate}' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input == source, '"%s" != "%s"' % (input, source) input = r'\item one' item = output[0].firstChild source = normalize(item.source) assert input == source, '"%s" != "%s"' % (input, source)
def testSection(self): input = r'\section{Heading 1} foo one \subsection{Heading 2} bar two' s = TeX() s.input(input) output = s.parse() source = normalize(output.source) assert input == source, '"%s" != "%s"' % (input, source) input = r'\subsection{Heading 2} bar two' item = output[0].lastChild source = normalize(item.source) assert input == source, '"%s" != "%s"' % (input, source)