PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/gluon/contrib/markmin/markmin2html.py

https://github.com/clach04/web2py
Python | 1431 lines | 1349 code | 66 blank | 16 comment | 14 complexity | b53d76517e4ecb89c8d6dc4e069e5cf6 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # created by Massimo Di Pierro
  4. # recreated by Vladyslav Kozlovskyy
  5. # license MIT/BSD/GPL
  6. import re
  7. from cgi import escape
  8. from string import maketrans
  9. """
  10. TODO: next version should use MathJax
  11. <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js">
  12. MathJax.Hub.Config({
  13. extensions: ["tex2jax.js","TeX/AMSmath.js","TeX/AMSsymbols.js"],
  14. jax: ["input/TeX", "output/HTML-CSS"],
  15. tex2jax: {
  16. inlineMath: [ ['$','$'], ["\\(","\\)"] ],
  17. displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
  18. },
  19. "HTML-CSS": { availableFonts: ["TeX"] }
  20. });
  21. </script>
  22. """
  23. __all__ = ['render', 'markmin2html', 'markmin_escape']
  24. __doc__ = """
  25. # Markmin markup language
  26. ## About
  27. 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``.
  28. Example of usage:
  29. ``
  30. m = "Hello **world** [[link http://web2py.com]]"
  31. from markmin2html import markmin2html
  32. print markmin2html(m)
  33. from markmin2latex import markmin2latex
  34. print markmin2latex(m)
  35. from markmin2pdf import markmin2pdf # requires pdflatex
  36. print markmin2pdf(m)
  37. ``
  38. ====================
  39. # This is a test block
  40. with new features:
  41. This is a blockquote with
  42. a list with tables in it:
  43. -----------
  44. This is a paragraph before list.
  45. You can continue paragraph on the
  46. next lines.
  47. This is an ordered list with tables:
  48. + Item 1
  49. + Item 2
  50. + --------
  51. aa|bb|cc
  52. 11|22|33
  53. --------:tableclass1[tableid1]
  54. + Item 4
  55. -----------
  56. T1| T2| t3
  57. ===========
  58. aaa|bbb|ccc
  59. ddd|fff|ggg
  60. 123|0 |5.0
  61. -----------:tableclass1
  62. -----------:blockquoteclass[blockquoteid]
  63. This this a new paragraph
  64. with a followed table.
  65. Table has header, footer, sections,
  66. odd and even rows:
  67. -------------------------------
  68. **Title 1**|**Title 2**|**Title 3**
  69. ==============================
  70. data 1 | data 2 | 2.00
  71. data 3 |data4(long)| 23.00
  72. |data 5 | 33.50
  73. ==============================
  74. New section|New data | 5.00
  75. data 1 |data2(long)|100.45
  76. |data 3 | 12.50
  77. data 4 | data 5 | .33
  78. data 6 |data7(long)| 8.01
  79. |data 8 | 514
  80. ==============================
  81. Total: | 9 items |698,79
  82. ------------------------------:tableclass1[tableid2]
  83. ## Multilevel
  84. lists
  85. Now lists can be multilevel:
  86. + Ordered item 1 on level 1.
  87. You can continue item text on
  88. next strings
  89. . paragraph in an item
  90. ++. Ordered item 1 of sublevel 2 with
  91. a paragraph (paragraph can start
  92. with point after plus or minus
  93. characters, e.g. **++.** or **--.**)
  94. ++. This is another item. But with 3 paragraphs,
  95. blockquote and sublists:
  96. .. This is the second paragraph in the item. You
  97. can add paragraphs to an item, using point
  98. notation, where first characters in the string
  99. are sequence of points with space between
  100. them and another string. For example, this
  101. paragraph (in sublevel 2) starts with two points:
  102. ``.. This is the second paragraph...``
  103. .. ----------
  104. ### this is a blockquote in a list
  105. You can use blockquote with headers, paragraphs,
  106. tables and lists in it:
  107. Tables can have or have not header and footer.
  108. This table is defined without any header
  109. and footer in it:
  110. ---------------------
  111. red |fox | 0
  112. blue |dolphin | 1000
  113. green|leaf | 10000
  114. ---------------------
  115. ----------
  116. .. This is yet another paragraph in the item.
  117. --- This is an item of unordered list **(sublevel 3)**
  118. --- This is the second item of the unordered list ''(sublevel 3)''
  119. ++++++ This is a single item of ordered list in sublevel 6
  120. .... and this is a paragraph in sublevel 4
  121. ---. This is a new item with paragraph in sublevel 3.
  122. ++++ Start ordered list in sublevel 4 with code block: ``
  123. line 1
  124. line 2
  125. line 3
  126. ``
  127. ++++. Yet another item with code block (we need to indent \`\` to add code block as part of item):
  128. ``
  129. line 1
  130. line 2
  131. line 3
  132. ``
  133. This item finishes with this paragraph.
  134. ... Item in sublevel 3 can be continued with paragraphs.
  135. ... ``
  136. this is another
  137. code block
  138. in the
  139. sublevel 3 item
  140. ``
  141. +++ The last item in sublevel 3
  142. .. This is a continuous paragraph for item 2 in sublevel 2.
  143. You can use such structure to create difficult structured
  144. documents.
  145. ++ item 3 in sublevel 2
  146. -- item 1 in sublevel 2 (new unordered list)
  147. -- item 2 in sublevel 2
  148. -- item 3 in sublevel 2
  149. ++ item 1 in sublevel 2 (new ordered list)
  150. ++ item 2 in sublevel 2
  151. ++ item 3 in sublevle 2
  152. + item 2 in level 1
  153. + item 3 in level 1
  154. - new unordered list (item 1 in level 1)
  155. - level 2 in level 1
  156. - level 3 in level 1
  157. - level 4 in level 1
  158. ## This is the last section of the test
  159. Single paragraph with '----' in it will be turned into separator:
  160. -----------
  161. And this is the last paragraph in
  162. the test. Be happy!
  163. ====================
  164. ## Why?
  165. We wanted a markup language with the following requirements:
  166. - less than 300 lines of functional code
  167. - easy to read
  168. - secure
  169. - support table, ul, ol, code
  170. - support html5 video and audio elements (html serialization only)
  171. - can align images and resize them
  172. - can specify class for tables, blockquotes and code elements
  173. - can add anchors
  174. - does not use _ for markup (since it creates odd behavior)
  175. - automatically links urls
  176. - fast
  177. - easy to extend
  178. - supports latex and pdf including references
  179. - allows to describe the markup in the markup (this document is generated from markmin syntax)
  180. (results depend on text but in average for text ~100K markmin is 30% faster than markdown, for text ~10K it is 10x faster)
  181. 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]]
  182. ## Download
  183. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2html.py
  184. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2latex.py
  185. - http://web2py.googlecode.com/hg/gluon/contrib/markmin/markmin2pdf.py
  186. markmin2html.py and markmin2latex.py are single files and have no web2py dependence. Their license is BSD.
  187. ## Examples
  188. ### Bold, italic, code and links
  189. ------------------------------------------------------------------------------
  190. **SOURCE** | **OUTPUT**
  191. ==============================================================================
  192. ``# title`` | **title**
  193. ``## section`` | **section**
  194. ``### subsection`` | **subsection**
  195. ``**bold**`` | **bold**
  196. ``''italic''`` | ''italic''
  197. ``~~strikeout~~`` | ~~strikeout~~
  198. ``!`!`verbatim`!`!`` | ``verbatim``
  199. ``\`\`color with **bold**\`\`:red`` | ``color with **bold**``:red
  200. ``\`\`many colors\`\`:color[blue:#ffff00]`` | ``many colors``:color[blue:#ffff00]
  201. ``http://google.com`` | http://google.com
  202. ``[[**click** me #myanchor]]`` | [[**click** me #myanchor]]
  203. ``[[click me [extra info] #myanchor popup]]`` | [[click me [extra info] #myanchor popup]]
  204. -------------------------------------------------------------------------------
  205. ### More on links
  206. The format is always ``[[title link]]`` or ``[[title [extra] link]]``. Notice you can nest bold, italic, strikeout and code inside the link ``title``.
  207. ### Anchors [[myanchor]]
  208. You can place an anchor anywhere in the text using the syntax ``[[name]]`` where ''name'' is the name of the anchor.
  209. You can then link the anchor with [[link #myanchor]], i.e. ``[[link #myanchor]]`` or [[link with an extra info [extra info] #myanchor]], i.e.
  210. ``[[link with an extra info [extra info] #myanchor]]``.
  211. ### Images
  212. [[alt-string for the image [the image title] http://www.web2py.com/examples/static/web2py_logo.png right 200px]]
  213. This paragraph has an image aligned to the right with a width of 200px. Its is placed using the code
  214. ``[[alt-string for the image [the image title] http://www.web2py.com/examples/static/web2py_logo.png right 200px]]``.
  215. ### Unordered Lists
  216. ``
  217. - Dog
  218. - Cat
  219. - Mouse
  220. ``
  221. is rendered as
  222. - Dog
  223. - Cat
  224. - Mouse
  225. Two new lines between items break the list in two lists.
  226. ### Ordered Lists
  227. ``
  228. + Dog
  229. + Cat
  230. + Mouse
  231. ``
  232. is rendered as
  233. + Dog
  234. + Cat
  235. + Mouse
  236. ### Multilevel Lists
  237. ``
  238. + Dogs
  239. -- red
  240. -- brown
  241. -- black
  242. + Cats
  243. -- fluffy
  244. -- smooth
  245. -- bald
  246. + Mice
  247. -- small
  248. -- big
  249. -- huge
  250. ``
  251. is rendered as
  252. + Dogs
  253. -- red
  254. -- brown
  255. -- black
  256. + Cats
  257. -- fluffy
  258. -- smooth
  259. -- bald
  260. + Mice
  261. -- small
  262. -- big
  263. -- huge
  264. ### Tables (with optional header and/or footer)
  265. Something like this
  266. ``
  267. -----------------
  268. **A**|**B**|**C**
  269. =================
  270. 0 | 0 | X
  271. 0 | X | 0
  272. X | 0 | 0
  273. =================
  274. **D**|**F**|**G**
  275. -----------------:abc[id]
  276. ``
  277. is a table and is rendered as
  278. -----------------
  279. **A**|**B**|**C**
  280. =================
  281. 0 | 0 | X
  282. 0 | X | 0
  283. X | 0 | 0
  284. =================
  285. **D**|**F**|**G**
  286. -----------------:abc[id]
  287. Four or more dashes delimit the table and | separates the columns.
  288. The ``:abc``, ``:id[abc_1]`` or ``:abc[abc_1]`` at the end sets the class and/or id for the table and it is optional.
  289. ### Blockquote
  290. A table with a single cell is rendered as a blockquote:
  291. -----
  292. Hello world
  293. -----
  294. Blockquote can contain headers, paragraphs, lists and tables:
  295. ``
  296. -----
  297. This is a paragraph in a blockquote
  298. + item 1
  299. + item 2
  300. -- item 2.1
  301. -- item 2.2
  302. + item 3
  303. ---------
  304. 0 | 0 | X
  305. 0 | X | 0
  306. X | 0 | 0
  307. ---------:tableclass1
  308. -----
  309. ``
  310. is rendered as:
  311. -----
  312. This is a paragraph in a blockquote
  313. + item 1
  314. + item 2
  315. -- item 2.1
  316. -- item 2.2
  317. + item 3
  318. ---------
  319. 0 | 0 | X
  320. 0 | X | 0
  321. X | 0 | 0
  322. ---------:tableclass1
  323. -----
  324. ### Code, ``<code>``, escaping and extra stuff
  325. ``
  326. def test():
  327. return "this is Python code"
  328. ``:python
  329. Optionally a ` inside a ``!`!`...`!`!`` block can be inserted escaped with !`!.
  330. **NOTE:** You can escape markmin constructions (\\'\\',\`\`,\*\*,\~\~,\[,\{,\]\},\$,\@) with '\\\\' character:
  331. so \\\\`\\\\` can replace !`!`! escape string
  332. The ``:python`` after the markup is also optional. If present, by default, it is used to set the class of the <code> block.
  333. The behavior can be overridden by passing an argument ``extra`` to the ``render`` function. For example:
  334. ``
  335. markmin2html("!`!!`!aaa!`!!`!:custom",
  336. extra=dict(custom=lambda text: 'x'+text+'x'))
  337. ``:python
  338. generates
  339. ``'xaaax'``:python
  340. (the ``!`!`...`!`!:custom`` block is rendered by the ``custom=lambda`` function passed to ``render``).
  341. ### Line breaks
  342. ``[[NEWLINE]]`` tag is used to break lines:
  343. ``
  344. #### Multiline [[NEWLINE]]
  345. title
  346. paragraph [[NEWLINE]]
  347. with breaks[[NEWLINE]]in it
  348. ``
  349. generates:
  350. #### Multiline [[NEWLINE]]
  351. title
  352. paragraph [[NEWLINE]]
  353. with breaks[[NEWLINE]]in it
  354. ### Html5 support
  355. Markmin also supports the <video> and <audio> html5 tags using the notation:
  356. ``
  357. [[message link video]]
  358. [[message link audio]]
  359. [[message [title] link video]]
  360. [[message [title] link audio]]
  361. ``
  362. where ``message`` will be shown in browsers without HTML5 video/audio tags support.
  363. ### Latex and other extensions
  364. Formulas can be embedded into HTML with ''\$\$``formula``\$\$''.
  365. You can use Google charts to render the formula:
  366. ``
  367. LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" />'
  368. markmin2html(text,{'latex':lambda code: LATEX % code.replace('"','\\\\"')})
  369. ``
  370. ### Code with syntax highlighting
  371. This requires a syntax highlighting tool, such as the web2py CODE helper.
  372. ``
  373. extra={'code_cpp':lambda text: CODE(text,language='cpp').xml(),
  374. 'code_java':lambda text: CODE(text,language='java').xml(),
  375. 'code_python':lambda text: CODE(text,language='python').xml(),
  376. 'code_html':lambda text: CODE(text,language='html').xml()}
  377. ``
  378. or simple:
  379. ``
  380. extra={'code':lambda text,lang='python': CODE(text,language=lang).xml()}
  381. ``
  382. ``
  383. markmin2html(text,extra=extra)
  384. ``
  385. Code can now be marked up as in this example:
  386. ``
  387. !`!`
  388. <html><body>example</body></html>
  389. !`!`:code_html
  390. ``
  391. OR
  392. ``
  393. !`!`
  394. <html><body>example</body></html>
  395. !`!`:code[html]
  396. ``
  397. ### Citations and References
  398. Citations are treated as internal links in html and proper citations in latex if there is a final section called "References". Items like
  399. ``
  400. - [[key]] value
  401. ``
  402. in the References will be translated into Latex
  403. ``
  404. \\bibitem{key} value
  405. ``
  406. Here is an example of usage:
  407. ``
  408. As shown in Ref.!`!`mdipierro`!`!:cite
  409. ## References
  410. - [[mdipierro]] web2py Manual, 3rd Edition, lulu.com
  411. ``
  412. ### Caveats
  413. ``<ul/>``, ``<ol/>``, ``<code/>``, ``<table/>``, ``<blockquote/>``, ``<h1/>``, ..., ``<h6/>`` do not have ``<p>...</p>`` around them.
  414. """
  415. html_colors=['aqua', 'black', 'blue', 'fuchsia', 'gray', 'green',
  416. 'lime', 'maroon', 'navy', 'olive', 'purple', 'red',
  417. 'silver', 'teal', 'white', 'yellow']
  418. META = '\x06'
  419. LINK = '\x07'
  420. DISABLED_META = '\x08'
  421. LATEX = '<img src="http://chart.apis.google.com/chart?cht=tx&chl=%s" />'
  422. regex_URL=re.compile(r'@/(?P<a>\w*)/(?P<c>\w*)/(?P<f>\w*(\.\w+)?)(/(?P<args>[\w\.\-/]+))?')
  423. regex_env=re.compile(r'@\{(?P<a>[\w\-\.]+?)(\:(?P<b>.*?))?\}')
  424. regex_expand_meta = re.compile('('+META+'|'+DISABLED_META+'|````)')
  425. regex_dd=re.compile(r'\$\$(?P<latex>.*?)\$\$')
  426. regex_code = re.compile('('+META+'|'+DISABLED_META+r'|````)|(``(?P<t>.+?)``(?::(?P<c>[a-zA-Z][_a-zA-Z\-\d]*)(?:\[(?P<p>[^\]]*)\])?)?)',re.S)
  427. regex_strong=re.compile(r'\*\*(?P<t>[^\s*]+( +[^\s*]+)*)\*\*')
  428. regex_del=re.compile(r'~~(?P<t>[^\s*]+( +[^\s*]+)*)~~')
  429. regex_em=re.compile(r"''(?P<t>[^\s']+(?: +[^\s']+)*)''")
  430. regex_num=re.compile(r"^\s*[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?\s*$")
  431. regex_list=re.compile('^(?:(?:(#{1,6})|(?:(\.+|\++|\-+)(\.)?))\s*)?(.*)$')
  432. regex_bq_headline=re.compile('^(?:(\.+|\++|\-+)(\.)?\s+)?(-{3}-*)$')
  433. regex_tq=re.compile('^(-{3}-*)(?::(?P<c>[a-zA-Z][_a-zA-Z\-\d]*)(?:\[(?P<p>[a-zA-Z][_a-zA-Z\-\d]*)\])?)?$')
  434. regex_proto = re.compile(r'(?<!["\w>/=])(?P<p>\w+):(?P<k>\w+://[\w\d\-+=?%&/:.]+)', re.M)
  435. regex_auto = re.compile(r'(?<!["\w>/=])(?P<k>\w+://[\w\d\-+_=?%&/:.]+)',re.M)
  436. regex_link=re.compile(r'('+LINK+r')|\[\[(?P<s>.+?)\]\]',re.S)
  437. regex_link_level2=re.compile(r'^(?P<t>\S.*?)?(?:\s+\[(?P<a>.+?)\])?(?:\s+(?P<k>\S+))?(?:\s+(?P<p>popup))?\s*$',re.S)
  438. regex_media_level2=re.compile(r'^(?P<t>\S.*?)?(?:\s+\[(?P<a>.+?)\])?(?:\s+(?P<k>\S+))?\s+(?P<p>img|IMG|left|right|center|video|audio)(?:\s+(?P<w>\d+px))?\s*$',re.S)
  439. regex_markmin_escape = re.compile(r"(\\*)(['`:*~\\[\]{}@\$+\-.#\n])")
  440. regex_backslash = re.compile(r"\\(['`:*~\\[\]{}@\$+\-.#\n])")
  441. ttab_in = maketrans("'`:*~\\[]{}@$+-.#\n", '\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x05')
  442. ttab_out = maketrans('\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x05',"'`:*~\\[]{}@$+-.#\n")
  443. def markmin_escape(text):
  444. """ insert \\ before markmin control characters: '`:*~[]{}@$ """
  445. return regex_markmin_escape.sub(
  446. lambda m: '\\'+m.group(0).replace('\\','\\\\'), text)
  447. def replace_autolinks(text,autolinks):
  448. return regex_auto.sub(lambda m: autolinks(m.group('k')), text)
  449. def replace_at_urls(text,url):
  450. # this is experimental @{function/args}
  451. def u1(match,url=url):
  452. a,c,f,args = match.group('a','c','f','args')
  453. return url(a=a or None,c=c or None,f = f or None,
  454. args=(args or '').split('/'), scheme=True, host=True)
  455. return regex_URL.sub(u1,text)
  456. def replace_components(text,env):
  457. def u2(match, env=env):
  458. f = env.get(match.group('a'), match.group(0))
  459. if callable(f):
  460. try:
  461. f = f(match.group('b'))
  462. except Exception, e:
  463. f = 'ERROR: %s' % e
  464. return str(f)
  465. return regex_env.sub(u2, text)
  466. def autolinks_simple(url):
  467. """
  468. it automatically converts the url to link,
  469. image, video or audio tag
  470. """
  471. u_url=url.lower()
  472. if u_url.endswith(('.jpg','.jpeg','.gif','.png')):
  473. return '<img src="%s" controls />' % url
  474. elif u_url.endswith(('.mp4','.mpeg','.mov','.ogv')):
  475. return '<video src="%s" controls></video>' % url
  476. elif u_url.endswith(('.mp3','.wav','.ogg')):
  477. return '<audio src="%s" controls></audio>' % url
  478. return '<a href="%s">%s</a>' % (url,url)
  479. def protolinks_simple(proto, url):
  480. """
  481. it converts url to html-string using appropriate proto-prefix:
  482. Uses for construction "proto:url", e.g.:
  483. "iframe:http://www.example.com/path" will call protolinks()
  484. with parameters:
  485. proto="iframe"
  486. url="http://www.example.com/path"
  487. """
  488. if proto in ('iframe','embed'): #== 'iframe':
  489. return '<iframe src="%s" frameborder="0" allowfullscreen></iframe>'%url
  490. #elif proto == 'embed': # NOTE: embed is a synonym to iframe now
  491. # return '<a href="%s" class="%sembed">%s></a>'%(url,class_prefix,url)
  492. elif proto == 'qr':
  493. return '<img style="width:100px" src="http://chart.apis.google.com/chart?cht=qr&chs=100x100&chl=%s&choe=UTF-8&chld=H" alt="QR Code" title="QR Code" />'%url
  494. return proto+':'+url
  495. def render(text,
  496. extra={},
  497. allowed={},
  498. sep='p',
  499. URL=None,
  500. environment=None,
  501. latex='google',
  502. autolinks='default',
  503. protolinks='default',
  504. class_prefix='',
  505. id_prefix='markmin_',
  506. pretty_print=False):
  507. """
  508. Arguments:
  509. - text is the text to be processed
  510. - extra is a dict like extra=dict(custom=lambda value: value) that process custom code
  511. as in " ``this is custom code``:custom "
  512. - allowed is a dictionary of list of allowed classes like
  513. allowed = dict(code=('python','cpp','java'))
  514. - sep can be 'p' to separate text in <p>...</p>
  515. or can be 'br' to separate text using <br />
  516. - URL -
  517. - environment is a dictionary of environment variables (can be accessed with @{variable}
  518. - latex -
  519. - autolinks is a function to convert auto urls to html-code (default is autolinks(url) )
  520. - protolinks is a function to convert proto-urls (e.g."proto:url") to html-code
  521. (default is protolinks(proto,url))
  522. - class_prefix is a prefix for ALL classes in markmin text. E.g. if class_prefix='my_'
  523. then for ``test``:cls class will be changed to "my_cls" (default value is '')
  524. - id_prefix is prefix for ALL ids in markmin text (default value is 'markmin_'). E.g.:
  525. -- [[id]] will be converted to <span class="anchor" id="markmin_id"></span>
  526. -- [[link #id]] will be converted to <a href="#markmin_id">link</a>
  527. -- ``test``:cls[id] will be converted to <code class="cls" id="markmin_id">test</code>
  528. >>> render('this is\\n# a section\\n\\nparagraph')
  529. '<p>this is</p><h1>a section</h1><p>paragraph</p>'
  530. >>> render('this is\\n## a subsection\\n\\nparagraph')
  531. '<p>this is</p><h2>a subsection</h2><p>paragraph</p>'
  532. >>> render('this is\\n### a subsubsection\\n\\nparagraph')
  533. '<p>this is</p><h3>a subsubsection</h3><p>paragraph</p>'
  534. >>> render('**hello world**')
  535. '<p><strong>hello world</strong></p>'
  536. >>> render('``hello world``')
  537. '<code>hello world</code>'
  538. >>> render('``hello world``:python')
  539. '<code class="python">hello world</code>'
  540. >>> render('``\\nhello\\nworld\\n``:python')
  541. '<pre><code class="python">hello\\nworld</code></pre>'
  542. >>> render('``hello world``:python[test_id]')
  543. '<code class="python" id="markmin_test_id">hello world</code>'
  544. >>> render('``hello world``:id[test_id]')
  545. '<code id="markmin_test_id">hello world</code>'
  546. >>> render('``\\nhello\\nworld\\n``:python[test_id]')
  547. '<pre><code class="python" id="markmin_test_id">hello\\nworld</code></pre>'
  548. >>> render('``\\nhello\\nworld\\n``:id[test_id]')
  549. '<pre><code id="markmin_test_id">hello\\nworld</code></pre>'
  550. >>> render("''hello world''")
  551. '<p><em>hello world</em></p>'
  552. >>> render('** hello** **world**')
  553. '<p>** hello** <strong>world</strong></p>'
  554. >>> render('- this\\n- is\\n- a list\\n\\nand this\\n- is\\n- another')
  555. '<ul><li>this</li><li>is</li><li>a list</li></ul><p>and this</p><ul><li>is</li><li>another</li></ul>'
  556. >>> render('+ this\\n+ is\\n+ a list\\n\\nand this\\n+ is\\n+ another')
  557. '<ol><li>this</li><li>is</li><li>a list</li></ol><p>and this</p><ol><li>is</li><li>another</li></ol>'
  558. >>> render("----\\na | b\\nc | d\\n----\\n")
  559. '<table><tbody><tr class="first"><td>a</td><td>b</td></tr><tr class="even"><td>c</td><td>d</td></tr></tbody></table>'
  560. >>> render("----\\nhello world\\n----\\n")
  561. '<blockquote>hello world</blockquote>'
  562. >>> render('[[http://example.com]]')
  563. '<p><span class="anchor" id="markmin_http://example.com"></span></p>'
  564. >>> render('[[ http://example.com]]')
  565. '<p><a href="http://example.com">http://example.com</a></p>'
  566. >>> render('[[bookmark [http://example.com] ]]')
  567. '<p><span class="anchor" id="markmin_bookmark"><a href="http://example.com">http://example.com</a></span></p>'
  568. >>> render('[[this is a link http://example.com]]')
  569. '<p><a href="http://example.com">this is a link</a></p>'
  570. >>> render('[[this is an image http://example.com left]]')
  571. '<p><img src="http://example.com" alt="this is an image" style="float:left" /></p>'
  572. >>> render('[[this is an image http://example.com left 200px]]')
  573. '<p><img src="http://example.com" alt="this is an image" style="float:left;width:200px" /></p>'
  574. >>> render("[[Your browser doesn't support <video> HTML5 tag http://example.com video]]")
  575. '<p><video controls="controls"><source src="http://example.com" />Your browser doesn\\'t support &lt;video&gt; HTML5 tag</video></p>'
  576. >>> render("[[Your browser doesn't support <audio> HTML5 tag http://example.com audio]]")
  577. '<p><audio controls="controls"><source src="http://example.com" />Your browser doesn\\'t support &lt;audio&gt; HTML5 tag</audio></p>'
  578. >>> render("[[Your\\nbrowser\\ndoesn't\\nsupport\\n<audio> HTML5 tag http://exam\\\\\\nple.com\\naudio]]")
  579. '<p><audio controls="controls"><source src="http://example.com" />Your browser doesn\\'t support &lt;audio&gt; HTML5 tag</audio></p>'
  580. >>> render('[[this is a **link** http://example.com]]')
  581. '<p><a href="http://example.com">this is a <strong>link</strong></a></p>'
  582. >>> render("``aaa``:custom", extra=dict(custom=lambda text: 'x'+text+'x'))
  583. 'xaaax'
  584. >>> print render(r"$$\int_a^b sin(x)dx$$")
  585. <img src="http://chart.apis.google.com/chart?cht=tx&chl=\\int_a^b sin(x)dx" />
  586. >>> markmin2html(r"use backslash: \[\[[[mess\[[ag\]]e link]]\]]")
  587. '<p>use backslash: [[<a href="link">mess[[ag]]e</a>]]</p>'
  588. >>> markmin2html("backslash instead of exclamation sign: \``probe``")
  589. '<p>backslash instead of exclamation sign: ``probe``</p>'
  590. >>> render(r"simple image: [[\[[this is an image\]] http://example.com IMG]]!!!")
  591. '<p>simple image: <img src="http://example.com" alt="[[this is an image]]" />!!!</p>'
  592. >>> render(r"simple link no anchor with popup: [[ http://example.com popup]]")
  593. '<p>simple link no anchor with popup: <a href="http://example.com" target="_blank">http://example.com</a></p>'
  594. >>> render("auto-url: http://example.com")
  595. '<p>auto-url: <a href="http://example.com">http://example.com</a></p>'
  596. >>> render("auto-image: (http://example.com/image.jpeg)")
  597. '<p>auto-image: (<img src="http://example.com/image.jpeg" controls />)</p>'
  598. >>> render("qr: (qr:http://example.com/image.jpeg)")
  599. '<p>qr: (<img style="width:100px" src="http://chart.apis.google.com/chart?cht=qr&chs=100x100&chl=http://example.com/image.jpeg&choe=UTF-8&chld=H" alt="QR Code" title="QR Code" />)</p>'
  600. >>> render("embed: (embed:http://example.com/page)")
  601. '<p>embed: (<iframe src="http://example.com/page" frameborder="0" allowfullscreen></iframe>)</p>'
  602. >>> render("iframe: (iframe:http://example.com/page)")
  603. '<p>iframe: (<iframe src="http://example.com/page" frameborder="0" allowfullscreen></iframe>)</p>'
  604. >>> render("title1: [[test message [simple \[test\] title] http://example.com ]] test")
  605. '<p>title1: <a href="http://example.com" title="simple [test] title">test message</a> test</p>'
  606. >>> render("title2: \[\[[[test message [simple title] http://example.com popup]]\]]")
  607. '<p>title2: [[<a href="http://example.com" title="simple title" target="_blank">test message</a>]]</p>'
  608. >>> render("title3: [[ [link w/o anchor but with title] http://www.example.com ]]")
  609. '<p>title3: <a href="http://www.example.com" title="link w/o anchor but with title">http://www.example.com</a></p>'
  610. >>> render("title4: [[ [simple title] http://www.example.com popup]]")
  611. '<p>title4: <a href="http://www.example.com" title="simple title" target="_blank">http://www.example.com</a></p>'
  612. >>> render("title5: [[test message [simple title] http://example.com IMG]]")
  613. '<p>title5: <img src="http://example.com" alt="test message" title="simple title" /></p>'
  614. >>> render("title6: [[[test message w/o title] http://example.com IMG]]")
  615. '<p>title6: <img src="http://example.com" alt="[test message w/o title]" /></p>'
  616. >>> render("title7: [[[this is not a title] [this is a title] http://example.com IMG]]")
  617. '<p>title7: <img src="http://example.com" alt="[this is not a title]" title="this is a title" /></p>'
  618. >>> render("title8: [[test message [title] http://example.com center]]")
  619. '<p>title8: <p style="text-align:center"><img src="http://example.com" alt="test message" title="title" /></p></p>'
  620. >>> render("title9: [[test message [title] http://example.com left]]")
  621. '<p>title9: <img src="http://example.com" alt="test message" title="title" style="float:left" /></p>'
  622. >>> render("title10: [[test message [title] http://example.com right 100px]]")
  623. '<p>title10: <img src="http://example.com" alt="test message" title="title" style="float:right;width:100px" /></p>'
  624. >>> render("title11: [[test message [title] http://example.com center 200px]]")
  625. '<p>title11: <p style="text-align:center"><img src="http://example.com" alt="test message" title="title" style="width:200px" /></p></p>'
  626. >>> render(r"\\[[probe]]")
  627. '<p>[[probe]]</p>'
  628. >>> render(r"\\\\[[probe]]")
  629. '<p>\\\\<span class="anchor" id="markmin_probe"></span></p>'
  630. >>> render(r"\\\\\\[[probe]]")
  631. '<p>\\\\[[probe]]</p>'
  632. >>> render(r"\\\\\\\\[[probe]]")
  633. '<p>\\\\\\\\<span class="anchor" id="markmin_probe"></span></p>'
  634. >>> render(r"\\\\\\\\\[[probe]]")
  635. '<p>\\\\\\\\[[probe]]</p>'
  636. >>> render(r"\\\\\\\\\\\[[probe]]")
  637. '<p>\\\\\\\\\\\\<span class="anchor" id="markmin_probe"></span></p>'
  638. >>> render("``[[ [\\[[probe\]\\]] URL\\[x\\]]]``:red[dummy_params]")
  639. '<span style="color: red"><a href="URL[x]" title="[[probe]]">URL[x]</a></span>'
  640. >>> render("the \\**text**")
  641. '<p>the **text**</p>'
  642. >>> render("the \\``text``")
  643. '<p>the ``text``</p>'
  644. >>> render("the \\\\''text''")
  645. "<p>the ''text''</p>"
  646. >>> render("the [[link [**with** ``<b>title</b>``:red] http://www.example.com]]")
  647. '<p>the <a href="http://www.example.com" title="**with** ``&lt;b&gt;title&lt;/b&gt;``:red">link</a></p>'
  648. >>> render("the [[link \\[**without** ``<b>title</b>``:red\\] http://www.example.com]]")
  649. '<p>the <a href="http://www.example.com">link [<strong>without</strong> <span style="color: red">&lt;b&gt;title&lt;/b&gt;</span>]</a></p>'
  650. >>> render("aaa-META-``code``:text[]-LINK-[[link http://www.example.com]]-LINK-[[image http://www.picture.com img]]-end")
  651. '<p>aaa-META-<code class="text">code</code>-LINK-<a href="http://www.example.com">link</a>-LINK-<img src="http://www.picture.com" alt="image" />-end</p>'
  652. >>> render("[[<a>test</a> [<a>test2</a>] <a>text3</a>]]")
  653. '<p><a href="&lt;a&gt;text3&lt;/a&gt;" title="&lt;a&gt;test2&lt;/a&gt;">&lt;a&gt;test&lt;/a&gt;</a></p>'
  654. >>> render("[[<a>test</a> [<a>test2</a>] <a>text3</a> IMG]]")
  655. '<p><img src="&lt;a&gt;text3&lt;/a&gt;" alt="&lt;a&gt;test&lt;/a&gt;" title="&lt;a&gt;test2&lt;/a&gt;" /></p>'
  656. >>> render("**bold** ''italic'' ~~strikeout~~")
  657. '<p><strong>bold</strong> <em>italic</em> <del>strikeout</del></p>'
  658. >>> render("this is ``a red on yellow text``:c[#FF0000:#FFFF00]")
  659. '<p>this is <span style="color: #FF0000;background-color: #FFFF00;">a red on yellow text</span></p>'
  660. >>> render("this is ``a text with yellow background``:c[:yellow]")
  661. '<p>this is <span style="background-color: yellow;">a text with yellow background</span></p>'
  662. >>> render("this is ``a colored text (RoyalBlue)``:color[rgb(65,105,225)]")
  663. '<p>this is <span style="color: rgb(65,105,225);">a colored text (RoyalBlue)</span></p>'
  664. >>> render("this is ``a green text``:color[green:]")
  665. '<p>this is <span style="color: green;">a green text</span></p>'
  666. >>> render("**@{probe:1}**", environment=dict(probe=lambda t:"test %s" % t))
  667. '<p><strong>test 1</strong></p>'
  668. >>> render('[[id1 [span **messag** in ''markmin''] ]] ... [[**link** to id [link\\\'s title] #mark1]]')
  669. '<p><span class="anchor" id="markmin_id1">span <strong>messag</strong> in markmin</span> ... <a href="#markmin_mark1" title="link\\\'s title"><strong>link</strong> to id</a></p>'
  670. >>> render('# Multiline[[NEWLINE]]\\n title\\nParagraph[[NEWLINE]]\\nwith breaks[[NEWLINE]]\\nin it')
  671. '<h1>Multiline<br /> title</h1><p>Paragraph<br /> with breaks<br /> in it</p>'
  672. >>> render("anchor with name 'NEWLINE': [[NEWLINE [ ] ]]")
  673. '<p>anchor with name \\'NEWLINE\\': <span class="anchor" id="markmin_NEWLINE"></span></p>'
  674. >>> render("anchor with name 'NEWLINE': [[NEWLINE [newline] ]]")
  675. '<p>anchor with name \\'NEWLINE\\': <span class="anchor" id="markmin_NEWLINE">newline</span></p>'
  676. """
  677. if autolinks=="default": autolinks = autolinks_simple
  678. if protolinks=="default": protolinks = protolinks_simple
  679. pp='\n' if pretty_print else ''
  680. text = str(text or '')
  681. text = regex_backslash.sub(lambda m: m.group(1).translate(ttab_in), text)
  682. text = text.replace('\x05','') # concatenate strings separeted by \\n
  683. if URL is not None:
  684. text = replace_at_urls(text,URL)
  685. if latex == 'google':
  686. text = regex_dd.sub('``\g<latex>``:latex ', text)
  687. #############################################################
  688. # replace all blocks marked with ``...``:class[id] with META
  689. # store them into segments they will be treated as code
  690. #############################################################
  691. segments = []
  692. def mark_code(m):
  693. g = m.group(0)
  694. if g in (META, DISABLED_META ):
  695. segments.append((None, None, None, g))
  696. return m.group()
  697. elif g == '````':
  698. segments.append((None, None, None, ''))
  699. return m.group()
  700. else:
  701. c = m.group('c') or ''
  702. p = m.group('p') or ''
  703. if 'code' in allowed and not c in allowed['code']: c = ''
  704. code = m.group('t').replace('!`!','`')
  705. segments.append((code, c, p, m.group(0)))
  706. return META
  707. text = regex_code.sub(mark_code, text)
  708. #############################################################
  709. # replace all blocks marked with [[...]] with LINK
  710. # store them into links they will be treated as link
  711. #############################################################
  712. links = []
  713. def mark_link(m):
  714. links.append( None if m.group() == LINK
  715. else m.group('s') )
  716. return LINK
  717. text = regex_link.sub(mark_link, text)
  718. text = escape(text)
  719. if protolinks:
  720. text = regex_proto.sub(lambda m: protolinks(*m.group('p','k')), text)
  721. if autolinks:
  722. text = replace_autolinks(text,autolinks)
  723. #############################################################
  724. # normalize spaces
  725. #############################################################
  726. strings=text.split('\n')
  727. def parse_title(t, s): #out, lev, etags, tag, s):
  728. hlevel=str(len(t))
  729. out.extend(etags[::-1])
  730. out.append("<h%s>%s"%(hlevel,s))
  731. etags[:]=["</h%s>%s"%(hlevel,pp)]
  732. lev=0
  733. ltags[:]=[]
  734. tlev[:]=[]
  735. return (lev, 'h')
  736. def parse_list(t, p, s, tag, lev, mtag, lineno):
  737. lent=len(t)
  738. if lent<lev: # current item level < previous item level
  739. while ltags[-1]>lent:
  740. ltags.pop()
  741. out.append(etags.pop())
  742. lev=lent
  743. tlev[lev:]=[]
  744. if lent>lev: # current item level > previous item level
  745. if lev==0: # previous line is not a list (paragraph or title)
  746. out.extend(etags[::-1])
  747. ltags[:]=[]
  748. tlev[:]=[]
  749. etags[:]=[]
  750. if pend and mtag == '.': # paragraph in a list:
  751. out.append(etags.pop())
  752. ltags.pop()
  753. for i in xrange(lent-lev):
  754. out.append('<'+tag+'>'+pp)
  755. etags.append('</'+tag+'>'+pp)
  756. lev+=1
  757. ltags.append(lev)
  758. tlev.append(tag)
  759. elif lent == lev:
  760. if tlev[-1] != tag:
  761. # type of list is changed (ul<=>ol):
  762. for i in xrange(ltags.count(lent)):
  763. ltags.pop()
  764. out.append(etags.pop())
  765. tlev[-1]=tag
  766. out.append('<'+tag+'>'+pp)
  767. etags.append('</'+tag+'>'+pp)
  768. ltags.append(lev)
  769. else:
  770. if ltags.count(lev)>1:
  771. out.append(etags.pop())
  772. ltags.pop()
  773. mtag='l'
  774. out.append('<li>')
  775. etags.append('</li>'+pp)
  776. ltags.append(lev)
  777. if s[:1] == '-':
  778. (s, mtag, lineno) = parse_table_or_blockquote(s, mtag, lineno)
  779. if p and mtag=='l':
  780. (lev,mtag,lineno)=parse_point(t, s, lev, '', lineno)
  781. else:
  782. out.append(s)
  783. return (lev, mtag, lineno)
  784. def parse_point(t, s, lev, mtag, lineno):
  785. """ paragraphs in lists """
  786. lent=len(t)
  787. if lent>lev:
  788. return parse_list(t, '.', s, 'ul', lev, mtag, lineno)
  789. elif lent<lev:
  790. while ltags[-1]>lent:
  791. ltags.pop()
  792. out.append(etags.pop())
  793. lev=lent
  794. tlev[lev:]=[]
  795. mtag=''
  796. elif lent==lev:
  797. if pend and mtag == '.':
  798. out.append(etags.pop())
  799. ltags.pop()
  800. if br and mtag in ('l','.'):
  801. out.append(br)
  802. if s == META:
  803. mtag = ''
  804. else:
  805. mtag = '.'
  806. if s[:1] == '-':
  807. (s, mtag, lineno) = parse_table_or_blockquote(s, mtag, lineno)
  808. if mtag == '.':
  809. out.append(pbeg)
  810. if pend:
  811. etags.append(pend)
  812. ltags.append(lev)
  813. out.append(s)
  814. return (lev, mtag, lineno)
  815. def parse_table_or_blockquote(s, mtag, lineno):
  816. # check next line. If next line :
  817. # - is empty -> this is an <hr /> tag
  818. # - consists '|' -> table
  819. # - consists other characters -> blockquote
  820. if ( lineno+1 >= strings_len or
  821. not (s.count('-') == len(s) and len(s)>3) ):
  822. return (s, mtag, lineno)
  823. lineno+=1
  824. s = strings[lineno].strip()
  825. if s:
  826. if '|' in s:
  827. # table
  828. tout=[]
  829. thead=[]
  830. tbody=[]
  831. rownum=0
  832. t_id = ''
  833. t_cls = ''
  834. # parse table:
  835. while lineno < strings_len:
  836. s = strings[lineno].strip()
  837. if s[:1] == '=':
  838. if s.count('=')==len(s) and len(s)>3: # header or footer
  839. if not thead: # if thead list is empty:
  840. thead = tout
  841. else:
  842. tbody.extend(tout)
  843. tout = []
  844. rownum=0
  845. lineno+=1
  846. continue
  847. m = regex_tq.match(s)
  848. if m:
  849. t_cls = m.group('c') or ''
  850. t_id = m.group('p') or ''
  851. break
  852. if rownum % 2:
  853. tr = '<tr class="even">'
  854. else:
  855. tr = '<tr class="first">' if rownum == 0 else '<tr>'
  856. tout.append(tr+''.join(['<td%s>%s</td>'% \
  857. (' class="num"'
  858. if regex_num.match(f)
  859. else '',
  860. f.strip()
  861. ) for f in s.split('|')])+'</tr>'+pp)
  862. rownum+=1
  863. lineno+=1
  864. t_cls = ' class="%s%s"'%(class_prefix, t_cls) if t_cls and t_cls != 'id' else ''
  865. t_id = ' id="%s%s"'%(id_prefix, t_id) if t_id else ''
  866. s = ''
  867. if thead:
  868. s += '<thead>'+pp+''.join([l for l in thead])+'</thead>'+pp
  869. if not tbody: # tbody strings are in tout list
  870. tbody = tout
  871. tout = []
  872. if tbody: # if tbody list is not empty:
  873. s += '<tbody>'+pp+''.join([l for l in tbody])+'</tbody>'+pp
  874. if tout: # tfoot is not empty:
  875. s += '<tfoot>'+pp+''.join([l for l in tout])+'</tfoot>'+pp
  876. s = '<table%s%s>%s%s</table>%s' % (t_cls, t_id, pp, s, pp)
  877. mtag='t'
  878. else:
  879. # parse blockquote:
  880. bq_begin=lineno
  881. t_mode = False # embidded table
  882. t_cls = ''
  883. t_id = ''
  884. # search blockquote closing line:
  885. while lineno < strings_len:
  886. s = strings[lineno].strip()
  887. if not t_mode:
  888. m = regex_tq.match(s)
  889. if m:
  890. if lineno+1 == strings_len or '|' not in strings[lineno+1]:
  891. t_cls = m.group('c') or ''
  892. t_id = m.group('p') or ''
  893. break
  894. if regex_bq_headline.match(s):
  895. if lineno+1 < strings_len and strings[lineno+1].strip():
  896. t_mode = True
  897. lineno+=1
  898. continue
  899. elif regex_tq.match(s):
  900. t_mode=False
  901. lineno+=1
  902. continue
  903. lineno+=1
  904. t_cls = ' class="%s%s"'%(class_prefix,t_cls) if t_cls and t_cls != 'id' else ''
  905. t_id = ' id="%s%s"'%(id_prefix,t_id) if t_id else ''
  906. s = '<blockquote%s%s>%s</blockquote>%s' \
  907. % (t_cls,
  908. t_id,
  909. render('\n'.join(strings[bq_begin:lineno]),
  910. extra,
  911. allowed,
  912. 'br',
  913. URL,
  914. environment,
  915. latex,
  916. autolinks,
  917. protolinks,
  918. class_prefix,
  919. id_prefix,
  920. pretty_print),
  921. pp
  922. )
  923. mtag='q'
  924. else:
  925. s = '<hr />'
  926. lineno-=1
  927. mtag='q'
  928. return (s, 'q', lineno)
  929. if sep == 'p':
  930. pbeg = "<p>"
  931. pend = "</p>"+pp
  932. br = ''
  933. else:
  934. pbeg = pend = ''
  935. br = "<br />"+pp if sep=='br' else ''
  936. lev = 0 # nesting level of lists
  937. c0 = '' # first character of current line
  938. out = [] # list of processed lines
  939. etags = [] # trailing tags
  940. ltags = [] # level# correspondent to trailing tag
  941. tlev = [] # list of tags for each level ('ul' or 'ol')
  942. mtag = '' # marked tag (~last tag) ('l','.','h','p','t'). Used to set <br/>
  943. # and to avoid <p></p> around tables and blockquotes
  944. lineno = 0
  945. strings_len = len(strings)
  946. while lineno < strings_len:
  947. s0 = strings[lineno][:1]
  948. s = strings[lineno].strip()
  949. """ # + - . ---------------------
  950. ## ++ -- .. ------- field | field | field <-title
  951. ### +++ --- ... quote =====================
  952. #### ++++ ---- .... ------- field | field | field <-body
  953. ##### +++++ ----- ..... ---------------------:class[id]
  954. """
  955. pc0=c0 # first character of previous line
  956. c0=s[:1]
  957. if c0: # for non empty strings
  958. if c0 in "#+-.": # first character is one of: # + - .
  959. (t1,t2,p,ss) = regex_list.findall(s)[0]
  960. # t1 - tag ("###")
  961. # t2 - tag ("+++", "---", "...")
  962. # p - paragraph point ('.')->for "++." or "--."
  963. # ss - other part of string
  964. if t1 or t2:
  965. # headers and lists:
  966. if c0 == '#': # headers
  967. (lev, mtag) = parse_title(t1, ss)
  968. lineno+=1
  969. continue
  970. elif c0 == '+': # ordered list
  971. (lev, mtag, lineno)= parse_list(t2, p, ss, 'ol', lev, mtag, lineno)
  972. lineno+=1
  973. continue
  974. elif c0 == '-': # unordered list, table or blockquote
  975. if p or ss:
  976. (lev, mtag, lineno) = parse_list(t2, p, ss, 'ul', lev, mtag, lineno)
  977. lineno+=1
  978. continue
  979. else:
  980. (s, mtag, lineno) = parse_table_or_blockquote(s, mtag, lineno)
  981. elif lev>0: # and c0 == '.' # paragraph in lists
  982. (lev, mtag, lineno) = parse_point(t2, ss, lev, mtag, lineno)
  983. lineno+=1
  984. continue
  985. if lev == 0 and (mtag == 'q' or s == META):
  986. # new paragraph
  987. pc0=''
  988. if pc0 == '' or (mtag != 'p' and s0 not in (' ','\t')):
  989. # paragraph
  990. out.extend(etags[::-1])
  991. etags=[]
  992. ltags=[]
  993. tlev=[]
  994. lev=0
  995. if br and mtag == 'p': out.append(br)
  996. if mtag != 'q' and s != META:
  997. if pend: etags=[pend]
  998. out.append(pbeg)
  999. mtag = 'p'
  1000. else:
  1001. mtag = ''
  1002. out.append(s)
  1003. else:
  1004. if lev>0 and mtag=='.' and s == META:
  1005. out.append(etags.pop())
  1006. ltags.pop()
  1007. out.append(s)
  1008. mtag = ''
  1009. else:
  1010. out.append(' '+s)
  1011. lineno+=1
  1012. out.extend(etags[::-1])
  1013. text = ''.join(out)
  1014. #############################################################
  1015. # do strong,em,del
  1016. #############################################################
  1017. text = regex_strong.sub('<strong>\g<t></strong>', text)
  1018. text = regex_del.sub('<del>\g<t></del>', text)
  1019. text = regex_em.sub('<em>\g<t></em>', text)
  1020. #############################################################
  1021. # deal with images, videos, audios and links
  1022. #############################################################
  1023. def sub_media(m):
  1024. t,a,k,p,w = m.group('t','a','k','p','w')
  1025. if not k:
  1026. return m.group(0)
  1027. k = escape(k)
  1028. t = t or ''
  1029. style = 'width:%s' % w if w else ''
  1030. title = ' title="%s"' % escape(a).replace(META, DISABLED_META) if a else ''
  1031. p_begin = p_end = ''
  1032. if p == 'center':
  1033. p_begin = '<p style="text-align:center">'
  1034. p_end = '</p>'+pp
  1035. elif p in ('left','right'):
  1036. style = ('float:%s' % p)+(';%s' % style if style else '')
  1037. if style:
  1038. style = ' style="%s"' % style
  1039. if p in ('video','audio'):
  1040. t = render(t, {}, {}, 'br', URL, environment, latex,
  1041. autolinks, protolinks, class_prefix, id_prefix, pretty_print)
  1042. return '<%(p)s controls="controls"%(title)s%(style)s><source src="%(k)s" />%(t)s</%(p)s>' \
  1043. % dict(p=p, title=title, style=style, k=k, t=t)
  1044. alt = ' alt="%s"'%escape(t).replace(META, DISABLED_META) if t else ''
  1045. return '%(begin)s<img src="%(k)s"%(alt)s%(title)s%(style)s />%(end)s' \
  1046. % dict(begin=p_begin, k=k, alt=alt, title=title, style=style, end=p_end)
  1047. def sub_link(m):
  1048. t,a,k,p = m.group('t','a','k','p')
  1049. if not k and not t:
  1050. return m.group(0)
  1051. t = t or ''
  1052. a = escape(a) if a else ''
  1053. if k:
  1054. if '#' in k and not ':' in k.split('#')[0]:
  1055. # wikipage, not external url
  1056. k=k.replace('#','#'+id_prefix)
  1057. k = escape(k)
  1058. title = ' title="%s"' % a.replace(META, DISABLED_META) if a else ''
  1059. target = ' target="_blank"' if p == 'popup' else ''
  1060. t = render(t, {}, {}, 'br', URL, environment, latex, None,
  1061. None, class_prefix, id_prefix, pretty_print) if t else k
  1062. return '<a href="%(k)s"%(title)s%(target)s>%(t)s</a>' \
  1063. % dict(k=k, title=title, target=target, t=t)
  1064. if t == 'NEWLINE' and not a:
  1065. return '<br />'+pp
  1066. return '<span class="anchor" id="%s">%s</span>' % (
  1067. escape(id_prefix+t),
  1068. render(a, {},{},'br', URL,
  1069. environment, latex, autolinks,
  1070. protolinks, class_prefix,
  1071. id_prefix, pretty_print))
  1072. parts = text.split(LINK)
  1073. text = parts[0]
  1074. for i,s in enumerate(links):
  1075. if s == None:
  1076. html = LINK
  1077. else:
  1078. html = regex_media_level2.sub(sub_media, s)
  1079. if html == s:
  1080. html = regex_link_level2.sub(sub_link, html)
  1081. if html == s:
  1082. # return unprocessed string as a signal of an error
  1083. html = '[[%s]]'%s
  1084. text += html + parts[i+1]
  1085. #############################################################
  1086. # process all code text
  1087. #############################################################
  1088. def expand_meta(m):
  1089. code,b,p,s = segments.pop(0)
  1090. if code==None or m.group() == DISABLED_META:
  1091. return escape(s)
  1092. if b in extra:
  1093. if code[:1]=='\n': code=code[1:]
  1094. if code[-1:]=='\n': code=code[:-1]
  1095. if p:
  1096. return str(extra[b](code,p))
  1097. else:
  1098. return str(extra[b](code))
  1099. elif b=='cite':
  1100. return '['+','.join('<a href="#%s" class="%s">%s</a>' \
  1101. % (d,b,d) \
  1102. for d in escape(code).split(','))+']'
  1103. elif b=='latex':
  1104. return LATEX % code.replace('"','\"').replace('\n',' ')
  1105. elif b in html_colors:
  1106. return '<span style="color: %s">%s</span>' \
  1107. % (b, render(code, {}, {}, 'br', URL, environment, latex,
  1108. autolinks, protolinks, class_prefix, id_prefix, pretty_print))
  1109. elif b in ('c', 'color') and p:
  1110. c=p.split(':')
  1111. fg='color: %s;' % c[0] if c[0] else ''
  1112. bg='background-color: %s;' % c[1] if len(c)>1 and c[1] else ''
  1113. return '<span style="%s%s">%s</span>' \
  1114. % (fg, bg, render(code, {}, {}, 'br', URL, environment, latex,
  1115. autolinks, protolinks, class_prefix, id_prefix, pretty_print))
  1116. cls = ' class="%s%s"'%(class_prefix,b) if b and b != 'id' else ''
  1117. id = ' id="%s%s"'%(id_prefix,escape(p)) if p else ''
  1118. beg=(code[:1]=='\n')
  1119. end=[None,-1][code[-1:]=='\n']
  1120. if beg and end:
  1121. return '<pre><code%s%s>%s</code></pre>%s' % (cls, id, escape(code[1:-1]), pp)
  1122. return '<code%s%s>%s</code>' % (cls, id, escape(code[beg:end]))
  1123. text = regex_expand_meta.sub(expand_meta, text)
  1124. if environment:
  1125. text = replace_components(text,environment)
  1126. return text.translate(ttab_out)
  1127. def markmin2html(text, extra={}, allowed={}, sep='p',
  1128. autolinks='default', protolinks='default',
  1129. class_prefix='', id_prefix='markmin_', pretty_print=False):
  1130. return render(text, extra, allowed, sep,
  1131. autolinks=autolinks, protolinks=protolinks,
  1132. class_prefix=class_prefix, id_prefix=id_prefix,
  1133. pretty_print=pretty_print)
  1134. def run_doctests():
  1135. import doctest
  1136. doctest.testmod()
  1137. if __name__ == '__main__':
  1138. import sys
  1139. import doctest
  1140. from textwrap import dedent
  1141. html=dedent("""
  1142. <!doctype html>
  1143. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  1144. <head>
  1145. <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  1146. %(style)s
  1147. <title>%(title)s</title>
  1148. </head>
  1149. <body>
  1150. %(body)s
  1151. </body>
  1152. </html>""")[1:]

Large files files are truncated, but you can click here to view the full file