Merge pull request #1284 from BuhtigithuB/more-markmin-pep8

More markmin pep8
This commit is contained in:
mdipierro committed 2016-04-11 13:38:54 -05:00
commit 5ca65d55d2
2 files changed
+45 -23

No files matched your search

+42 -21
View File
@@ -39,16 +39,20 @@ 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_left = re.compile('"(?=\w)')
# regex_quote_right = re.compile('(?=\w\.)"') # regex_quote_right = re.compile('(?=\w\.)"')
def latex_escape(text, pound=True): def latex_escape(text, pound=True):
text = text.replace('\\', '{\\textbackslash}') text = text.replace('\\', '{\\textbackslash}')
for c in '^_&$%{}': text=text.replace(c,'\\'+c) for c in '^_&$%{}':
text = text.replace(c, '\\' + c)
text = text.replace('\\{\\textbackslash\\}', '{\\textbackslash}') text = text.replace('\\{\\textbackslash\\}', '{\\textbackslash}')
if pound: text = text.replace('#', '\\#') if pound: text = text.replace('#', '\\#')
return text return text
def render(text, def render(text,
extra={}, extra={},
allowed={}, allowed={},
@@ -65,26 +69,29 @@ def render(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:
break
if item.group() == META: if item.group() == META:
segments.append((None, None)) segments.append((None, None))
text = text[:item.start()] + META + text[item.end():] 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']:
c = ''
code = item.group('t').replace('!`!', '`') code = item.group('t').replace('!`!', '`')
segments.append((code, c)) segments.append((code, c))
text = text[:item.start()] + META + text[item.end():] text = text[:item.start()] + META + text[item.end():]
i = item.start() + 3 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)
@@ -106,9 +113,11 @@ def render(text,
############################################################# #############################################################
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(' | ', ' & ')
@@ -116,7 +125,8 @@ def render(text,
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():]
@@ -127,8 +137,10 @@ 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
return '\n\\begin{center}\\includegraphics[width=8cm]{%s}\\end{center}\n' % f
text = regex_image_width.sub(sub, text) text = regex_image_width.sub(sub, text)
text = regex_image.sub(sub, text) text = regex_image.sub(sub, text)
@@ -140,7 +152,8 @@ def render(text,
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:
break
text = text[:match.start()] + text[match.start() + 1:] text = text[:match.start()] + text[match.start() + 1:]
# text = regex_quote_left.sub('``',text) # text = regex_quote_left.sub('``',text)
# text = regex_quote_right.sub("''",text) # text = regex_quote_right.sub("''",text)
@@ -157,7 +170,7 @@ def render(text,
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':
@@ -185,19 +198,25 @@ def render(text,
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]
@@ -207,6 +226,7 @@ def render(text,
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",
@@ -261,6 +283,7 @@ if __name__ == '__main__':
(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()
@@ -287,5 +310,3 @@ if __name__ == '__main__':
wrapper=wrapper, wrapper=wrapper,
chapters=options.chapters) chapters=options.chapters)
print output print output
+3 -2
View File
@@ -13,9 +13,10 @@ from markmin2latex import markmin2latex
__all__ = ['markmin2pdf'] __all__ = ['markmin2pdf']
def removeall(path):
def removeall(path):
ERROR_STR = """Error removing %(path)s, %(error)s """ ERROR_STR = """Error removing %(path)s, %(error)s """
def rmgeneric(path, __func__): def rmgeneric(path, __func__):
try: try:
__func__(path) __func__(path)
@@ -107,6 +108,7 @@ 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:
@@ -127,4 +129,3 @@ if __name__ == '__main__':
print data print data
else: else:
doctest.testmod() doctest.testmod()