html.py 32 KB

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