PageRenderTime 52ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/gluon/contrib/markmin/markmin2html.py

https://bitbucket.org/rochacbruno/dal_on_flask/
Python | 424 lines | 417 code | 5 blank | 2 comment | 12 complexity | 005675d426ca5c790853d96eedb3d7e0 MD5 | raw file
  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
  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. ### Citations and References
  140. Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like
  141. ``
  142. - [[key]] value
  143. ``
  144. in the References will be translated into Latex
  145. ``
  146. \\bibitem{key} value
  147. ``
  148. Here is an example of usage:
  149. ``
  150. As shown in Ref.!`!`mdipierro`!`!:cite
  151. ## References
  152. - [[mdipierro]] web2py Manual, 3rd Edition, lulu.com
  153. ``
  154. ### Caveats
  155. ``<ul/>``, ``<ol/>``, ``<code/>``, ``<table/>``, ``<blockquote/>``, ``<h1/>``, ..., ``<h6/>`` do not have ``<p>...</p>`` around them.
  156. """
  157. META = 'META'
  158. regex_newlines = re.compile('(\n\r)|(\r\n)')
  159. regex_dd=re.compile('\$\$(?P<latex>.*?)\$\$')
  160. regex_code = re.compile('('+META+')|(``(?P<t>.*?)``(:(?P<c>\w+))?)',re.S)
  161. regex_maps = [
  162. (re.compile('[ \t\r]+\n'),'\n'),
  163. (re.compile('[ \t\r]+\n'),'\n'),
  164. (re.compile('\*\*(?P<t>[^\s\*]+( +[^\s\*]+)*)\*\*'),'<b>\g<t></b>'),
  165. (re.compile("''(?P<t>[^\s']+( +[^\s']+)*)''"),'<i>\g<t></i>'),
  166. (re.compile('^#{6} (?P<t>[^\n]+)',re.M),'\n\n<<h6>\g<t></h6>\n'),
  167. (re.compile('^#{5} (?P<t>[^\n]+)',re.M),'\n\n<<h5>\g<t></h5>\n'),
  168. (re.compile('^#{4} (?P<t>[^\n]+)',re.M),'\n\n<<h4>\g<t></h4>\n'),
  169. (re.compile('^#{3} (?P<t>[^\n]+)',re.M),'\n\n<<h3>\g<t></h3>\n'),
  170. (re.compile('^#{2} (?P<t>[^\n]+)',re.M),'\n\n<<h2>\g<t></h2>\n'),
  171. (re.compile('^#{1} (?P<t>[^\n]+)',re.M),'\n\n<<h1>\g<t></h1>\n'),
  172. (re.compile('^\- +(?P<t>.*)',re.M),'<<ul><li>\g<t></li></ul>'),
  173. (re.compile('^\+ +(?P<t>.*)',re.M),'<<ol><li>\g<t></li></ol>'),
  174. (re.compile('</ol>\n<<ol>'),''),
  175. (re.compile('</ul>\n<<ul>'),''),
  176. (re.compile('<<'),'\n\n<<'),
  177. (re.compile('\n\s+\n'),'\n\n')]
  178. regex_table = re.compile('^\-{4,}\n(?P<t>.*?)\n\-{4,}(:(?P<c>\w+))?\n',re.M|re.S)
  179. regex_anchor = re.compile('\[\[(?P<t>\S+)\]\]')
  180. regex_image_width = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center) +(?P<w>\d+px)\]\]')
  181. regex_image = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +(?P<p>left|right|center)\]\]')
  182. regex_video = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +video\]\]')
  183. regex_audio = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) +audio\]\]')
  184. regex_link = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+)\]\]')
  185. regex_link_popup = re.compile('\[\[(?P<t>.*?) +(?P<k>\S+) popup\]\]')
  186. regex_auto = re.compile('(?<!["\w\>])(?P<k>\w+://[\w\.\-\+\?&%\/]+)',re.M)
  187. def render(text,extra={},allowed={},sep='p'):
  188. """
  189. Arguments:
  190. - text is the text to be processed
  191. - extra is a dict like extra=dict(custom=lambda value: value) that process custom code
  192. as in " ``this is custom code``:custom "
  193. - allowed is a dictionary of list of allowed classes like
  194. allowed = dict(code=('python','cpp','java'))
  195. - sep can be 'p' to separate text in <p>...</p>
  196. or can be 'br' to separate text using <br />
  197. >>> render('this is\\n# a section\\nparagraph')
  198. '<p>this is</p><h1>a section</h1><p>paragraph</p>'
  199. >>> render('this is\\n## a subsection\\nparagraph')
  200. '<p>this is</p><h2>a subsection</h2><p>paragraph</p>'
  201. >>> render('this is\\n### a subsubsection\\nparagraph')
  202. '<p>this is</p><h3>a subsubsection</h3><p>paragraph</p>'
  203. >>> render('**hello world**')
  204. '<p><b>hello world</b></p>'
  205. >>> render('``hello world``')
  206. '<code class="">hello world</code>'
  207. >>> render('``hello world``:python')
  208. '<code class="python">hello world</code>'
  209. >>> render('``\\nhello\\nworld\\n``:python')
  210. '<pre><code class="python">hello\\nworld</code></pre>'
  211. >>> render("''hello world''")
  212. '<p><i>hello world</i></p>'
  213. >>> render('** hello** **world**')
  214. '<p>** hello** <b>world</b></p>'
  215. >>> render('- this\\n- is\\n- a list\\n\\nand this\\n- is\\n- another')
  216. '<ul><li>this</li><li>is</li><li>a list</li></ul><p>and this</p><ul><li>is</li><li>another</li></ul>'
  217. >>> render('+ this\\n+ is\\n+ a list\\n\\nand this\\n+ is\\n+ another')
  218. '<ol><li>this</li><li>is</li><li>a list</li></ol><p>and this</p><ol><li>is</li><li>another</li></ol>'
  219. >>> render("----\\na | b\\nc | d\\n----\\n")
  220. '<table class=""><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>'
  221. >>> render("----\\nhello world\\n----\\n")
  222. '<blockquote class="">hello world</blockquote>'
  223. >>> render('[[this is a link http://example.com]]')
  224. '<p><a href="http://example.com">this is a link</a></p>'
  225. >>> render('[[this is an image http://example.com left]]')
  226. '<p><img src="http://example.com" alt="this is an image" align="left" /></p>'
  227. >>> render('[[this is an image http://example.com left 200px]]')
  228. '<p><img src="http://example.com" alt="this is an image" align="left" width="200px" /></p>'
  229. >>> render('[[this is an image http://example.com video]]')
  230. '<p><video src="http://example.com" controls></video></p>'
  231. >>> render('[[this is an image http://example.com audio]]')
  232. '<p><audio src="http://example.com" controls></audio></p>'
  233. >>> render('[[this is a **link** http://example.com]]')
  234. '<p><a href="http://example.com">this is a <b>link</b></a></p>'
  235. >>> render("``aaa``:custom",extra=dict(custom=lambda text: 'x'+text+'x'))
  236. 'xaaax'
  237. >>> render(r"$$\int_a^b sin(x)dx$$")
  238. '<code class="latex">\\\\int_a^b sin(x)dx</code>'
  239. """
  240. #############################################################
  241. # replace all blocks marked with ``...``:class with META
  242. # store them into segments they will be treated as code
  243. #############################################################
  244. segments, i = [], 0
  245. text = regex_dd.sub('``\g<latex>``:latex ',text)
  246. text = regex_newlines.sub('\n',text)
  247. while True:
  248. item = regex_code.search(text,i)
  249. if not item: break
  250. if item.group()==META:
  251. segments.append((None,None))
  252. text = text[:item.start()]+META+text[item.end():]
  253. else:
  254. c = item.group('c') or ''
  255. if 'code' in allowed and not c in allowed['code']: c = ''
  256. code = item.group('t').replace('!`!','`')
  257. segments.append((code,c))
  258. text = text[:item.start()]+META+text[item.end():]
  259. i=item.start()+3
  260. #############################################################
  261. # do h1,h2,h3,h4,h5,h6,b,i,ol,ul and normalize spaces
  262. #############################################################
  263. text = '\n'.join(t.strip() for t in text.split('\n'))
  264. text = cgi.escape(text)
  265. for regex, sub in regex_maps:
  266. text = regex.sub(sub,text)
  267. #############################################################
  268. # process tables and blockquotes
  269. #############################################################
  270. while True:
  271. item = regex_table.search(text)
  272. if not item: break
  273. c = item.group('c') or ''
  274. if 'table' in allowed and not c in allowed['table']: c = ''
  275. content = item.group('t')
  276. if ' | ' in content:
  277. rows = content.replace('\n','</td></tr><tr><td>').replace(' | ','</td><td>')
  278. text = text[:item.start()] + '<<table class="%s"><tr><td>'%c + rows + '</td></tr></table>' + text[item.end():]
  279. else:
  280. text = text[:item.start()] + '<<blockquote class="%s">'%c + content + '</blockquote>' + text[item.end():]
  281. #############################################################
  282. # deal with images, videos, audios and links
  283. #############################################################
  284. text = regex_anchor.sub('<span id="\g<t>"><span>', text)
  285. text = regex_image_width.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" width="\g<w>" />', text)
  286. text = regex_image.sub('<img src="\g<k>" alt="\g<t>" align="\g<p>" />', text)
  287. text = regex_video.sub('<video src="\g<k>" controls></video>', text)
  288. text = regex_audio.sub('<audio src="\g<k>" controls></audio>', text)
  289. text = regex_link_popup.sub('<a href="\g<k>" target="_blank">\g<t></a>', text)
  290. text = regex_link.sub('<a href="\g<k>">\g<t></a>', text)
  291. text = regex_auto.sub('<a href="\g<k>">\g<k></a>', text)
  292. #############################################################
  293. # deal with paragraphs (trick <<ul, <<ol, <<table, <<h1, etc)
  294. # the << indicates that there should NOT be a new paragraph
  295. # META indicates a code block therefore no new paragraph
  296. #############################################################
  297. items = [item.strip() for item in text.split('\n\n')]
  298. if sep=='p':
  299. text = ''.join(p[:2]!='<<' and p!=META and '<p>%s</p>'%p or '%s'%p for p in items if p)
  300. elif sep=='br':
  301. text = '<br />'.join(items)
  302. #############################################################
  303. # finally get rid of <<
  304. #############################################################
  305. text=text.replace('<<','<')
  306. #############################################################
  307. # process all code text
  308. #############################################################
  309. parts = text.split(META)
  310. text = parts[0]
  311. for i,(code,b) in enumerate(segments):
  312. if code==None:
  313. html = META
  314. else:
  315. if b in extra:
  316. if code[:1]=='\n': code=code[1:]
  317. if code[-1:]=='\n': code=code[:-1]
  318. html = extra[b](code)
  319. elif b=='cite':
  320. html = '['+','.join('<a href="#%s" class="%s">%s</a>' % (d,b,d) \
  321. for d in cgi.escape(code).split(','))+']'
  322. elif code[:1]=='\n' or code[-1:]=='\n':
  323. if code[:1]=='\n': code=code[1:]
  324. if code[-1:]=='\n': code=code[:-1]
  325. html = '<pre><code class="%s">%s</code></pre>' % (b,cgi.escape(code))
  326. else:
  327. if code[:1]=='\n': code=code[1:]
  328. if code[-1:]=='\n': code=code[:-1]
  329. html = '<code class="%s">%s</code>' % (b,cgi.escape(code))
  330. text = text+html+parts[i+1]
  331. return text
  332. def markmin2html(text,extra={},allowed={},sep='p'):
  333. return render(text,extra,allowed,sep)
  334. if __name__ == '__main__':
  335. import sys
  336. import doctest
  337. if sys.argv[1:2]==['-h']:
  338. print '<html><body>'+markmin2html(__doc__)+'</body></html>'
  339. elif len(sys.argv)>1:
  340. print '<html><body>'+markmin2html(open(sys.argv[1],'r').read())+'</body></html>'
  341. else:
  342. doctest.testmod()