PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/gluon/contrib/markmin/markmin2html.py

http://github.com/web2py/web2py
Python | 1564 lines | 1463 code | 77 blank | 24 comment | 38 complexity | af3e85381050157f22f69fc54f405622 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, BSD-2-Clause, MPL-2.0-no-copyleft-exception, Apache-2.0

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

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