markdown2.py 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 Trent Mick.
  3. # Copyright (c) 2007-2008 ActiveState Corp.
  4. # License: MIT (http://www.opensource.org/licenses/mit-license.php)
  5. r"""A fast and complete Python implementation of Markdown.
  6. [from http://daringfireball.net/projects/markdown/]
  7. > Markdown is a text-to-HTML filter; it translates an easy-to-read /
  8. > easy-to-write structured text format into HTML. Markdown's text
  9. > format is most similar to that of plain text email, and supports
  10. > features such as headers, *emphasis*, code blocks, blockquotes, and
  11. > links.
  12. >
  13. > Markdown's syntax is designed not as a generic markup language, but
  14. > specifically to serve as a front-end to (X)HTML. You can use span-level
  15. > HTML tags anywhere in a Markdown document, and you can use block level
  16. > HTML tags (like <div> and <table> as well).
  17. Module usage:
  18. >>> import markdown2
  19. >>> markdown2.markdown("*boo!*") # or use `html = markdown_path(PATH)`
  20. u'<p><em>boo!</em></p>\n'
  21. >>> markdowner = Markdown()
  22. >>> markdowner.convert("*boo!*")
  23. u'<p><em>boo!</em></p>\n'
  24. >>> markdowner.convert("**boom!**")
  25. u'<p><strong>boom!</strong></p>\n'
  26. This implementation of Markdown implements the full "core" syntax plus a
  27. number of extras (e.g., code syntax coloring, footnotes) as described on
  28. <https://github.com/trentm/python-markdown2/wiki/Extras>.
  29. """
  30. cmdln_desc = """A fast and complete Python implementation of Markdown, a
  31. text-to-HTML conversion tool for web writers.
  32. Supported extra syntax options (see -x|--extras option below and
  33. see <https://github.com/trentm/python-markdown2/wiki/Extras> for details):
  34. * break-on-newline: Replace single new line characters with <br> when True
  35. * code-friendly: Disable _ and __ for em and strong.
  36. * cuddled-lists: Allow lists to be cuddled to the preceding paragraph.
  37. * fenced-code-blocks: Allows a code block to not have to be indented
  38. by fencing it with '```' on a line before and after. Based on
  39. <http://github.github.com/github-flavored-markdown/> with support for
  40. syntax highlighting.
  41. * footnotes: Support footnotes as in use on daringfireball.net and
  42. implemented in other Markdown processors (tho not in Markdown.pl v1.0.1).
  43. * header-ids: Adds "id" attributes to headers. The id value is a slug of
  44. the header text.
  45. * highlightjs-lang: Allows specifying the language which used for syntax
  46. highlighting when using fenced-code-blocks and highlightjs.
  47. * html-classes: Takes a dict mapping html tag names (lowercase) to a
  48. string to use for a "class" tag attribute. Currently only supports "img",
  49. "table", "pre" and "code" tags. Add an issue if you require this for other
  50. tags.
  51. * link-patterns: Auto-link given regex patterns in text (e.g. bug number
  52. references, revision number references).
  53. * markdown-in-html: Allow the use of `markdown="1"` in a block HTML tag to
  54. have markdown processing be done on its contents. Similar to
  55. <http://michelf.com/projects/php-markdown/extra/#markdown-attr> but with
  56. some limitations.
  57. * metadata: Extract metadata from a leading '---'-fenced block.
  58. See <https://github.com/trentm/python-markdown2/issues/77> for details.
  59. * nofollow: Add `rel="nofollow"` to add `<a>` tags with an href. See
  60. <http://en.wikipedia.org/wiki/Nofollow>.
  61. * numbering: Support of generic counters. Non standard extension to
  62. allow sequential numbering of figures, tables, equations, exhibits etc.
  63. * pyshell: Treats unindented Python interactive shell sessions as <code>
  64. blocks.
  65. * smarty-pants: Replaces ' and " with curly quotation marks or curly
  66. apostrophes. Replaces --, ---, ..., and . . . with en dashes, em dashes,
  67. and ellipses.
  68. * spoiler: A special kind of blockquote commonly hidden behind a
  69. click on SO. Syntax per <http://meta.stackexchange.com/a/72878>.
  70. * strike: text inside of double tilde is ~~strikethrough~~
  71. * tag-friendly: Requires atx style headers to have a space between the # and
  72. the header text. Useful for applications that require twitter style tags to
  73. pass through the parser.
  74. * tables: Tables using the same format as GFM
  75. <https://help.github.com/articles/github-flavored-markdown#tables> and
  76. PHP-Markdown Extra <https://michelf.ca/projects/php-markdown/extra/#table>.
  77. * toc: The returned HTML string gets a new "toc_html" attribute which is
  78. a Table of Contents for the document. (experimental)
  79. * use-file-vars: Look for an Emacs-style markdown-extras file variable to turn
  80. on Extras.
  81. * wiki-tables: Google Code Wiki-style tables. See
  82. <http://code.google.com/p/support/wiki/WikiSyntax#Tables>.
  83. * xml: Passes one-liner processing instructions and namespaced XML tags.
  84. """
  85. # Dev Notes:
  86. # - Python's regex syntax doesn't have '\z', so I'm using '\Z'. I'm
  87. # not yet sure if there implications with this. Compare 'pydoc sre'
  88. # and 'perldoc perlre'.
  89. __version_info__ = (2, 4, 1)
  90. __version__ = '.'.join(map(str, __version_info__))
  91. __author__ = "Trent Mick"
  92. import sys
  93. import re
  94. import logging
  95. from hashlib import sha256
  96. import optparse
  97. from random import random, randint
  98. import codecs
  99. from collections import defaultdict
  100. # ---- Python version compat
  101. # Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).
  102. if sys.version_info[0] <= 2:
  103. py3 = False
  104. try:
  105. bytes
  106. except NameError:
  107. bytes = str
  108. base_string_type = basestring
  109. elif sys.version_info[0] >= 3:
  110. py3 = True
  111. unicode = str
  112. base_string_type = str
  113. # ---- globals
  114. DEBUG = False
  115. log = logging.getLogger("markdown")
  116. DEFAULT_TAB_WIDTH = 4
  117. SECRET_SALT = bytes(randint(0, 1000000))
  118. # MD5 function was previously used for this; the "md5" prefix was kept for
  119. # backwards compatibility.
  120. def _hash_text(s):
  121. return 'md5-' + sha256(SECRET_SALT + s.encode("utf-8")).hexdigest()[32:]
  122. # Table of hash values for escaped characters:
  123. g_escape_table = dict([(ch, _hash_text(ch))
  124. for ch in '\\`*_{}[]()>#+-.!'])
  125. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  126. # http://bumppo.net/projects/amputator/
  127. _AMPERSAND_RE = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)')
  128. # ---- exceptions
  129. class MarkdownError(Exception):
  130. pass
  131. # ---- public api
  132. def markdown_path(path, encoding="utf-8",
  133. html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  134. safe_mode=None, extras=None, link_patterns=None,
  135. footnote_title=None, footnote_return_symbol=None,
  136. use_file_vars=False):
  137. fp = codecs.open(path, 'r', encoding)
  138. text = fp.read()
  139. fp.close()
  140. return Markdown(html4tags=html4tags, tab_width=tab_width,
  141. safe_mode=safe_mode, extras=extras,
  142. link_patterns=link_patterns,
  143. footnote_title=footnote_title,
  144. footnote_return_symbol=footnote_return_symbol,
  145. use_file_vars=use_file_vars).convert(text)
  146. def markdown(text, html4tags=False, tab_width=DEFAULT_TAB_WIDTH,
  147. safe_mode=None, extras=None, link_patterns=None,
  148. footnote_title=None, footnote_return_symbol=None,
  149. use_file_vars=False, cli=False):
  150. return Markdown(html4tags=html4tags, tab_width=tab_width,
  151. safe_mode=safe_mode, extras=extras,
  152. link_patterns=link_patterns,
  153. footnote_title=footnote_title,
  154. footnote_return_symbol=footnote_return_symbol,
  155. use_file_vars=use_file_vars, cli=cli).convert(text)
  156. class Markdown(object):
  157. # The dict of "extras" to enable in processing -- a mapping of
  158. # extra name to argument for the extra. Most extras do not have an
  159. # argument, in which case the value is None.
  160. #
  161. # This can be set via (a) subclassing and (b) the constructor
  162. # "extras" argument.
  163. extras = None
  164. urls = None
  165. titles = None
  166. html_blocks = None
  167. html_spans = None
  168. html_removed_text = "{(#HTML#)}" # placeholder removed text that does not trigger bold
  169. html_removed_text_compat = "[HTML_REMOVED]" # for compat with markdown.py
  170. _toc = None
  171. # Used to track when we're inside an ordered or unordered list
  172. # (see _ProcessListItems() for details):
  173. list_level = 0
  174. _ws_only_line_re = re.compile(r"^[ \t]+$", re.M)
  175. def __init__(self, html4tags=False, tab_width=4, safe_mode=None,
  176. extras=None, link_patterns=None,
  177. footnote_title=None, footnote_return_symbol=None,
  178. use_file_vars=False, cli=False):
  179. if html4tags:
  180. self.empty_element_suffix = ">"
  181. else:
  182. self.empty_element_suffix = " />"
  183. self.tab_width = tab_width
  184. self.tab = tab_width * " "
  185. # For compatibility with earlier markdown2.py and with
  186. # markdown.py's safe_mode being a boolean,
  187. # safe_mode == True -> "replace"
  188. if safe_mode is True:
  189. self.safe_mode = "replace"
  190. else:
  191. self.safe_mode = safe_mode
  192. # Massaging and building the "extras" info.
  193. if self.extras is None:
  194. self.extras = {}
  195. elif not isinstance(self.extras, dict):
  196. self.extras = dict([(e, None) for e in self.extras])
  197. if extras:
  198. if not isinstance(extras, dict):
  199. extras = dict([(e, None) for e in extras])
  200. self.extras.update(extras)
  201. assert isinstance(self.extras, dict)
  202. if "toc" in self.extras:
  203. if "header-ids" not in self.extras:
  204. self.extras["header-ids"] = None # "toc" implies "header-ids"
  205. if self.extras["toc"] is None:
  206. self._toc_depth = 6
  207. else:
  208. self._toc_depth = self.extras["toc"].get("depth", 6)
  209. self._instance_extras = self.extras.copy()
  210. self.link_patterns = link_patterns
  211. self.footnote_title = footnote_title
  212. self.footnote_return_symbol = footnote_return_symbol
  213. self.use_file_vars = use_file_vars
  214. self._outdent_re = re.compile(r'^(\t|[ ]{1,%d})' % tab_width, re.M)
  215. self.cli = cli
  216. self._escape_table = g_escape_table.copy()
  217. if "smarty-pants" in self.extras:
  218. self._escape_table['"'] = _hash_text('"')
  219. self._escape_table["'"] = _hash_text("'")
  220. def reset(self):
  221. self.urls = {}
  222. self.titles = {}
  223. self.html_blocks = {}
  224. self.html_spans = {}
  225. self.list_level = 0
  226. self.extras = self._instance_extras.copy()
  227. if "footnotes" in self.extras:
  228. self.footnotes = {}
  229. self.footnote_ids = []
  230. if "header-ids" in self.extras:
  231. self._count_from_header_id = defaultdict(int)
  232. if "metadata" in self.extras:
  233. self.metadata = {}
  234. self._toc = None
  235. # Per <https://developer.mozilla.org/en-US/docs/HTML/Element/a> "rel"
  236. # should only be used in <a> tags with an "href" attribute.
  237. # Opens the linked document in a new window or tab
  238. # should only used in <a> tags with an "href" attribute.
  239. # same with _a_nofollow
  240. _a_nofollow_or_blank_links = re.compile(r"""
  241. <(a)
  242. (
  243. [^>]*
  244. href= # href is required
  245. ['"]? # HTML5 attribute values do not have to be quoted
  246. [^#'"] # We don't want to match href values that start with # (like footnotes)
  247. )
  248. """,
  249. re.IGNORECASE | re.VERBOSE
  250. )
  251. def convert(self, text):
  252. """Convert the given text."""
  253. # Main function. The order in which other subs are called here is
  254. # essential. Link and image substitutions need to happen before
  255. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  256. # and <img> tags get encoded.
  257. # Clear the global hashes. If we don't clear these, you get conflicts
  258. # from other articles when generating a page which contains more than
  259. # one article (e.g. an index page that shows the N most recent
  260. # articles):
  261. self.reset()
  262. if not isinstance(text, unicode):
  263. # TODO: perhaps shouldn't presume UTF-8 for string input?
  264. text = unicode(text, 'utf-8')
  265. if self.use_file_vars:
  266. # Look for emacs-style file variable hints.
  267. emacs_vars = self._get_emacs_vars(text)
  268. if "markdown-extras" in emacs_vars:
  269. splitter = re.compile("[ ,]+")
  270. for e in splitter.split(emacs_vars["markdown-extras"]):
  271. if '=' in e:
  272. ename, earg = e.split('=', 1)
  273. try:
  274. earg = int(earg)
  275. except ValueError:
  276. pass
  277. else:
  278. ename, earg = e, None
  279. self.extras[ename] = earg
  280. # Standardize line endings:
  281. text = text.replace("\r\n", "\n")
  282. text = text.replace("\r", "\n")
  283. # Make sure $text ends with a couple of newlines:
  284. text += "\n\n"
  285. # Convert all tabs to spaces.
  286. text = self._detab(text)
  287. # Strip any lines consisting only of spaces and tabs.
  288. # This makes subsequent regexen easier to write, because we can
  289. # match consecutive blank lines with /\n+/ instead of something
  290. # contorted like /[ \t]*\n+/ .
  291. text = self._ws_only_line_re.sub("", text)
  292. # strip metadata from head and extract
  293. if "metadata" in self.extras:
  294. text = self._extract_metadata(text)
  295. text = self.preprocess(text)
  296. if "fenced-code-blocks" in self.extras and not self.safe_mode:
  297. text = self._do_fenced_code_blocks(text)
  298. if self.safe_mode:
  299. text = self._hash_html_spans(text)
  300. # Turn block-level HTML blocks into hash entries
  301. text = self._hash_html_blocks(text, raw=True)
  302. if "fenced-code-blocks" in self.extras and self.safe_mode:
  303. text = self._do_fenced_code_blocks(text)
  304. # Because numbering references aren't links (yet?) then we can do everything associated with counters
  305. # before we get started
  306. if "numbering" in self.extras:
  307. text = self._do_numbering(text)
  308. # Strip link definitions, store in hashes.
  309. if "footnotes" in self.extras:
  310. # Must do footnotes first because an unlucky footnote defn
  311. # looks like a link defn:
  312. # [^4]: this "looks like a link defn"
  313. text = self._strip_footnote_definitions(text)
  314. text = self._strip_link_definitions(text)
  315. text = self._run_block_gamut(text)
  316. if "footnotes" in self.extras:
  317. text = self._add_footnotes(text)
  318. text = self.postprocess(text)
  319. text = self._unescape_special_chars(text)
  320. if self.safe_mode:
  321. text = self._unhash_html_spans(text)
  322. # return the removed text warning to its markdown.py compatible form
  323. text = text.replace(self.html_removed_text, self.html_removed_text_compat)
  324. do_target_blank_links = "target-blank-links" in self.extras
  325. do_nofollow_links = "nofollow" in self.extras
  326. if do_target_blank_links and do_nofollow_links:
  327. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="nofollow noopener" target="_blank"\2', text)
  328. elif do_target_blank_links:
  329. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="noopener" target="_blank"\2', text)
  330. elif do_nofollow_links:
  331. text = self._a_nofollow_or_blank_links.sub(r'<\1 rel="nofollow"\2', text)
  332. if "toc" in self.extras and self._toc:
  333. self._toc_html = calculate_toc_html(self._toc)
  334. # Prepend toc html to output
  335. if self.cli:
  336. text = '{}\n{}'.format(self._toc_html, text)
  337. text += "\n"
  338. # Attach attrs to output
  339. rv = UnicodeWithAttrs(text)
  340. if "toc" in self.extras and self._toc:
  341. rv.toc_html = self._toc_html
  342. if "metadata" in self.extras:
  343. rv.metadata = self.metadata
  344. return rv
  345. def postprocess(self, text):
  346. """A hook for subclasses to do some postprocessing of the html, if
  347. desired. This is called before unescaping of special chars and
  348. unhashing of raw HTML spans.
  349. """
  350. return text
  351. def preprocess(self, text):
  352. """A hook for subclasses to do some preprocessing of the Markdown, if
  353. desired. This is called after basic formatting of the text, but prior
  354. to any extras, safe mode, etc. processing.
  355. """
  356. return text
  357. # Is metadata if the content starts with optional '---'-fenced `key: value`
  358. # pairs. E.g. (indented for presentation):
  359. # ---
  360. # foo: bar
  361. # another-var: blah blah
  362. # ---
  363. # # header
  364. # or:
  365. # foo: bar
  366. # another-var: blah blah
  367. #
  368. # # header
  369. _meta_data_pattern = re.compile(r'^(?:---[\ \t]*\n)?((?:[\S\w]+\s*:(?:\n+[ \t]+.*)+)|(?:.*:\s+>\n\s+[\S\s]+?)(?=\n\w+\s*:\s*\w+\n|\Z)|(?:\s*[\S\w]+\s*:(?! >)[ \t]*.*\n?))(?:---[\ \t]*\n)?', re.MULTILINE)
  370. _key_val_pat = re.compile(r"[\S\w]+\s*:(?! >)[ \t]*.*\n?", re.MULTILINE)
  371. # this allows key: >
  372. # value
  373. # conutiues over multiple lines
  374. _key_val_block_pat = re.compile(
  375. r"(.*:\s+>\n\s+[\S\s]+?)(?=\n\w+\s*:\s*\w+\n|\Z)", re.MULTILINE
  376. )
  377. _key_val_list_pat = re.compile(
  378. r"^-(?:[ \t]*([^\n]*)(?:[ \t]*[:-][ \t]*(\S+))?)(?:\n((?:[ \t]+[^\n]+\n?)+))?",
  379. re.MULTILINE,
  380. )
  381. _key_val_dict_pat = re.compile(
  382. r"^([^:\n]+)[ \t]*:[ \t]*([^\n]*)(?:((?:\n[ \t]+[^\n]+)+))?", re.MULTILINE
  383. ) # grp0: key, grp1: value, grp2: multiline value
  384. _meta_data_fence_pattern = re.compile(r'^---[\ \t]*\n', re.MULTILINE)
  385. _meta_data_newline = re.compile("^\n", re.MULTILINE)
  386. def _extract_metadata(self, text):
  387. if text.startswith("---"):
  388. fence_splits = re.split(self._meta_data_fence_pattern, text, maxsplit=2)
  389. metadata_content = fence_splits[1]
  390. match = re.findall(self._meta_data_pattern, metadata_content)
  391. if not match:
  392. return text
  393. tail = fence_splits[2]
  394. else:
  395. metadata_split = re.split(self._meta_data_newline, text, maxsplit=1)
  396. metadata_content = metadata_split[0]
  397. match = re.findall(self._meta_data_pattern, metadata_content)
  398. if not match:
  399. return text
  400. tail = metadata_split[1]
  401. def parse_structured_value(value):
  402. vs = value.lstrip()
  403. vs = value.replace(v[: len(value) - len(vs)], "\n")[1:]
  404. # List
  405. if vs.startswith("-"):
  406. r = []
  407. for match in re.findall(self._key_val_list_pat, vs):
  408. if match[0] and not match[1] and not match[2]:
  409. r.append(match[0].strip())
  410. elif match[0] == ">" and not match[1] and match[2]:
  411. r.append(match[2].strip())
  412. elif match[0] and match[1]:
  413. r.append({match[0].strip(): match[1].strip()})
  414. elif not match[0] and not match[1] and match[2]:
  415. r.append(parse_structured_value(match[2]))
  416. else:
  417. # Broken case
  418. pass
  419. return r
  420. # Dict
  421. else:
  422. return {
  423. match[0].strip(): (
  424. match[1].strip()
  425. if match[1]
  426. else parse_structured_value(match[2])
  427. )
  428. for match in re.findall(self._key_val_dict_pat, vs)
  429. }
  430. for item in match:
  431. k, v = item.split(":", 1)
  432. # Multiline value
  433. if v[:3] == " >\n":
  434. self.metadata[k.strip()] = v[3:].strip()
  435. # Empty value
  436. elif v == "\n":
  437. self.metadata[k.strip()] = ""
  438. # Structured value
  439. elif v[0] == "\n":
  440. self.metadata[k.strip()] = parse_structured_value(v)
  441. # Simple value
  442. else:
  443. self.metadata[k.strip()] = v.strip()
  444. return tail
  445. _emacs_oneliner_vars_pat = re.compile(r"-\*-\s*(?:(\S[^\r\n]*?)([\r\n]\s*)?)?-\*-", re.UNICODE)
  446. # This regular expression is intended to match blocks like this:
  447. # PREFIX Local Variables: SUFFIX
  448. # PREFIX mode: Tcl SUFFIX
  449. # PREFIX End: SUFFIX
  450. # Some notes:
  451. # - "[ \t]" is used instead of "\s" to specifically exclude newlines
  452. # - "(\r\n|\n|\r)" is used instead of "$" because the sre engine does
  453. # not like anything other than Unix-style line terminators.
  454. _emacs_local_vars_pat = re.compile(r"""^
  455. (?P<prefix>(?:[^\r\n|\n|\r])*?)
  456. [\ \t]*Local\ Variables:[\ \t]*
  457. (?P<suffix>.*?)(?:\r\n|\n|\r)
  458. (?P<content>.*?\1End:)
  459. """, re.IGNORECASE | re.MULTILINE | re.DOTALL | re.VERBOSE)
  460. def _get_emacs_vars(self, text):
  461. """Return a dictionary of emacs-style local variables.
  462. Parsing is done loosely according to this spec (and according to
  463. some in-practice deviations from this):
  464. http://www.gnu.org/software/emacs/manual/html_node/emacs/Specifying-File-Variables.html#Specifying-File-Variables
  465. """
  466. emacs_vars = {}
  467. SIZE = pow(2, 13) # 8kB
  468. # Search near the start for a '-*-'-style one-liner of variables.
  469. head = text[:SIZE]
  470. if "-*-" in head:
  471. match = self._emacs_oneliner_vars_pat.search(head)
  472. if match:
  473. emacs_vars_str = match.group(1)
  474. assert '\n' not in emacs_vars_str
  475. emacs_var_strs = [s.strip() for s in emacs_vars_str.split(';')
  476. if s.strip()]
  477. if len(emacs_var_strs) == 1 and ':' not in emacs_var_strs[0]:
  478. # While not in the spec, this form is allowed by emacs:
  479. # -*- Tcl -*-
  480. # where the implied "variable" is "mode". This form
  481. # is only allowed if there are no other variables.
  482. emacs_vars["mode"] = emacs_var_strs[0].strip()
  483. else:
  484. for emacs_var_str in emacs_var_strs:
  485. try:
  486. variable, value = emacs_var_str.strip().split(':', 1)
  487. except ValueError:
  488. log.debug("emacs variables error: malformed -*- "
  489. "line: %r", emacs_var_str)
  490. continue
  491. # Lowercase the variable name because Emacs allows "Mode"
  492. # or "mode" or "MoDe", etc.
  493. emacs_vars[variable.lower()] = value.strip()
  494. tail = text[-SIZE:]
  495. if "Local Variables" in tail:
  496. match = self._emacs_local_vars_pat.search(tail)
  497. if match:
  498. prefix = match.group("prefix")
  499. suffix = match.group("suffix")
  500. lines = match.group("content").splitlines(0)
  501. # print "prefix=%r, suffix=%r, content=%r, lines: %s"\
  502. # % (prefix, suffix, match.group("content"), lines)
  503. # Validate the Local Variables block: proper prefix and suffix
  504. # usage.
  505. for i, line in enumerate(lines):
  506. if not line.startswith(prefix):
  507. log.debug("emacs variables error: line '%s' "
  508. "does not use proper prefix '%s'"
  509. % (line, prefix))
  510. return {}
  511. # Don't validate suffix on last line. Emacs doesn't care,
  512. # neither should we.
  513. if i != len(lines)-1 and not line.endswith(suffix):
  514. log.debug("emacs variables error: line '%s' "
  515. "does not use proper suffix '%s'"
  516. % (line, suffix))
  517. return {}
  518. # Parse out one emacs var per line.
  519. continued_for = None
  520. for line in lines[:-1]: # no var on the last line ("PREFIX End:")
  521. if prefix: line = line[len(prefix):] # strip prefix
  522. if suffix: line = line[:-len(suffix)] # strip suffix
  523. line = line.strip()
  524. if continued_for:
  525. variable = continued_for
  526. if line.endswith('\\'):
  527. line = line[:-1].rstrip()
  528. else:
  529. continued_for = None
  530. emacs_vars[variable] += ' ' + line
  531. else:
  532. try:
  533. variable, value = line.split(':', 1)
  534. except ValueError:
  535. log.debug("local variables error: missing colon "
  536. "in local variables entry: '%s'" % line)
  537. continue
  538. # Do NOT lowercase the variable name, because Emacs only
  539. # allows "mode" (and not "Mode", "MoDe", etc.) in this block.
  540. value = value.strip()
  541. if value.endswith('\\'):
  542. value = value[:-1].rstrip()
  543. continued_for = variable
  544. else:
  545. continued_for = None
  546. emacs_vars[variable] = value
  547. # Unquote values.
  548. for var, val in list(emacs_vars.items()):
  549. if len(val) > 1 and (val.startswith('"') and val.endswith('"')
  550. or val.startswith('"') and val.endswith('"')):
  551. emacs_vars[var] = val[1:-1]
  552. return emacs_vars
  553. def _detab_line(self, line):
  554. r"""Recusively convert tabs to spaces in a single line.
  555. Called from _detab()."""
  556. if '\t' not in line:
  557. return line
  558. chunk1, chunk2 = line.split('\t', 1)
  559. chunk1 += (' ' * (self.tab_width - len(chunk1) % self.tab_width))
  560. output = chunk1 + chunk2
  561. return self._detab_line(output)
  562. def _detab(self, text):
  563. r"""Iterate text line by line and convert tabs to spaces.
  564. >>> m = Markdown()
  565. >>> m._detab("\tfoo")
  566. ' foo'
  567. >>> m._detab(" \tfoo")
  568. ' foo'
  569. >>> m._detab("\t foo")
  570. ' foo'
  571. >>> m._detab(" foo")
  572. ' foo'
  573. >>> m._detab(" foo\n\tbar\tblam")
  574. ' foo\n bar blam'
  575. """
  576. if '\t' not in text:
  577. return text
  578. output = []
  579. for line in text.splitlines():
  580. output.append(self._detab_line(line))
  581. return '\n'.join(output)
  582. # I broke out the html5 tags here and add them to _block_tags_a and
  583. # _block_tags_b. This way html5 tags are easy to keep track of.
  584. _html5tags = '|article|aside|header|hgroup|footer|nav|section|figure|figcaption'
  585. _block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del'
  586. _block_tags_a += _html5tags
  587. _strict_tag_block_re = re.compile(r"""
  588. ( # save in \1
  589. ^ # start of line (with re.M)
  590. <(%s) # start tag = \2
  591. \b # word break
  592. (.*\n)*? # any number of lines, minimally matching
  593. </\2> # the matching end tag
  594. [ \t]* # trailing spaces/tabs
  595. (?=\n+|\Z) # followed by a newline or end of document
  596. )
  597. """ % _block_tags_a,
  598. re.X | re.M)
  599. _block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math'
  600. _block_tags_b += _html5tags
  601. _liberal_tag_block_re = re.compile(r"""
  602. ( # save in \1
  603. ^ # start of line (with re.M)
  604. <(%s) # start tag = \2
  605. \b # word break
  606. (.*\n)*? # any number of lines, minimally matching
  607. .*</\2> # the matching end tag
  608. [ \t]* # trailing spaces/tabs
  609. (?=\n+|\Z) # followed by a newline or end of document
  610. )
  611. """ % _block_tags_b,
  612. re.X | re.M)
  613. _html_markdown_attr_re = re.compile(
  614. r'''\s+markdown=("1"|'1')''')
  615. def _hash_html_block_sub(self, match, raw=False):
  616. html = match.group(1)
  617. if raw and self.safe_mode:
  618. html = self._sanitize_html(html)
  619. elif 'markdown-in-html' in self.extras and 'markdown=' in html:
  620. first_line = html.split('\n', 1)[0]
  621. m = self._html_markdown_attr_re.search(first_line)
  622. if m:
  623. lines = html.split('\n')
  624. middle = '\n'.join(lines[1:-1])
  625. last_line = lines[-1]
  626. first_line = first_line[:m.start()] + first_line[m.end():]
  627. f_key = _hash_text(first_line)
  628. self.html_blocks[f_key] = first_line
  629. l_key = _hash_text(last_line)
  630. self.html_blocks[l_key] = last_line
  631. return ''.join(["\n\n", f_key,
  632. "\n\n", middle, "\n\n",
  633. l_key, "\n\n"])
  634. key = _hash_text(html)
  635. self.html_blocks[key] = html
  636. return "\n\n" + key + "\n\n"
  637. def _hash_html_blocks(self, text, raw=False):
  638. """Hashify HTML blocks
  639. We only want to do this for block-level HTML tags, such as headers,
  640. lists, and tables. That's because we still want to wrap <p>s around
  641. "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  642. phrase emphasis, and spans. The list of tags we're looking for is
  643. hard-coded.
  644. @param raw {boolean} indicates if these are raw HTML blocks in
  645. the original source. It makes a difference in "safe" mode.
  646. """
  647. if '<' not in text:
  648. return text
  649. # Pass `raw` value into our calls to self._hash_html_block_sub.
  650. hash_html_block_sub = _curry(self._hash_html_block_sub, raw=raw)
  651. # First, look for nested blocks, e.g.:
  652. # <div>
  653. # <div>
  654. # tags for inner block must be indented.
  655. # </div>
  656. # </div>
  657. #
  658. # The outermost tags must start at the left margin for this to match, and
  659. # the inner nested divs must be indented.
  660. # We need to do this before the next, more liberal match, because the next
  661. # match will start at the first `<div>` and stop at the first `</div>`.
  662. text = self._strict_tag_block_re.sub(hash_html_block_sub, text)
  663. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  664. text = self._liberal_tag_block_re.sub(hash_html_block_sub, text)
  665. # Special case just for <hr />. It was easier to make a special
  666. # case than to make the other regex more complicated.
  667. if "<hr" in text:
  668. _hr_tag_re = _hr_tag_re_from_tab_width(self.tab_width)
  669. text = _hr_tag_re.sub(hash_html_block_sub, text)
  670. # Special case for standalone HTML comments:
  671. if "<!--" in text:
  672. start = 0
  673. while True:
  674. # Delimiters for next comment block.
  675. try:
  676. start_idx = text.index("<!--", start)
  677. except ValueError:
  678. break
  679. try:
  680. end_idx = text.index("-->", start_idx) + 3
  681. except ValueError:
  682. break
  683. # Start position for next comment block search.
  684. start = end_idx
  685. # Validate whitespace before comment.
  686. if start_idx:
  687. # - Up to `tab_width - 1` spaces before start_idx.
  688. for i in range(self.tab_width - 1):
  689. if text[start_idx - 1] != ' ':
  690. break
  691. start_idx -= 1
  692. if start_idx == 0:
  693. break
  694. # - Must be preceded by 2 newlines or hit the start of
  695. # the document.
  696. if start_idx == 0:
  697. pass
  698. elif start_idx == 1 and text[0] == '\n':
  699. start_idx = 0 # to match minute detail of Markdown.pl regex
  700. elif text[start_idx-2:start_idx] == '\n\n':
  701. pass
  702. else:
  703. break
  704. # Validate whitespace after comment.
  705. # - Any number of spaces and tabs.
  706. while end_idx < len(text):
  707. if text[end_idx] not in ' \t':
  708. break
  709. end_idx += 1
  710. # - Must be following by 2 newlines or hit end of text.
  711. if text[end_idx:end_idx+2] not in ('', '\n', '\n\n'):
  712. continue
  713. # Escape and hash (must match `_hash_html_block_sub`).
  714. html = text[start_idx:end_idx]
  715. if raw and self.safe_mode:
  716. html = self._sanitize_html(html)
  717. key = _hash_text(html)
  718. self.html_blocks[key] = html
  719. text = text[:start_idx] + "\n\n" + key + "\n\n" + text[end_idx:]
  720. if "xml" in self.extras:
  721. # Treat XML processing instructions and namespaced one-liner
  722. # tags as if they were block HTML tags. E.g., if standalone
  723. # (i.e. are their own paragraph), the following do not get
  724. # wrapped in a <p> tag:
  725. # <?foo bar?>
  726. #
  727. # <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="chapter_1.md"/>
  728. _xml_oneliner_re = _xml_oneliner_re_from_tab_width(self.tab_width)
  729. text = _xml_oneliner_re.sub(hash_html_block_sub, text)
  730. return text
  731. def _strip_link_definitions(self, text):
  732. # Strips link definitions from text, stores the URLs and titles in
  733. # hash references.
  734. less_than_tab = self.tab_width - 1
  735. # Link defs are in the form:
  736. # [id]: url "optional title"
  737. _link_def_re = re.compile(r"""
  738. ^[ ]{0,%d}\[(.+)\]: # id = \1
  739. [ \t]*
  740. \n? # maybe *one* newline
  741. [ \t]*
  742. <?(.+?)>? # url = \2
  743. [ \t]*
  744. (?:
  745. \n? # maybe one newline
  746. [ \t]*
  747. (?<=\s) # lookbehind for whitespace
  748. ['"(]
  749. ([^\n]*) # title = \3
  750. ['")]
  751. [ \t]*
  752. )? # title is optional
  753. (?:\n+|\Z)
  754. """ % less_than_tab, re.X | re.M | re.U)
  755. return _link_def_re.sub(self._extract_link_def_sub, text)
  756. def _extract_link_def_sub(self, match):
  757. id, url, title = match.groups()
  758. key = id.lower() # Link IDs are case-insensitive
  759. self.urls[key] = self._encode_amps_and_angles(url)
  760. if title:
  761. self.titles[key] = title
  762. return ""
  763. def _do_numbering(self, text):
  764. ''' We handle the special extension for generic numbering for
  765. tables, figures etc.
  766. '''
  767. # First pass to define all the references
  768. self.regex_defns = re.compile(r'''
  769. \[\#(\w+) # the counter. Open square plus hash plus a word \1
  770. ([^@]*) # Some optional characters, that aren't an @. \2
  771. @(\w+) # the id. Should this be normed? \3
  772. ([^\]]*)\] # The rest of the text up to the terminating ] \4
  773. ''', re.VERBOSE)
  774. self.regex_subs = re.compile(r"\[@(\w+)\s*\]") # [@ref_id]
  775. counters = {}
  776. references = {}
  777. replacements = []
  778. definition_html = '<figcaption class="{}" id="counter-ref-{}">{}{}{}</figcaption>'
  779. reference_html = '<a class="{}" href="#counter-ref-{}">{}</a>'
  780. for match in self.regex_defns.finditer(text):
  781. # We must have four match groups otherwise this isn't a numbering reference
  782. if len(match.groups()) != 4:
  783. continue
  784. counter = match.group(1)
  785. text_before = match.group(2).strip()
  786. ref_id = match.group(3)
  787. text_after = match.group(4)
  788. number = counters.get(counter, 1)
  789. references[ref_id] = (number, counter)
  790. replacements.append((match.start(0),
  791. definition_html.format(counter,
  792. ref_id,
  793. text_before,
  794. number,
  795. text_after),
  796. match.end(0)))
  797. counters[counter] = number + 1
  798. for repl in reversed(replacements):
  799. text = text[:repl[0]] + repl[1] + text[repl[2]:]
  800. # Second pass to replace the references with the right
  801. # value of the counter
  802. # Fwiw, it's vaguely annoying to have to turn the iterator into
  803. # a list and then reverse it but I can't think of a better thing to do.
  804. for match in reversed(list(self.regex_subs.finditer(text))):
  805. number, counter = references.get(match.group(1), (None, None))
  806. if number is not None:
  807. repl = reference_html.format(counter,
  808. match.group(1),
  809. number)
  810. else:
  811. repl = reference_html.format(match.group(1),
  812. 'countererror',
  813. '?' + match.group(1) + '?')
  814. if "smarty-pants" in self.extras:
  815. repl = repl.replace('"', self._escape_table['"'])
  816. text = text[:match.start()] + repl + text[match.end():]
  817. return text
  818. def _extract_footnote_def_sub(self, match):
  819. id, text = match.groups()
  820. text = _dedent(text, skip_first_line=not text.startswith('\n')).strip()
  821. normed_id = re.sub(r'\W', '-', id)
  822. # Ensure footnote text ends with a couple newlines (for some
  823. # block gamut matches).
  824. self.footnotes[normed_id] = text + "\n\n"
  825. return ""
  826. def _strip_footnote_definitions(self, text):
  827. """A footnote definition looks like this:
  828. [^note-id]: Text of the note.
  829. May include one or more indented paragraphs.
  830. Where,
  831. - The 'note-id' can be pretty much anything, though typically it
  832. is the number of the footnote.
  833. - The first paragraph may start on the next line, like so:
  834. [^note-id]:
  835. Text of the note.
  836. """
  837. less_than_tab = self.tab_width - 1
  838. footnote_def_re = re.compile(r'''
  839. ^[ ]{0,%d}\[\^(.+)\]: # id = \1
  840. [ \t]*
  841. ( # footnote text = \2
  842. # First line need not start with the spaces.
  843. (?:\s*.*\n+)
  844. (?:
  845. (?:[ ]{%d} | \t) # Subsequent lines must be indented.
  846. .*\n+
  847. )*
  848. )
  849. # Lookahead for non-space at line-start, or end of doc.
  850. (?:(?=^[ ]{0,%d}\S)|\Z)
  851. ''' % (less_than_tab, self.tab_width, self.tab_width),
  852. re.X | re.M)
  853. return footnote_def_re.sub(self._extract_footnote_def_sub, text)
  854. _hr_re = re.compile(r'^[ ]{0,3}([-_*][ ]{0,2}){3,}$', re.M)
  855. def _run_block_gamut(self, text):
  856. # These are all the transformations that form block-level
  857. # tags like paragraphs, headers, and list items.
  858. if "fenced-code-blocks" in self.extras:
  859. text = self._do_fenced_code_blocks(text)
  860. text = self._do_headers(text)
  861. # Do Horizontal Rules:
  862. # On the number of spaces in horizontal rules: The spec is fuzzy: "If
  863. # you wish, you may use spaces between the hyphens or asterisks."
  864. # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the
  865. # hr chars to one or two. We'll reproduce that limit here.
  866. hr = "\n<hr"+self.empty_element_suffix+"\n"
  867. text = re.sub(self._hr_re, hr, text)
  868. text = self._do_lists(text)
  869. if "pyshell" in self.extras:
  870. text = self._prepare_pyshell_blocks(text)
  871. if "wiki-tables" in self.extras:
  872. text = self._do_wiki_tables(text)
  873. if "tables" in self.extras:
  874. text = self._do_tables(text)
  875. text = self._do_code_blocks(text)
  876. text = self._do_block_quotes(text)
  877. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  878. # was to escape raw HTML in the original Markdown source. This time,
  879. # we're escaping the markup we've just created, so that we don't wrap
  880. # <p> tags around block-level tags.
  881. text = self._hash_html_blocks(text)
  882. text = self._form_paragraphs(text)
  883. return text
  884. def _pyshell_block_sub(self, match):
  885. if "fenced-code-blocks" in self.extras:
  886. dedented = _dedent(match.group(0))
  887. return self._do_fenced_code_blocks("```pycon\n" + dedented + "```\n")
  888. lines = match.group(0).splitlines(0)
  889. _dedentlines(lines)
  890. indent = ' ' * self.tab_width
  891. s = ('\n' # separate from possible cuddled paragraph
  892. + indent + ('\n'+indent).join(lines)
  893. + '\n\n')
  894. return s
  895. def _prepare_pyshell_blocks(self, text):
  896. """Ensure that Python interactive shell sessions are put in
  897. code blocks -- even if not properly indented.
  898. """
  899. if ">>>" not in text:
  900. return text
  901. less_than_tab = self.tab_width - 1
  902. _pyshell_block_re = re.compile(r"""
  903. ^([ ]{0,%d})>>>[ ].*\n # first line
  904. ^(\1.*\S+.*\n)* # any number of subsequent lines
  905. ^\n # ends with a blank line
  906. """ % less_than_tab, re.M | re.X)
  907. return _pyshell_block_re.sub(self._pyshell_block_sub, text)
  908. def _table_sub(self, match):
  909. trim_space_re = '^[ \t\n]+|[ \t\n]+$'
  910. trim_bar_re = r'^\||\|$'
  911. split_bar_re = r'^\||(?<!\\)\|'
  912. escape_bar_re = r'\\\|'
  913. head, underline, body = match.groups()
  914. # Determine aligns for columns.
  915. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", underline)))]
  916. align_from_col_idx = {}
  917. for col_idx, col in enumerate(cols):
  918. if col[0] == ':' and col[-1] == ':':
  919. align_from_col_idx[col_idx] = ' style="text-align:center;"'
  920. elif col[0] == ':':
  921. align_from_col_idx[col_idx] = ' style="text-align:left;"'
  922. elif col[-1] == ':':
  923. align_from_col_idx[col_idx] = ' style="text-align:right;"'
  924. # thead
  925. hlines = ['<table%s>' % self._html_class_str_from_tag('table'), '<thead>', '<tr>']
  926. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", head)))]
  927. for col_idx, col in enumerate(cols):
  928. hlines.append(' <th%s>%s</th>' % (
  929. align_from_col_idx.get(col_idx, ''),
  930. self._run_span_gamut(col)
  931. ))
  932. hlines.append('</tr>')
  933. hlines.append('</thead>')
  934. # tbody
  935. hlines.append('<tbody>')
  936. for line in body.strip('\n').split('\n'):
  937. hlines.append('<tr>')
  938. cols = [re.sub(escape_bar_re, '|', cell.strip()) for cell in re.split(split_bar_re, re.sub(trim_bar_re, "", re.sub(trim_space_re, "", line)))]
  939. for col_idx, col in enumerate(cols):
  940. hlines.append(' <td%s>%s</td>' % (
  941. align_from_col_idx.get(col_idx, ''),
  942. self._run_span_gamut(col)
  943. ))
  944. hlines.append('</tr>')
  945. hlines.append('</tbody>')
  946. hlines.append('</table>')
  947. return '\n'.join(hlines) + '\n'
  948. def _do_tables(self, text):
  949. """Copying PHP-Markdown and GFM table syntax. Some regex borrowed from
  950. https://github.com/michelf/php-markdown/blob/lib/Michelf/Markdown.php#L2538
  951. """
  952. less_than_tab = self.tab_width - 1
  953. table_re = re.compile(r'''
  954. (?:(?<=\n\n)|\A\n?) # leading blank line
  955. ^[ ]{0,%d} # allowed whitespace
  956. (.*[|].*) \n # $1: header row (at least one pipe)
  957. ^[ ]{0,%d} # allowed whitespace
  958. ( # $2: underline row
  959. # underline row with leading bar
  960. (?: \|\ *:?-+:?\ * )+ \|? \s? \n
  961. |
  962. # or, underline row without leading bar
  963. (?: \ *:?-+:?\ *\| )+ (?: \ *:?-+:?\ * )? \s? \n
  964. )
  965. ( # $3: data rows
  966. (?:
  967. ^[ ]{0,%d}(?!\ ) # ensure line begins with 0 to less_than_tab spaces
  968. .*\|.* \n
  969. )+
  970. )
  971. ''' % (less_than_tab, less_than_tab, less_than_tab), re.M | re.X)
  972. return table_re.sub(self._table_sub, text)
  973. def _wiki_table_sub(self, match):
  974. ttext = match.group(0).strip()
  975. # print('wiki table: %r' % match.group(0))
  976. rows = []
  977. for line in ttext.splitlines(0):
  978. line = line.strip()[2:-2].strip()
  979. row = [c.strip() for c in re.split(r'(?<!\\)\|\|', line)]
  980. rows.append(row)
  981. # from pprint import pprint
  982. # pprint(rows)
  983. hlines = []
  984. def add_hline(line, indents=0):
  985. hlines.append((self.tab * indents) + line)
  986. def format_cell(text):
  987. return self._run_span_gamut(re.sub(r"^\s*~", "", cell).strip(" "))
  988. add_hline('<table%s>' % self._html_class_str_from_tag('table'))
  989. # Check if first cell of first row is a header cell. If so, assume the whole row is a header row.
  990. if rows and rows[0] and re.match(r"^\s*~", rows[0][0]):
  991. add_hline('<thead>', 1)
  992. add_hline('<tr>', 2)
  993. for cell in rows[0]:
  994. add_hline("<th>{}</th>".format(format_cell(cell)), 3)
  995. add_hline('</tr>', 2)
  996. add_hline('</thead>', 1)
  997. # Only one header row allowed.
  998. rows = rows[1:]
  999. # If no more rows, don't create a tbody.
  1000. if rows:
  1001. add_hline('<tbody>', 1)
  1002. for row in rows:
  1003. add_hline('<tr>', 2)
  1004. for cell in row:
  1005. add_hline('<td>{}</td>'.format(format_cell(cell)), 3)
  1006. add_hline('</tr>', 2)
  1007. add_hline('</tbody>', 1)
  1008. add_hline('</table>')
  1009. return '\n'.join(hlines) + '\n'
  1010. def _do_wiki_tables(self, text):
  1011. # Optimization.
  1012. if "||" not in text:
  1013. return text
  1014. less_than_tab = self.tab_width - 1
  1015. wiki_table_re = re.compile(r'''
  1016. (?:(?<=\n\n)|\A\n?) # leading blank line
  1017. ^([ ]{0,%d})\|\|.+?\|\|[ ]*\n # first line
  1018. (^\1\|\|.+?\|\|\n)* # any number of subsequent lines
  1019. ''' % less_than_tab, re.M | re.X)
  1020. return wiki_table_re.sub(self._wiki_table_sub, text)
  1021. def _run_span_gamut(self, text):
  1022. # These are all the transformations that occur *within* block-level
  1023. # tags like paragraphs, headers, and list items.
  1024. text = self._do_code_spans(text)
  1025. text = self._escape_special_chars(text)
  1026. # Process anchor and image tags.
  1027. if "link-patterns" in self.extras:
  1028. text = self._do_link_patterns(text)
  1029. text = self._do_links(text)
  1030. # Make links out of things like `<http://example.com/>`
  1031. # Must come after _do_links(), because you can use < and >
  1032. # delimiters in inline links like [this](<url>).
  1033. text = self._do_auto_links(text)
  1034. text = self._encode_amps_and_angles(text)
  1035. if "strike" in self.extras:
  1036. text = self._do_strike(text)
  1037. if "underline" in self.extras:
  1038. text = self._do_underline(text)
  1039. text = self._do_italics_and_bold(text)
  1040. if "smarty-pants" in self.extras:
  1041. text = self._do_smart_punctuation(text)
  1042. # Do hard breaks:
  1043. if "break-on-newline" in self.extras:
  1044. text = re.sub(r" *\n", "<br%s\n" % self.empty_element_suffix, text)
  1045. else:
  1046. text = re.sub(r" {2,}\n", " <br%s\n" % self.empty_element_suffix, text)
  1047. return text
  1048. # "Sorta" because auto-links are identified as "tag" tokens.
  1049. _sorta_html_tokenize_re = re.compile(r"""
  1050. (
  1051. # tag
  1052. </?
  1053. (?:\w+) # tag name
  1054. (?:\s+(?:[\w-]+:)?[\w-]+=(?:".*?"|'.*?'))* # attributes
  1055. \s*/?>
  1056. |
  1057. # auto-link (e.g., <http://www.activestate.com/>)
  1058. <\w+[^>]*>
  1059. |
  1060. <!--.*?--> # comment
  1061. |
  1062. <\?.*?\?> # processing instruction
  1063. )
  1064. """, re.X)
  1065. def _escape_special_chars(self, text):
  1066. # Python markdown note: the HTML tokenization here differs from
  1067. # that in Markdown.pl, hence the behaviour for subtle cases can
  1068. # differ (I believe the tokenizer here does a better job because
  1069. # it isn't susceptible to unmatched '<' and '>' in HTML tags).
  1070. # Note, however, that '>' is not allowed in an auto-link URL
  1071. # here.
  1072. escaped = []
  1073. is_html_markup = False
  1074. for token in self._sorta_html_tokenize_re.split(text):
  1075. if is_html_markup:
  1076. # Within tags/HTML-comments/auto-links, encode * and _
  1077. # so they don't conflict with their use in Markdown for
  1078. # italics and strong. We're replacing each such
  1079. # character with its corresponding MD5 checksum value;
  1080. # this is likely overkill, but it should prevent us from
  1081. # colliding with the escape values by accident.
  1082. escaped.append(token.replace('*', self._escape_table['*'])
  1083. .replace('_', self._escape_table['_']))
  1084. else:
  1085. escaped.append(self._encode_backslash_escapes(token))
  1086. is_html_markup = not is_html_markup
  1087. return ''.join(escaped)
  1088. def _hash_html_spans(self, text):
  1089. # Used for safe_mode.
  1090. def _is_auto_link(s):
  1091. if ':' in s and self._auto_link_re.match(s):
  1092. return True
  1093. elif '@' in s and self._auto_email_link_re.match(s):
  1094. return True
  1095. return False
  1096. tokens = []
  1097. is_html_markup = False
  1098. for token in self._sorta_html_tokenize_re.split(text):
  1099. if is_html_markup and not _is_auto_link(token):
  1100. sanitized = self._sanitize_html(token)
  1101. key = _hash_text(sanitized)
  1102. self.html_spans[key] = sanitized
  1103. tokens.append(key)
  1104. else:
  1105. tokens.append(self._encode_incomplete_tags(token))
  1106. is_html_markup = not is_html_markup
  1107. return ''.join(tokens)
  1108. def _unhash_html_spans(self, text):
  1109. for key, sanitized in list(self.html_spans.items()):
  1110. text = text.replace(key, sanitized)
  1111. return text
  1112. def _sanitize_html(self, s):
  1113. if self.safe_mode == "replace":
  1114. return self.html_removed_text
  1115. elif self.safe_mode == "escape":
  1116. replacements = [
  1117. ('&', '&amp;'),
  1118. ('<', '&lt;'),
  1119. ('>', '&gt;'),
  1120. ]
  1121. for before, after in replacements:
  1122. s = s.replace(before, after)
  1123. return s
  1124. else:
  1125. raise MarkdownError("invalid value for 'safe_mode': %r (must be "
  1126. "'escape' or 'replace')" % self.safe_mode)
  1127. _inline_link_title = re.compile(r'''
  1128. ( # \1
  1129. [ \t]+
  1130. (['"]) # quote char = \2
  1131. (?P<title>.*?)
  1132. \2
  1133. )? # title is optional
  1134. \)$
  1135. ''', re.X | re.S)
  1136. _tail_of_reference_link_re = re.compile(r'''
  1137. # Match tail of: [text][id]
  1138. [ ]? # one optional space
  1139. (?:\n[ ]*)? # one optional newline followed by spaces
  1140. \[
  1141. (?P<id>.*?)
  1142. \]
  1143. ''', re.X | re.S)
  1144. _whitespace = re.compile(r'\s*')
  1145. _strip_anglebrackets = re.compile(r'<(.*)>.*')
  1146. def _find_non_whitespace(self, text, start):
  1147. """Returns the index of the first non-whitespace character in text
  1148. after (and including) start
  1149. """
  1150. match = self._whitespace.match(text, start)
  1151. return match.end()
  1152. def _find_balanced(self, text, start, open_c, close_c):
  1153. """Returns the index where the open_c and close_c characters balance
  1154. out - the same number of open_c and close_c are encountered - or the
  1155. end of string if it's reached before the balance point is found.
  1156. """
  1157. i = start
  1158. l = len(text)
  1159. count = 1
  1160. while count > 0 and i < l:
  1161. if text[i] == open_c:
  1162. count += 1
  1163. elif text[i] == close_c:
  1164. count -= 1
  1165. i += 1
  1166. return i
  1167. def _extract_url_and_title(self, text, start):
  1168. """Extracts the url and (optional) title from the tail of a link"""
  1169. # text[start] equals the opening parenthesis
  1170. idx = self._find_non_whitespace(text, start+1)
  1171. if idx == len(text):
  1172. return None, None, None
  1173. end_idx = idx
  1174. has_anglebrackets = text[idx] == "<"
  1175. if has_anglebrackets:
  1176. end_idx = self._find_balanced(text, end_idx+1, "<", ">")
  1177. end_idx = self._find_balanced(text, end_idx, "(", ")")
  1178. match = self._inline_link_title.search(text, idx, end_idx)
  1179. if not match:
  1180. return None, None, None
  1181. url, title = text[idx:match.start()], match.group("title")
  1182. if has_anglebrackets:
  1183. url = self._strip_anglebrackets.sub(r'\1', url)
  1184. return url, title, end_idx
  1185. _safe_protocols = re.compile(r'(https?|ftp):', re.I)
  1186. def _do_links(self, text):
  1187. """Turn Markdown link shortcuts into XHTML <a> and <img> tags.
  1188. This is a combination of Markdown.pl's _DoAnchors() and
  1189. _DoImages(). They are done together because that simplified the
  1190. approach. It was necessary to use a different approach than
  1191. Markdown.pl because of the lack of atomic matching support in
  1192. Python's regex engine used in $g_nested_brackets.
  1193. """
  1194. MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24
  1195. # `anchor_allowed_pos` is used to support img links inside
  1196. # anchors, but not anchors inside anchors. An anchor's start
  1197. # pos must be `>= anchor_allowed_pos`.
  1198. anchor_allowed_pos = 0
  1199. curr_pos = 0
  1200. while True: # Handle the next link.
  1201. # The next '[' is the start of:
  1202. # - an inline anchor: [text](url "title")
  1203. # - a reference anchor: [text][id]
  1204. # - an inline img: ![text](url "title")
  1205. # - a reference img: ![text][id]
  1206. # - a footnote ref: [^id]
  1207. # (Only if 'footnotes' extra enabled)
  1208. # - a footnote defn: [^id]: ...
  1209. # (Only if 'footnotes' extra enabled) These have already
  1210. # been stripped in _strip_footnote_definitions() so no
  1211. # need to watch for them.
  1212. # - a link definition: [id]: url "title"
  1213. # These have already been stripped in
  1214. # _strip_link_definitions() so no need to watch for them.
  1215. # - not markup: [...anything else...
  1216. try:
  1217. start_idx = text.index('[', curr_pos)
  1218. except ValueError:
  1219. break
  1220. text_length = len(text)
  1221. # Find the matching closing ']'.
  1222. # Markdown.pl allows *matching* brackets in link text so we
  1223. # will here too. Markdown.pl *doesn't* currently allow
  1224. # matching brackets in img alt text -- we'll differ in that
  1225. # regard.
  1226. bracket_depth = 0
  1227. for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,
  1228. text_length)):
  1229. ch = text[p]
  1230. if ch == ']':
  1231. bracket_depth -= 1
  1232. if bracket_depth < 0:
  1233. break
  1234. elif ch == '[':
  1235. bracket_depth += 1
  1236. else:
  1237. # Closing bracket not found within sentinel length.
  1238. # This isn't markup.
  1239. curr_pos = start_idx + 1
  1240. continue
  1241. link_text = text[start_idx+1:p]
  1242. # Fix for issue 341 - Injecting XSS into link text
  1243. if self.safe_mode:
  1244. link_text = self._hash_html_spans(link_text)
  1245. link_text = self._unhash_html_spans(link_text)
  1246. # Possibly a footnote ref?
  1247. if "footnotes" in self.extras and link_text.startswith("^"):
  1248. normed_id = re.sub(r'\W', '-', link_text[1:])
  1249. if normed_id in self.footnotes:
  1250. self.footnote_ids.append(normed_id)
  1251. result = '<sup class="footnote-ref" id="fnref-%s">' \
  1252. '<a href="#fn-%s">%s</a></sup>' \
  1253. % (normed_id, normed_id, len(self.footnote_ids))
  1254. text = text[:start_idx] + result + text[p+1:]
  1255. else:
  1256. # This id isn't defined, leave the markup alone.
  1257. curr_pos = p+1
  1258. continue
  1259. # Now determine what this is by the remainder.
  1260. p += 1
  1261. if p == text_length:
  1262. return text
  1263. # Inline anchor or img?
  1264. if text[p] == '(': # attempt at perf improvement
  1265. url, title, url_end_idx = self._extract_url_and_title(text, p)
  1266. if url is not None:
  1267. # Handle an inline anchor or img.
  1268. is_img = start_idx > 0 and text[start_idx-1] == "!"
  1269. if is_img:
  1270. start_idx -= 1
  1271. # We've got to encode these to avoid conflicting
  1272. # with italics/bold.
  1273. url = url.replace('*', self._escape_table['*']) \
  1274. .replace('_', self._escape_table['_'])
  1275. if title:
  1276. title_str = ' title="%s"' % (
  1277. _xml_escape_attr(title)
  1278. .replace('*', self._escape_table['*'])
  1279. .replace('_', self._escape_table['_']))
  1280. else:
  1281. title_str = ''
  1282. if is_img:
  1283. img_class_str = self._html_class_str_from_tag("img")
  1284. result = '<img src="%s" alt="%s"%s%s%s' \
  1285. % (_html_escape_url(url, safe_mode=self.safe_mode),
  1286. _xml_escape_attr(link_text),
  1287. title_str,
  1288. img_class_str,
  1289. self.empty_element_suffix)
  1290. if "smarty-pants" in self.extras:
  1291. result = result.replace('"', self._escape_table['"'])
  1292. curr_pos = start_idx + len(result)
  1293. text = text[:start_idx] + result + text[url_end_idx:]
  1294. elif start_idx >= anchor_allowed_pos:
  1295. safe_link = self._safe_protocols.match(url) or url.startswith('#')
  1296. if self.safe_mode and not safe_link:
  1297. result_head = '<a href="#"%s>' % (title_str)
  1298. else:
  1299. result_head = '<a href="%s"%s>' % (_html_escape_url(url, safe_mode=self.safe_mode), title_str)
  1300. result = '%s%s</a>' % (result_head, link_text)
  1301. if "smarty-pants" in self.extras:
  1302. result = result.replace('"', self._escape_table['"'])
  1303. # <img> allowed from curr_pos on, <a> from
  1304. # anchor_allowed_pos on.
  1305. curr_pos = start_idx + len(result_head)
  1306. anchor_allowed_pos = start_idx + len(result)
  1307. text = text[:start_idx] + result + text[url_end_idx:]
  1308. else:
  1309. # Anchor not allowed here.
  1310. curr_pos = start_idx + 1
  1311. continue
  1312. # Reference anchor or img?
  1313. else:
  1314. match = self._tail_of_reference_link_re.match(text, p)
  1315. if match:
  1316. # Handle a reference-style anchor or img.
  1317. is_img = start_idx > 0 and text[start_idx-1] == "!"
  1318. if is_img:
  1319. start_idx -= 1
  1320. link_id = match.group("id").lower()
  1321. if not link_id:
  1322. link_id = link_text.lower() # for links like [this][]
  1323. if link_id in self.urls:
  1324. url = self.urls[link_id]
  1325. # We've got to encode these to avoid conflicting
  1326. # with italics/bold.
  1327. url = url.replace('*', self._escape_table['*']) \
  1328. .replace('_', self._escape_table['_'])
  1329. title = self.titles.get(link_id)
  1330. if title:
  1331. title = _xml_escape_attr(title) \
  1332. .replace('*', self._escape_table['*']) \
  1333. .replace('_', self._escape_table['_'])
  1334. title_str = ' title="%s"' % title
  1335. else:
  1336. title_str = ''
  1337. if is_img:
  1338. img_class_str = self._html_class_str_from_tag("img")
  1339. result = '<img src="%s" alt="%s"%s%s%s' \
  1340. % (_html_escape_url(url, safe_mode=self.safe_mode),
  1341. _xml_escape_attr(link_text),
  1342. title_str,
  1343. img_class_str,
  1344. self.empty_element_suffix)
  1345. if "smarty-pants" in self.extras:
  1346. result = result.replace('"', self._escape_table['"'])
  1347. curr_pos = start_idx + len(result)
  1348. text = text[:start_idx] + result + text[match.end():]
  1349. elif start_idx >= anchor_allowed_pos:
  1350. if self.safe_mode and not self._safe_protocols.match(url):
  1351. result_head = '<a href="#"%s>' % (title_str)
  1352. else:
  1353. result_head = '<a href="%s"%s>' % (_html_escape_url(url, safe_mode=self.safe_mode), title_str)
  1354. result = '%s%s</a>' % (result_head, link_text)
  1355. if "smarty-pants" in self.extras:
  1356. result = result.replace('"', self._escape_table['"'])
  1357. # <img> allowed from curr_pos on, <a> from
  1358. # anchor_allowed_pos on.
  1359. curr_pos = start_idx + len(result_head)
  1360. anchor_allowed_pos = start_idx + len(result)
  1361. text = text[:start_idx] + result + text[match.end():]
  1362. else:
  1363. # Anchor not allowed here.
  1364. curr_pos = start_idx + 1
  1365. else:
  1366. # This id isn't defined, leave the markup alone.
  1367. curr_pos = match.end()
  1368. continue
  1369. # Otherwise, it isn't markup.
  1370. curr_pos = start_idx + 1
  1371. return text
  1372. def header_id_from_text(self, text, prefix, n):
  1373. """Generate a header id attribute value from the given header
  1374. HTML content.
  1375. This is only called if the "header-ids" extra is enabled.
  1376. Subclasses may override this for different header ids.
  1377. @param text {str} The text of the header tag
  1378. @param prefix {str} The requested prefix for header ids. This is the
  1379. value of the "header-ids" extra key, if any. Otherwise, None.
  1380. @param n {int} The <hN> tag number, i.e. `1` for an <h1> tag.
  1381. @returns {str} The value for the header tag's "id" attribute. Return
  1382. None to not have an id attribute and to exclude this header from
  1383. the TOC (if the "toc" extra is specified).
  1384. """
  1385. header_id = _slugify(text)
  1386. if prefix and isinstance(prefix, base_string_type):
  1387. header_id = prefix + '-' + header_id
  1388. self._count_from_header_id[header_id] += 1
  1389. if 0 == len(header_id) or self._count_from_header_id[header_id] > 1:
  1390. header_id += '-%s' % self._count_from_header_id[header_id]
  1391. return header_id
  1392. def _toc_add_entry(self, level, id, name):
  1393. if level > self._toc_depth:
  1394. return
  1395. if self._toc is None:
  1396. self._toc = []
  1397. self._toc.append((level, id, self._unescape_special_chars(name)))
  1398. _h_re_base = r'''
  1399. (^(.+)[ \t]*\n(=+|-+)[ \t]*\n+)
  1400. |
  1401. (^(\#{1,6}) # \1 = string of #'s
  1402. [ \t]%s
  1403. (.+?) # \2 = Header text
  1404. [ \t]*
  1405. (?<!\\) # ensure not an escaped trailing '#'
  1406. \#* # optional closing #'s (not counted)
  1407. \n+
  1408. )
  1409. '''
  1410. _h_re = re.compile(_h_re_base % '*', re.X | re.M)
  1411. _h_re_tag_friendly = re.compile(_h_re_base % '+', re.X | re.M)
  1412. def _h_sub(self, match):
  1413. if match.group(1) is not None and match.group(3) == "-":
  1414. return match.group(1)
  1415. elif match.group(1) is not None:
  1416. # Setext header
  1417. n = {"=": 1, "-": 2}[match.group(3)[0]]
  1418. header_group = match.group(2)
  1419. else:
  1420. # atx header
  1421. n = len(match.group(5))
  1422. header_group = match.group(6)
  1423. demote_headers = self.extras.get("demote-headers")
  1424. if demote_headers:
  1425. n = min(n + demote_headers, 6)
  1426. header_id_attr = ""
  1427. if "header-ids" in self.extras:
  1428. header_id = self.header_id_from_text(header_group,
  1429. self.extras["header-ids"], n)
  1430. if header_id:
  1431. header_id_attr = ' id="%s"' % header_id
  1432. html = self._run_span_gamut(header_group)
  1433. if "toc" in self.extras and header_id:
  1434. self._toc_add_entry(n, header_id, html)
  1435. return "<h%d%s>%s</h%d>\n\n" % (n, header_id_attr, html, n)
  1436. def _do_headers(self, text):
  1437. # Setext-style headers:
  1438. # Header 1
  1439. # ========
  1440. #
  1441. # Header 2
  1442. # --------
  1443. # atx-style headers:
  1444. # # Header 1
  1445. # ## Header 2
  1446. # ## Header 2 with closing hashes ##
  1447. # ...
  1448. # ###### Header 6
  1449. if 'tag-friendly' in self.extras:
  1450. return self._h_re_tag_friendly.sub(self._h_sub, text)
  1451. return self._h_re.sub(self._h_sub, text)
  1452. _marker_ul_chars = '*+-'
  1453. _marker_any = r'(?:[%s]|\d+\.)' % _marker_ul_chars
  1454. _marker_ul = '(?:[%s])' % _marker_ul_chars
  1455. _marker_ol = r'(?:\d+\.)'
  1456. def _list_sub(self, match):
  1457. lst = match.group(1)
  1458. lst_type = match.group(3) in self._marker_ul_chars and "ul" or "ol"
  1459. result = self._process_list_items(lst)
  1460. if self.list_level:
  1461. return "<%s>\n%s</%s>\n" % (lst_type, result, lst_type)
  1462. else:
  1463. return "<%s>\n%s</%s>\n\n" % (lst_type, result, lst_type)
  1464. def _do_lists(self, text):
  1465. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  1466. # Iterate over each *non-overlapping* list match.
  1467. pos = 0
  1468. while True:
  1469. # Find the *first* hit for either list style (ul or ol). We
  1470. # match ul and ol separately to avoid adjacent lists of different
  1471. # types running into each other (see issue #16).
  1472. hits = []
  1473. for marker_pat in (self._marker_ul, self._marker_ol):
  1474. less_than_tab = self.tab_width - 1
  1475. whole_list = r'''
  1476. ( # \1 = whole list
  1477. ( # \2
  1478. [ ]{0,%d}
  1479. (%s) # \3 = first list item marker
  1480. [ \t]+
  1481. (?!\ *\3\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case.
  1482. )
  1483. (?:.+?)
  1484. ( # \4
  1485. \Z
  1486. |
  1487. \n{2,}
  1488. (?=\S)
  1489. (?! # Negative lookahead for another list item marker
  1490. [ \t]*
  1491. %s[ \t]+
  1492. )
  1493. )
  1494. )
  1495. ''' % (less_than_tab, marker_pat, marker_pat)
  1496. if self.list_level: # sub-list
  1497. list_re = re.compile("^"+whole_list, re.X | re.M | re.S)
  1498. else:
  1499. list_re = re.compile(r"(?:(?<=\n\n)|\A\n?)"+whole_list,
  1500. re.X | re.M | re.S)
  1501. match = list_re.search(text, pos)
  1502. if match:
  1503. hits.append((match.start(), match))
  1504. if not hits:
  1505. break
  1506. hits.sort()
  1507. match = hits[0][1]
  1508. start, end = match.span()
  1509. middle = self._list_sub(match)
  1510. text = text[:start] + middle + text[end:]
  1511. pos = start + len(middle) # start pos for next attempted match
  1512. return text
  1513. _list_item_re = re.compile(r'''
  1514. (\n)? # leading line = \1
  1515. (^[ \t]*) # leading whitespace = \2
  1516. (?P<marker>%s) [ \t]+ # list marker = \3
  1517. ((?:.+?) # list item text = \4
  1518. (\n{1,2})) # eols = \5
  1519. (?= \n* (\Z | \2 (?P<next_marker>%s) [ \t]+))
  1520. ''' % (_marker_any, _marker_any),
  1521. re.M | re.X | re.S)
  1522. _task_list_item_re = re.compile(r'''
  1523. (\[[\ xX]\])[ \t]+ # tasklist marker = \1
  1524. (.*) # list item text = \2
  1525. ''', re.M | re.X | re.S)
  1526. _task_list_warpper_str = r'<input type="checkbox" class="task-list-item-checkbox" %sdisabled> %s'
  1527. def _task_list_item_sub(self, match):
  1528. marker = match.group(1)
  1529. item_text = match.group(2)
  1530. if marker in ['[x]','[X]']:
  1531. return self._task_list_warpper_str % ('checked ', item_text)
  1532. elif marker == '[ ]':
  1533. return self._task_list_warpper_str % ('', item_text)
  1534. _last_li_endswith_two_eols = False
  1535. def _list_item_sub(self, match):
  1536. item = match.group(4)
  1537. leading_line = match.group(1)
  1538. if leading_line or "\n\n" in item or self._last_li_endswith_two_eols:
  1539. item = self._run_block_gamut(self._outdent(item))
  1540. else:
  1541. # Recursion for sub-lists:
  1542. item = self._do_lists(self._outdent(item))
  1543. if item.endswith('\n'):
  1544. item = item[:-1]
  1545. item = self._run_span_gamut(item)
  1546. self._last_li_endswith_two_eols = (len(match.group(5)) == 2)
  1547. if "task_list" in self.extras:
  1548. item = self._task_list_item_re.sub(self._task_list_item_sub, item)
  1549. return "<li>%s</li>\n" % item
  1550. def _process_list_items(self, list_str):
  1551. # Process the contents of a single ordered or unordered list,
  1552. # splitting it into individual list items.
  1553. # The $g_list_level global keeps track of when we're inside a list.
  1554. # Each time we enter a list, we increment it; when we leave a list,
  1555. # we decrement. If it's zero, we're not in a list anymore.
  1556. #
  1557. # We do this because when we're not inside a list, we want to treat
  1558. # something like this:
  1559. #
  1560. # I recommend upgrading to version
  1561. # 8. Oops, now this line is treated
  1562. # as a sub-list.
  1563. #
  1564. # As a single paragraph, despite the fact that the second line starts
  1565. # with a digit-period-space sequence.
  1566. #
  1567. # Whereas when we're inside a list (or sub-list), that line will be
  1568. # treated as the start of a sub-list. What a kludge, huh? This is
  1569. # an aspect of Markdown's syntax that's hard to parse perfectly
  1570. # without resorting to mind-reading. Perhaps the solution is to
  1571. # change the syntax rules such that sub-lists must start with a
  1572. # starting cardinal number; e.g. "1." or "a.".
  1573. self.list_level += 1
  1574. self._last_li_endswith_two_eols = False
  1575. list_str = list_str.rstrip('\n') + '\n'
  1576. list_str = self._list_item_re.sub(self._list_item_sub, list_str)
  1577. self.list_level -= 1
  1578. return list_str
  1579. def _get_pygments_lexer(self, lexer_name):
  1580. try:
  1581. from pygments import lexers, util
  1582. except ImportError:
  1583. return None
  1584. try:
  1585. return lexers.get_lexer_by_name(lexer_name)
  1586. except util.ClassNotFound:
  1587. return None
  1588. def _color_with_pygments(self, codeblock, lexer, **formatter_opts):
  1589. import pygments
  1590. import pygments.formatters
  1591. class HtmlCodeFormatter(pygments.formatters.HtmlFormatter):
  1592. def _wrap_code(self, inner):
  1593. """A function for use in a Pygments Formatter which
  1594. wraps in <code> tags.
  1595. """
  1596. yield 0, "<code>"
  1597. for tup in inner:
  1598. yield tup
  1599. yield 0, "</code>"
  1600. def wrap(self, source, outfile):
  1601. """Return the source with a code, pre, and div."""
  1602. return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
  1603. formatter_opts.setdefault("cssclass", "codehilite")
  1604. formatter = HtmlCodeFormatter(**formatter_opts)
  1605. return pygments.highlight(codeblock, lexer, formatter)
  1606. def _code_block_sub(self, match, is_fenced_code_block=False):
  1607. lexer_name = None
  1608. if is_fenced_code_block:
  1609. lexer_name = match.group(1)
  1610. if lexer_name:
  1611. formatter_opts = self.extras['fenced-code-blocks'] or {}
  1612. codeblock = match.group(2)
  1613. codeblock = codeblock[:-1] # drop one trailing newline
  1614. else:
  1615. codeblock = match.group(1)
  1616. codeblock = self._outdent(codeblock)
  1617. codeblock = self._detab(codeblock)
  1618. codeblock = codeblock.lstrip('\n') # trim leading newlines
  1619. codeblock = codeblock.rstrip() # trim trailing whitespace
  1620. # Note: "code-color" extra is DEPRECATED.
  1621. if "code-color" in self.extras and codeblock.startswith(":::"):
  1622. lexer_name, rest = codeblock.split('\n', 1)
  1623. lexer_name = lexer_name[3:].strip()
  1624. codeblock = rest.lstrip("\n") # Remove lexer declaration line.
  1625. formatter_opts = self.extras['code-color'] or {}
  1626. # Use pygments only if not using the highlightjs-lang extra
  1627. if lexer_name and "highlightjs-lang" not in self.extras:
  1628. def unhash_code(codeblock):
  1629. for key, sanitized in list(self.html_spans.items()):
  1630. codeblock = codeblock.replace(key, sanitized)
  1631. replacements = [
  1632. ("&amp;", "&"),
  1633. ("&lt;", "<"),
  1634. ("&gt;", ">")
  1635. ]
  1636. for old, new in replacements:
  1637. codeblock = codeblock.replace(old, new)
  1638. return codeblock
  1639. lexer = self._get_pygments_lexer(lexer_name)
  1640. if lexer:
  1641. codeblock = unhash_code( codeblock )
  1642. colored = self._color_with_pygments(codeblock, lexer,
  1643. **formatter_opts)
  1644. return "\n\n%s\n\n" % colored
  1645. codeblock = self._encode_code(codeblock)
  1646. pre_class_str = self._html_class_str_from_tag("pre")
  1647. if "highlightjs-lang" in self.extras and lexer_name:
  1648. code_class_str = ' class="%s language-%s"' % (lexer_name, lexer_name)
  1649. else:
  1650. code_class_str = self._html_class_str_from_tag("code")
  1651. return "\n\n<pre%s><code%s>%s\n</code></pre>\n\n" % (
  1652. pre_class_str, code_class_str, codeblock)
  1653. def _html_class_str_from_tag(self, tag):
  1654. """Get the appropriate ' class="..."' string (note the leading
  1655. space), if any, for the given tag.
  1656. """
  1657. if "html-classes" not in self.extras:
  1658. return ""
  1659. try:
  1660. html_classes_from_tag = self.extras["html-classes"]
  1661. except TypeError:
  1662. return ""
  1663. else:
  1664. if tag in html_classes_from_tag:
  1665. return ' class="%s"' % html_classes_from_tag[tag]
  1666. return ""
  1667. def _do_code_blocks(self, text):
  1668. """Process Markdown `<pre><code>` blocks."""
  1669. code_block_re = re.compile(r'''
  1670. (?:\n\n|\A\n?)
  1671. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1672. (?:
  1673. (?:[ ]{%d} | \t) # Lines must start with a tab or a tab-width of spaces
  1674. .*\n+
  1675. )+
  1676. )
  1677. ((?=^[ ]{0,%d}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1678. # Lookahead to make sure this block isn't already in a code block.
  1679. # Needed when syntax highlighting is being used.
  1680. (?![^<]*\</code\>)
  1681. ''' % (self.tab_width, self.tab_width),
  1682. re.M | re.X)
  1683. return code_block_re.sub(self._code_block_sub, text)
  1684. _fenced_code_block_re = re.compile(r'''
  1685. (?:\n+|\A\n?)
  1686. ^```\s{0,99}([\w+-]+)?\s{0,99}\n # opening fence, $1 = optional lang
  1687. (.*?) # $2 = code block content
  1688. ^```[ \t]*\n # closing fence
  1689. ''', re.M | re.X | re.S)
  1690. def _fenced_code_block_sub(self, match):
  1691. return self._code_block_sub(match, is_fenced_code_block=True)
  1692. def _do_fenced_code_blocks(self, text):
  1693. """Process ```-fenced unindented code blocks ('fenced-code-blocks' extra)."""
  1694. return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)
  1695. # Rules for a code span:
  1696. # - backslash escapes are not interpreted in a code span
  1697. # - to include one or or a run of more backticks the delimiters must
  1698. # be a longer run of backticks
  1699. # - cannot start or end a code span with a backtick; pad with a
  1700. # space and that space will be removed in the emitted HTML
  1701. # See `test/tm-cases/escapes.text` for a number of edge-case
  1702. # examples.
  1703. _code_span_re = re.compile(r'''
  1704. (?<!\\)
  1705. (`+) # \1 = Opening run of `
  1706. (?!`) # See Note A test/tm-cases/escapes.text
  1707. (.+?) # \2 = The code block
  1708. (?<!`)
  1709. \1 # Matching closer
  1710. (?!`)
  1711. ''', re.X | re.S)
  1712. def _code_span_sub(self, match):
  1713. c = match.group(2).strip(" \t")
  1714. c = self._encode_code(c)
  1715. return "<code>%s</code>" % c
  1716. def _do_code_spans(self, text):
  1717. # * Backtick quotes are used for <code></code> spans.
  1718. #
  1719. # * You can use multiple backticks as the delimiters if you want to
  1720. # include literal backticks in the code span. So, this input:
  1721. #
  1722. # Just type ``foo `bar` baz`` at the prompt.
  1723. #
  1724. # Will translate to:
  1725. #
  1726. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1727. #
  1728. # There's no arbitrary limit to the number of backticks you
  1729. # can use as delimters. If you need three consecutive backticks
  1730. # in your code, use four for delimiters, etc.
  1731. #
  1732. # * You can use spaces to get literal backticks at the edges:
  1733. #
  1734. # ... type `` `bar` `` ...
  1735. #
  1736. # Turns to:
  1737. #
  1738. # ... type <code>`bar`</code> ...
  1739. return self._code_span_re.sub(self._code_span_sub, text)
  1740. def _encode_code(self, text):
  1741. """Encode/escape certain characters inside Markdown code runs.
  1742. The point is that in code, these characters are literals,
  1743. and lose their special Markdown meanings.
  1744. """
  1745. replacements = [
  1746. # Encode all ampersands; HTML entities are not
  1747. # entities within a Markdown code span.
  1748. ('&', '&amp;'),
  1749. # Do the angle bracket song and dance:
  1750. ('<', '&lt;'),
  1751. ('>', '&gt;'),
  1752. ]
  1753. for before, after in replacements:
  1754. text = text.replace(before, after)
  1755. hashed = _hash_text(text)
  1756. self._escape_table[text] = hashed
  1757. return hashed
  1758. _strike_re = re.compile(r"~~(?=\S)(.+?)(?<=\S)~~", re.S)
  1759. def _do_strike(self, text):
  1760. text = self._strike_re.sub(r"<strike>\1</strike>", text)
  1761. return text
  1762. _underline_re = re.compile(r"--(?=\S)(.+?)(?<=\S)--", re.S)
  1763. def _do_underline(self, text):
  1764. text = self._underline_re.sub(r"<u>\1</u>", text)
  1765. return text
  1766. _strong_re = re.compile(r"(\*\*|__)(?=\S)(.+?[*_]*)(?<=\S)\1", re.S)
  1767. _em_re = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1", re.S)
  1768. _code_friendly_strong_re = re.compile(r"\*\*(?=\S)(.+?[*_]*)(?<=\S)\*\*", re.S)
  1769. _code_friendly_em_re = re.compile(r"\*(?=\S)(.+?)(?<=\S)\*", re.S)
  1770. def _do_italics_and_bold(self, text):
  1771. # <strong> must go first:
  1772. if "code-friendly" in self.extras:
  1773. text = self._code_friendly_strong_re.sub(r"<strong>\1</strong>", text)
  1774. text = self._code_friendly_em_re.sub(r"<em>\1</em>", text)
  1775. else:
  1776. text = self._strong_re.sub(r"<strong>\2</strong>", text)
  1777. text = self._em_re.sub(r"<em>\2</em>", text)
  1778. return text
  1779. # "smarty-pants" extra: Very liberal in interpreting a single prime as an
  1780. # apostrophe; e.g. ignores the fact that "round", "bout", "twer", and
  1781. # "twixt" can be written without an initial apostrophe. This is fine because
  1782. # using scare quotes (single quotation marks) is rare.
  1783. _apostrophe_year_re = re.compile(r"'(\d\d)(?=(\s|,|;|\.|\?|!|$))")
  1784. _contractions = ["tis", "twas", "twer", "neath", "o", "n",
  1785. "round", "bout", "twixt", "nuff", "fraid", "sup"]
  1786. def _do_smart_contractions(self, text):
  1787. text = self._apostrophe_year_re.sub(r"&#8217;\1", text)
  1788. for c in self._contractions:
  1789. text = text.replace("'%s" % c, "&#8217;%s" % c)
  1790. text = text.replace("'%s" % c.capitalize(),
  1791. "&#8217;%s" % c.capitalize())
  1792. return text
  1793. # Substitute double-quotes before single-quotes.
  1794. _opening_single_quote_re = re.compile(r"(?<!\S)'(?=\S)")
  1795. _opening_double_quote_re = re.compile(r'(?<!\S)"(?=\S)')
  1796. _closing_single_quote_re = re.compile(r"(?<=\S)'")
  1797. _closing_double_quote_re = re.compile(r'(?<=\S)"(?=(\s|,|;|\.|\?|!|$))')
  1798. def _do_smart_punctuation(self, text):
  1799. """Fancifies 'single quotes', "double quotes", and apostrophes.
  1800. Converts --, ---, and ... into en dashes, em dashes, and ellipses.
  1801. Inspiration is: <http://daringfireball.net/projects/smartypants/>
  1802. See "test/tm-cases/smarty_pants.text" for a full discussion of the
  1803. support here and
  1804. <http://code.google.com/p/python-markdown2/issues/detail?id=42> for a
  1805. discussion of some diversion from the original SmartyPants.
  1806. """
  1807. if "'" in text: # guard for perf
  1808. text = self._do_smart_contractions(text)
  1809. text = self._opening_single_quote_re.sub("&#8216;", text)
  1810. text = self._closing_single_quote_re.sub("&#8217;", text)
  1811. if '"' in text: # guard for perf
  1812. text = self._opening_double_quote_re.sub("&#8220;", text)
  1813. text = self._closing_double_quote_re.sub("&#8221;", text)
  1814. text = text.replace("---", "&#8212;")
  1815. text = text.replace("--", "&#8211;")
  1816. text = text.replace("...", "&#8230;")
  1817. text = text.replace(" . . . ", "&#8230;")
  1818. text = text.replace(". . .", "&#8230;")
  1819. # TODO: Temporary hack to fix https://github.com/trentm/python-markdown2/issues/150
  1820. if "footnotes" in self.extras and "footnote-ref" in text:
  1821. # Quotes in the footnote back ref get converted to "smart" quotes
  1822. # Change them back here to ensure they work.
  1823. text = text.replace('class="footnote-ref&#8221;', 'class="footnote-ref"')
  1824. return text
  1825. _block_quote_base = r'''
  1826. ( # Wrap whole match in \1
  1827. (
  1828. ^[ \t]*>%s[ \t]? # '>' at the start of a line
  1829. .+\n # rest of the first line
  1830. (.+\n)* # subsequent consecutive lines
  1831. )+
  1832. )
  1833. '''
  1834. _block_quote_re = re.compile(_block_quote_base % '', re.M | re.X)
  1835. _block_quote_re_spoiler = re.compile(_block_quote_base % '[ \t]*?!?', re.M | re.X)
  1836. _bq_one_level_re = re.compile('^[ \t]*>[ \t]?', re.M)
  1837. _bq_one_level_re_spoiler = re.compile('^[ \t]*>[ \t]*?![ \t]?', re.M)
  1838. _bq_all_lines_spoilers = re.compile(r'\A(?:^[ \t]*>[ \t]*?!.*[\n\r]*)+\Z', re.M)
  1839. _html_pre_block_re = re.compile(r'(\s*<pre>.+?</pre>)', re.S)
  1840. def _dedent_two_spaces_sub(self, match):
  1841. return re.sub(r'(?m)^ ', '', match.group(1))
  1842. def _block_quote_sub(self, match):
  1843. bq = match.group(1)
  1844. is_spoiler = 'spoiler' in self.extras and self._bq_all_lines_spoilers.match(bq)
  1845. # trim one level of quoting
  1846. if is_spoiler:
  1847. bq = self._bq_one_level_re_spoiler.sub('', bq)
  1848. else:
  1849. bq = self._bq_one_level_re.sub('', bq)
  1850. # trim whitespace-only lines
  1851. bq = self._ws_only_line_re.sub('', bq)
  1852. bq = self._run_block_gamut(bq) # recurse
  1853. bq = re.sub('(?m)^', ' ', bq)
  1854. # These leading spaces screw with <pre> content, so we need to fix that:
  1855. bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)
  1856. if is_spoiler:
  1857. return '<blockquote class="spoiler">\n%s\n</blockquote>\n\n' % bq
  1858. else:
  1859. return '<blockquote>\n%s\n</blockquote>\n\n' % bq
  1860. def _do_block_quotes(self, text):
  1861. if '>' not in text:
  1862. return text
  1863. if 'spoiler' in self.extras:
  1864. return self._block_quote_re_spoiler.sub(self._block_quote_sub, text)
  1865. else:
  1866. return self._block_quote_re.sub(self._block_quote_sub, text)
  1867. def _form_paragraphs(self, text):
  1868. # Strip leading and trailing lines:
  1869. text = text.strip('\n')
  1870. # Wrap <p> tags.
  1871. grafs = []
  1872. for i, graf in enumerate(re.split(r"\n{2,}", text)):
  1873. if graf in self.html_blocks:
  1874. # Unhashify HTML blocks
  1875. grafs.append(self.html_blocks[graf])
  1876. else:
  1877. cuddled_list = None
  1878. if "cuddled-lists" in self.extras:
  1879. # Need to put back trailing '\n' for `_list_item_re`
  1880. # match at the end of the paragraph.
  1881. li = self._list_item_re.search(graf + '\n')
  1882. # Two of the same list marker in this paragraph: a likely
  1883. # candidate for a list cuddled to preceding paragraph
  1884. # text (issue 33). Note the `[-1]` is a quick way to
  1885. # consider numeric bullets (e.g. "1." and "2.") to be
  1886. # equal.
  1887. if (li and len(li.group(2)) <= 3
  1888. and (
  1889. (li.group("next_marker") and li.group("marker")[-1] == li.group("next_marker")[-1])
  1890. or
  1891. li.group("next_marker") is None
  1892. )
  1893. ):
  1894. start = li.start()
  1895. cuddled_list = self._do_lists(graf[start:]).rstrip("\n")
  1896. assert cuddled_list.startswith("<ul>") or cuddled_list.startswith("<ol>")
  1897. graf = graf[:start]
  1898. # Wrap <p> tags.
  1899. graf = self._run_span_gamut(graf)
  1900. grafs.append("<p%s>" % self._html_class_str_from_tag('p') + graf.lstrip(" \t") + "</p>")
  1901. if cuddled_list:
  1902. grafs.append(cuddled_list)
  1903. return "\n\n".join(grafs)
  1904. def _add_footnotes(self, text):
  1905. if self.footnotes:
  1906. footer = [
  1907. '<div class="footnotes">',
  1908. '<hr' + self.empty_element_suffix,
  1909. '<ol>',
  1910. ]
  1911. if not self.footnote_title:
  1912. self.footnote_title = "Jump back to footnote %d in the text."
  1913. if not self.footnote_return_symbol:
  1914. self.footnote_return_symbol = "&#8617;"
  1915. for i, id in enumerate(self.footnote_ids):
  1916. if i != 0:
  1917. footer.append('')
  1918. footer.append('<li id="fn-%s">' % id)
  1919. footer.append(self._run_block_gamut(self.footnotes[id]))
  1920. try:
  1921. backlink = ('<a href="#fnref-%s" ' +
  1922. 'class="footnoteBackLink" ' +
  1923. 'title="' + self.footnote_title + '">' +
  1924. self.footnote_return_symbol +
  1925. '</a>') % (id, i+1)
  1926. except TypeError:
  1927. log.debug("Footnote error. `footnote_title` "
  1928. "must include parameter. Using defaults.")
  1929. backlink = ('<a href="#fnref-%s" '
  1930. 'class="footnoteBackLink" '
  1931. 'title="Jump back to footnote %d in the text.">'
  1932. '&#8617;</a>' % (id, i+1))
  1933. if footer[-1].endswith("</p>"):
  1934. footer[-1] = footer[-1][:-len("</p>")] \
  1935. + '&#160;' + backlink + "</p>"
  1936. else:
  1937. footer.append("\n<p>%s</p>" % backlink)
  1938. footer.append('</li>')
  1939. footer.append('</ol>')
  1940. footer.append('</div>')
  1941. return text + '\n\n' + '\n'.join(footer)
  1942. else:
  1943. return text
  1944. _naked_lt_re = re.compile(r'<(?![a-z/?\$!])', re.I)
  1945. _naked_gt_re = re.compile(r'''(?<![a-z0-9?!/'"-])>''', re.I)
  1946. def _encode_amps_and_angles(self, text):
  1947. # Smart processing for ampersands and angle brackets that need
  1948. # to be encoded.
  1949. text = _AMPERSAND_RE.sub('&amp;', text)
  1950. # Encode naked <'s
  1951. text = self._naked_lt_re.sub('&lt;', text)
  1952. # Encode naked >'s
  1953. # Note: Other markdown implementations (e.g. Markdown.pl, PHP
  1954. # Markdown) don't do this.
  1955. text = self._naked_gt_re.sub('&gt;', text)
  1956. return text
  1957. _incomplete_tags_re = re.compile(r"<(/?\w+?(?!\w).+?[\s/]+?)")
  1958. def _encode_incomplete_tags(self, text):
  1959. if self.safe_mode not in ("replace", "escape"):
  1960. return text
  1961. if text.endswith(">"):
  1962. return text # this is not an incomplete tag, this is a link in the form <http://x.y.z>
  1963. return self._incomplete_tags_re.sub("&lt;\\1", text)
  1964. def _encode_backslash_escapes(self, text):
  1965. for ch, escape in list(self._escape_table.items()):
  1966. text = text.replace("\\"+ch, escape)
  1967. return text
  1968. _auto_link_re = re.compile(r'<((https?|ftp):[^\'">\s]+)>', re.I)
  1969. def _auto_link_sub(self, match):
  1970. g1 = match.group(1)
  1971. return '<a href="%s">%s</a>' % (g1, g1)
  1972. _auto_email_link_re = re.compile(r"""
  1973. <
  1974. (?:mailto:)?
  1975. (
  1976. [-.\w]+
  1977. \@
  1978. [-\w]+(\.[-\w]+)*\.[a-z]+
  1979. )
  1980. >
  1981. """, re.I | re.X | re.U)
  1982. def _auto_email_link_sub(self, match):
  1983. return self._encode_email_address(
  1984. self._unescape_special_chars(match.group(1)))
  1985. def _do_auto_links(self, text):
  1986. text = self._auto_link_re.sub(self._auto_link_sub, text)
  1987. text = self._auto_email_link_re.sub(self._auto_email_link_sub, text)
  1988. return text
  1989. def _encode_email_address(self, addr):
  1990. # Input: an email address, e.g. "foo@example.com"
  1991. #
  1992. # Output: the email address as a mailto link, with each character
  1993. # of the address encoded as either a decimal or hex entity, in
  1994. # the hopes of foiling most address harvesting spam bots. E.g.:
  1995. #
  1996. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1997. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1998. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1999. #
  2000. # Based on a filter by Matthew Wickline, posted to the BBEdit-Talk
  2001. # mailing list: <http://tinyurl.com/yu7ue>
  2002. chars = [_xml_encode_email_char_at_random(ch)
  2003. for ch in "mailto:" + addr]
  2004. # Strip the mailto: from the visible part.
  2005. addr = '<a href="%s">%s</a>' \
  2006. % (''.join(chars), ''.join(chars[7:]))
  2007. return addr
  2008. def _do_link_patterns(self, text):
  2009. link_from_hash = {}
  2010. for regex, repl in self.link_patterns:
  2011. replacements = []
  2012. for match in regex.finditer(text):
  2013. if hasattr(repl, "__call__"):
  2014. href = repl(match)
  2015. else:
  2016. href = match.expand(repl)
  2017. replacements.append((match.span(), href))
  2018. for (start, end), href in reversed(replacements):
  2019. # Do not match against links inside brackets.
  2020. if text[start - 1:start] == '[' and text[end:end + 1] == ']':
  2021. continue
  2022. # Do not match against links in the standard markdown syntax.
  2023. if text[start - 2:start] == '](' or text[end:end + 2] == '")':
  2024. continue
  2025. # Do not match against links which are escaped.
  2026. if text[start - 3:start] == '"""' and text[end:end + 3] == '"""':
  2027. text = text[:start - 3] + text[start:end] + text[end + 3:]
  2028. continue
  2029. escaped_href = (
  2030. href.replace('"', '&quot;') # b/c of attr quote
  2031. # To avoid markdown <em> and <strong>:
  2032. .replace('*', self._escape_table['*'])
  2033. .replace('_', self._escape_table['_']))
  2034. link = '<a href="%s">%s</a>' % (escaped_href, text[start:end])
  2035. hash = _hash_text(link)
  2036. link_from_hash[hash] = link
  2037. text = text[:start] + hash + text[end:]
  2038. for hash, link in list(link_from_hash.items()):
  2039. text = text.replace(hash, link)
  2040. return text
  2041. def _unescape_special_chars(self, text):
  2042. # Swap back in all the special characters we've hidden.
  2043. for ch, hash in list(self._escape_table.items()):
  2044. text = text.replace(hash, ch)
  2045. return text
  2046. def _outdent(self, text):
  2047. # Remove one level of line-leading tabs or spaces
  2048. return self._outdent_re.sub('', text)
  2049. class MarkdownWithExtras(Markdown):
  2050. """A markdowner class that enables most extras:
  2051. - footnotes
  2052. - code-color (only has effect if 'pygments' Python module on path)
  2053. These are not included:
  2054. - pyshell (specific to Python-related documenting)
  2055. - code-friendly (because it *disables* part of the syntax)
  2056. - link-patterns (because you need to specify some actual
  2057. link-patterns anyway)
  2058. """
  2059. extras = ["footnotes", "code-color"]
  2060. # ---- internal support functions
  2061. def calculate_toc_html(toc):
  2062. """Return the HTML for the current TOC.
  2063. This expects the `_toc` attribute to have been set on this instance.
  2064. """
  2065. if toc is None:
  2066. return None
  2067. def indent():
  2068. return ' ' * (len(h_stack) - 1)
  2069. lines = []
  2070. h_stack = [0] # stack of header-level numbers
  2071. for level, id, name in toc:
  2072. if level > h_stack[-1]:
  2073. lines.append("%s<ul>" % indent())
  2074. h_stack.append(level)
  2075. elif level == h_stack[-1]:
  2076. lines[-1] += "</li>"
  2077. else:
  2078. while level < h_stack[-1]:
  2079. h_stack.pop()
  2080. if not lines[-1].endswith("</li>"):
  2081. lines[-1] += "</li>"
  2082. lines.append("%s</ul></li>" % indent())
  2083. lines.append('%s<li><a href="#%s">%s</a>' % (
  2084. indent(), id, name))
  2085. while len(h_stack) > 1:
  2086. h_stack.pop()
  2087. if not lines[-1].endswith("</li>"):
  2088. lines[-1] += "</li>"
  2089. lines.append("%s</ul>" % indent())
  2090. return '\n'.join(lines) + '\n'
  2091. class UnicodeWithAttrs(unicode):
  2092. """A subclass of unicode used for the return value of conversion to
  2093. possibly attach some attributes. E.g. the "toc_html" attribute when
  2094. the "toc" extra is used.
  2095. """
  2096. metadata = None
  2097. toc_html = None
  2098. ## {{{ http://code.activestate.com/recipes/577257/ (r1)
  2099. _slugify_strip_re = re.compile(r'[^\w\s-]')
  2100. _slugify_hyphenate_re = re.compile(r'[-\s]+')
  2101. def _slugify(value):
  2102. """
  2103. Normalizes string, converts to lowercase, removes non-alpha characters,
  2104. and converts spaces to hyphens.
  2105. From Django's "django/template/defaultfilters.py".
  2106. """
  2107. import unicodedata
  2108. value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode()
  2109. value = _slugify_strip_re.sub('', value).strip().lower()
  2110. return _slugify_hyphenate_re.sub('-', value)
  2111. ## end of http://code.activestate.com/recipes/577257/ }}}
  2112. # From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
  2113. def _curry(*args, **kwargs):
  2114. function, args = args[0], args[1:]
  2115. def result(*rest, **kwrest):
  2116. combined = kwargs.copy()
  2117. combined.update(kwrest)
  2118. return function(*args + rest, **combined)
  2119. return result
  2120. # Recipe: regex_from_encoded_pattern (1.0)
  2121. def _regex_from_encoded_pattern(s):
  2122. """'foo' -> re.compile(re.escape('foo'))
  2123. '/foo/' -> re.compile('foo')
  2124. '/foo/i' -> re.compile('foo', re.I)
  2125. """
  2126. if s.startswith('/') and s.rfind('/') != 0:
  2127. # Parse it: /PATTERN/FLAGS
  2128. idx = s.rfind('/')
  2129. _, flags_str = s[1:idx], s[idx+1:]
  2130. flag_from_char = {
  2131. "i": re.IGNORECASE,
  2132. "l": re.LOCALE,
  2133. "s": re.DOTALL,
  2134. "m": re.MULTILINE,
  2135. "u": re.UNICODE,
  2136. }
  2137. flags = 0
  2138. for char in flags_str:
  2139. try:
  2140. flags |= flag_from_char[char]
  2141. except KeyError:
  2142. raise ValueError("unsupported regex flag: '%s' in '%s' "
  2143. "(must be one of '%s')"
  2144. % (char, s, ''.join(list(flag_from_char.keys()))))
  2145. return re.compile(s[1:idx], flags)
  2146. else: # not an encoded regex
  2147. return re.compile(re.escape(s))
  2148. # Recipe: dedent (0.1.2)
  2149. def _dedentlines(lines, tabsize=8, skip_first_line=False):
  2150. """_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines
  2151. "lines" is a list of lines to dedent.
  2152. "tabsize" is the tab width to use for indent width calculations.
  2153. "skip_first_line" is a boolean indicating if the first line should
  2154. be skipped for calculating the indent width and for dedenting.
  2155. This is sometimes useful for docstrings and similar.
  2156. Same as dedent() except operates on a sequence of lines. Note: the
  2157. lines list is modified **in-place**.
  2158. """
  2159. DEBUG = False
  2160. if DEBUG:
  2161. print("dedent: dedent(..., tabsize=%d, skip_first_line=%r)"\
  2162. % (tabsize, skip_first_line))
  2163. margin = None
  2164. for i, line in enumerate(lines):
  2165. if i == 0 and skip_first_line: continue
  2166. indent = 0
  2167. for ch in line:
  2168. if ch == ' ':
  2169. indent += 1
  2170. elif ch == '\t':
  2171. indent += tabsize - (indent % tabsize)
  2172. elif ch in '\r\n':
  2173. continue # skip all-whitespace lines
  2174. else:
  2175. break
  2176. else:
  2177. continue # skip all-whitespace lines
  2178. if DEBUG: print("dedent: indent=%d: %r" % (indent, line))
  2179. if margin is None:
  2180. margin = indent
  2181. else:
  2182. margin = min(margin, indent)
  2183. if DEBUG: print("dedent: margin=%r" % margin)
  2184. if margin is not None and margin > 0:
  2185. for i, line in enumerate(lines):
  2186. if i == 0 and skip_first_line: continue
  2187. removed = 0
  2188. for j, ch in enumerate(line):
  2189. if ch == ' ':
  2190. removed += 1
  2191. elif ch == '\t':
  2192. removed += tabsize - (removed % tabsize)
  2193. elif ch in '\r\n':
  2194. if DEBUG: print("dedent: %r: EOL -> strip up to EOL" % line)
  2195. lines[i] = lines[i][j:]
  2196. break
  2197. else:
  2198. raise ValueError("unexpected non-whitespace char %r in "
  2199. "line %r while removing %d-space margin"
  2200. % (ch, line, margin))
  2201. if DEBUG:
  2202. print("dedent: %r: %r -> removed %d/%d"\
  2203. % (line, ch, removed, margin))
  2204. if removed == margin:
  2205. lines[i] = lines[i][j+1:]
  2206. break
  2207. elif removed > margin:
  2208. lines[i] = ' '*(removed-margin) + lines[i][j+1:]
  2209. break
  2210. else:
  2211. if removed:
  2212. lines[i] = lines[i][removed:]
  2213. return lines
  2214. def _dedent(text, tabsize=8, skip_first_line=False):
  2215. """_dedent(text, tabsize=8, skip_first_line=False) -> dedented text
  2216. "text" is the text to dedent.
  2217. "tabsize" is the tab width to use for indent width calculations.
  2218. "skip_first_line" is a boolean indicating if the first line should
  2219. be skipped for calculating the indent width and for dedenting.
  2220. This is sometimes useful for docstrings and similar.
  2221. textwrap.dedent(s), but don't expand tabs to spaces
  2222. """
  2223. lines = text.splitlines(1)
  2224. _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)
  2225. return ''.join(lines)
  2226. class _memoized(object):
  2227. """Decorator that caches a function's return value each time it is called.
  2228. If called later with the same arguments, the cached value is returned, and
  2229. not re-evaluated.
  2230. http://wiki.python.org/moin/PythonDecoratorLibrary
  2231. """
  2232. def __init__(self, func):
  2233. self.func = func
  2234. self.cache = {}
  2235. def __call__(self, *args):
  2236. try:
  2237. return self.cache[args]
  2238. except KeyError:
  2239. self.cache[args] = value = self.func(*args)
  2240. return value
  2241. except TypeError:
  2242. # uncachable -- for instance, passing a list as an argument.
  2243. # Better to not cache than to blow up entirely.
  2244. return self.func(*args)
  2245. def __repr__(self):
  2246. """Return the function's docstring."""
  2247. return self.func.__doc__
  2248. def _xml_oneliner_re_from_tab_width(tab_width):
  2249. """Standalone XML processing instruction regex."""
  2250. return re.compile(r"""
  2251. (?:
  2252. (?<=\n\n) # Starting after a blank line
  2253. | # or
  2254. \A\n? # the beginning of the doc
  2255. )
  2256. ( # save in $1
  2257. [ ]{0,%d}
  2258. (?:
  2259. <\?\w+\b\s+.*?\?> # XML processing instruction
  2260. |
  2261. <\w+:\w+\b\s+.*?/> # namespaced single tag
  2262. )
  2263. [ \t]*
  2264. (?=\n{2,}|\Z) # followed by a blank line or end of document
  2265. )
  2266. """ % (tab_width - 1), re.X)
  2267. _xml_oneliner_re_from_tab_width = _memoized(_xml_oneliner_re_from_tab_width)
  2268. def _hr_tag_re_from_tab_width(tab_width):
  2269. return re.compile(r"""
  2270. (?:
  2271. (?<=\n\n) # Starting after a blank line
  2272. | # or
  2273. \A\n? # the beginning of the doc
  2274. )
  2275. ( # save in \1
  2276. [ ]{0,%d}
  2277. <(hr) # start tag = \2
  2278. \b # word break
  2279. ([^<>])*? #
  2280. /?> # the matching end tag
  2281. [ \t]*
  2282. (?=\n{2,}|\Z) # followed by a blank line or end of document
  2283. )
  2284. """ % (tab_width - 1), re.X)
  2285. _hr_tag_re_from_tab_width = _memoized(_hr_tag_re_from_tab_width)
  2286. def _xml_escape_attr(attr, skip_single_quote=True):
  2287. """Escape the given string for use in an HTML/XML tag attribute.
  2288. By default this doesn't bother with escaping `'` to `&#39;`, presuming that
  2289. the tag attribute is surrounded by double quotes.
  2290. """
  2291. escaped = _AMPERSAND_RE.sub('&amp;', attr)
  2292. escaped = (attr
  2293. .replace('"', '&quot;')
  2294. .replace('<', '&lt;')
  2295. .replace('>', '&gt;'))
  2296. if not skip_single_quote:
  2297. escaped = escaped.replace("'", "&#39;")
  2298. return escaped
  2299. def _xml_encode_email_char_at_random(ch):
  2300. r = random()
  2301. # Roughly 10% raw, 45% hex, 45% dec.
  2302. # '@' *must* be encoded. I [John Gruber] insist.
  2303. # Issue 26: '_' must be encoded.
  2304. if r > 0.9 and ch not in "@_":
  2305. return ch
  2306. elif r < 0.45:
  2307. # The [1:] is to drop leading '0': 0x63 -> x63
  2308. return '&#%s;' % hex(ord(ch))[1:]
  2309. else:
  2310. return '&#%s;' % ord(ch)
  2311. def _html_escape_url(attr, safe_mode=False):
  2312. """Replace special characters that are potentially malicious in url string."""
  2313. escaped = (attr
  2314. .replace('"', '&quot;')
  2315. .replace('<', '&lt;')
  2316. .replace('>', '&gt;'))
  2317. if safe_mode:
  2318. escaped = escaped.replace('+', ' ')
  2319. escaped = escaped.replace("'", "&#39;")
  2320. return escaped
  2321. # ---- mainline
  2322. class _NoReflowFormatter(optparse.IndentedHelpFormatter):
  2323. """An optparse formatter that does NOT reflow the description."""
  2324. def format_description(self, description):
  2325. return description or ""
  2326. def _test():
  2327. import doctest
  2328. doctest.testmod()
  2329. def main(argv=None):
  2330. if argv is None:
  2331. argv = sys.argv
  2332. if not logging.root.handlers:
  2333. logging.basicConfig()
  2334. usage = "usage: %prog [PATHS...]"
  2335. version = "%prog "+__version__
  2336. parser = optparse.OptionParser(prog="markdown2", usage=usage,
  2337. version=version, description=cmdln_desc,
  2338. formatter=_NoReflowFormatter())
  2339. parser.add_option("-v", "--verbose", dest="log_level",
  2340. action="store_const", const=logging.DEBUG,
  2341. help="more verbose output")
  2342. parser.add_option("--encoding",
  2343. help="specify encoding of text content")
  2344. parser.add_option("--html4tags", action="store_true", default=False,
  2345. help="use HTML 4 style for empty element tags")
  2346. parser.add_option("-s", "--safe", metavar="MODE", dest="safe_mode",
  2347. help="sanitize literal HTML: 'escape' escapes "
  2348. "HTML meta chars, 'replace' replaces with an "
  2349. "[HTML_REMOVED] note")
  2350. parser.add_option("-x", "--extras", action="append",
  2351. help="Turn on specific extra features (not part of "
  2352. "the core Markdown spec). See above.")
  2353. parser.add_option("--use-file-vars",
  2354. help="Look for and use Emacs-style 'markdown-extras' "
  2355. "file var to turn on extras. See "
  2356. "<https://github.com/trentm/python-markdown2/wiki/Extras>")
  2357. parser.add_option("--link-patterns-file",
  2358. help="path to a link pattern file")
  2359. parser.add_option("--self-test", action="store_true",
  2360. help="run internal self-tests (some doctests)")
  2361. parser.add_option("--compare", action="store_true",
  2362. help="run against Markdown.pl as well (for testing)")
  2363. parser.set_defaults(log_level=logging.INFO, compare=False,
  2364. encoding="utf-8", safe_mode=None, use_file_vars=False)
  2365. opts, paths = parser.parse_args()
  2366. log.setLevel(opts.log_level)
  2367. if opts.self_test:
  2368. return _test()
  2369. if opts.extras:
  2370. extras = {}
  2371. for s in opts.extras:
  2372. splitter = re.compile("[,;: ]+")
  2373. for e in splitter.split(s):
  2374. if '=' in e:
  2375. ename, earg = e.split('=', 1)
  2376. try:
  2377. earg = int(earg)
  2378. except ValueError:
  2379. pass
  2380. else:
  2381. ename, earg = e, None
  2382. extras[ename] = earg
  2383. else:
  2384. extras = None
  2385. if opts.link_patterns_file:
  2386. link_patterns = []
  2387. f = open(opts.link_patterns_file)
  2388. try:
  2389. for i, line in enumerate(f.readlines()):
  2390. if not line.strip(): continue
  2391. if line.lstrip().startswith("#"): continue
  2392. try:
  2393. pat, href = line.rstrip().rsplit(None, 1)
  2394. except ValueError:
  2395. raise MarkdownError("%s:%d: invalid link pattern line: %r"
  2396. % (opts.link_patterns_file, i+1, line))
  2397. link_patterns.append(
  2398. (_regex_from_encoded_pattern(pat), href))
  2399. finally:
  2400. f.close()
  2401. else:
  2402. link_patterns = None
  2403. from os.path import join, dirname, abspath, exists
  2404. markdown_pl = join(dirname(dirname(abspath(__file__))), "test",
  2405. "Markdown.pl")
  2406. if not paths:
  2407. paths = ['-']
  2408. for path in paths:
  2409. if path == '-':
  2410. text = sys.stdin.read()
  2411. else:
  2412. fp = codecs.open(path, 'r', opts.encoding)
  2413. text = fp.read()
  2414. fp.close()
  2415. if opts.compare:
  2416. from subprocess import Popen, PIPE
  2417. print("==== Markdown.pl ====")
  2418. p = Popen('perl %s' % markdown_pl, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
  2419. p.stdin.write(text.encode('utf-8'))
  2420. p.stdin.close()
  2421. perl_html = p.stdout.read().decode('utf-8')
  2422. if py3:
  2423. sys.stdout.write(perl_html)
  2424. else:
  2425. sys.stdout.write(perl_html.encode(
  2426. sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  2427. print("==== markdown2.py ====")
  2428. html = markdown(text,
  2429. html4tags=opts.html4tags,
  2430. safe_mode=opts.safe_mode,
  2431. extras=extras, link_patterns=link_patterns,
  2432. use_file_vars=opts.use_file_vars,
  2433. cli=True)
  2434. if py3:
  2435. sys.stdout.write(html)
  2436. else:
  2437. sys.stdout.write(html.encode(
  2438. sys.stdout.encoding or "utf-8", 'xmlcharrefreplace'))
  2439. if extras and "toc" in extras:
  2440. log.debug("toc_html: " +
  2441. str(html.toc_html.encode(sys.stdout.encoding or "utf-8", 'xmlcharrefreplace')))
  2442. if opts.compare:
  2443. test_dir = join(dirname(dirname(abspath(__file__))), "test")
  2444. if exists(join(test_dir, "test_markdown2.py")):
  2445. sys.path.insert(0, test_dir)
  2446. from test_markdown2 import norm_html_from_html
  2447. norm_html = norm_html_from_html(html)
  2448. norm_perl_html = norm_html_from_html(perl_html)
  2449. else:
  2450. norm_html = html
  2451. norm_perl_html = perl_html
  2452. print("==== match? %r ====" % (norm_perl_html == norm_html))
  2453. if __name__ == "__main__":
  2454. sys.exit(main(sys.argv))