latex.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. # -*- coding: utf-8 -*-
  2. """
  3. pygments.formatters.latex
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Formatter for LaTeX fancyvrb output.
  6. :copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
  7. :license: BSD, see LICENSE for details.
  8. """
  9. from __future__ import division
  10. from pygments.formatter import Formatter
  11. from pygments.lexer import Lexer
  12. from pygments.token import Token, STANDARD_TYPES
  13. from pygments.util import get_bool_opt, get_int_opt, StringIO, xrange, \
  14. iteritems
  15. __all__ = ['LatexFormatter']
  16. def escape_tex(text, commandprefix):
  17. return text.replace('\\', '\x00'). \
  18. replace('{', '\x01'). \
  19. replace('}', '\x02'). \
  20. replace('\x00', r'\%sZbs{}' % commandprefix). \
  21. replace('\x01', r'\%sZob{}' % commandprefix). \
  22. replace('\x02', r'\%sZcb{}' % commandprefix). \
  23. replace('^', r'\%sZca{}' % commandprefix). \
  24. replace('_', r'\%sZus{}' % commandprefix). \
  25. replace('&', r'\%sZam{}' % commandprefix). \
  26. replace('<', r'\%sZlt{}' % commandprefix). \
  27. replace('>', r'\%sZgt{}' % commandprefix). \
  28. replace('#', r'\%sZsh{}' % commandprefix). \
  29. replace('%', r'\%sZpc{}' % commandprefix). \
  30. replace('$', r'\%sZdl{}' % commandprefix). \
  31. replace('-', r'\%sZhy{}' % commandprefix). \
  32. replace("'", r'\%sZsq{}' % commandprefix). \
  33. replace('"', r'\%sZdq{}' % commandprefix). \
  34. replace('~', r'\%sZti{}' % commandprefix)
  35. DOC_TEMPLATE = r'''
  36. \documentclass{%(docclass)s}
  37. \usepackage{fancyvrb}
  38. \usepackage{color}
  39. \usepackage[%(encoding)s]{inputenc}
  40. %(preamble)s
  41. %(styledefs)s
  42. \begin{document}
  43. \section*{%(title)s}
  44. %(code)s
  45. \end{document}
  46. '''
  47. ## Small explanation of the mess below :)
  48. #
  49. # The previous version of the LaTeX formatter just assigned a command to
  50. # each token type defined in the current style. That obviously is
  51. # problematic if the highlighted code is produced for a different style
  52. # than the style commands themselves.
  53. #
  54. # This version works much like the HTML formatter which assigns multiple
  55. # CSS classes to each <span> tag, from the most specific to the least
  56. # specific token type, thus falling back to the parent token type if one
  57. # is not defined. Here, the classes are there too and use the same short
  58. # forms given in token.STANDARD_TYPES.
  59. #
  60. # Highlighted code now only uses one custom command, which by default is
  61. # \PY and selectable by the commandprefix option (and in addition the
  62. # escapes \PYZat, \PYZlb and \PYZrb which haven't been renamed for
  63. # backwards compatibility purposes).
  64. #
  65. # \PY has two arguments: the classes, separated by +, and the text to
  66. # render in that style. The classes are resolved into the respective
  67. # style commands by magic, which serves to ignore unknown classes.
  68. #
  69. # The magic macros are:
  70. # * \PY@it, \PY@bf, etc. are unconditionally wrapped around the text
  71. # to render in \PY@do. Their definition determines the style.
  72. # * \PY@reset resets \PY@it etc. to do nothing.
  73. # * \PY@toks parses the list of classes, using magic inspired by the
  74. # keyval package (but modified to use plusses instead of commas
  75. # because fancyvrb redefines commas inside its environments).
  76. # * \PY@tok processes one class, calling the \PY@tok@classname command
  77. # if it exists.
  78. # * \PY@tok@classname sets the \PY@it etc. to reflect the chosen style
  79. # for its class.
  80. # * \PY resets the style, parses the classnames and then calls \PY@do.
  81. #
  82. # Tip: to read this code, print it out in substituted form using e.g.
  83. # >>> print STYLE_TEMPLATE % {'cp': 'PY'}
  84. STYLE_TEMPLATE = r'''
  85. \makeatletter
  86. \def\%(cp)s@reset{\let\%(cp)s@it=\relax \let\%(cp)s@bf=\relax%%
  87. \let\%(cp)s@ul=\relax \let\%(cp)s@tc=\relax%%
  88. \let\%(cp)s@bc=\relax \let\%(cp)s@ff=\relax}
  89. \def\%(cp)s@tok#1{\csname %(cp)s@tok@#1\endcsname}
  90. \def\%(cp)s@toks#1+{\ifx\relax#1\empty\else%%
  91. \%(cp)s@tok{#1}\expandafter\%(cp)s@toks\fi}
  92. \def\%(cp)s@do#1{\%(cp)s@bc{\%(cp)s@tc{\%(cp)s@ul{%%
  93. \%(cp)s@it{\%(cp)s@bf{\%(cp)s@ff{#1}}}}}}}
  94. \def\%(cp)s#1#2{\%(cp)s@reset\%(cp)s@toks#1+\relax+\%(cp)s@do{#2}}
  95. %(styles)s
  96. \def\%(cp)sZbs{\char`\\}
  97. \def\%(cp)sZus{\char`\_}
  98. \def\%(cp)sZob{\char`\{}
  99. \def\%(cp)sZcb{\char`\}}
  100. \def\%(cp)sZca{\char`\^}
  101. \def\%(cp)sZam{\char`\&}
  102. \def\%(cp)sZlt{\char`\<}
  103. \def\%(cp)sZgt{\char`\>}
  104. \def\%(cp)sZsh{\char`\#}
  105. \def\%(cp)sZpc{\char`\%%}
  106. \def\%(cp)sZdl{\char`\$}
  107. \def\%(cp)sZhy{\char`\-}
  108. \def\%(cp)sZsq{\char`\'}
  109. \def\%(cp)sZdq{\char`\"}
  110. \def\%(cp)sZti{\char`\~}
  111. %% for compatibility with earlier versions
  112. \def\%(cp)sZat{@}
  113. \def\%(cp)sZlb{[}
  114. \def\%(cp)sZrb{]}
  115. \makeatother
  116. '''
  117. def _get_ttype_name(ttype):
  118. fname = STANDARD_TYPES.get(ttype)
  119. if fname:
  120. return fname
  121. aname = ''
  122. while fname is None:
  123. aname = ttype[-1] + aname
  124. ttype = ttype.parent
  125. fname = STANDARD_TYPES.get(ttype)
  126. return fname + aname
  127. class LatexFormatter(Formatter):
  128. r"""
  129. Format tokens as LaTeX code. This needs the `fancyvrb` and `color`
  130. standard packages.
  131. Without the `full` option, code is formatted as one ``Verbatim``
  132. environment, like this:
  133. .. sourcecode:: latex
  134. \begin{Verbatim}[commandchars=\\\{\}]
  135. \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}):
  136. \PY{k}{pass}
  137. \end{Verbatim}
  138. The special command used here (``\PY``) and all the other macros it needs
  139. are output by the `get_style_defs` method.
  140. With the `full` option, a complete LaTeX document is output, including
  141. the command definitions in the preamble.
  142. The `get_style_defs()` method of a `LatexFormatter` returns a string
  143. containing ``\def`` commands defining the macros needed inside the
  144. ``Verbatim`` environments.
  145. Additional options accepted:
  146. `style`
  147. The style to use, can be a string or a Style subclass (default:
  148. ``'default'``).
  149. `full`
  150. Tells the formatter to output a "full" document, i.e. a complete
  151. self-contained document (default: ``False``).
  152. `title`
  153. If `full` is true, the title that should be used to caption the
  154. document (default: ``''``).
  155. `docclass`
  156. If the `full` option is enabled, this is the document class to use
  157. (default: ``'article'``).
  158. `preamble`
  159. If the `full` option is enabled, this can be further preamble commands,
  160. e.g. ``\usepackage`` (default: ``''``).
  161. `linenos`
  162. If set to ``True``, output line numbers (default: ``False``).
  163. `linenostart`
  164. The line number for the first line (default: ``1``).
  165. `linenostep`
  166. If set to a number n > 1, only every nth line number is printed.
  167. `verboptions`
  168. Additional options given to the Verbatim environment (see the *fancyvrb*
  169. docs for possible values) (default: ``''``).
  170. `commandprefix`
  171. The LaTeX commands used to produce colored output are constructed
  172. using this prefix and some letters (default: ``'PY'``).
  173. .. versionadded:: 0.7
  174. .. versionchanged:: 0.10
  175. The default is now ``'PY'`` instead of ``'C'``.
  176. `texcomments`
  177. If set to ``True``, enables LaTeX comment lines. That is, LaTex markup
  178. in comment tokens is not escaped so that LaTeX can render it (default:
  179. ``False``).
  180. .. versionadded:: 1.2
  181. `mathescape`
  182. If set to ``True``, enables LaTeX math mode escape in comments. That
  183. is, ``'$...$'`` inside a comment will trigger math mode (default:
  184. ``False``).
  185. .. versionadded:: 1.2
  186. `escapeinside`
  187. If set to a string of length 2, enables escaping to LaTeX. Text
  188. delimited by these 2 characters is read as LaTeX code and
  189. typeset accordingly. It has no effect in string literals. It has
  190. no effect in comments if `texcomments` or `mathescape` is
  191. set. (default: ``''``).
  192. .. versionadded:: 2.0
  193. `envname`
  194. Allows you to pick an alternative environment name replacing Verbatim.
  195. The alternate environment still has to support Verbatim's option syntax.
  196. (default: ``'Verbatim'``).
  197. .. versionadded:: 2.0
  198. """
  199. name = 'LaTeX'
  200. aliases = ['latex', 'tex']
  201. filenames = ['*.tex']
  202. def __init__(self, **options):
  203. Formatter.__init__(self, **options)
  204. self.docclass = options.get('docclass', 'article')
  205. self.preamble = options.get('preamble', '')
  206. self.linenos = get_bool_opt(options, 'linenos', False)
  207. self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
  208. self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
  209. self.verboptions = options.get('verboptions', '')
  210. self.nobackground = get_bool_opt(options, 'nobackground', False)
  211. self.commandprefix = options.get('commandprefix', 'PY')
  212. self.texcomments = get_bool_opt(options, 'texcomments', False)
  213. self.mathescape = get_bool_opt(options, 'mathescape', False)
  214. self.escapeinside = options.get('escapeinside', '')
  215. if len(self.escapeinside) == 2:
  216. self.left = self.escapeinside[0]
  217. self.right = self.escapeinside[1]
  218. else:
  219. self.escapeinside = ''
  220. self.envname = options.get('envname', u'Verbatim')
  221. self._create_stylesheet()
  222. def _create_stylesheet(self):
  223. t2n = self.ttype2name = {Token: ''}
  224. c2d = self.cmd2def = {}
  225. cp = self.commandprefix
  226. def rgbcolor(col):
  227. if col:
  228. return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)
  229. for i in (0, 2, 4)])
  230. else:
  231. return '1,1,1'
  232. for ttype, ndef in self.style:
  233. name = _get_ttype_name(ttype)
  234. cmndef = ''
  235. if ndef['bold']:
  236. cmndef += r'\let\$$@bf=\textbf'
  237. if ndef['italic']:
  238. cmndef += r'\let\$$@it=\textit'
  239. if ndef['underline']:
  240. cmndef += r'\let\$$@ul=\underline'
  241. if ndef['roman']:
  242. cmndef += r'\let\$$@ff=\textrm'
  243. if ndef['sans']:
  244. cmndef += r'\let\$$@ff=\textsf'
  245. if ndef['mono']:
  246. cmndef += r'\let\$$@ff=\textsf'
  247. if ndef['color']:
  248. cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
  249. rgbcolor(ndef['color']))
  250. if ndef['border']:
  251. cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}'
  252. r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}' %
  253. (rgbcolor(ndef['border']),
  254. rgbcolor(ndef['bgcolor'])))
  255. elif ndef['bgcolor']:
  256. cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}'
  257. r'\colorbox[rgb]{%s}{\strut ##1}}' %
  258. rgbcolor(ndef['bgcolor']))
  259. if cmndef == '':
  260. continue
  261. cmndef = cmndef.replace('$$', cp)
  262. t2n[ttype] = name
  263. c2d[name] = cmndef
  264. def get_style_defs(self, arg=''):
  265. """
  266. Return the command sequences needed to define the commands
  267. used to format text in the verbatim environment. ``arg`` is ignored.
  268. """
  269. cp = self.commandprefix
  270. styles = []
  271. for name, definition in iteritems(self.cmd2def):
  272. styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' %
  273. (cp, name, definition))
  274. return STYLE_TEMPLATE % {'cp': self.commandprefix,
  275. 'styles': '\n'.join(styles)}
  276. def format_unencoded(self, tokensource, outfile):
  277. # TODO: add support for background colors
  278. t2n = self.ttype2name
  279. cp = self.commandprefix
  280. if self.full:
  281. realoutfile = outfile
  282. outfile = StringIO()
  283. outfile.write(u'\\begin{' + self.envname + u'}[commandchars=\\\\\\{\\}')
  284. if self.linenos:
  285. start, step = self.linenostart, self.linenostep
  286. outfile.write(u',numbers=left' +
  287. (start and u',firstnumber=%d' % start or u'') +
  288. (step and u',stepnumber=%d' % step or u''))
  289. if self.mathescape or self.texcomments or self.escapeinside:
  290. outfile.write(u',codes={\\catcode`\\$=3\\catcode`\\^=7\\catcode`\\_=8}')
  291. if self.verboptions:
  292. outfile.write(u',' + self.verboptions)
  293. outfile.write(u']\n')
  294. for ttype, value in tokensource:
  295. if ttype in Token.Comment:
  296. if self.texcomments:
  297. # Try to guess comment starting lexeme and escape it ...
  298. start = value[0:1]
  299. for i in xrange(1, len(value)):
  300. if start[0] != value[i]:
  301. break
  302. start += value[i]
  303. value = value[len(start):]
  304. start = escape_tex(start, cp)
  305. # ... but do not escape inside comment.
  306. value = start + value
  307. elif self.mathescape:
  308. # Only escape parts not inside a math environment.
  309. parts = value.split('$')
  310. in_math = False
  311. for i, part in enumerate(parts):
  312. if not in_math:
  313. parts[i] = escape_tex(part, cp)
  314. in_math = not in_math
  315. value = '$'.join(parts)
  316. elif self.escapeinside:
  317. text = value
  318. value = ''
  319. while text:
  320. a, sep1, text = text.partition(self.left)
  321. if sep1:
  322. b, sep2, text = text.partition(self.right)
  323. if sep2:
  324. value += escape_tex(a, cp) + b
  325. else:
  326. value += escape_tex(a + sep1 + b, cp)
  327. else:
  328. value += escape_tex(a, cp)
  329. else:
  330. value = escape_tex(value, cp)
  331. elif ttype not in Token.Escape:
  332. value = escape_tex(value, cp)
  333. styles = []
  334. while ttype is not Token:
  335. try:
  336. styles.append(t2n[ttype])
  337. except KeyError:
  338. # not in current style
  339. styles.append(_get_ttype_name(ttype))
  340. ttype = ttype.parent
  341. styleval = '+'.join(reversed(styles))
  342. if styleval:
  343. spl = value.split('\n')
  344. for line in spl[:-1]:
  345. if line:
  346. outfile.write("\\%s{%s}{%s}" % (cp, styleval, line))
  347. outfile.write('\n')
  348. if spl[-1]:
  349. outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1]))
  350. else:
  351. outfile.write(value)
  352. outfile.write(u'\\end{' + self.envname + u'}\n')
  353. if self.full:
  354. encoding = self.encoding or 'utf8'
  355. # map known existings encodings from LaTeX distribution
  356. encoding = {
  357. 'utf_8': 'utf8',
  358. 'latin_1': 'latin1',
  359. 'iso_8859_1': 'latin1',
  360. }.get(encoding.replace('-', '_'), encoding)
  361. realoutfile.write(DOC_TEMPLATE %
  362. dict(docclass = self.docclass,
  363. preamble = self.preamble,
  364. title = self.title,
  365. encoding = encoding,
  366. styledefs = self.get_style_defs(),
  367. code = outfile.getvalue()))
  368. class LatexEmbeddedLexer(Lexer):
  369. """
  370. This lexer takes one lexer as argument, the lexer for the language
  371. being formatted, and the left and right delimiters for escaped text.
  372. First everything is scanned using the language lexer to obtain
  373. strings and comments. All other consecutive tokens are merged and
  374. the resulting text is scanned for escaped segments, which are given
  375. the Token.Escape type. Finally text that is not escaped is scanned
  376. again with the language lexer.
  377. """
  378. def __init__(self, left, right, lang, **options):
  379. self.left = left
  380. self.right = right
  381. self.lang = lang
  382. Lexer.__init__(self, **options)
  383. def get_tokens_unprocessed(self, text):
  384. buf = ''
  385. idx = 0
  386. for i, t, v in self.lang.get_tokens_unprocessed(text):
  387. if t in Token.Comment or t in Token.String:
  388. if buf:
  389. for x in self.get_tokens_aux(idx, buf):
  390. yield x
  391. buf = ''
  392. yield i, t, v
  393. else:
  394. if not buf:
  395. idx = i
  396. buf += v
  397. if buf:
  398. for x in self.get_tokens_aux(idx, buf):
  399. yield x
  400. def get_tokens_aux(self, index, text):
  401. while text:
  402. a, sep1, text = text.partition(self.left)
  403. if a:
  404. for i, t, v in self.lang.get_tokens_unprocessed(a):
  405. yield index + i, t, v
  406. index += len(a)
  407. if sep1:
  408. b, sep2, text = text.partition(self.right)
  409. if sep2:
  410. yield index + len(sep1), Token.Escape, b
  411. index += len(sep1) + len(b) + len(sep2)
  412. else:
  413. yield index, Token.Error, sep1
  414. index += len(sep1)
  415. text = b