latex.py 19 KB

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