Merge pull request #1284 from BuhtigithuB/more-markmin-pep8
More markmin pep8
This commit is contained in:
@@ -7,53 +7,57 @@ import sys
|
|||||||
import doctest
|
import doctest
|
||||||
from optparse import OptionParser
|
from optparse import OptionParser
|
||||||
|
|
||||||
__all__ = ['render','markmin2latex']
|
__all__ = ['render', 'markmin2latex']
|
||||||
|
|
||||||
META = 'META'
|
META = 'META'
|
||||||
regex_newlines = re.compile('(\n\r)|(\r\n)')
|
regex_newlines = re.compile('(\n\r)|(\r\n)')
|
||||||
regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$')
|
regex_dd = re.compile('\$\$(?P<latex>.*?)\$\$')
|
||||||
regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S)
|
regex_code = re.compile('(' + META + ')|(``(?P<t>.*?)``(:(?P<c>\w+))?)', re.S)
|
||||||
regex_title = re.compile('^#{1} (?P<t>[^\n]+)',re.M)
|
regex_title = re.compile('^#{1} (?P<t>[^\n]+)', re.M)
|
||||||
regex_maps = [
|
regex_maps = [
|
||||||
(re.compile('[ \t\r]+\n'),'\n'),
|
(re.compile('[ \t\r]+\n'), '\n'),
|
||||||
(re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'{\\\\bf \g<t>}'),
|
(re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'), '{\\\\bf \g<t>}'),
|
||||||
(re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'{\\it \g<t>}'),
|
(re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"), '{\\it \g<t>}'),
|
||||||
(re.compile('^#{5,6}\s*(?P<t>[^\n]+)',re.M),'\n\n{\\\\bf \g<t>}\n'),
|
(re.compile('^#{5,6}\s*(?P<t>[^\n]+)', re.M), '\n\n{\\\\bf \g<t>}\n'),
|
||||||
(re.compile('^#{4}\s*(?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsubsection{\g<t>}\n'),
|
(re.compile('^#{4}\s*(?P<t>[^\n]+)', re.M), '\n\n\\\\goodbreak\\subsubsection{\g<t>}\n'),
|
||||||
(re.compile('^#{3}\s*(?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsection{\g<t>}\n'),
|
(re.compile('^#{3}\s*(?P<t>[^\n]+)', re.M), '\n\n\\\\goodbreak\\subsection{\g<t>}\n'),
|
||||||
(re.compile('^#{2}\s*(?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\section{\g<t>}\n'),
|
(re.compile('^#{2}\s*(?P<t>[^\n]+)', re.M), '\n\n\\\\goodbreak\\section{\g<t>}\n'),
|
||||||
(re.compile('^#{1}\s*(?P<t>[^\n]+)',re.M),''),
|
(re.compile('^#{1}\s*(?P<t>[^\n]+)', re.M), ''),
|
||||||
(re.compile('^\- +(?P<t>.*)',re.M),'\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'),
|
(re.compile('^\- +(?P<t>.*)', re.M), '\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'),
|
||||||
(re.compile('^\+ +(?P<t>.*)',re.M),'\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'),
|
(re.compile('^\+ +(?P<t>.*)', re.M), '\\\\begin{itemize}\n\\item \g<t>\n\\end{itemize}'),
|
||||||
(re.compile('\\\\end\{itemize\}\s+\\\\begin\{itemize\}'),'\n'),
|
(re.compile('\\\\end\{itemize\}\s+\\\\begin\{itemize\}'), '\n'),
|
||||||
(re.compile('\n\s+\n'),'\n\n')]
|
(re.compile('\n\s+\n'), '\n\n')]
|
||||||
regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n',re.M|re.S)
|
regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n', re.M | re.S)
|
||||||
|
|
||||||
regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]')
|
regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]')
|
||||||
regex_bibitem = re.compile('\-\s*\[\[(?P<t>\S+)\]\]')
|
regex_bibitem = re.compile('\-\s*\[\[(?P<t>\S+)\]\]')
|
||||||
regex_image_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]')
|
regex_image_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]')
|
||||||
regex_image = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]')
|
regex_image = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]')
|
||||||
#regex_video = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +video\]\]')
|
# regex_video = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +video\]\]')
|
||||||
#regex_audio = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +audio\]\]')
|
# regex_audio = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +audio\]\]')
|
||||||
regex_link = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+)\]\]')
|
regex_link = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+)\]\]')
|
||||||
regex_auto = re.compile('(?<!["\w])(?P<k>\w+://[\w\.\-\?&%\:]+)',re.M)
|
regex_auto = re.compile('(?<!["\w])(?P<k>\w+://[\w\.\-\?&%\:]+)', re.M)
|
||||||
regex_commas = re.compile('[ ]+(?P<t>[,;\.])')
|
regex_commas = re.compile('[ ]+(?P<t>[,;\.])')
|
||||||
regex_noindent = re.compile('\n\n(?P<t>[a-z])')
|
regex_noindent = re.compile('\n\n(?P<t>[a-z])')
|
||||||
#regex_quote_left = re.compile('"(?=\w)')
|
|
||||||
#regex_quote_right = re.compile('(?=\w\.)"')
|
|
||||||
|
|
||||||
def latex_escape(text,pound=True):
|
|
||||||
text=text.replace('\\','{\\textbackslash}')
|
# regex_quote_left = re.compile('"(?=\w)')
|
||||||
for c in '^_&$%{}': text=text.replace(c,'\\'+c)
|
# regex_quote_right = re.compile('(?=\w\.)"')
|
||||||
text=text.replace('\\{\\textbackslash\\}','{\\textbackslash}')
|
|
||||||
if pound: text=text.replace('#','\\#')
|
def latex_escape(text, pound=True):
|
||||||
|
text = text.replace('\\', '{\\textbackslash}')
|
||||||
|
for c in '^_&$%{}':
|
||||||
|
text = text.replace(c, '\\' + c)
|
||||||
|
text = text.replace('\\{\\textbackslash\\}', '{\\textbackslash}')
|
||||||
|
if pound: text = text.replace('#', '\\#')
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
def render(text,
|
def render(text,
|
||||||
extra={},
|
extra={},
|
||||||
allowed={},
|
allowed={},
|
||||||
sep='p',
|
sep='p',
|
||||||
image_mapper=lambda x:x,
|
image_mapper=lambda x: x,
|
||||||
chapters=False):
|
chapters=False):
|
||||||
#############################################################
|
#############################################################
|
||||||
# replace all blocks marked with ``...``:class with META
|
# replace all blocks marked with ``...``:class with META
|
||||||
@@ -61,62 +65,68 @@ def render(text,
|
|||||||
#############################################################
|
#############################################################
|
||||||
text = str(text or '')
|
text = str(text or '')
|
||||||
segments, i = [], 0
|
segments, i = [], 0
|
||||||
text = regex_dd.sub('``\g<latex>``:latex ',text)
|
text = regex_dd.sub('``\g<latex>``:latex ', text)
|
||||||
text = regex_newlines.sub('\n',text)
|
text = regex_newlines.sub('\n', text)
|
||||||
while True:
|
while True:
|
||||||
item = regex_code.search(text,i)
|
item = regex_code.search(text, i)
|
||||||
if not item: break
|
if not item:
|
||||||
if item.group()==META:
|
break
|
||||||
segments.append((None,None))
|
if item.group() == META:
|
||||||
text = text[:item.start()]+META+text[item.end():]
|
segments.append((None, None))
|
||||||
|
text = text[:item.start()] + META + text[item.end():]
|
||||||
else:
|
else:
|
||||||
c = item.group('c') or ''
|
c = item.group('c') or ''
|
||||||
if 'code' in allowed and not c in allowed['code']: c = ''
|
if 'code' in allowed and c not in allowed['code']:
|
||||||
code = item.group('t').replace('!`!','`')
|
c = ''
|
||||||
segments.append((code,c))
|
code = item.group('t').replace('!`!', '`')
|
||||||
text = text[:item.start()]+META+text[item.end():]
|
segments.append((code, c))
|
||||||
i=item.start()+3
|
text = text[:item.start()] + META + text[item.end():]
|
||||||
|
i = item.start() + 3
|
||||||
|
|
||||||
#############################################################
|
#############################################################
|
||||||
# do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces
|
# do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces
|
||||||
#############################################################
|
#############################################################
|
||||||
|
|
||||||
title = regex_title.search(text)
|
title = regex_title.search(text)
|
||||||
if not title: title='Title'
|
if not title:
|
||||||
else: title=title.group('t')
|
title = 'Title'
|
||||||
|
else:
|
||||||
|
title = title.group('t')
|
||||||
|
|
||||||
text = latex_escape(text,pound=False)
|
text = latex_escape(text, pound=False)
|
||||||
|
|
||||||
texts = text.split('## References',1)
|
texts = text.split('## References', 1)
|
||||||
text = regex_anchor.sub('\\label{\g<t>}', texts[0])
|
text = regex_anchor.sub('\\label{\g<t>}', texts[0])
|
||||||
if len(texts)==2:
|
if len(texts) == 2:
|
||||||
text += '\n\\begin{thebibliography}{999}\n'
|
text += '\n\\begin{thebibliography}{999}\n'
|
||||||
text += regex_bibitem.sub('\n\\\\bibitem{\g<t>}', texts[1])
|
text += regex_bibitem.sub('\n\\\\bibitem{\g<t>}', texts[1])
|
||||||
text += '\n\\end{thebibliography}\n'
|
text += '\n\\end{thebibliography}\n'
|
||||||
|
|
||||||
text = '\n'.join(t.strip() for t in text.split('\n'))
|
text = '\n'.join(t.strip() for t in text.split('\n'))
|
||||||
for regex, sub in regex_maps:
|
for regex, sub in regex_maps:
|
||||||
text = regex.sub(sub,text)
|
text = regex.sub(sub, text)
|
||||||
text=text.replace('#','\\#')
|
text = text.replace('#', '\\#')
|
||||||
text=text.replace('`',"'")
|
text = text.replace('`', "'")
|
||||||
|
|
||||||
#############################################################
|
#############################################################
|
||||||
# process tables and blockquotes
|
# process tables and blockquotes
|
||||||
#############################################################
|
#############################################################
|
||||||
while True:
|
while True:
|
||||||
item = regex_table.search(text)
|
item = regex_table.search(text)
|
||||||
if not item: break
|
if not item:
|
||||||
|
break
|
||||||
c = item.group('c') or ''
|
c = item.group('c') or ''
|
||||||
if 'table' in allowed and not c in allowed['table']: c = ''
|
if 'table' in allowed and c not in allowed['table']:
|
||||||
|
c = ''
|
||||||
content = item.group('t')
|
content = item.group('t')
|
||||||
if ' | ' in content:
|
if ' | ' in content:
|
||||||
rows = content.replace('\n','\\\\\n').replace(' | ',' & ')
|
rows = content.replace('\n', '\\\\\n').replace(' | ', ' & ')
|
||||||
row0,row2 = rows.split('\\\\\n',1)
|
row0, row2 = rows.split('\\\\\n', 1)
|
||||||
cols=row0.count(' & ')+1
|
cols = row0.count(' & ') + 1
|
||||||
cal='{'+''.join('l' for j in range(cols))+'}'
|
cal = '{' + ''.join('l' for j in range(cols)) + '}'
|
||||||
tabular = '\\begin{center}\n{\\begin{tabular}'+cal+'\\hline\n' + row0+'\\\\ \\hline\n'+row2 + ' \\\\ \\hline\n\\end{tabular}}\n\\end{center}'
|
tabular = '\\begin{center}\n{\\begin{tabular}' + cal + '\\hline\n' + row0 + '\\\\ \\hline\n' + row2 + ' \\\\ \\hline\n\\end{tabular}}\n\\end{center}'
|
||||||
if row2.count('\n')>20: tabular='\\newpage\n'+tabular
|
if row2.count('\n') > 20:
|
||||||
|
tabular = '\\newpage\n' + tabular
|
||||||
text = text[:item.start()] + tabular + text[item.end():]
|
text = text[:item.start()] + tabular + text[item.end():]
|
||||||
else:
|
else:
|
||||||
text = text[:item.start()] + '\\begin{quote}' + content + '\\end{quote}' + text[item.end():]
|
text = text[:item.start()] + '\\begin{quote}' + content + '\\end{quote}' + text[item.end():]
|
||||||
@@ -126,29 +136,32 @@ def render(text,
|
|||||||
#############################################################
|
#############################################################
|
||||||
|
|
||||||
def sub(x):
|
def sub(x):
|
||||||
f=image_mapper(x.group('k'))
|
f = image_mapper(x.group('k'))
|
||||||
if not f: return None
|
if not f:
|
||||||
return '\n\\begin{center}\\includegraphics[width=8cm]{%s}\\end{center}\n' % (f)
|
return None
|
||||||
text = regex_image_width.sub(sub,text)
|
return '\n\\begin{center}\\includegraphics[width=8cm]{%s}\\end{center}\n' % f
|
||||||
text = regex_image.sub(sub,text)
|
|
||||||
|
text = regex_image_width.sub(sub, text)
|
||||||
|
text = regex_image.sub(sub, text)
|
||||||
|
|
||||||
text = regex_link.sub('{\\\\footnotesize\\href{\g<k>}{\g<t>}}', text)
|
text = regex_link.sub('{\\\\footnotesize\\href{\g<k>}{\g<t>}}', text)
|
||||||
text = regex_commas.sub('\g<t>',text)
|
text = regex_commas.sub('\g<t>', text)
|
||||||
text = regex_noindent.sub('\n\\\\noindent \g<t>',text)
|
text = regex_noindent.sub('\n\\\\noindent \g<t>', text)
|
||||||
|
|
||||||
### fix paths in images
|
# ## fix paths in images
|
||||||
regex=re.compile('\\\\_\w*\.(eps|png|jpg|gif)')
|
regex = re.compile('\\\\_\w*\.(eps|png|jpg|gif)')
|
||||||
while True:
|
while True:
|
||||||
match=regex.search(text)
|
match = regex.search(text)
|
||||||
if not match: break
|
if not match:
|
||||||
text=text[:match.start()]+text[match.start()+1:]
|
break
|
||||||
#text = regex_quote_left.sub('``',text)
|
text = text[:match.start()] + text[match.start() + 1:]
|
||||||
#text = regex_quote_right.sub("''",text)
|
# text = regex_quote_left.sub('``',text)
|
||||||
|
# text = regex_quote_right.sub("''",text)
|
||||||
|
|
||||||
if chapters:
|
if chapters:
|
||||||
text=text.replace(r'\section*{',r'\chapter*{')
|
text = text.replace(r'\section*{', r'\chapter*{')
|
||||||
text=text.replace(r'\section{',r'\chapter{')
|
text = text.replace(r'\section{', r'\chapter{')
|
||||||
text=text.replace(r'subsection{',r'section{')
|
text = text.replace(r'subsection{', r'section{')
|
||||||
|
|
||||||
#############################################################
|
#############################################################
|
||||||
# process all code text
|
# process all code text
|
||||||
@@ -156,57 +169,64 @@ def render(text,
|
|||||||
parts = text.split(META)
|
parts = text.split(META)
|
||||||
text = parts[0]
|
text = parts[0]
|
||||||
authors = []
|
authors = []
|
||||||
for i,(code,b) in enumerate(segments):
|
for i, (code, b) in enumerate(segments):
|
||||||
if code==None:
|
if code is None:
|
||||||
html = META
|
html = META
|
||||||
else:
|
else:
|
||||||
if b=='hidden':
|
if b == 'hidden':
|
||||||
html=''
|
html = ''
|
||||||
elif b=='author':
|
elif b == 'author':
|
||||||
author = latex_escape(code.strip())
|
author = latex_escape(code.strip())
|
||||||
authors.append(author)
|
authors.append(author)
|
||||||
html=''
|
html = ''
|
||||||
elif b=='inxx':
|
elif b == 'inxx':
|
||||||
html='\inxx{%s}' % latex_escape(code)
|
html = '\inxx{%s}' % latex_escape(code)
|
||||||
elif b=='cite':
|
elif b == 'cite':
|
||||||
html='~\cite{%s}' % latex_escape(code.strip())
|
html = '~\cite{%s}' % latex_escape(code.strip())
|
||||||
elif b=='ref':
|
elif b == 'ref':
|
||||||
html='~\ref{%s}' % latex_escape(code.strip())
|
html = '~\ref{%s}' % latex_escape(code.strip())
|
||||||
elif b=='latex':
|
elif b == 'latex':
|
||||||
if '\n' in code:
|
if '\n' in code:
|
||||||
html='\n\\begin{equation}\n%s\n\\end{equation}\n' % code.strip()
|
html = '\n\\begin{equation}\n%s\n\\end{equation}\n' % code.strip()
|
||||||
else:
|
else:
|
||||||
html='$%s$' % code.strip()
|
html = '$%s$' % code.strip()
|
||||||
elif b=='latex_eqnarray':
|
elif b == 'latex_eqnarray':
|
||||||
code=code.strip()
|
code = code.strip()
|
||||||
code='\\\\'.join(x.replace('=','&=&',1) for x in code.split('\\\\'))
|
code = '\\\\'.join(x.replace('=', '&=&', 1) for x in code.split('\\\\'))
|
||||||
html='\n\\begin{eqnarray}\n%s\n\\end{eqnarray}\n' % code
|
html = '\n\\begin{eqnarray}\n%s\n\\end{eqnarray}\n' % code
|
||||||
elif b.startswith('latex_'):
|
elif b.startswith('latex_'):
|
||||||
key=b[6:]
|
key = b[6:]
|
||||||
html='\\begin{%s}%s\\end{%s}' % (key,code,key)
|
html = '\\begin{%s}%s\\end{%s}' % (key, code, key)
|
||||||
elif b in extra:
|
elif b in extra:
|
||||||
if code[:1]=='\n': code=code[1:]
|
if code[:1] == '\n':
|
||||||
if code[-1:]=='\n': code=code[:-1]
|
code = code[1:]
|
||||||
|
if code[-1:] == '\n':
|
||||||
|
code = code[:-1]
|
||||||
html = extra[b](code)
|
html = extra[b](code)
|
||||||
elif code[:1]=='\n' or code[:-1]=='\n':
|
elif code[:1] == '\n' or code[:-1] == '\n':
|
||||||
if code[:1]=='\n': code=code[1:]
|
if code[:1] == '\n':
|
||||||
if code[-1:]=='\n': code=code[:-1]
|
code = code[1:]
|
||||||
|
if code[-1:] == '\n':
|
||||||
|
code = code[:-1]
|
||||||
if code.startswith('<') or code.startswith('{{') or code.startswith('http'):
|
if code.startswith('<') or code.startswith('{{') or code.startswith('http'):
|
||||||
html = '\\begin{lstlisting}[keywords={}]\n%s\n\\end{lstlisting}' % code
|
html = '\\begin{lstlisting}[keywords={}]\n%s\n\\end{lstlisting}' % code
|
||||||
else:
|
else:
|
||||||
html = '\\begin{lstlisting}\n%s\n\\end{lstlisting}' % code
|
html = '\\begin{lstlisting}\n%s\n\\end{lstlisting}' % code
|
||||||
else:
|
else:
|
||||||
if code[:1]=='\n': code=code[1:]
|
if code[:1] == '\n':
|
||||||
if code[-1:]=='\n': code=code[:-1]
|
code = code[1:]
|
||||||
|
if code[-1:] == '\n':
|
||||||
|
code = code[:-1]
|
||||||
html = '{\\ft %s}' % latex_escape(code)
|
html = '{\\ft %s}' % latex_escape(code)
|
||||||
try:
|
try:
|
||||||
text = text+html+parts[i+1]
|
text = text + html + parts[i + 1]
|
||||||
except:
|
except:
|
||||||
text = text + '... WIKI PROCESSING ERROR ...'
|
text = text + '... WIKI PROCESSING ERROR ...'
|
||||||
break
|
break
|
||||||
text = text.replace(' ~\\cite','~\\cite')
|
text = text.replace(' ~\\cite', '~\\cite')
|
||||||
return text, title, authors
|
return text, title, authors
|
||||||
|
|
||||||
|
|
||||||
WRAPPER = """
|
WRAPPER = """
|
||||||
\\documentclass[12pt]{article}
|
\\documentclass[12pt]{article}
|
||||||
\\usepackage{hyperref}
|
\\usepackage{hyperref}
|
||||||
@@ -239,12 +259,14 @@ WRAPPER = """
|
|||||||
\\end{document}
|
\\end{document}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def markmin2latex(data, image_mapper=lambda x:x, extra={},
|
|
||||||
|
def markmin2latex(data, image_mapper=lambda x: x, extra={},
|
||||||
wrapper=WRAPPER):
|
wrapper=WRAPPER):
|
||||||
body, title, authors = render(data, extra=extra, image_mapper=image_mapper)
|
body, title, authors = render(data, extra=extra, image_mapper=image_mapper)
|
||||||
author = '\n\\and\n'.join(a.replace('\n','\\\\\n\\footnotesize ') for a in authors)
|
author = '\n\\and\n'.join(a.replace('\n', '\\\\\n\\footnotesize ') for a in authors)
|
||||||
return wrapper % dict(title=title, author=author, body=body)
|
return wrapper % dict(title=title, author=author, body=body)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
parser = OptionParser()
|
parser = OptionParser()
|
||||||
parser.add_option("-i", "--info", dest="info",
|
parser.add_option("-i", "--info", dest="info",
|
||||||
@@ -252,40 +274,39 @@ if __name__ == '__main__':
|
|||||||
parser.add_option("-t", "--test", dest="test", action="store_true",
|
parser.add_option("-t", "--test", dest="test", action="store_true",
|
||||||
default=False)
|
default=False)
|
||||||
parser.add_option("-n", "--no_wrapper", dest="no_wrapper",
|
parser.add_option("-n", "--no_wrapper", dest="no_wrapper",
|
||||||
action="store_true",default=False)
|
action="store_true", default=False)
|
||||||
parser.add_option("-c", "--chapters", dest="chapters",action="store_true",
|
parser.add_option("-c", "--chapters", dest="chapters", action="store_true",
|
||||||
default=False,help="switch section for chapter")
|
default=False, help="switch section for chapter")
|
||||||
parser.add_option("-w", "--wrapper", dest="wrapper", default=False,
|
parser.add_option("-w", "--wrapper", dest="wrapper", default=False,
|
||||||
help="latex file containing header and footer")
|
help="latex file containing header and footer")
|
||||||
|
|
||||||
(options, args) = parser.parse_args()
|
(options, args) = parser.parse_args()
|
||||||
if options.info:
|
if options.info:
|
||||||
import markmin2html
|
import markmin2html
|
||||||
|
|
||||||
markmin2latex(markmin2html.__doc__)
|
markmin2latex(markmin2html.__doc__)
|
||||||
elif options.test:
|
elif options.test:
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
else:
|
else:
|
||||||
if options.wrapper:
|
if options.wrapper:
|
||||||
fwrapper = open(options.wrapper,'rb')
|
fwrapper = open(options.wrapper, 'rb')
|
||||||
try:
|
try:
|
||||||
wrapper = fwrapper.read()
|
wrapper = fwrapper.read()
|
||||||
finally:
|
finally:
|
||||||
fwrapper.close()
|
fwrapper.close()
|
||||||
elif options.no_wrapper:
|
elif options.no_wrapper:
|
||||||
wrapper = '%(body)s'
|
wrapper = '%(body)s'
|
||||||
else:
|
else:
|
||||||
wrapper = WRAPPER
|
wrapper = WRAPPER
|
||||||
for f in args:
|
for f in args:
|
||||||
fargs = open(f,'r')
|
fargs = open(f, 'r')
|
||||||
content_data = []
|
content_data = []
|
||||||
try:
|
try:
|
||||||
content_data.append(fargs.read())
|
content_data.append(fargs.read())
|
||||||
finally:
|
finally:
|
||||||
fargs.close()
|
fargs.close()
|
||||||
content = '\n'.join(content_data)
|
content = '\n'.join(content_data)
|
||||||
output= markmin2latex(content,
|
output = markmin2latex(content,
|
||||||
wrapper=wrapper,
|
wrapper=wrapper,
|
||||||
chapters=options.chapters)
|
chapters=options.chapters)
|
||||||
print output
|
print output
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -13,21 +13,22 @@ from markmin2latex import markmin2latex
|
|||||||
|
|
||||||
__all__ = ['markmin2pdf']
|
__all__ = ['markmin2pdf']
|
||||||
|
|
||||||
def removeall(path):
|
|
||||||
|
|
||||||
ERROR_STR= """Error removing %(path)s, %(error)s """
|
def removeall(path):
|
||||||
|
ERROR_STR = """Error removing %(path)s, %(error)s """
|
||||||
|
|
||||||
def rmgeneric(path, __func__):
|
def rmgeneric(path, __func__):
|
||||||
try:
|
try:
|
||||||
__func__(path)
|
__func__(path)
|
||||||
except OSError, (errno, strerror):
|
except OSError, (errno, strerror):
|
||||||
print ERROR_STR % {'path' : path, 'error': strerror }
|
print ERROR_STR % {'path': path, 'error': strerror}
|
||||||
|
|
||||||
files=[path]
|
files = [path]
|
||||||
|
|
||||||
while files:
|
while files:
|
||||||
file=files[0]
|
file = files[0]
|
||||||
if os.path.isfile(file):
|
if os.path.isfile(file):
|
||||||
f=os.remove
|
f = os.remove
|
||||||
rmgeneric(file, os.remove)
|
rmgeneric(file, os.remove)
|
||||||
del files[0]
|
del files[0]
|
||||||
elif os.path.isdir(file):
|
elif os.path.isdir(file):
|
||||||
@@ -36,7 +37,7 @@ def removeall(path):
|
|||||||
rmgeneric(file, os.rmdir)
|
rmgeneric(file, os.rmdir)
|
||||||
del files[0]
|
del files[0]
|
||||||
else:
|
else:
|
||||||
files = [os.path.join(file,x) for x in nested] + files
|
files = [os.path.join(file, x) for x in nested] + files
|
||||||
|
|
||||||
|
|
||||||
def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
||||||
@@ -49,13 +50,13 @@ def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
|||||||
- passes: defines how often pdflates should be run in the texfile.
|
- passes: defines how often pdflates should be run in the texfile.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
pdflatex=pdflatex
|
pdflatex = pdflatex
|
||||||
passes=passes
|
passes = passes
|
||||||
warnings=[]
|
warnings = []
|
||||||
|
|
||||||
# setup the envoriment
|
# setup the envoriment
|
||||||
tmpdir = mkdtemp()
|
tmpdir = mkdtemp()
|
||||||
texfile = open(tmpdir+'/test.tex','wb')
|
texfile = open(tmpdir + '/test.tex', 'wb')
|
||||||
texfile.write(latex)
|
texfile.write(latex)
|
||||||
texfile.seek(0)
|
texfile.seek(0)
|
||||||
texfile.close()
|
texfile.close()
|
||||||
@@ -63,8 +64,8 @@ def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
|||||||
|
|
||||||
# start doing some work
|
# start doing some work
|
||||||
for i in range(0, passes):
|
for i in range(0, passes):
|
||||||
logfd,logname = mkstemp()
|
logfd, logname = mkstemp()
|
||||||
outfile=os.fdopen(logfd)
|
outfile = os.fdopen(logfd)
|
||||||
try:
|
try:
|
||||||
ret = subprocess.call([pdflatex,
|
ret = subprocess.call([pdflatex,
|
||||||
'-interaction=nonstopmode',
|
'-interaction=nonstopmode',
|
||||||
@@ -75,18 +76,18 @@ def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
|||||||
stderr=subprocess.PIPE)
|
stderr=subprocess.PIPE)
|
||||||
finally:
|
finally:
|
||||||
outfile.close()
|
outfile.close()
|
||||||
re_errors=re.compile('^\!(.*)$',re.M)
|
re_errors = re.compile('^\!(.*)$', re.M)
|
||||||
re_warnings=re.compile('^LaTeX Warning\:(.*)$',re.M)
|
re_warnings = re.compile('^LaTeX Warning\:(.*)$', re.M)
|
||||||
flog = open(logname)
|
flog = open(logname)
|
||||||
try:
|
try:
|
||||||
loglines = flog.read()
|
loglines = flog.read()
|
||||||
finally:
|
finally:
|
||||||
flog.close()
|
flog.close()
|
||||||
errors=re_errors.findall(loglines)
|
errors = re_errors.findall(loglines)
|
||||||
warnings=re_warnings.findall(loglines)
|
warnings = re_warnings.findall(loglines)
|
||||||
os.unlink(logname)
|
os.unlink(logname)
|
||||||
|
|
||||||
pdffile=texfile.rsplit('.',1)[0]+'.pdf'
|
pdffile = texfile.rsplit('.', 1)[0] + '.pdf'
|
||||||
if os.path.isfile(pdffile):
|
if os.path.isfile(pdffile):
|
||||||
fpdf = open(pdffile, 'rb')
|
fpdf = open(pdffile, 'rb')
|
||||||
try:
|
try:
|
||||||
@@ -100,31 +101,31 @@ def latex2pdf(latex, pdflatex='pdflatex', passes=3):
|
|||||||
|
|
||||||
|
|
||||||
def markmin2pdf(text, image_mapper=lambda x: None, extra={}):
|
def markmin2pdf(text, image_mapper=lambda x: None, extra={}):
|
||||||
return latex2pdf(markmin2latex(text,image_mapper=image_mapper, extra=extra))
|
return latex2pdf(markmin2latex(text, image_mapper=image_mapper, extra=extra))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import sys
|
import sys
|
||||||
import doctest
|
import doctest
|
||||||
import markmin2html
|
import markmin2html
|
||||||
if sys.argv[1:2]==['-h']:
|
|
||||||
|
if sys.argv[1:2] == ['-h']:
|
||||||
data, warnings, errors = markmin2pdf(markmin2html.__doc__)
|
data, warnings, errors = markmin2pdf(markmin2html.__doc__)
|
||||||
if errors:
|
if errors:
|
||||||
print 'ERRORS:'+'\n'.join(errors)
|
print 'ERRORS:' + '\n'.join(errors)
|
||||||
print 'WARNGINS:'+'\n'.join(warnings)
|
print 'WARNGINS:' + '\n'.join(warnings)
|
||||||
else:
|
else:
|
||||||
print data
|
print data
|
||||||
elif len(sys.argv)>1:
|
elif len(sys.argv) > 1:
|
||||||
fargv = open(sys.argv[1],'rb')
|
fargv = open(sys.argv[1], 'rb')
|
||||||
try:
|
try:
|
||||||
data, warnings, errors = markmin2pdf(fargv.read())
|
data, warnings, errors = markmin2pdf(fargv.read())
|
||||||
finally:
|
finally:
|
||||||
fargv.close()
|
fargv.close()
|
||||||
if errors:
|
if errors:
|
||||||
print 'ERRORS:'+'\n'.join(errors)
|
print 'ERRORS:' + '\n'.join(errors)
|
||||||
print 'WARNGINS:'+'\n'.join(warnings)
|
print 'WARNGINS:' + '\n'.join(warnings)
|
||||||
else:
|
else:
|
||||||
print data
|
print data
|
||||||
else:
|
else:
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user