PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Library/python26/lib/python2.6/site-packages/gluon/contrib/markmin/markmin2html.py

http://github.com/jyr/MNPP
Python | 451 lines | 444 code | 5 blank | 2 comment | 13 complexity | 79d82736a5589021196674db8ac1011b MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, LGPL-2.0, LGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-2.0, BSD-3-Clause, GPL-3.0, BSD-2-Clause
  1. #!/usr/bin/env python # created my Massimo Di Pierro
  2. # license MIT/BSD/GPL
  3. import re
  4. import cgi
  5. __all__ = ['render', 'markmin2html']
  6. __doc__ = """
  7. # Markmin markup language
  8. ## About
  9. 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``.
  10. Example of usage:
  11. ``
  12. >>> m = "Hello **world** [[link http://web2py.com]]"
  13. >>> from markmin2html import markmin2html
  14. >>> print markmin2html(m)
  15. >>> from markmin2latex import markmin2latex
  16. >>> print markmin2latex(m)
  17. >>> from markmin2pdf import markmin2pdf # requires pdflatex
  18. >>> print markmin2pdf(m)
  19. ``
  20. ## Why?
  21. We wanted a markup language with the following requirements:
  22. - less than 100 lines of functional code
  23. - easy to read
  24. - secure
  25. - support table, ul, ol, code
  26. - support html5 video and audio elements (html serialization only)
  27. - can align images and resize them
  28. - can specify class for tables and code elements
  29. - can add anchors
  30. - does not use _ for markup (since it creates odd behavior)
  31. - automatically links urls
  32. - fast
  33. - easy to extend
  34. - supports latex and pdf including references
  35. - allows to describe the markup in the markup (this document is generated from markmin syntax)
  36. (results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster)
  37. 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]]
  38. ## Download
  39. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py
  40. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py
  41. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py
  42. markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD.
  43. ## Examples
  44. ### Bold, italic, code and links
  45. --------------------------------------------------
  46. **SOURCE** | **OUTPUT**
  47. ``# title`` | **title**
  48. ``## section`` | **section**
  49. ``### subsection`` | **subsection**
  50. ``**bold**`` | **bold**
  51. ``''italic''`` | ''italic''
  52. ``!`!`verbatim`!`!`` | ``verbatim``
  53. ``http://google.com`` | http://google.com
  54. ``[[click me #myanchor]]`` | [[click me #myanchor]]
  55. ---------------------------------------------------
  56. ### More on links
  57. The format is always ``[[title link]]``. Notice you can nest bold, italic and code inside the link title.
  58. ### Anchors [[myanchor]]
  59. You can place an anchor anywhere in the text using the syntax ``[[name]]`` where ''name'' is the name of the anchor.
  60. You can then link the anchor with [[link #myanchor]], i.e. ``[[link #myanchor]]``.
  61. ### Images
  62. [[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]
  63. This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code
  64. ``[[some image http://www.web2py.com/examples/static/web2py_logo.png right 200px]]``.
  65. ### Unordered Lists
  66. ``
  67. - Dog
  68. - Cat
  69. - Mouse
  70. ``
  71. is rendered as
  72. - Dog
  73. - Cat
  74. - Mouse
  75. Two new lines between items break the list in two lists.
  76. ### Ordered Lists
  77. ``
  78. + Dog
  79. + Cat
  80. + Mouse
  81. ``
  82. is rendered as
  83. + Dog
  84. + Cat
  85. + Mouse
  86. ### Tables
  87. Something like this
  88. ``
  89. ---------
  90. **A** | **B** | **C**
  91. 0 | 0 | X
  92. 0 | X | 0
  93. X | 0 | 0
  94. -----:abc
  95. ``
  96. is a table and is rendered as
  97. ---------
  98. **A** | **B** | **C**
  99. 0 | 0 | X
  100. 0 | X | 0
  101. X | 0 | 0
  102. -----:abc
  103. Four or more dashes delimit the table and | separates the columns.
  104. The ``:abc`` at the end sets the class for the table and it is optional.
  105. ### Blockquote
  106. A table with a single cell is rendered as a blockquote:
  107. -----
  108. Hello world
  109. -----
  110. ### Code, ``<code>``, escaping and extra stuff
  111. ``
  112. def test():
  113. return "this is Python code"
  114. ``:python
  115. Optionally a ` inside a ``!`!`...`!`!`` block can be inserted escaped with !`!.
  116. The ``:python`` after the markup is also optional. If present, by default, it is used to set the class of the <code> block.
  117. The behavior can be overridden by passing an argument ``extra`` to the ``render`` function. For example:
  118. ``
  119. >>> markmin2html("!`!!`!aaa!`!!`!:custom",
  120. extra=dict(custom=lambda text: 'x'+text+'x'))
  121. ``:python
  122. generates
  123. ``'xaaax'``:python
  124. (the ``!`!`...`!`!:custom`` block is rendered by the ``custom=lambda`` function passed to ``render``).
  125. ### Html5 support
  126. Markmin also supports the <video> and <audio> html5 tags using the notation:
  127. ``
  128. [[title link video]]
  129. [[title link audio]]
  130. ``
  131. ### Latex and other extensions
  132. Formulas can be embedded into HTML with ``$````$``formula``$````$``.
  133. You can use Google charts to render the formula:
  134. ``
  135. >>> LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" align="ce\
  136. nter"/>'
  137. >>> markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','\"')})
  138. ``
  139. ### Code with syntax highlighting
  140. This requires a syntax highlighting tool, such as the web2py CODE helper.
  141. ``
  142. >>> extra={'code_cpp':lambda text: CODE(text,language='cpp').xml(),
  143. 'code_java':lambda text: CODE(text,language='java').xml(),
  144. 'code_python':lambda text: CODE(text,language='python').xml(),
  145. 'code_html':lambda text: CODE(text,language='html').xml()}
  146. >>> markmin2html(text,extra=extra)
  147. ``
  148. Code can now be marked up as in this example:
  149. ``
  150. !`!`
  151. <html><body>example</body></html>
  152. !`!`:code_html
  153. ``
  154. ### Citations and References
  155. Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like
  156. ``
  157. - [[key]] value
  158. ``
  159. in the References will be translated into Latex
  160. ``
  161. \\bibitem{key} value
  162. ``
  163. Here is an example of usage:
  164. ``
  165. As shown in Ref.!`!`mdipierro`!`!:cite
  166. ## References
  167. - [[mdipierro]] web2py Manual, 3rd Edition, lulu.com
  168. ``
  169. ### Caveats
  170. ``<ul/>``, ``<ol/>``, ``<code/>``, ``<table/>``, ``<blockquote/>``, ``<h1/>``, ..., ``<h6/>`` do not have ``<p>...</p>`` around them.
  171. """
  172. META = 'META'
  173. LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" align="center"/>'
  174. regex_newlines = re.compile('(\n\r)|(\r\n)')
  175. regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$')
  176. regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S)
  177. regex_maps = [
  178. (re.compile('[ \t\r]+\n'),'\n'),
  179. (re.compile('[ \t\r]+\n'),'\n'),
  180. (re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'<b>\g<t></b>'),
  181. (re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'<i>\g<t></i>'),
  182. (re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n<<h6>\g<t></h6>\n'),
  183. (re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n<<h5>\g<t></h5>\n'),
  184. (re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n<<h4>\g<t></h4>\n'),
  185. (re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n<<h3>\g<t></h3>\n'),
  186. (re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n<<h2>\g<t></h2>\n'),
  187. (re.compile('^#{1} (?P<t>[^\n]+)',re.M),'\n\n<<h1>\g<t></h1>\n'),
  188. (re.compile('^\- +(?P<t>.*)',re.M),'<<ul><li>\g<t></li></ul>'),
  189. (re.compile('^\+ +(?P<t>.*)',re.M),'<<ol><li>\g<t></li></ol>'),
  190. (re.compile('</ol>\n<<ol>'),''),
  191. (re.compile('</ul>\n<<ul>'),''),
  192. (re.compile('<<'),'\n\n<<'),
  193. (re.compile('\n\s+\n'),'\n\n')]
  194. regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n',re.M|re.S)
  195. regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]')
  196. regex_image_width = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]')
  197. regex_image = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]')
  198. regex_video = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +video\]\]')
  199. regex_audio = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +audio\]\]')
  200. regex_link = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+)\]\]')
  201. regex_link_popup = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) popup\]\]')
  202. regex_link_no_anchor = re.compile('\[\[ +(?P<k>\S+)\]\]')
  203. regex_auto = re.compile('(?<!["\w\>])(?P<k>\w+://[\w\.\-\+\?&%\/]+)',re.M)
  204. def render(text,extra={},allowed={},sep='p'):
  205. """
  206. Arguments:
  207. - text is the text to be processed
  208. - extra is a dict like extra=dict(custom=lambda value: value) that process custom code
  209. as in " ``this is custom code``:custom "
  210. - allowed is a dictionary of list of allowed classes like
  211. allowed = dict(code=('python','cpp','java'))
  212. - sep can be 'p' to separate text in <p>...</p>
  213. or can be 'br' to separate text using <br />
  214. >>> render('this is\\n# a section\\nparagraph')
  215. '<p>this is</p><h1>a section</h1><p>paragraph</p>'
  216. >>> render('this is\\n## a subsection\\nparagraph')
  217. '<p>this is</p><h2>a subsection</h2><p>paragraph</p>'
  218. >>> render('this is\\n### a subsubsection\\nparagraph')
  219. '<p>this is</p><h3>a subsubsection</h3><p>paragraph</p>'
  220. >>> render('**hello world**')
  221. '<p><b>hello world</b></p>'
  222. >>> render('``hello world``')
  223. '<code class="">hello world</code>'
  224. >>> render('``hello world``:python')
  225. '<code class="python">hello world</code>'
  226. >>> render('``\\nhello\\nworld\\n``:python')
  227. '<pre><code class="python">hello\\nworld</code></pre>'
  228. >>> render("''hello world''")
  229. '<p><i>hello world</i></p>'
  230. >>> render('** hello** **world**')
  231. '<p>** hello** <b>world</b></p>'
  232. >>> render('- this\\n- is\\n- a list\\n\\nand this\\n- is\\n- another')
  233. '<ul><li>this</li><li>is</li><li>a list</li></ul><p>and this</p><ul><li>is</li><li>another</li></ul>'
  234. >>> render('+ this\\n+ is\\n+ a list\\n\\nand this\\n+ is\\n+ another')
  235. '<ol><li>this</li><li>is</li><li>a list</li></ol><p>and this</p><ol><li>is</li><li>another</li></ol>'
  236. >>> render("----\\na | b\\nc | d\\n----\\n")
  237. '<table class=""><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>'
  238. >>> render("----\\nhello world\\n----\\n")
  239. '<blockquote class="">hello world</blockquote>'
  240. >>> render('[[this is a link http://example.com]]')
  241. '<p><a href="http://example.com">this is a link</a></p>'
  242. >>> render('[[this is an image http://example.com left]]')
  243. '<p><img src="http://example.com" alt="this is an image" align="left" /></p>'
  244. >>> render('[[this is an image http://example.com left 200px]]')
  245. '<p><img src="http://example.com" alt="this is an image" align="left" width="200px" /></p>'
  246. >>> render('[[this is an image http://example.com video]]')
  247. '<p><video src="http://example.com" controls></video></p>'
  248. >>> render('[[this is an image http://example.com audio]]')
  249. '<p><audio src="http://example.com" controls></audio></p>'
  250. >>> render('[[this is a **link** http://example.com]]')
  251. '<p><a href="http://example.com">this is a <b>link</b></a></p>'
  252. >>> render("``aaa``:custom",extra=dict(custom=lambda text: 'x'+text+'x'))
  253. 'xaaax'
  254. >>> render(r"$$\int_a^b sin(x)dx$$")
  255. '<code class="latex">\\\\int_a^b sin(x)dx</code>'
  256. """
  257. text = str(text or '')
  258. #############################################################
  259. # replace all blocks marked with ``...``:class with META
  260. # store them into segments they will be treated as code
  261. #############################################################
  262. segments, i = [], 0
  263. text = regex_dd.sub('``\g<latex>``:latex ',text)
  264. text = regex_newlines.sub('\n',text)
  265. while True:
  266. item = regex_code.search(text,i)
  267. if not item: break
  268. if item.group()==META:
  269. segments.append((None,None))
  270. text = text[:item.start()]+META+text[item.end():]
  271. else:
  272. c = item.group('c') or ''
  273. if 'code' in allowed and not c in allowed['code']: c = ''
  274. code = item.group('t').replace('!`!','`')
  275. segments.append((code,c))
  276. text = text[:item.start()]+META+text[item.end():]
  277. i=item.start()+3
  278. #############################################################
  279. # do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces
  280. #############################################################
  281. text = '\n'.join(t.strip() for t in text.split('\n'))
  282. text = cgi.escape(text)
  283. for regex, sub in regex_maps:
  284. text = regex.sub(sub,text)
  285. #############################################################
  286. # process tables and blockquotes
  287. #############################################################
  288. while True:
  289. item = regex_table.search(text)
  290. if not item: break
  291. c = item.group('c') or ''
  292. if 'table' in allowed and not c in allowed['table']: c = ''
  293. content = item.group('t')
  294. if ' | ' in content:
  295. rows = content.replace('\n','</td></tr><tr><td>').replace(' | ','</td><td>')
  296. text = text[:item.start()] + '<<table class="%s"><tr><td>'%c + rows + '</td></tr></table>' + text[item.end():]
  297. else:
  298. text = text[:item.start()] + '<<blockquote class="%s">'%c + content + '</blockquote>' + text[item.end():]
  299. #############################################################
  300. # deal with images, videos, audios and links
  301. #############################################################
  302. text = regex_anchor.sub('<span id="\g<t>"><span>', text)
  303. text = regex_image_width.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" width="\g<w>" />', text)
  304. text = regex_image.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" />', text)
  305. text = regex_video.sub('<video src="\g<k>" controls></video>', text)
  306. text = regex_audio.sub('<audio src="\g<k>" controls></audio>', text)
  307. text = regex_link_popup.sub('<a href="\g<k>" target="_blank">\g<t></a>', text)
  308. text = regex_link_no_anchor.sub('<a href="\g<k>">\g<k></a>', text)
  309. text = regex_link.sub('<a href="\g<k>">\g<t></a>', text)
  310. text = regex_auto.sub('<a href="\g<k>">\g<k></a>', text)
  311. #############################################################
  312. # deal with paragraphs (trick <<ul, <<ol, <<table, <<h1, etc)
  313. # the << indicates that there should NOT be a new paragraph
  314. # META indicates a code block therefore no new paragraph
  315. #############################################################
  316. items = [item.strip() for item in text.split('\n\n')]
  317. if sep=='p':
  318. text = ''.join(p[:2]!='<<' and p!=META and '<p>%s</p>'%p or '%s'%p for p in items if p)
  319. elif sep=='br':
  320. text = '<br />'.join(items)
  321. #############################################################
  322. # finally get rid of <<
  323. #############################################################
  324. text=text.replace('<<','<')
  325. #############################################################
  326. # process all code text
  327. #############################################################
  328. parts = text.split(META)
  329. text = parts[0]
  330. for i,(code,b) in enumerate(segments):
  331. if code==None:
  332. html = META
  333. else:
  334. if b in extra:
  335. if code[:1]=='\n': code=code[1:]
  336. if code[-1:]=='\n': code=code[:-1]
  337. html = extra[b](code)
  338. elif b=='cite':
  339. html = '['+','.join('<a href="#%s" class="%s">%s</a>' \
  340. % (d,b,d) \
  341. for d in cgi.escape(code).split(','))+']'
  342. elif b=='latex':
  343. html = LATEX % code.replace('"','\"').replace('\n',' ')
  344. elif code[:1]=='\n' or code[-1:]=='\n':
  345. if code[:1]=='\n': code=code[1:]
  346. if code[-1:]=='\n': code=code[:-1]
  347. html = '<pre><code class="%s">%s</code></pre>' % (b,cgi.escape(code))
  348. else:
  349. if code[:1]=='\n': code=code[1:]
  350. if code[-1:]=='\n': code=code[:-1]
  351. html = '<code class="%s">%s</code>' % (b,cgi.escape(code))
  352. text = text+html+parts[i+1]
  353. return text
  354. def markmin2html(text,extra={},allowed={},sep='p'):
  355. return render(text,extra,allowed,sep)
  356. if __name__ == '__main__':
  357. import sys
  358. import doctest
  359. if sys.argv[1:2]==['-h']:
  360. print '<html><body>'+markmin2html(__doc__)+'</body></html>'
  361. elif len(sys.argv)>1:
  362. print '<html><body>'+markmin2html(open(sys.argv[1],'r').read())+'</body></html>'
  363. else:
  364. doctest.testmod()