html.py 31 KB

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