util.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. """
  2. Python Markdown
  3. A Python implementation of John Gruber's Markdown.
  4. Documentation: https://python-markdown.github.io/
  5. GitHub: https://github.com/Python-Markdown/markdown/
  6. PyPI: https://pypi.org/project/Markdown/
  7. Started by Manfred Stienstra (http://www.dwerg.net/).
  8. Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org).
  9. Currently maintained by Waylan Limberg (https://github.com/waylan),
  10. Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser).
  11. Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later)
  12. Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  13. Copyright 2004 Manfred Stienstra (the original version)
  14. License: BSD (see LICENSE.md for details).
  15. """
  16. import re
  17. import sys
  18. from collections import namedtuple
  19. from functools import wraps
  20. import warnings
  21. import xml.etree.ElementTree
  22. from .pep562 import Pep562
  23. try:
  24. from importlib import metadata
  25. except ImportError:
  26. # <PY38 use backport
  27. import importlib_metadata as metadata
  28. PY37 = (3, 7) <= sys.version_info
  29. # TODO: Remove deprecated variables in a future release.
  30. __deprecated__ = {
  31. 'etree': ('xml.etree.ElementTree', xml.etree.ElementTree),
  32. 'string_type': ('str', str),
  33. 'text_type': ('str', str),
  34. 'int2str': ('chr', chr),
  35. 'iterrange': ('range', range)
  36. }
  37. """
  38. Constants you might want to modify
  39. -----------------------------------------------------------------------------
  40. """
  41. BLOCK_LEVEL_ELEMENTS = [
  42. # Elements which are invalid to wrap in a `<p>` tag.
  43. # See https://w3c.github.io/html/grouping-content.html#the-p-element
  44. 'address', 'article', 'aside', 'blockquote', 'details', 'div', 'dl',
  45. 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3',
  46. 'h4', 'h5', 'h6', 'header', 'hr', 'main', 'menu', 'nav', 'ol', 'p', 'pre',
  47. 'section', 'table', 'ul',
  48. # Other elements which Markdown should not be mucking up the contents of.
  49. 'canvas', 'dd', 'dt', 'group', 'iframe', 'li', 'math', 'noscript', 'output',
  50. 'progress', 'script', 'style', 'tbody', 'td', 'th', 'thead', 'tr', 'video'
  51. ]
  52. # Placeholders
  53. STX = '\u0002' # Use STX ("Start of text") for start-of-placeholder
  54. ETX = '\u0003' # Use ETX ("End of text") for end-of-placeholder
  55. INLINE_PLACEHOLDER_PREFIX = STX+"klzzwxh:"
  56. INLINE_PLACEHOLDER = INLINE_PLACEHOLDER_PREFIX + "%s" + ETX
  57. INLINE_PLACEHOLDER_RE = re.compile(INLINE_PLACEHOLDER % r'([0-9]+)')
  58. AMP_SUBSTITUTE = STX+"amp"+ETX
  59. HTML_PLACEHOLDER = STX + "wzxhzdk:%s" + ETX
  60. HTML_PLACEHOLDER_RE = re.compile(HTML_PLACEHOLDER % r'([0-9]+)')
  61. TAG_PLACEHOLDER = STX + "hzzhzkh:%s" + ETX
  62. """
  63. Constants you probably do not need to change
  64. -----------------------------------------------------------------------------
  65. """
  66. # Only load extension entry_points once.
  67. INSTALLED_EXTENSIONS = metadata.entry_points().get('markdown.extensions', ())
  68. RTL_BIDI_RANGES = (
  69. ('\u0590', '\u07FF'),
  70. # Hebrew (0590-05FF), Arabic (0600-06FF),
  71. # Syriac (0700-074F), Arabic supplement (0750-077F),
  72. # Thaana (0780-07BF), Nko (07C0-07FF).
  73. ('\u2D30', '\u2D7F') # Tifinagh
  74. )
  75. """
  76. AUXILIARY GLOBAL FUNCTIONS
  77. =============================================================================
  78. """
  79. def deprecated(message, stacklevel=2):
  80. """
  81. Raise a DeprecationWarning when wrapped function/method is called.
  82. Borrowed from https://stackoverflow.com/a/48632082/866026
  83. """
  84. def deprecated_decorator(func):
  85. @wraps(func)
  86. def deprecated_func(*args, **kwargs):
  87. warnings.warn(
  88. "'{}' is deprecated. {}".format(func.__name__, message),
  89. category=DeprecationWarning,
  90. stacklevel=stacklevel
  91. )
  92. return func(*args, **kwargs)
  93. return deprecated_func
  94. return deprecated_decorator
  95. @deprecated("Use 'Markdown.is_block_level' instead.")
  96. def isBlockLevel(tag):
  97. """Check if the tag is a block level HTML tag."""
  98. if isinstance(tag, str):
  99. return tag.lower().rstrip('/') in BLOCK_LEVEL_ELEMENTS
  100. # Some ElementTree tags are not strings, so return False.
  101. return False
  102. def parseBoolValue(value, fail_on_errors=True, preserve_none=False):
  103. """Parses a string representing bool value. If parsing was successful,
  104. returns True or False. If preserve_none=True, returns True, False,
  105. or None. If parsing was not successful, raises ValueError, or, if
  106. fail_on_errors=False, returns None."""
  107. if not isinstance(value, str):
  108. if preserve_none and value is None:
  109. return value
  110. return bool(value)
  111. elif preserve_none and value.lower() == 'none':
  112. return None
  113. elif value.lower() in ('true', 'yes', 'y', 'on', '1'):
  114. return True
  115. elif value.lower() in ('false', 'no', 'n', 'off', '0', 'none'):
  116. return False
  117. elif fail_on_errors:
  118. raise ValueError('Cannot parse bool value: %r' % value)
  119. def code_escape(text):
  120. """Escape code."""
  121. if "&" in text:
  122. text = text.replace("&", "&amp;")
  123. if "<" in text:
  124. text = text.replace("<", "&lt;")
  125. if ">" in text:
  126. text = text.replace(">", "&gt;")
  127. return text
  128. """
  129. MISC AUXILIARY CLASSES
  130. =============================================================================
  131. """
  132. class AtomicString(str):
  133. """A string which should not be further processed."""
  134. pass
  135. class Processor:
  136. def __init__(self, md=None):
  137. self.md = md
  138. @property
  139. @deprecated("Use 'md' instead.")
  140. def markdown(self):
  141. # TODO: remove this later
  142. return self.md
  143. class HtmlStash:
  144. """
  145. This class is used for stashing HTML objects that we extract
  146. in the beginning and replace with place-holders.
  147. """
  148. def __init__(self):
  149. """ Create a HtmlStash. """
  150. self.html_counter = 0 # for counting inline html segments
  151. self.rawHtmlBlocks = []
  152. self.tag_counter = 0
  153. self.tag_data = [] # list of dictionaries in the order tags appear
  154. def store(self, html):
  155. """
  156. Saves an HTML segment for later reinsertion. Returns a
  157. placeholder string that needs to be inserted into the
  158. document.
  159. Keyword arguments:
  160. * html: an html segment
  161. Returns : a placeholder string
  162. """
  163. self.rawHtmlBlocks.append(html)
  164. placeholder = self.get_placeholder(self.html_counter)
  165. self.html_counter += 1
  166. return placeholder
  167. def reset(self):
  168. self.html_counter = 0
  169. self.rawHtmlBlocks = []
  170. def get_placeholder(self, key):
  171. return HTML_PLACEHOLDER % key
  172. def store_tag(self, tag, attrs, left_index, right_index):
  173. """Store tag data and return a placeholder."""
  174. self.tag_data.append({'tag': tag, 'attrs': attrs,
  175. 'left_index': left_index,
  176. 'right_index': right_index})
  177. placeholder = TAG_PLACEHOLDER % str(self.tag_counter)
  178. self.tag_counter += 1 # equal to the tag's index in self.tag_data
  179. return placeholder
  180. # Used internally by `Registry` for each item in its sorted list.
  181. # Provides an easier to read API when editing the code later.
  182. # For example, `item.name` is more clear than `item[0]`.
  183. _PriorityItem = namedtuple('PriorityItem', ['name', 'priority'])
  184. class Registry:
  185. """
  186. A priority sorted registry.
  187. A `Registry` instance provides two public methods to alter the data of the
  188. registry: `register` and `deregister`. Use `register` to add items and
  189. `deregister` to remove items. See each method for specifics.
  190. When registering an item, a "name" and a "priority" must be provided. All
  191. items are automatically sorted by "priority" from highest to lowest. The
  192. "name" is used to remove ("deregister") and get items.
  193. A `Registry` instance it like a list (which maintains order) when reading
  194. data. You may iterate over the items, get an item and get a count (length)
  195. of all items. You may also check that the registry contains an item.
  196. When getting an item you may use either the index of the item or the
  197. string-based "name". For example:
  198. registry = Registry()
  199. registry.register(SomeItem(), 'itemname', 20)
  200. # Get the item by index
  201. item = registry[0]
  202. # Get the item by name
  203. item = registry['itemname']
  204. When checking that the registry contains an item, you may use either the
  205. string-based "name", or a reference to the actual item. For example:
  206. someitem = SomeItem()
  207. registry.register(someitem, 'itemname', 20)
  208. # Contains the name
  209. assert 'itemname' in registry
  210. # Contains the item instance
  211. assert someitem in registry
  212. The method `get_index_for_name` is also available to obtain the index of
  213. an item using that item's assigned "name".
  214. """
  215. def __init__(self):
  216. self._data = {}
  217. self._priority = []
  218. self._is_sorted = False
  219. def __contains__(self, item):
  220. if isinstance(item, str):
  221. # Check if an item exists by this name.
  222. return item in self._data.keys()
  223. # Check if this instance exists.
  224. return item in self._data.values()
  225. def __iter__(self):
  226. self._sort()
  227. return iter([self._data[k] for k, p in self._priority])
  228. def __getitem__(self, key):
  229. self._sort()
  230. if isinstance(key, slice):
  231. data = Registry()
  232. for k, p in self._priority[key]:
  233. data.register(self._data[k], k, p)
  234. return data
  235. if isinstance(key, int):
  236. return self._data[self._priority[key].name]
  237. return self._data[key]
  238. def __len__(self):
  239. return len(self._priority)
  240. def __repr__(self):
  241. return '<{}({})>'.format(self.__class__.__name__, list(self))
  242. def get_index_for_name(self, name):
  243. """
  244. Return the index of the given name.
  245. """
  246. if name in self:
  247. self._sort()
  248. return self._priority.index(
  249. [x for x in self._priority if x.name == name][0]
  250. )
  251. raise ValueError('No item named "{}" exists.'.format(name))
  252. def register(self, item, name, priority):
  253. """
  254. Add an item to the registry with the given name and priority.
  255. Parameters:
  256. * `item`: The item being registered.
  257. * `name`: A string used to reference the item.
  258. * `priority`: An integer or float used to sort against all items.
  259. If an item is registered with a "name" which already exists, the
  260. existing item is replaced with the new item. Tread carefully as the
  261. old item is lost with no way to recover it. The new item will be
  262. sorted according to its priority and will **not** retain the position
  263. of the old item.
  264. """
  265. if name in self:
  266. # Remove existing item of same name first
  267. self.deregister(name)
  268. self._is_sorted = False
  269. self._data[name] = item
  270. self._priority.append(_PriorityItem(name, priority))
  271. def deregister(self, name, strict=True):
  272. """
  273. Remove an item from the registry.
  274. Set `strict=False` to fail silently.
  275. """
  276. try:
  277. index = self.get_index_for_name(name)
  278. del self._priority[index]
  279. del self._data[name]
  280. except ValueError:
  281. if strict:
  282. raise
  283. def _sort(self):
  284. """
  285. Sort the registry by priority from highest to lowest.
  286. This method is called internally and should never be explicitly called.
  287. """
  288. if not self._is_sorted:
  289. self._priority.sort(key=lambda item: item.priority, reverse=True)
  290. self._is_sorted = True
  291. # Deprecated Methods which provide a smooth transition from OrderedDict
  292. def __setitem__(self, key, value):
  293. """ Register item with priorty 5 less than lowest existing priority. """
  294. if isinstance(key, str):
  295. warnings.warn(
  296. 'Using setitem to register a processor or pattern is deprecated. '
  297. 'Use the `register` method instead.',
  298. DeprecationWarning,
  299. stacklevel=2,
  300. )
  301. if key in self:
  302. # Key already exists, replace without altering priority
  303. self._data[key] = value
  304. return
  305. if len(self) == 0:
  306. # This is the first item. Set priority to 50.
  307. priority = 50
  308. else:
  309. self._sort()
  310. priority = self._priority[-1].priority - 5
  311. self.register(value, key, priority)
  312. else:
  313. raise TypeError
  314. def __delitem__(self, key):
  315. """ Deregister an item by name. """
  316. if key in self:
  317. self.deregister(key)
  318. warnings.warn(
  319. 'Using del to remove a processor or pattern is deprecated. '
  320. 'Use the `deregister` method instead.',
  321. DeprecationWarning,
  322. stacklevel=2,
  323. )
  324. else:
  325. raise KeyError('Cannot delete key {}, not registered.'.format(key))
  326. def add(self, key, value, location):
  327. """ Register a key by location. """
  328. if len(self) == 0:
  329. # This is the first item. Set priority to 50.
  330. priority = 50
  331. elif location == '_begin':
  332. self._sort()
  333. # Set priority 5 greater than highest existing priority
  334. priority = self._priority[0].priority + 5
  335. elif location == '_end':
  336. self._sort()
  337. # Set priority 5 less than lowest existing priority
  338. priority = self._priority[-1].priority - 5
  339. elif location.startswith('<') or location.startswith('>'):
  340. # Set priority halfway between existing priorities.
  341. i = self.get_index_for_name(location[1:])
  342. if location.startswith('<'):
  343. after = self._priority[i].priority
  344. if i > 0:
  345. before = self._priority[i-1].priority
  346. else:
  347. # Location is first item`
  348. before = after + 10
  349. else:
  350. # location.startswith('>')
  351. before = self._priority[i].priority
  352. if i < len(self) - 1:
  353. after = self._priority[i+1].priority
  354. else:
  355. # location is last item
  356. after = before - 10
  357. priority = before - ((before - after) / 2)
  358. else:
  359. raise ValueError('Not a valid location: "%s". Location key '
  360. 'must start with a ">" or "<".' % location)
  361. self.register(value, key, priority)
  362. warnings.warn(
  363. 'Using the add method to register a processor or pattern is deprecated. '
  364. 'Use the `register` method instead.',
  365. DeprecationWarning,
  366. stacklevel=2,
  367. )
  368. def __getattr__(name):
  369. """Get attribute."""
  370. deprecated = __deprecated__.get(name)
  371. if deprecated:
  372. warnings.warn(
  373. "'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
  374. category=DeprecationWarning,
  375. stacklevel=(3 if PY37 else 4)
  376. )
  377. return deprecated[1]
  378. raise AttributeError("module '{}' has no attribute '{}'".format(__name__, name))
  379. if not PY37:
  380. Pep562(__name__)