html.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. """
  2. pygments.formatters.html
  3. ~~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for HTML output.
  5. :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import functools
  9. import os
  10. import sys
  11. import os.path
  12. from io import StringIO
  13. from html import escape as _escape
  14. from pygments.formatter import Formatter
  15. from pygments.token import Token, Text, STANDARD_TYPES
  16. from pygments.util import get_bool_opt, get_int_opt, get_list_opt, html_escape
  17. try:
  18. import ctags
  19. except ImportError:
  20. ctags = None
  21. __all__ = ['HtmlFormatter']
  22. def webify(color):
  23. if color == 'transparent' or color.startswith('calc') or color.startswith('var'):
  24. return color
  25. else:
  26. # Check if the color can be shortened from 6 to 3 characters
  27. color = color.upper()
  28. if (len(color) == 6 and
  29. ( color[0] == color[1]
  30. and color[2] == color[3]
  31. and color[4] == color[5])):
  32. return f'#{color[0]}{color[2]}{color[4]}'
  33. else:
  34. return f'#{color}'
  35. def _get_ttype_class(ttype):
  36. fname = STANDARD_TYPES.get(ttype)
  37. if fname:
  38. return fname
  39. aname = ''
  40. while fname is None:
  41. aname = '-' + ttype[-1] + aname
  42. ttype = ttype.parent
  43. fname = STANDARD_TYPES.get(ttype)
  44. return fname + aname
  45. CSSFILE_TEMPLATE = '''\
  46. /*
  47. generated by Pygments <https://pygments.org/>
  48. Copyright 2006-present by the Pygments team.
  49. Licensed under the BSD license, see LICENSE for details.
  50. */
  51. %(styledefs)s
  52. '''
  53. DOC_HEADER = '''\
  54. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
  55. "http://www.w3.org/TR/html4/strict.dtd">
  56. <!--
  57. generated by Pygments <https://pygments.org/>
  58. Copyright 2006-present by the Pygments team.
  59. Licensed under the BSD license, see LICENSE for details.
  60. -->
  61. <html>
  62. <head>
  63. <title>%(title)s</title>
  64. <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
  65. <style type="text/css">
  66. ''' + CSSFILE_TEMPLATE + '''
  67. </style>
  68. </head>
  69. <body>
  70. <h2>%(title)s</h2>
  71. '''
  72. DOC_HEADER_EXTERNALCSS = '''\
  73. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
  74. "http://www.w3.org/TR/html4/strict.dtd">
  75. <html>
  76. <head>
  77. <title>%(title)s</title>
  78. <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
  79. <link rel="stylesheet" href="%(cssfile)s" type="text/css">
  80. </head>
  81. <body>
  82. <h2>%(title)s</h2>
  83. '''
  84. DOC_FOOTER = '''\
  85. </body>
  86. </html>
  87. '''
  88. class HtmlFormatter(Formatter):
  89. r"""
  90. Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed
  91. in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option).
  92. The ``<div>``'s CSS class can be set by the `cssclass` option.
  93. If the `linenos` option is set to ``"table"``, the ``<pre>`` is
  94. additionally wrapped inside a ``<table>`` which has one row and two
  95. cells: one containing the line numbers and one containing the code.
  96. Example:
  97. .. sourcecode:: html
  98. <div class="highlight" >
  99. <table><tr>
  100. <td class="linenos" title="click to toggle"
  101. onclick="with (this.firstChild.style)
  102. { display = (display == '') ? 'none' : '' }">
  103. <pre>1
  104. 2</pre>
  105. </td>
  106. <td class="code">
  107. <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar):
  108. <span class="Ke">pass</span>
  109. </pre>
  110. </td>
  111. </tr></table></div>
  112. (whitespace added to improve clarity).
  113. A list of lines can be specified using the `hl_lines` option to make these
  114. lines highlighted (as of Pygments 0.11).
  115. With the `full` option, a complete HTML 4 document is output, including
  116. the style definitions inside a ``<style>`` tag, or in a separate file if
  117. the `cssfile` option is given.
  118. When `tagsfile` is set to the path of a ctags index file, it is used to
  119. generate hyperlinks from names to their definition. You must enable
  120. `lineanchors` and run ctags with the `-n` option for this to work. The
  121. `python-ctags` module from PyPI must be installed to use this feature;
  122. otherwise a `RuntimeError` will be raised.
  123. The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string
  124. containing CSS rules for the CSS classes used by the formatter. The
  125. argument `arg` can be used to specify additional CSS selectors that
  126. are prepended to the classes. A call `fmter.get_style_defs('td .code')`
  127. would result in the following CSS classes:
  128. .. sourcecode:: css
  129. td .code .kw { font-weight: bold; color: #00FF00 }
  130. td .code .cm { color: #999999 }
  131. ...
  132. If you have Pygments 0.6 or higher, you can also pass a list or tuple to the
  133. `get_style_defs()` method to request multiple prefixes for the tokens:
  134. .. sourcecode:: python
  135. formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])
  136. The output would then look like this:
  137. .. sourcecode:: css
  138. div.syntax pre .kw,
  139. pre.syntax .kw { font-weight: bold; color: #00FF00 }
  140. div.syntax pre .cm,
  141. pre.syntax .cm { color: #999999 }
  142. ...
  143. Additional options accepted:
  144. `nowrap`
  145. If set to ``True``, don't add a ``<pre>`` and a ``<div>`` tag
  146. around the tokens. This disables most other options (default: ``False``).
  147. `full`
  148. Tells the formatter to output a "full" document, i.e. a complete
  149. self-contained document (default: ``False``).
  150. `title`
  151. If `full` is true, the title that should be used to caption the
  152. document (default: ``''``).
  153. `style`
  154. The style to use, can be a string or a Style subclass (default:
  155. ``'default'``). This option has no effect if the `cssfile`
  156. and `noclobber_cssfile` option are given and the file specified in
  157. `cssfile` exists.
  158. `noclasses`
  159. If set to true, token ``<span>`` tags (as well as line number elements)
  160. will not use CSS classes, but inline styles. This is not recommended
  161. for larger pieces of code since it increases output size by quite a bit
  162. (default: ``False``).
  163. `classprefix`
  164. Since the token types use relatively short class names, they may clash
  165. with some of your own class names. In this case you can use the
  166. `classprefix` option to give a string to prepend to all Pygments-generated
  167. CSS class names for token types.
  168. Note that this option also affects the output of `get_style_defs()`.
  169. `cssclass`
  170. CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``).
  171. If you set this option, the default selector for `get_style_defs()`
  172. will be this class.
  173. .. versionadded:: 0.9
  174. If you select the ``'table'`` line numbers, the wrapping table will
  175. have a CSS class of this string plus ``'table'``, the default is
  176. accordingly ``'highlighttable'``.
  177. `cssstyles`
  178. Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``).
  179. `prestyles`
  180. Inline CSS styles for the ``<pre>`` tag (default: ``''``).
  181. .. versionadded:: 0.11
  182. `cssfile`
  183. If the `full` option is true and this option is given, it must be the
  184. name of an external file. If the filename does not include an absolute
  185. path, the file's path will be assumed to be relative to the main output
  186. file's path, if the latter can be found. The stylesheet is then written
  187. to this file instead of the HTML file.
  188. .. versionadded:: 0.6
  189. `noclobber_cssfile`
  190. If `cssfile` is given and the specified file exists, the css file will
  191. not be overwritten. This allows the use of the `full` option in
  192. combination with a user specified css file. Default is ``False``.
  193. .. versionadded:: 1.1
  194. `linenos`
  195. If set to ``'table'``, output line numbers as a table with two cells,
  196. one containing the line numbers, the other the whole code. This is
  197. copy-and-paste-friendly, but may cause alignment problems with some
  198. browsers or fonts. If set to ``'inline'``, the line numbers will be
  199. integrated in the ``<pre>`` tag that contains the code (that setting
  200. is *new in Pygments 0.8*).
  201. For compatibility with Pygments 0.7 and earlier, every true value
  202. except ``'inline'`` means the same as ``'table'`` (in particular, that
  203. means also ``True``).
  204. The default value is ``False``, which means no line numbers at all.
  205. **Note:** with the default ("table") line number mechanism, the line
  206. numbers and code can have different line heights in Internet Explorer
  207. unless you give the enclosing ``<pre>`` tags an explicit ``line-height``
  208. CSS property (you get the default line spacing with ``line-height:
  209. 125%``).
  210. `hl_lines`
  211. Specify a list of lines to be highlighted. The line numbers are always
  212. relative to the input (i.e. the first line is line 1) and are
  213. independent of `linenostart`.
  214. .. versionadded:: 0.11
  215. `linenostart`
  216. The line number for the first line (default: ``1``).
  217. `linenostep`
  218. If set to a number n > 1, only every nth line number is printed.
  219. `linenospecial`
  220. If set to a number n > 0, every nth line number is given the CSS
  221. class ``"special"`` (default: ``0``).
  222. `nobackground`
  223. If set to ``True``, the formatter won't output the background color
  224. for the wrapping element (this automatically defaults to ``False``
  225. when there is no wrapping element [eg: no argument for the
  226. `get_syntax_defs` method given]) (default: ``False``).
  227. .. versionadded:: 0.6
  228. `lineseparator`
  229. This string is output between lines of code. It defaults to ``"\n"``,
  230. which is enough to break a line inside ``<pre>`` tags, but you can
  231. e.g. set it to ``"<br>"`` to get HTML line breaks.
  232. .. versionadded:: 0.7
  233. `lineanchors`
  234. If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
  235. output line in an anchor tag with an ``id`` (and `name`) of ``foo-linenumber``.
  236. This allows easy linking to certain lines.
  237. .. versionadded:: 0.9
  238. `linespans`
  239. If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
  240. output line in a span tag with an ``id`` of ``foo-linenumber``.
  241. This allows easy access to lines via javascript.
  242. .. versionadded:: 1.6
  243. `anchorlinenos`
  244. If set to `True`, will wrap line numbers in <a> tags. Used in
  245. combination with `linenos` and `lineanchors`.
  246. `tagsfile`
  247. If set to the path of a ctags file, wrap names in anchor tags that
  248. link to their definitions. `lineanchors` should be used, and the
  249. tags file should specify line numbers (see the `-n` option to ctags).
  250. The tags file is assumed to be encoded in UTF-8.
  251. .. versionadded:: 1.6
  252. `tagurlformat`
  253. A string formatting pattern used to generate links to ctags definitions.
  254. Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`.
  255. Defaults to an empty string, resulting in just `#prefix-number` links.
  256. .. versionadded:: 1.6
  257. `filename`
  258. A string used to generate a filename when rendering ``<pre>`` blocks,
  259. for example if displaying source code. If `linenos` is set to
  260. ``'table'`` then the filename will be rendered in an initial row
  261. containing a single `<th>` which spans both columns.
  262. .. versionadded:: 2.1
  263. `wrapcode`
  264. Wrap the code inside ``<pre>`` blocks using ``<code>``, as recommended
  265. by the HTML5 specification.
  266. .. versionadded:: 2.4
  267. `debug_token_types`
  268. Add ``title`` attributes to all token ``<span>`` tags that show the
  269. name of the token.
  270. .. versionadded:: 2.10
  271. **Subclassing the HTML formatter**
  272. .. versionadded:: 0.7
  273. The HTML formatter is now built in a way that allows easy subclassing, thus
  274. customizing the output HTML code. The `format()` method calls
  275. `self._format_lines()` which returns a generator that yields tuples of ``(1,
  276. line)``, where the ``1`` indicates that the ``line`` is a line of the
  277. formatted source code.
  278. If the `nowrap` option is set, the generator is the iterated over and the
  279. resulting HTML is output.
  280. Otherwise, `format()` calls `self.wrap()`, which wraps the generator with
  281. other generators. These may add some HTML code to the one generated by
  282. `_format_lines()`, either by modifying the lines generated by the latter,
  283. then yielding them again with ``(1, line)``, and/or by yielding other HTML
  284. code before or after the lines, with ``(0, html)``. The distinction between
  285. source lines and other code makes it possible to wrap the generator multiple
  286. times.
  287. The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag.
  288. A custom `HtmlFormatter` subclass could look like this:
  289. .. sourcecode:: python
  290. class CodeHtmlFormatter(HtmlFormatter):
  291. def wrap(self, source, *, include_div):
  292. return self._wrap_code(source)
  293. def _wrap_code(self, source):
  294. yield 0, '<code>'
  295. for i, t in source:
  296. if i == 1:
  297. # it's a line of formatted code
  298. t += '<br>'
  299. yield i, t
  300. yield 0, '</code>'
  301. This results in wrapping the formatted lines with a ``<code>`` tag, where the
  302. source lines are broken using ``<br>`` tags.
  303. After calling `wrap()`, the `format()` method also adds the "line numbers"
  304. and/or "full document" wrappers if the respective options are set. Then, all
  305. HTML yielded by the wrapped generator is output.
  306. """
  307. name = 'HTML'
  308. aliases = ['html']
  309. filenames = ['*.html', '*.htm']
  310. def __init__(self, **options):
  311. Formatter.__init__(self, **options)
  312. self.title = self._decodeifneeded(self.title)
  313. self.nowrap = get_bool_opt(options, 'nowrap', False)
  314. self.noclasses = get_bool_opt(options, 'noclasses', False)
  315. self.classprefix = options.get('classprefix', '')
  316. self.cssclass = html_escape(self._decodeifneeded(options.get('cssclass', 'highlight')))
  317. self.cssstyles = html_escape(self._decodeifneeded(options.get('cssstyles', '')))
  318. self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
  319. self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
  320. self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
  321. self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
  322. self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))
  323. self.filename = html_escape(self._decodeifneeded(options.get('filename', '')))
  324. self.wrapcode = get_bool_opt(options, 'wrapcode', False)
  325. self.span_element_openers = {}
  326. self.debug_token_types = get_bool_opt(options, 'debug_token_types', False)
  327. if self.tagsfile:
  328. if not ctags:
  329. raise RuntimeError('The "ctags" package must to be installed '
  330. 'to be able to use the "tagsfile" feature.')
  331. self._ctags = ctags.CTags(self.tagsfile)
  332. linenos = options.get('linenos', False)
  333. if linenos == 'inline':
  334. self.linenos = 2
  335. elif linenos:
  336. # compatibility with <= 0.7
  337. self.linenos = 1
  338. else:
  339. self.linenos = 0
  340. self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
  341. self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
  342. self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
  343. self.nobackground = get_bool_opt(options, 'nobackground', False)
  344. self.lineseparator = html_escape(options.get('lineseparator', '\n'))
  345. self.lineanchors = html_escape(options.get('lineanchors', ''))
  346. self.linespans = html_escape(options.get('linespans', ''))
  347. self.anchorlinenos = get_bool_opt(options, 'anchorlinenos', False)
  348. self.hl_lines = set()
  349. for lineno in get_list_opt(options, 'hl_lines', []):
  350. try:
  351. self.hl_lines.add(int(lineno))
  352. except ValueError:
  353. pass
  354. self._create_stylesheet()
  355. def _get_css_class(self, ttype):
  356. """Return the css class of this token type prefixed with
  357. the classprefix option."""
  358. ttypeclass = _get_ttype_class(ttype)
  359. if ttypeclass:
  360. return self.classprefix + ttypeclass
  361. return ''
  362. def _get_css_classes(self, ttype):
  363. """Return the CSS classes of this token type prefixed with the classprefix option."""
  364. cls = self._get_css_class(ttype)
  365. while ttype not in STANDARD_TYPES:
  366. ttype = ttype.parent
  367. cls = self._get_css_class(ttype) + ' ' + cls
  368. return cls or ''
  369. def _get_css_inline_styles(self, ttype):
  370. """Return the inline CSS styles for this token type."""
  371. cclass = self.ttype2class.get(ttype)
  372. while cclass is None:
  373. ttype = ttype.parent
  374. cclass = self.ttype2class.get(ttype)
  375. return cclass or ''
  376. def _create_stylesheet(self):
  377. t2c = self.ttype2class = {Token: ''}
  378. c2s = self.class2style = {}
  379. for ttype, ndef in self.style:
  380. name = self._get_css_class(ttype)
  381. style = ''
  382. if ndef['color']:
  383. style += 'color: {}; '.format(webify(ndef['color']))
  384. if ndef['bold']:
  385. style += 'font-weight: bold; '
  386. if ndef['italic']:
  387. style += 'font-style: italic; '
  388. if ndef['underline']:
  389. style += 'text-decoration: underline; '
  390. if ndef['bgcolor']:
  391. style += 'background-color: {}; '.format(webify(ndef['bgcolor']))
  392. if ndef['border']:
  393. style += 'border: 1px solid {}; '.format(webify(ndef['border']))
  394. if style:
  395. t2c[ttype] = name
  396. # save len(ttype) to enable ordering the styles by
  397. # hierarchy (necessary for CSS cascading rules!)
  398. c2s[name] = (style[:-2], ttype, len(ttype))
  399. def get_style_defs(self, arg=None):
  400. """
  401. Return CSS style definitions for the classes produced by the current
  402. highlighting style. ``arg`` can be a string or list of selectors to
  403. insert before the token type classes.
  404. """
  405. style_lines = []
  406. style_lines.extend(self.get_linenos_style_defs())
  407. style_lines.extend(self.get_background_style_defs(arg))
  408. style_lines.extend(self.get_token_style_defs(arg))
  409. return '\n'.join(style_lines)
  410. def get_token_style_defs(self, arg=None):
  411. prefix = self.get_css_prefix(arg)
  412. styles = [
  413. (level, ttype, cls, style)
  414. for cls, (style, ttype, level) in self.class2style.items()
  415. if cls and style
  416. ]
  417. styles.sort()
  418. lines = [
  419. f'{prefix(cls)} {{ {style} }} /* {repr(ttype)[6:]} */'
  420. for (level, ttype, cls, style) in styles
  421. ]
  422. return lines
  423. def get_background_style_defs(self, arg=None):
  424. prefix = self.get_css_prefix(arg)
  425. bg_color = self.style.background_color
  426. hl_color = self.style.highlight_color
  427. lines = []
  428. if arg and not self.nobackground and bg_color is not None:
  429. text_style = ''
  430. if Text in self.ttype2class:
  431. text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
  432. lines.insert(
  433. 0, '{}{{ background: {};{} }}'.format(
  434. prefix(''), bg_color, text_style
  435. )
  436. )
  437. if hl_color is not None:
  438. lines.insert(
  439. 0, '{} {{ background-color: {} }}'.format(prefix('hll'), hl_color)
  440. )
  441. return lines
  442. def get_linenos_style_defs(self):
  443. lines = [
  444. f'pre {{ {self._pre_style} }}',
  445. f'td.linenos .normal {{ {self._linenos_style} }}',
  446. f'span.linenos {{ {self._linenos_style} }}',
  447. f'td.linenos .special {{ {self._linenos_special_style} }}',
  448. f'span.linenos.special {{ {self._linenos_special_style} }}',
  449. ]
  450. return lines
  451. def get_css_prefix(self, arg):
  452. if arg is None:
  453. arg = ('cssclass' in self.options and '.'+self.cssclass or '')
  454. if isinstance(arg, str):
  455. args = [arg]
  456. else:
  457. args = list(arg)
  458. def prefix(cls):
  459. if cls:
  460. cls = '.' + cls
  461. tmp = []
  462. for arg in args:
  463. tmp.append((arg and arg + ' ' or '') + cls)
  464. return ', '.join(tmp)
  465. return prefix
  466. @property
  467. def _pre_style(self):
  468. return 'line-height: 125%;'
  469. @property
  470. def _linenos_style(self):
  471. color = self.style.line_number_color
  472. background_color = self.style.line_number_background_color
  473. return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
  474. @property
  475. def _linenos_special_style(self):
  476. color = self.style.line_number_special_color
  477. background_color = self.style.line_number_special_background_color
  478. return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
  479. def _decodeifneeded(self, value):
  480. if isinstance(value, bytes):
  481. if self.encoding:
  482. return value.decode(self.encoding)
  483. return value.decode()
  484. return value
  485. def _wrap_full(self, inner, outfile):
  486. if self.cssfile:
  487. if os.path.isabs(self.cssfile):
  488. # it's an absolute filename
  489. cssfilename = self.cssfile
  490. else:
  491. try:
  492. filename = outfile.name
  493. if not filename or filename[0] == '<':
  494. # pseudo files, e.g. name == '<fdopen>'
  495. raise AttributeError
  496. cssfilename = os.path.join(os.path.dirname(filename),
  497. self.cssfile)
  498. except AttributeError:
  499. print('Note: Cannot determine output file name, '
  500. 'using current directory as base for the CSS file name',
  501. file=sys.stderr)
  502. cssfilename = self.cssfile
  503. # write CSS file only if noclobber_cssfile isn't given as an option.
  504. try:
  505. if not os.path.exists(cssfilename) or not self.noclobber_cssfile:
  506. with open(cssfilename, "w", encoding="utf-8") as cf:
  507. cf.write(CSSFILE_TEMPLATE %
  508. {'styledefs': self.get_style_defs('body')})
  509. except OSError as err:
  510. err.strerror = 'Error writing CSS file: ' + err.strerror
  511. raise
  512. yield 0, (DOC_HEADER_EXTERNALCSS %
  513. dict(title=self.title,
  514. cssfile=self.cssfile,
  515. encoding=self.encoding))
  516. else:
  517. yield 0, (DOC_HEADER %
  518. dict(title=self.title,
  519. styledefs=self.get_style_defs('body'),
  520. encoding=self.encoding))
  521. yield from inner
  522. yield 0, DOC_FOOTER
  523. def _wrap_tablelinenos(self, inner):
  524. dummyoutfile = StringIO()
  525. lncount = 0
  526. for t, line in inner:
  527. if t:
  528. lncount += 1
  529. dummyoutfile.write(line)
  530. fl = self.linenostart
  531. mw = len(str(lncount + fl - 1))
  532. sp = self.linenospecial
  533. st = self.linenostep
  534. anchor_name = self.lineanchors or self.linespans
  535. aln = self.anchorlinenos
  536. nocls = self.noclasses
  537. lines = []
  538. for i in range(fl, fl+lncount):
  539. print_line = i % st == 0
  540. special_line = sp and i % sp == 0
  541. if print_line:
  542. line = '%*d' % (mw, i)
  543. if aln:
  544. line = '<a href="#%s-%d">%s</a>' % (anchor_name, i, line)
  545. else:
  546. line = ' ' * mw
  547. if nocls:
  548. if special_line:
  549. style = f' style="{self._linenos_special_style}"'
  550. else:
  551. style = f' style="{self._linenos_style}"'
  552. else:
  553. if special_line:
  554. style = ' class="special"'
  555. else:
  556. style = ' class="normal"'
  557. if style:
  558. line = f'<span{style}>{line}</span>'
  559. lines.append(line)
  560. ls = '\n'.join(lines)
  561. # If a filename was specified, we can't put it into the code table as it
  562. # would misalign the line numbers. Hence we emit a separate row for it.
  563. filename_tr = ""
  564. if self.filename:
  565. filename_tr = (
  566. '<tr><th colspan="2" class="filename">'
  567. '<span class="filename">' + self.filename + '</span>'
  568. '</th></tr>')
  569. # in case you wonder about the seemingly redundant <div> here: since the
  570. # content in the other cell also is wrapped in a div, some browsers in
  571. # some configurations seem to mess up the formatting...
  572. yield 0, (f'<table class="{self.cssclass}table">' + filename_tr +
  573. '<tr><td class="linenos"><div class="linenodiv"><pre>' +
  574. ls + '</pre></div></td><td class="code">')
  575. yield 0, '<div>'
  576. yield 0, dummyoutfile.getvalue()
  577. yield 0, '</div>'
  578. yield 0, '</td></tr></table>'
  579. def _wrap_inlinelinenos(self, inner):
  580. # need a list of lines since we need the width of a single number :(
  581. inner_lines = list(inner)
  582. sp = self.linenospecial
  583. st = self.linenostep
  584. num = self.linenostart
  585. mw = len(str(len(inner_lines) + num - 1))
  586. anchor_name = self.lineanchors or self.linespans
  587. aln = self.anchorlinenos
  588. nocls = self.noclasses
  589. for _, inner_line in inner_lines:
  590. print_line = num % st == 0
  591. special_line = sp and num % sp == 0
  592. if print_line:
  593. line = '%*d' % (mw, num)
  594. else:
  595. line = ' ' * mw
  596. if nocls:
  597. if special_line:
  598. style = f' style="{self._linenos_special_style}"'
  599. else:
  600. style = f' style="{self._linenos_style}"'
  601. else:
  602. if special_line:
  603. style = ' class="linenos special"'
  604. else:
  605. style = ' class="linenos"'
  606. if style:
  607. linenos = f'<span{style}>{line}</span>'
  608. else:
  609. linenos = line
  610. if aln:
  611. yield 1, ('<a href="#%s-%d">%s</a>' % (anchor_name, num, linenos) +
  612. inner_line)
  613. else:
  614. yield 1, linenos + inner_line
  615. num += 1
  616. def _wrap_lineanchors(self, inner):
  617. s = self.lineanchors
  618. # subtract 1 since we have to increment i *before* yielding
  619. i = self.linenostart - 1
  620. for t, line in inner:
  621. if t:
  622. i += 1
  623. href = "" if self.linenos else ' href="#%s-%d"' % (s, i)
  624. yield 1, '<a id="%s-%d" name="%s-%d"%s></a>' % (s, i, s, i, href) + line
  625. else:
  626. yield 0, line
  627. def _wrap_linespans(self, inner):
  628. s = self.linespans
  629. i = self.linenostart - 1
  630. for t, line in inner:
  631. if t:
  632. i += 1
  633. yield 1, '<span id="%s-%d">%s</span>' % (s, i, line)
  634. else:
  635. yield 0, line
  636. def _wrap_div(self, inner):
  637. style = []
  638. if (self.noclasses and not self.nobackground and
  639. self.style.background_color is not None):
  640. style.append(f'background: {self.style.background_color}')
  641. if self.cssstyles:
  642. style.append(self.cssstyles)
  643. style = '; '.join(style)
  644. yield 0, ('<div' + (self.cssclass and f' class="{self.cssclass}"') +
  645. (style and (f' style="{style}"')) + '>')
  646. yield from inner
  647. yield 0, '</div>\n'
  648. def _wrap_pre(self, inner):
  649. style = []
  650. if self.prestyles:
  651. style.append(self.prestyles)
  652. if self.noclasses:
  653. style.append(self._pre_style)
  654. style = '; '.join(style)
  655. if self.filename and self.linenos != 1:
  656. yield 0, ('<span class="filename">' + self.filename + '</span>')
  657. # the empty span here is to keep leading empty lines from being
  658. # ignored by HTML parsers
  659. yield 0, ('<pre' + (style and f' style="{style}"') + '><span></span>')
  660. yield from inner
  661. yield 0, '</pre>'
  662. def _wrap_code(self, inner):
  663. yield 0, '<code>'
  664. yield from inner
  665. yield 0, '</code>'
  666. @functools.lru_cache(maxsize=100)
  667. def _translate_parts(self, value):
  668. """HTML-escape a value and split it by newlines.
  669. ``quote=False`` is intentional: token values are emitted as element
  670. text content (inside ``<span>``/``<pre>``), where ``"`` and ``'`` do
  671. not need escaping. Skipping those two replacements is measurably
  672. faster on the per-token hot path.
  673. """
  674. return _escape(value, quote=False).split('\n')
  675. def _format_lines(self, tokensource):
  676. """
  677. Just format the tokens, without any wrapping tags.
  678. Yield individual lines.
  679. """
  680. nocls = self.noclasses
  681. lsep = self.lineseparator
  682. tagsfile = self.tagsfile
  683. span_openers = self.span_element_openers
  684. translate = self._translate_parts
  685. lspan = ''
  686. line = []
  687. for ttype, value in tokensource:
  688. try:
  689. cspan = span_openers[ttype]
  690. except KeyError:
  691. title = ' title="{}"'.format('.'.join(ttype)) if self.debug_token_types else ''
  692. if nocls:
  693. css_style = self._get_css_inline_styles(ttype)
  694. if css_style:
  695. css_style = self.class2style[css_style][0]
  696. cspan = f'<span style="{css_style}"{title}>'
  697. else:
  698. cspan = ''
  699. else:
  700. css_class = self._get_css_classes(ttype)
  701. if css_class:
  702. cspan = f'<span class="{css_class}"{title}>'
  703. else:
  704. cspan = ''
  705. span_openers[ttype] = cspan
  706. parts = translate(value)
  707. if tagsfile and ttype in Token.Name:
  708. filename, linenumber = self._lookup_ctag(value)
  709. if linenumber:
  710. base, filename = os.path.split(filename)
  711. if base:
  712. base += '/'
  713. filename, extension = os.path.splitext(filename)
  714. url = self.tagurlformat % {'path': base, 'fname': filename,
  715. 'fext': extension}
  716. parts[0] = "<a href=\"%s#%s-%d\">%s" % \
  717. (url, self.lineanchors, linenumber, parts[0])
  718. parts[-1] = parts[-1] + "</a>"
  719. # for all but the last line (skipped entirely for single-line
  720. # tokens, which are the common case, to avoid the parts[:-1] slice)
  721. if len(parts) > 1:
  722. for part in parts[:-1]:
  723. if line:
  724. # Also check for part being non-empty, so we avoid
  725. # creating empty <span> tags
  726. if lspan != cspan and part:
  727. line.extend(((lspan and '</span>'), cspan, part,
  728. (cspan and '</span>'), lsep))
  729. else: # both are the same, or the current part was empty
  730. line.extend((part, (lspan and '</span>'), lsep))
  731. yield 1, ''.join(line)
  732. line = []
  733. elif part:
  734. yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))
  735. else:
  736. yield 1, lsep
  737. # for the last line
  738. last = parts[-1]
  739. if line and last:
  740. if lspan != cspan:
  741. line.extend(((lspan and '</span>'), cspan, last))
  742. lspan = cspan
  743. else:
  744. line.append(last)
  745. elif last:
  746. line = [cspan, last]
  747. lspan = cspan
  748. # else we neither have to open a new span nor set lspan
  749. if line:
  750. line.extend(((lspan and '</span>'), lsep))
  751. yield 1, ''.join(line)
  752. def _lookup_ctag(self, token):
  753. entry = ctags.TagEntry()
  754. if self._ctags.find(entry, token.encode(), 0):
  755. return entry['file'].decode(), entry['lineNumber']
  756. else:
  757. return None, None
  758. def _highlight_lines(self, tokensource):
  759. """
  760. Highlighted the lines specified in the `hl_lines` option by
  761. post-processing the token stream coming from `_format_lines`.
  762. """
  763. hls = self.hl_lines
  764. for i, (t, value) in enumerate(tokensource):
  765. if t != 1:
  766. yield t, value
  767. if i + 1 in hls: # i + 1 because Python indexes start at 0
  768. if self.noclasses:
  769. style = ''
  770. if self.style.highlight_color is not None:
  771. style = (f' style="background-color: {self.style.highlight_color}"')
  772. yield 1, f'<span{style}>{value}</span>'
  773. else:
  774. yield 1, f'<span class="hll">{value}</span>'
  775. else:
  776. yield 1, value
  777. def wrap(self, source):
  778. """
  779. Wrap the ``source``, which is a generator yielding
  780. individual lines, in custom generators. See docstring
  781. for `format`. Can be overridden.
  782. """
  783. output = source
  784. if self.wrapcode:
  785. output = self._wrap_code(output)
  786. output = self._wrap_pre(output)
  787. return output
  788. def format_unencoded(self, tokensource, outfile):
  789. """
  790. The formatting process uses several nested generators; which of
  791. them are used is determined by the user's options.
  792. Each generator should take at least one argument, ``inner``,
  793. and wrap the pieces of text generated by this.
  794. Always yield 2-tuples: (code, text). If "code" is 1, the text
  795. is part of the original tokensource being highlighted, if it's
  796. 0, the text is some piece of wrapping. This makes it possible to
  797. use several different wrappers that process the original source
  798. linewise, e.g. line number generators.
  799. """
  800. source = self._format_lines(tokensource)
  801. # As a special case, we wrap line numbers before line highlighting
  802. # so the line numbers get wrapped in the highlighting tag.
  803. if not self.nowrap and self.linenos == 2:
  804. source = self._wrap_inlinelinenos(source)
  805. if self.hl_lines:
  806. source = self._highlight_lines(source)
  807. if not self.nowrap:
  808. if self.lineanchors:
  809. source = self._wrap_lineanchors(source)
  810. if self.linespans:
  811. source = self._wrap_linespans(source)
  812. source = self.wrap(source)
  813. if self.linenos == 1:
  814. source = self._wrap_tablelinenos(source)
  815. source = self._wrap_div(source)
  816. if self.full:
  817. source = self._wrap_full(source, outfile)
  818. for t, piece in source:
  819. outfile.write(piece)