initial commit

This commit is contained in:
Massimo Di Pierro
2011-11-22 23:30:42 -06:00
commit d421c1321b
580 changed files with 115527 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
+35
View File
@@ -0,0 +1,35 @@
<html><body><h1>Markmin markup language</h1><h2>About</h2><p>This is a new markup language that we call markmin designed to produce high quality scientific papers and books and also put them online. We provide serializers for html, latex and pdf. It is implemented in the <code class="">markmin2html</code> function in the <code class="">markmin2html.py</code>.</p><p>Example of usage:</p><pre><code class="">&gt;&gt;&gt; m = "Hello **world** [[link http://web2py.com]]"
&gt;&gt;&gt; from markmin2html import markmin2html
&gt;&gt;&gt; print markmin2html(m)
&gt;&gt;&gt; from markmin2latex import markmin2latex
&gt;&gt;&gt; print markmin2latex(m)
&gt;&gt;&gt; from markmin2pdf import markmin2pdf # requires pdflatex
&gt;&gt;&gt; print markmin2pdf(m)</code></pre><h2>Why?</h2><p>We wanted a markup language with the following requirements:</p><ul><li>less than 100 lines of functional code</li><li>easy to read</li><li>secure</li><li>support table, ul, ol, code</li><li>support html5 video and audio elements (html serialization only)</li><li>can align images and resize them</li><li>can specify class for tables and code elements</li><li>can add anchors</li><li>does not use _ for markup (since it creates odd behavior)</li><li>automatically links urls</li><li>fast</li><li>easy to extend</li><li>supports latex and pdf including references</li><li>allows to describe the markup in the markup (this document is generated from markmin syntax)</li></ul><p>(results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster)</p><p>The <a href="http://www.lulu.com/product/paperback/web2py-%283rd-edition%29/12822827">web2py book</a> published by lulu, for example, was entirely generated with markmin2pdf from the online <a href="http://www.web2py.com/book">web2py wiki</a></p><h2>Download</h2><ul><li>http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py</li><li>http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py</li><li>http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py</li></ul><p>markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD.</p><h2>Examples</h2><h3>Bold, italic, code and links</h3><table class=""><tr><td><b>SOURCE</b> </td><td><b>OUTPUT</b></td></tr><tr><td><code class=""># title</code> </td><td><b>title</b></td></tr><tr><td><code class="">## section</code> </td><td><b>section</b></td></tr><tr><td><code class="">### subsection</code> </td><td><b>subsection</b></td></tr><tr><td><code class="">**bold**</code> </td><td><b>bold</b></td></tr><tr><td><code class="">''italic''</code> </td><td><i>italic</i></td></tr><tr><td><code class="">``verbatim``</code> </td><td><code class="">verbatim</code></td></tr><tr><td><code class="">http://google.com</code> </td><td>http://google.com</td></tr><tr><td><code class="">[[click me #myanchor]]</code></td><td><a href="#myanchor">click me</a></td></tr></table>
<h3>More on links</h3><p>The format is always <code class="">[[title link]]</code>. Notice you can nest bold, italic and code inside the link title.</p><h3>Anchors <span id="myanchor"><span></h3><p>You can place an anchor anywhere in the text using the syntax <code class="">[[name]]</code> where <i>name</i> is the name of the anchor.
You can then link the anchor with <a href="#myanchor">link</a>, i.e. <code class="">[[link #myanchor]]</code>.</p><h3>Images</h3><p><img src="http://www.web2py.com/examples/static/web2py_logo.png" alt="some image" align="right" width="200px" />
This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code</p><p><code class="">[[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]</code>.</p><h3>Unordered Lists</h3><pre><code class="">- Dog
- Cat
- Mouse</code></pre><p>is rendered as</p><ul><li>Dog</li><li>Cat</li><li>Mouse</li></ul><p>Two new lines between items break the list in two lists.</p><h3>Ordered Lists</h3><pre><code class="">+ Dog
+ Cat
+ Mouse</code></pre><p>is rendered as</p><ol><li>Dog</li><li>Cat</li><li>Mouse</li></ol><h3>Tables</h3><p>Something like this
<pre><code class="">---------
**A** | **B** | **C**
0 | 0 | X
0 | X | 0
X | 0 | 0
-----:abc</code></pre>
is a table and is rendered as
<table class="abc"><tr><td><b>A</b></td><td><b>B</b></td><td><b>C</b></td></tr><tr><td>0</td><td>0</td><td>X</td></tr><tr><td>0</td><td>X</td><td>0</td></tr><tr><td>X</td><td>0</td><td>0</td></tr></table>Four or more dashes delimit the table and | separates the columns.
The <code class="">:abc</code> at the end sets the class for the table and it is optional.</p><h3>Blockquote</h3><p>A table with a single cell is rendered as a blockquote:</p><blockquote class="">Hello world</blockquote>
<h3>Code, <code class="">&lt;code&gt;</code>, escaping and extra stuff</h3><pre><code class="python">def test():
return "this is Python code"</code></pre><p>Optionally a ` inside a <code class="">``...``</code> block can be inserted escaped with !`!.
The <code class="">:python</code> after the markup is also optional. If present, by default, it is used to set the class of the &lt;code&gt; block.
The behavior can be overridden by passing an argument <code class="">extra</code> to the <code class="">render</code> function. For example:</p><pre><code class="python">&gt;&gt;&gt; markmin2html("``aaa``:custom",
extra=dict(custom=lambda text: 'x'+text+'x'))</code></pre><p>generates</p><code class="python">'xaaax'</code><p>(the <code class="">``...``:custom</code> block is rendered by the <code class="">custom=lambda</code> function passed to <code class="">render</code>).</p><h3>Html5 support</h3><p>Markmin also supports the &lt;video&gt; and &lt;audio&gt; html5 tags using the notation:
<pre><code class="">[[title link video]]
[[title link audio]]</code></pre></p><h3>Latex</h3><p>Formulas can be embedded into HTML with <code class="">$</code><code class="">$</code>formula<code class="">$</code><code class="">$</code>.
You can use Google charts to render the formula:</p><pre><code class="">&gt;&gt;&gt; LATEX = '&lt;img src="http://chart.apis.google.com/chart?cht=tx&amp;chl=%s" align="center"/&gt;'
&gt;&gt;&gt; markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','"')})</code></pre><h3>Citations and References</h3><p>Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like</p><pre><code class="">- [[key]] value</code></pre><p>in the References will be translated into Latex</p><pre><code class="">\bibitem{key} value</code></pre><p>Here is an example of usage:</p><pre><code class="">As shown in Ref.``mdipierro``:cite
## References
- [[mdipierro]] web2py Manual, 3rd Edition, lulu.com</code></pre><h3>Caveats</h3><p><code class="">&lt;ul/&gt;</code>, <code class="">&lt;ol/&gt;</code>, <code class="">&lt;code/&gt;</code>, <code class="">&lt;table/&gt;</code>, <code class="">&lt;blockquote/&gt;</code>, <code class="">&lt;h1/&gt;</code>, ..., <code class="">&lt;h6/&gt;</code> do not have <code class="">&lt;p&gt;...&lt;/p&gt;</code> around them.</p></body></html>
Binary file not shown.
+463
View File
@@ -0,0 +1,463 @@
#!/usr/bin/env python
# created my Massimo Di Pierro
# license MIT/BSD/GPL
import re
import cgi
__all__ = ['render', 'markmin2html']
__doc__ = """
# Markmin markup language
## About
This is a new markup language that we call markmin designed to produce high quality scientific papers and books and also put them online. We provide serializers for html, latex and pdf. It is implemented in the ``markmin2html`` function in the ``markmin2html.py``.
Example of usage:
``
m = "Hello **world** [[link http://web2py.com]]"
from markmin2html import markmin2html
print markmin2html(m)
from markmin2latex import markmin2latex
print markmin2latex(m)
from markmin2pdf import markmin2pdf # requires pdflatex
print markmin2pdf(m)
``
## Why?
We wanted a markup language with the following requirements:
- less than 100 lines of functional code
- easy to read
- secure
- support table, ul, ol, code
- support html5 video and audio elements (html serialization only)
- can align images and resize them
- can specify class for tables and code elements
- can add anchors
- does not use _ for markup (since it creates odd behavior)
- automatically links urls
- fast
- easy to extend
- supports latex and pdf including references
- allows to describe the markup in the markup (this document is generated from markmin syntax)
(results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster)
The [[web2py book http://www.lulu.com/product/paperback/web2py-%283rd-edition%29/12822827]] published by lulu, for example, was entirely generated with markmin2pdf from the online [[web2py wiki http://www.web2py.com/book]]
## Download
- http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py
- http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py
- http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py
markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD.
## Examples
### Bold, italic, code and links
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``[[click me #myanchor]]`` | [[click me #myanchor]]
---------------------------------------------------
### More on links
The format is always ``[[title link]]``. Notice you can nest bold, italic and code inside the link title.
### Anchors [[myanchor]]
You can place an anchor anywhere in the text using the syntax ``[[name]]`` where ''name'' is the name of the anchor.
You can then link the anchor with [[link #myanchor]], i.e. ``[[link #myanchor]]``.
### Images
[[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]
This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code
``[[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]``.
### Unordered Lists
``
- Dog
- Cat
- Mouse
``
is rendered as
- Dog
- Cat
- Mouse
Two new lines between items break the list in two lists.
### Ordered Lists
``
+ Dog
+ Cat
+ Mouse
``
is rendered as
+ Dog
+ Cat
+ Mouse
### Tables
Something like this
``
---------
**A** | **B** | **C**
0 | 0 | X
0 | X | 0
X | 0 | 0
-----:abc
``
is a table and is rendered as
---------
**A** | **B** | **C**
0 | 0 | X
0 | X | 0
X | 0 | 0
-----:abc
Four or more dashes delimit the table and | separates the columns.
The ``:abc`` at the end sets the class for the table and it is optional.
### Blockquote
A table with a single cell is rendered as a blockquote:
-----
Hello world
-----
### Code, ``<code>``, escaping and extra stuff
``
def test():
return "this is Python code"
``:python
Optionally a ` inside a ``!`!`...`!`!`` block can be inserted escaped with !`!.
The ``:python`` after the markup is also optional. If present, by default, it is used to set the class of the <code> block.
The behavior can be overridden by passing an argument ``extra`` to the ``render`` function. For example:
``
markmin2html("!`!!`!aaa!`!!`!:custom",
extra=dict(custom=lambda text: 'x'+text+'x'))
``:python
generates
``'xaaax'``:python
(the ``!`!`...`!`!:custom`` block is rendered by the ``custom=lambda`` function passed to ``render``).
### Html5 support
Markmin also supports the <video> and <audio> html5 tags using the notation:
``
[[title link video]]
[[title link audio]]
``
### Latex and other extensions
Formulas can be embedded into HTML with ``$````$``formula``$````$``.
You can use Google charts to render the formula:
``
LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" />'
markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','\"')})
``
### Code with syntax highlighting
This requires a syntax highlighting tool, such as the web2py CODE helper.
``
extra={'code_cpp':lambda text: CODE(text,language='cpp').xml(),
'code_java':lambda text: CODE(text,language='java').xml(),
'code_python':lambda text: CODE(text,language='python').xml(),
'code_html':lambda text: CODE(text,language='html').xml()}
markmin2html(text,extra=extra)
``
Code can now be marked up as in this example:
``
!`!`
<html><body>example</body></html>
!`!`:code_html
``
### Citations and References
Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like
``
- [[key]] value
``
in the References will be translated into Latex
``
\\bibitem{key} value
``
Here is an example of usage:
``
As shown in Ref.!`!`mdipierro`!`!:cite
## References
- [[mdipierro]] web2py Manual, 3rd Edition, lulu.com
``
### Caveats
``<ul/>``, ``<ol/>``, ``<code/>``, ``<table/>``, ``<blockquote/>``, ``<h1/>``, ..., ``<h6/>`` do not have ``<p>...</p>`` around them.
"""
META = 'META'
LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" />'
regex_newlines = re.compile('(\n\r)|(\r\n)')
regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$')
regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S)
regex_maps = [
(re.compile('[ \t\r]+\n'),'\n'),
(re.compile('[ \t\r]+\n'),'\n'),
(re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'<b>\g<t></b>'),
(re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'<i>\g<t></i>'),
(re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n<<h6>\g<t></h6>\n'),
(re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n<<h5>\g<t></h5>\n'),
(re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n<<h4>\g<t></h4>\n'),
(re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n<<h3>\g<t></h3>\n'),
(re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n<<h2>\g<t></h2>\n'),
(re.compile('^#{1} (?P<t>[^\n]+)',re.M),'\n\n<<h1>\g<t></h1>\n'),
(re.compile('^\- +(?P<t>.*)',re.M),'<<ul><li>\g<t></li></ul>'),
(re.compile('^\+ +(?P<t>.*)',re.M),'<<ol><li>\g<t></li></ol>'),
(re.compile('</ol>\n<<ol>'),''),
(re.compile('</ul>\n<<ul>'),''),
(re.compile('<<'),'\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_anchor = re.compile('\[\[(?P<t>\S+)\]\]')
regex_image_center_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +center +(?P<w>\d+px)\]\]')
regex_image_width = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right) +(?P<w>\d+px)\]\]')
regex_image_center = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +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_audio = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +audio\]\]')
regex_link = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+)\]\]')
regex_link_popup = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) popup\]\]')
regex_link_no_anchor = re.compile('\[\[ +(?P<k>\S+)\]\]')
regex_auto = re.compile('(?<!["\w\>])(?P<k>\w+://[\w\.\-\+\?&%\/]+)',re.M)
def render(text,extra={},allowed={},sep='p'):
"""
Arguments:
- text is the text to be processed
- extra is a dict like extra=dict(custom=lambda value: value) that process custom code
as in " ``this is custom code``:custom "
- allowed is a dictionary of list of allowed classes like
allowed = dict(code=('python','cpp','java'))
- sep can be 'p' to separate text in <p>...</p>
or can be 'br' to separate text using <br />
>>> render('this is\\n# a section\\nparagraph')
'<p>this is</p><h1>a section</h1><p>paragraph</p>'
>>> render('this is\\n## a subsection\\nparagraph')
'<p>this is</p><h2>a subsection</h2><p>paragraph</p>'
>>> render('this is\\n### a subsubsection\\nparagraph')
'<p>this is</p><h3>a subsubsection</h3><p>paragraph</p>'
>>> render('**hello world**')
'<p><b>hello world</b></p>'
>>> render('``hello world``')
'<code class="">hello world</code>'
>>> render('``hello world``:python')
'<code class="python">hello world</code>'
>>> render('``\\nhello\\nworld\\n``:python')
'<pre><code class="python">hello\\nworld</code></pre>'
>>> render("''hello world''")
'<p><i>hello world</i></p>'
>>> render('** hello** **world**')
'<p>** hello** <b>world</b></p>'
>>> render('- this\\n- is\\n- a list\\n\\nand this\\n- is\\n- another')
'<ul><li>this</li><li>is</li><li>a list</li></ul><p>and this</p><ul><li>is</li><li>another</li></ul>'
>>> render('+ this\\n+ is\\n+ a list\\n\\nand this\\n+ is\\n+ another')
'<ol><li>this</li><li>is</li><li>a list</li></ol><p>and this</p><ol><li>is</li><li>another</li></ol>'
>>> render("----\\na | b\\nc | d\\n----\\n")
'<table class=""><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>'
>>> render("----\\nhello world\\n----\\n")
'<blockquote class="">hello world</blockquote>'
>>> render('[[this is a link http://example.com]]')
'<p><a href="http://example.com">this is a link</a></p>'
>>> render('[[this is an image http://example.com left]]')
'<p><img src="http://example.com" alt="this is an image" align="left" /></p>'
>>> render('[[this is an image http://example.com left 200px]]')
'<p><img src="http://example.com" alt="this is an image" align="left" width="200px" /></p>'
>>> render('[[this is an image http://example.com video]]')
'<p><video src="http://example.com" controls></video></p>'
>>> render('[[this is an image http://example.com audio]]')
'<p><audio src="http://example.com" controls></audio></p>'
>>> render('[[this is a **link** http://example.com]]')
'<p><a href="http://example.com">this is a <b>link</b></a></p>'
>>> render("``aaa``:custom",extra=dict(custom=lambda text: 'x'+text+'x'))
'xaaax'
>>> print render(r"$$\int_a^b sin(x)dx$$")
<img src="http://chart.apis.google.com/chart?cht=tx&chl=\\int_a^b sin(x)dx" />
"""
text = str(text or '')
#############################################################
# replace all blocks marked with ``...``:class with META
# store them into segments they will be treated as code
#############################################################
segments, i = [], 0
text = regex_dd.sub('``\g<latex>``:latex ',text)
text = regex_newlines.sub('\n',text)
while True:
item = regex_code.search(text,i)
if not item: break
if item.group()==META:
segments.append((None,None))
text = text[:item.start()]+META+text[item.end():]
else:
c = item.group('c') or ''
if 'code' in allowed and not c in allowed['code']: c = ''
code = item.group('t').replace('!`!','`')
segments.append((code,c))
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
#############################################################
text = '\n'.join(t.strip() for t in text.split('\n'))
text = cgi.escape(text)
for regex, sub in regex_maps:
text = regex.sub(sub,text)
#############################################################
# process tables and blockquotes
#############################################################
while True:
item = regex_table.search(text)
if not item: break
c = item.group('c') or ''
if 'table' in allowed and not c in allowed['table']: c = ''
content = item.group('t')
if ' | ' in content:
rows = content.replace('\n','</td></tr><tr><td>').replace(' | ','</td><td>')
text = text[:item.start()] + '<<table class="%s"><tr><td>'%c + rows + '</td></tr></table>' + text[item.end():]
else:
text = text[:item.start()] + '<<blockquote class="%s">'%c + content + '</blockquote>' + text[item.end():]
#############################################################
# deal with images, videos, audios and links
#############################################################
text = regex_anchor.sub('<span id="\g<t>"><span>', text)
text = regex_image_center_width.sub('<p align="center"><img src="\g<k>" alt="\g<t>" width="\g<w>" /></p>', text)
text = regex_image_width.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" width="\g<w>" />', text)
text = regex_image_center.sub('<p align="center"><img src="\g<k>" alt="\g<t>" /></p>', text)
text = regex_image.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" />', text)
text = regex_video.sub('<video src="\g<k>" controls></video>', text)
text = regex_audio.sub('<audio src="\g<k>" controls></audio>', text)
text = regex_link_popup.sub('<a href="\g<k>" target="_blank">\g<t></a>', text)
text = regex_link_no_anchor.sub('<a href="\g<k>">\g<k></a>', text)
text = regex_link.sub('<a href="\g<k>">\g<t></a>', text)
text = regex_auto.sub('<a href="\g<k>">\g<k></a>', text)
#############################################################
# deal with paragraphs (trick <<ul, <<ol, <<table, <<h1, etc)
# the << indicates that there should NOT be a new paragraph
# META indicates a code block therefore no new paragraph
#############################################################
items = [item.strip() for item in text.split('\n\n')]
if sep=='p':
text = ''.join(
(p[:2]!='<<' and p!=META and '<p>%s</p>'%p or '%s'%p) \
for p in items if p.strip())
elif sep=='br':
text = '<br />'.join(items)
#############################################################
# finally get rid of <<
#############################################################
text=text.replace('<<','<')
#############################################################
# process all code text
#############################################################
parts = text.split(META)
text = parts[0]
for i,(code,b) in enumerate(segments):
if code==None:
html = META
else:
if b in extra:
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
html = extra[b](code)
elif b=='cite':
html = '['+','.join('<a href="#%s" class="%s">%s</a>' \
% (d,b,d) \
for d in cgi.escape(code).split(','))+']'
elif b=='latex':
html = LATEX % code.replace('"','\"').replace('\n',' ')
elif code[:1]=='\n' or code[-1:]=='\n':
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
html = '<pre><code class="%s">%s</code></pre>' % (b,cgi.escape(code))
else:
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
html = '<code class="%s">%s</code>' % (b,cgi.escape(code))
text = text+html+parts[i+1]
return text
def markmin2html(text,extra={},allowed={},sep='p'):
return render(text,extra,allowed,sep)
if __name__ == '__main__':
import sys
import doctest
if sys.argv[1:2]==['-h']:
print '<html><body>'+markmin2html(__doc__)+'</body></html>'
elif len(sys.argv)>1:
fargv = open(sys.argv[1],'r')
try:
print '<html><body>'+markmin2html(fargv.read())+'</body></html>'
finally:
fargv.close()
else:
doctest.testmod()
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env python
# created my Massimo Di Pierro
# license MIT/BSD/GPL
import re
import cgi
import sys
import doctest
from optparse import OptionParser
__all__ = ['render','markmin2latex']
META = 'META'
regex_newlines = re.compile('(\n\r)|(\r\n)')
regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$')
regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S)
regex_title = re.compile('^#{1} (?P<t>[^\n]+)',re.M)
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']+)*)''"),'{\\it \g<t>}'),
(re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n{\\\\bf \g<t>}\n'),
(re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n{\\\\bf \g<t>}\n'),
(re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsubsection{\g<t>}\n'),
(re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\subsection{\g<t>}\n'),
(re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n\\\\goodbreak\\section{\g<t>}\n'),
(re.compile('^#{1} (?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('\\\\end\{itemize\}\s+\\\\begin\{itemize\}'),'\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_anchor = re.compile('\[\[(?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 = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]')
#regex_video = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +video\]\]')
#regex_audio = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+) +audio\]\]')
regex_link = re.compile('\[\[(?P<t>[^\]]*?) +(?P<k>\S+)\]\]')
regex_auto = re.compile('(?<!["\w])(?P<k>\w+://[\w\.\-\?&%]+)',re.M)
regex_commas = re.compile('[ ]+(?P<t>[,;\.])')
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}')
for c in '^_&$%{}': text=text.replace(c,'\\'+c)
text=text.replace('\\{\\textbackslash\\}','{\\textbackslash}')
if pound: text=text.replace('#','\\#')
return text
def render(text,extra={},allowed={},sep='p',image_mapper=lambda x:x):
#############################################################
# replace all blocks marked with ``...``:class with META
# store them into segments they will be treated as code
#############################################################
text = str(text or '')
segments, i = [], 0
text = regex_dd.sub('``\g<latex>``:latex ',text)
text = regex_newlines.sub('\n',text)
while True:
item = regex_code.search(text,i)
if not item: break
if item.group()==META:
segments.append((None,None))
text = text[:item.start()]+META+text[item.end():]
else:
c = item.group('c') or ''
if 'code' in allowed and not c in allowed['code']: c = ''
code = item.group('t').replace('!`!','`')
segments.append((code,c))
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
#############################################################
title = regex_title.search(text)
if not title: title='Title'
else: title=title.group('t')
text = latex_escape(text,pound=False)
texts = text.split('## References',1)
text = regex_anchor.sub('\\label{\g<t>}', texts[0])
if len(texts)==2:
text += '\n\\begin{thebibliography}{999}\n'
text += regex_bibitem.sub('\n\\\\bibitem{\g<t>}', texts[1])
text += '\n\\end{thebibliography}\n'
text = '\n'.join(t.strip() for t in text.split('\n'))
for regex, sub in regex_maps:
text = regex.sub(sub,text)
text=text.replace('#','\\#')
text=text.replace('`',"'")
#############################################################
# process tables and blockquotes
#############################################################
while True:
item = regex_table.search(text)
if not item: break
c = item.group('c') or ''
if 'table' in allowed and not c in allowed['table']: c = ''
content = item.group('t')
if ' | ' in content:
rows = content.replace('\n','\\\\\n').replace(' | ',' & ')
row0,row2 = rows.split('\\\\\n',1)
cols=row0.count(' & ')+1
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}'
if row2.count('\n')>20: tabular='\\newpage\n'+tabular
text = text[:item.start()] + tabular + text[item.end():]
else:
text = text[:item.start()] + '\\begin{quote}' + content + '\\end{quote}' + text[item.end():]
#############################################################
# deal with images, videos, audios and links
#############################################################
def sub(x):
f=image_mapper(x.group('k'))
if not 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.sub(sub,text)
text = regex_link.sub('{\\\\footnotesize\\href{\g<k>}{\g<t>}}', text)
text = regex_commas.sub('\g<t>',text)
text = regex_noindent.sub('\n\\\\noindent \g<t>',text)
### fix paths in images
regex=re.compile('\\\\_[\w_]*\.(eps|png|jpg|gif)')
while True:
match=regex.search(text)
if not match: break
text=text[:match.start()]+text[match.start()+1:]
text = regex_quote_left.sub('``',text)
text = regex_quote_right.sub("''",text)
#############################################################
# process all code text
#############################################################
parts = text.split(META)
text = parts[0]
authors = []
for i,(code,b) in enumerate(segments):
if code==None:
html = META
else:
if b=='hidden':
html=''
elif b=='author':
author = latex_escape(code.strip())
authors.append(author)
html=''
elif b=='inxx':
html='\inxx{%s}' % latex_escape(code)
elif b=='cite':
html='~\cite{%s}' % latex_escape(code.strip())
elif b=='ref':
html='~\ref{%s}' % latex_escape(code.strip())
elif b=='latex':
if '\n' in code:
html='\n\\begin{equation}\n%s\n\\end{equation}\n' % code.strip()
else:
html='$%s$' % code.strip()
elif b=='latex_eqnarray':
code=code.strip()
code='\\\\'.join(x.replace('=','&=&',1) for x in code.split('\\\\'))
html='\n\\begin{eqnarray}\n%s\n\\end{eqnarray}\n' % code
elif b.startswith('latex_'):
key=b[6:]
html='\\begin{%s}%s\\end{%s}' % (key,code,key)
elif b in extra:
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
html = extra[b](code)
elif code[:1]=='\n' or code[:-1]=='\n':
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
if code.startswith('<') or code.startswith('{{') or code.startswith('http'):
html = '\\begin{lstlisting}[keywords={}]\n%s\n\\end{lstlisting}' % code
else:
html = '\\begin{lstlisting}\n%s\n\\end{lstlisting}' % code
else:
if code[:1]=='\n': code=code[1:]
if code[-1:]=='\n': code=code[:-1]
html = '{\\ft %s}' % latex_escape(code)
try:
text = text+html+parts[i+1]
except:
text = text + '... WIKI PROCESSING ERROR ...'
break
text = text.replace(' ~\\cite','~\\cite')
return text, title, authors
WRAPPER = """
\\documentclass[12pt]{article}
\\usepackage{hyperref}
\\usepackage{listings}
\\usepackage{upquote}
\\usepackage{color}
\\usepackage{graphicx}
\\usepackage{grffile}
\\usepackage[utf8x]{inputenc}
\\definecolor{lg}{rgb}{0.9,0.9,0.9}
\\definecolor{dg}{rgb}{0.3,0.3,0.3}
\\def\\ft{\\small\\tt}
\\lstset{
basicstyle=\\footnotesize,
breaklines=true, basicstyle=\\ttfamily\\color{black}\\footnotesize,
keywordstyle=\\bf\\ttfamily,
commentstyle=\\it\\ttfamily,
stringstyle=\\color{dg}\\it\\ttfamily,
numbers=left, numberstyle=\\color{dg}\\tiny, stepnumber=1, numbersep=5pt,
backgroundcolor=\\color{lg}, tabsize=4, showspaces=false,
showstringspaces=false
}
\\title{%(title)s}
\\author{%(author)s}
\\begin{document}
\\maketitle
\\tableofcontents
\\newpage
%(body)s
\\end{document}
"""
def markmin2latex(data, image_mapper=lambda x:x, extra={},
wrapper=WRAPPER):
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)
return wrapper % dict(title=title, author=author, body=body)
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-i", "--info", dest="info",
help="markmin help")
parser.add_option("-t", "--test", dest="test", action="store_true",
default=False)
parser.add_option("-n", "--no_wrapper", dest="no_wrapper",
action="store_true",default=False)
parser.add_option("-1", "--one", dest="one",action="store_true",
default=False,help="switch section for chapter")
parser.add_option("-w", "--wrapper", dest="wrapper", default=False,
help="latex file containing header and footer")
(options, args) = parser.parse_args()
if options.info:
import markmin2html
markmin2latex(markmin2html.__doc__)
elif options.test:
doctest.testmod()
else:
if options.wrapper:
fwrapper = open(options.wrapper,'rb')
try:
wrapper = fwrapper.read()
finally:
fwrapper.close()
elif options.no_wrapper:
wrapper = '%(body)s'
else:
wrapper = WRAPPER
for f in args:
fargs = open(f,'r')
content_data = []
try:
content_data.append(fargs.read())
finally:
fargs.close()
content = '\n'.join(content_data)
output= markmin2latex(content,wrapper=wrapper)
if options.one:
output=output.replace(r'\section*{',r'\chapter*{')
output=output.replace(r'\section{',r'\chapter{')
output=output.replace(r'subsection{',r'section{')
print output
+130
View File
@@ -0,0 +1,130 @@
"""
Created by Massimo Di Pierro
Licese BSD
"""
import subprocess
import os
import os.path
import re
import sys
from tempfile import mkstemp, mkdtemp, NamedTemporaryFile
from markmin2latex import markmin2latex
__all__ = ['markmin2pdf']
def removeall(path):
ERROR_STR= """Error removing %(path)s, %(error)s """
def rmgeneric(path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
print ERROR_STR % {'path' : path, 'error': strerror }
files=[path]
while files:
file=files[0]
if os.path.isfile(file):
f=os.remove
rmgeneric(file, os.remove)
del files[0]
elif os.path.isdir(file):
nested = os.listdir(file)
if not nested:
rmgeneric(file, os.rmdir)
del files[0]
else:
files = [os.path.join(file,x) for x in nested] + files
def latex2pdf(latex, pdflatex='pdflatex', passes=3):
"""
calls pdflatex in a tempfolder
Arguments:
- pdflatex: path to the pdflatex command. Default is just 'pdflatex'.
- passes: defines how often pdflates should be run in the texfile.
"""
pdflatex=pdflatex
passes=passes
warnings=[]
# setup the envoriment
tmpdir = mkdtemp()
texfile = open(tmpdir+'/test.tex','wb')
texfile.write(latex)
texfile.seek(0)
texfile.close()
texfile = os.path.abspath(texfile.name)
# start doing some work
for i in range(0, passes):
logfd,logname = mkstemp()
outfile=os.fdopen(logfd)
try:
ret = subprocess.call([pdflatex,
'-interaction=nonstopmode',
'-output-format', 'pdf',
'-output-directory', tmpdir,
texfile],
cwd=os.path.dirname(texfile), stdout=outfile,
stderr=subprocess.PIPE)
finally:
outfile.close()
re_errors=re.compile('^\!(.*)$',re.M)
re_warnings=re.compile('^LaTeX Warning\:(.*)$',re.M)
flog = open(logname)
try:
loglines = flog.read()
finally:
flog.close()
errors=re_errors.findall(loglines)
warnings=re_warnings.findall(loglines)
os.unlink(logname)
pdffile=texfile.rsplit('.',1)[0]+'.pdf'
if os.path.isfile(pdffile):
fpdf = open(pdffile, 'rb')
try:
data = fpdf.read()
finally:
fpdf.close()
else:
data = None
removeall(tmpdir)
return data, warnings, errors
def markmin2pdf(text, image_mapper=lambda x: None, extra={}):
return latex2pdf(markmin2latex(text,image_mapper=image_mapper, extra=extra))
if __name__ == '__main__':
import sys
import doctest
import markmin2html
if sys.argv[1:2]==['-h']:
data, warnings, errors = markmin2pdf(markmin2html.__doc__)
if errors:
print 'ERRORS:'+'\n'.join(errors)
print 'WARNGINS:'+'\n'.join(warnings)
else:
print data
elif len(sys.argv)>1:
fargv = open(sys.argv[1],'rb')
try:
data, warnings, errors = markmin2pdf(fargv.read())
finally:
fargv.close()
if errors:
print 'ERRORS:'+'\n'.join(errors)
print 'WARNGINS:'+'\n'.join(warnings)
else:
print data
else:
doctest.testmod()