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