highlight.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. """
  2. Highlight.
  3. A library for managing code highlighting.
  4. All Changes Copyright 2014-2017 Isaac Muse.
  5. ---
  6. CodeHilite Extension for Python-Markdown
  7. ========================================
  8. Adds code/syntax highlighting to standard Python-Markdown code blocks.
  9. See <https://pythonhosted.org/Markdown/extensions/code_hilite.html>
  10. for documentation.
  11. Original code Copyright 2006-2008 [Waylan Limberg](http://achinghead.com/).
  12. All changes Copyright 2008-2014 The Python Markdown Project
  13. License: [BSD](http://www.opensource.org/licenses/bsd-license.php)
  14. """
  15. import re
  16. from markdown import Extension
  17. from markdown.treeprocessors import Treeprocessor
  18. import xml.etree.ElementTree as etree
  19. import copy
  20. from collections import OrderedDict
  21. try:
  22. from pygments import highlight
  23. from pygments.lexers import get_lexer_by_name, guess_lexer
  24. from pygments.formatters import find_formatter_class
  25. HtmlFormatter = find_formatter_class('html')
  26. pygments = True
  27. except ImportError: # pragma: no cover
  28. pygments = False
  29. CODE_WRAP = '<pre%s%s><code%s>%s</code></pre>'
  30. CLASS_ATTR = ' class="%s"'
  31. ID_ATTR = ' id="%s"'
  32. DEFAULT_CONFIG = {
  33. 'use_pygments': [
  34. True,
  35. 'Use Pygments to highlight code blocks. '
  36. 'Disable if using a JavaScript library. '
  37. 'Default: True'
  38. ],
  39. 'guess_lang': [
  40. False,
  41. "Automatic language detection - Default: True"
  42. ],
  43. 'css_class': [
  44. 'highlight',
  45. "CSS class to apply to wrapper element."
  46. ],
  47. 'pygments_style': [
  48. 'default',
  49. 'Pygments HTML Formatter Style '
  50. '(color scheme) - Default: default'
  51. ],
  52. 'noclasses': [
  53. False,
  54. 'Use inline styles instead of CSS classes - '
  55. 'Default false'
  56. ],
  57. 'linenums': [
  58. False,
  59. 'Display line numbers in block code output (not inline) - Default: False'
  60. ],
  61. 'linenums_style': [
  62. 'table',
  63. 'Line number style -Default: "table"'
  64. ],
  65. 'linenums_special': [
  66. -1,
  67. 'Globally make nth line special - Default: -1'
  68. ],
  69. 'linenums_class': [
  70. "linenums",
  71. "Control the linenums class name when not using Pygments - Default: 'linenums'"
  72. ],
  73. 'extend_pygments_lang': [
  74. [],
  75. 'Extend pygments language with special language entry - Default: {}'
  76. ],
  77. 'legacy_no_wrap_code': [
  78. False,
  79. 'Do not wrap block code under pre elements with code elements - Default: False'
  80. ],
  81. '_enabled': [
  82. True,
  83. 'Used internally to communicate if extension has been explicitly enabled - Default: False'
  84. ]
  85. }
  86. if pygments:
  87. class InlineHtmlFormatter(HtmlFormatter):
  88. """Format the code blocks."""
  89. def wrap(self, source, outfile):
  90. """Overload wrap."""
  91. return self._wrap_code(source)
  92. def _wrap_code(self, source):
  93. """Return source, but do not wrap in inline <code> block."""
  94. yield 0, ''
  95. for i, t in source:
  96. yield i, t.strip()
  97. yield 0, ''
  98. class BlockHtmlFormatter(HtmlFormatter):
  99. """Adds ability to output line numbers in a new way."""
  100. # Capture `<span class="lineno"> 1 </span>`
  101. RE_SPAN_NUMS = re.compile(r'(<span[^>]*?)(class="[^"]*\blineno\b[^"]*)"([^>]*)>([^<]+)(</span>)')
  102. # Capture `<pre>` that is not followed by `<span></span>`
  103. RE_TABLE_NUMS = re.compile(r'(<pre[^>]*>)(?!<span></span>)')
  104. def __init__(self, **options):
  105. """Initialize."""
  106. self.pymdownx_inline = options.get('linenos', False) == 'pymdownx-inline'
  107. if self.pymdownx_inline:
  108. options['linenos'] = 'inline'
  109. HtmlFormatter.__init__(self, **options)
  110. def _format_custom_line(self, m):
  111. """Format the custom line number."""
  112. # We've broken up the match in such a way that we not only
  113. # move the line number value to `data-linenos`, but we could
  114. # wrap the gutter number in the future with a highlight class.
  115. # The decision to do this has still not be made.
  116. return (
  117. m.group(1) +
  118. m.group(2) +
  119. '"' +
  120. m.group(3) +
  121. ' data-linenos="' + m.group(4) + '">' +
  122. m.group(5)
  123. )
  124. def _wrap_customlinenums(self, inner):
  125. """
  126. Wrapper to handle block inline line numbers.
  127. For our special inline version, don't display line numbers via `<span> 1</span>`,
  128. but include as `<span data-linenos=" 1"></span>` and use CSS to display them:
  129. `[data-linenos]:before {content: attr(data-linenos);}`. This allows us to use
  130. inline and copy and paste without issue.
  131. """
  132. for t, line in inner:
  133. if t:
  134. line = self.RE_SPAN_NUMS.sub(self._format_custom_line, line)
  135. yield t, line
  136. def wrap(self, source, outfile):
  137. """Wrap the source code."""
  138. if self.linenos == 2 and self.pymdownx_inline:
  139. source = self._wrap_customlinenums(source)
  140. return HtmlFormatter.wrap(self, source, outfile)
  141. def _wrap_tablelinenos(self, inner):
  142. """
  143. Wrapper to handle line numbers better in table.
  144. Pygments currently has a bug with line step where leading blank lines collapse.
  145. Use the same fix Pygments uses for code content for code line numbers.
  146. This fix should be pull requested on the Pygments repository.
  147. """
  148. for t, line in HtmlFormatter._wrap_tablelinenos(self, inner):
  149. yield t, self.RE_TABLE_NUMS.sub(r'\1<span></span>', line)
  150. class Highlight(object):
  151. """Highlight class."""
  152. def __init__(
  153. self, guess_lang=True, pygments_style='default', use_pygments=True,
  154. noclasses=False, extend_pygments_lang=None, linenums=False, linenums_special=-1,
  155. linenums_style='table', linenums_class='linenums', wrapcode=True
  156. ):
  157. """Initialize."""
  158. self.guess_lang = guess_lang
  159. self.pygments_style = pygments_style
  160. self.use_pygments = use_pygments
  161. self.noclasses = noclasses
  162. self.linenums = linenums
  163. self.linenums_style = linenums_style
  164. self.linenums_special = linenums_special
  165. self.linenums_class = linenums_class
  166. self.wrapcode = wrapcode
  167. if extend_pygments_lang is None: # pragma: no cover
  168. extend_pygments_lang = []
  169. self.extend_pygments_lang = {}
  170. for language in extend_pygments_lang:
  171. if isinstance(language, (dict, OrderedDict)):
  172. name = language.get('name')
  173. if name is not None and name not in self.extend_pygments_lang:
  174. self.extend_pygments_lang[name] = [
  175. language.get('lang'),
  176. language.get('options', {})
  177. ]
  178. def get_extended_language(self, language):
  179. """Get extended language."""
  180. return self.extend_pygments_lang.get(language, (language, {}))
  181. def get_lexer(self, src, language):
  182. """Get the Pygments lexer."""
  183. if language:
  184. language, lexer_options = self.get_extended_language(language)
  185. else:
  186. lexer_options = {}
  187. # Try and get lexer by the name given.
  188. try:
  189. lexer = get_lexer_by_name(language, **lexer_options)
  190. except Exception:
  191. lexer = None
  192. if lexer is None:
  193. if self.guess_lang:
  194. try:
  195. lexer = guess_lexer(src)
  196. except Exception: # pragma: no cover
  197. pass
  198. if lexer is None:
  199. lexer = get_lexer_by_name('text')
  200. return lexer
  201. def escape(self, txt):
  202. """Basic HTML escaping."""
  203. txt = txt.replace('&', '&amp;')
  204. txt = txt.replace('<', '&lt;')
  205. txt = txt.replace('>', '&gt;')
  206. return txt
  207. def highlight(
  208. self, src, language, css_class='highlight', hl_lines=None,
  209. linestart=-1, linestep=-1, linespecial=-1, inline=False, classes=None, id_value=''
  210. ):
  211. """Highlight code."""
  212. class_names = classes[:] if classes else []
  213. # Convert with Pygments.
  214. if pygments and self.use_pygments:
  215. # Setup language lexer.
  216. lexer = self.get_lexer(src, language)
  217. linenums = self.linenums_style if (self.linenums or linestart >= 0) and not inline > 0 else False
  218. if class_names:
  219. css_class = ' {}'.format('' if not css_class else css_class)
  220. css_class = ' '.join(class_names) + css_class
  221. stripped = css_class.strip()
  222. if not isinstance(linenums, str) or linenums != 'table':
  223. css_class = stripped
  224. # Setup line specific settings.
  225. if not linenums or linestep < 1:
  226. linestep = 1
  227. if not linenums or linestart < 1:
  228. linestart = 1
  229. if self.linenums_special >= 0 and linespecial < 0:
  230. linespecial = self.linenums_special
  231. if not linenums or linespecial < 0:
  232. linespecial = 0
  233. if hl_lines is None or inline:
  234. hl_lines = []
  235. # Setup formatter
  236. html_formatter = InlineHtmlFormatter if inline else BlockHtmlFormatter
  237. formatter = html_formatter(
  238. cssclass=css_class,
  239. linenos=linenums,
  240. linenostart=linestart,
  241. linenostep=linestep,
  242. linenospecial=linespecial,
  243. style=self.pygments_style,
  244. noclasses=self.noclasses,
  245. hl_lines=hl_lines,
  246. wrapcode=self.wrapcode
  247. )
  248. # Convert
  249. code = highlight(src, lexer, formatter)
  250. if inline:
  251. class_str = css_class
  252. elif inline:
  253. # Format inline code for a JavaScript Syntax Highlighter by specifying language.
  254. code = self.escape(src)
  255. classes = class_names + ([css_class] if css_class else [])
  256. if language:
  257. classes.append('language-%s' % language)
  258. class_str = ''
  259. if len(classes):
  260. class_str = ' '.join(classes)
  261. else:
  262. # Format block code for a JavaScript Syntax Highlighter by specifying language.
  263. classes = class_names
  264. linenums = self.linenums_style if (self.linenums or linestart >= 0) and not inline > 0 else False
  265. if language:
  266. classes.append('language-%s' % language)
  267. class_str = ''
  268. if linenums:
  269. classes.append(self.linenums_class)
  270. if classes:
  271. class_str = CLASS_ATTR % ' '.join(classes)
  272. if id_value:
  273. id_value = ID_ATTR % id_value
  274. highlight_class = (CLASS_ATTR % css_class) if css_class else ''
  275. code = CODE_WRAP % (id_value, highlight_class, class_str, self.escape(src))
  276. if inline:
  277. el = etree.Element('code', {'class': class_str} if class_str else {})
  278. el.text = code
  279. return el
  280. else:
  281. return code.strip()
  282. class HighlightTreeprocessor(Treeprocessor):
  283. """Highlight source code in code blocks."""
  284. def __init__(self, md):
  285. """Initialize."""
  286. super(HighlightTreeprocessor, self).__init__(md)
  287. def code_unescape(self, text):
  288. """Unescape code."""
  289. text = text.replace("&amp;", "&")
  290. text = text.replace("&lt;", "<")
  291. text = text.replace("&gt;", ">")
  292. return text
  293. def run(self, root):
  294. """Find code blocks and store in `htmlStash`."""
  295. blocks = root.iter('pre')
  296. for block in blocks:
  297. if len(block) == 1 and block[0].tag == 'code':
  298. code = Highlight(
  299. guess_lang=self.config['guess_lang'],
  300. pygments_style=self.config['pygments_style'],
  301. use_pygments=self.config['use_pygments'],
  302. noclasses=self.config['noclasses'],
  303. linenums=self.config['linenums'],
  304. linenums_style=self.config['linenums_style'],
  305. linenums_special=self.config['linenums_special'],
  306. linenums_class=self.config['linenums_class'],
  307. extend_pygments_lang=self.config['extend_pygments_lang'],
  308. wrapcode=not self.config['legacy_no_wrap_code']
  309. )
  310. placeholder = self.md.htmlStash.store(
  311. code.highlight(
  312. self.code_unescape(block[0].text),
  313. '',
  314. self.config['css_class']
  315. )
  316. )
  317. # Clear code block in `etree` instance
  318. block.clear()
  319. # Change to `p` element which will later
  320. # be removed when inserting raw HTML
  321. block.tag = 'p'
  322. block.text = placeholder
  323. class HighlightExtension(Extension):
  324. """Configure highlight settings globally."""
  325. def __init__(self, *args, **kwargs):
  326. """Initialize."""
  327. self.config = copy.deepcopy(DEFAULT_CONFIG)
  328. super(HighlightExtension, self).__init__(*args, **kwargs)
  329. def get_pymdownx_highlight_settings(self):
  330. """Get the specified extension."""
  331. target = None
  332. if self.enabled:
  333. target = self.getConfigs()
  334. if target is None:
  335. target = {}
  336. config_clone = copy.deepcopy(DEFAULT_CONFIG)
  337. for k, v in config_clone.items():
  338. target[k] = config_clone[k][0]
  339. return target
  340. def get_pymdownx_highlighter(self):
  341. """Get the highlighter."""
  342. return Highlight
  343. def extendMarkdown(self, md):
  344. """Add support for code highlighting."""
  345. config = self.getConfigs()
  346. self.md = md
  347. self.enabled = config.get("_enabled", False)
  348. if self.enabled:
  349. ht = HighlightTreeprocessor(self.md)
  350. ht.config = self.getConfigs()
  351. self.md.treeprocessors.register(ht, "indent-highlight", 30)
  352. index = 0
  353. register = None
  354. for ext in self.md.registeredExtensions:
  355. if isinstance(ext, HighlightExtension):
  356. register = not ext.enabled and self.enabled
  357. break
  358. if register is None:
  359. register = True
  360. index = -1
  361. if register:
  362. if index == -1:
  363. self.md.registerExtension(self)
  364. else:
  365. self.md.registeredExtensions[index] = self
  366. def makeExtension(*args, **kwargs):
  367. """Return extension."""
  368. return HighlightExtension(*args, **kwargs)