latex.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. """
  2. pygments.formatters.latex
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for LaTeX fancyvrb output.
  5. :copyright: Copyright 2006-2024 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', rf'\{commandprefix}Zbs{{}}'). \
  19. replace('\x01', rf'\{commandprefix}Zob{{}}'). \
  20. replace('\x02', rf'\{commandprefix}Zcb{{}}'). \
  21. replace('^', rf'\{commandprefix}Zca{{}}'). \
  22. replace('_', rf'\{commandprefix}Zus{{}}'). \
  23. replace('&', rf'\{commandprefix}Zam{{}}'). \
  24. replace('<', rf'\{commandprefix}Zlt{{}}'). \
  25. replace('>', rf'\{commandprefix}Zgt{{}}'). \
  26. replace('#', rf'\{commandprefix}Zsh{{}}'). \
  27. replace('%', rf'\{commandprefix}Zpc{{}}'). \
  28. replace('$', rf'\{commandprefix}Zdl{{}}'). \
  29. replace('-', rf'\{commandprefix}Zhy{{}}'). \
  30. replace("'", rf'\{commandprefix}Zsq{{}}'). \
  31. replace('"', rf'\{commandprefix}Zdq{{}}'). \
  32. replace('~', rf'\{commandprefix}Zti{{}}')
  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]{{{}}}{{##1}}}}'.format(rgbcolor(ndef['color'])))
  253. if ndef['border']:
  254. cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}'
  255. r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']),
  256. rgbcolor(ndef['bgcolor'])))
  257. elif ndef['bgcolor']:
  258. cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{0pt}}'
  259. r'\colorbox[rgb]{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['bgcolor'])))
  260. if cmndef == '':
  261. continue
  262. cmndef = cmndef.replace('$$', cp)
  263. t2n[ttype] = name
  264. c2d[name] = cmndef
  265. def get_style_defs(self, arg=''):
  266. """
  267. Return the command sequences needed to define the commands
  268. used to format text in the verbatim environment. ``arg`` is ignored.
  269. """
  270. cp = self.commandprefix
  271. styles = []
  272. for name, definition in self.cmd2def.items():
  273. styles.append(rf'\@namedef{{{cp}@tok@{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. if not self.nowrap:
  284. outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}')
  285. if self.linenos:
  286. start, step = self.linenostart, self.linenostep
  287. outfile.write(',numbers=left' +
  288. (start and ',firstnumber=%d' % start or '') +
  289. (step and ',stepnumber=%d' % step or ''))
  290. if self.mathescape or self.texcomments or self.escapeinside:
  291. outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7'
  292. '\\catcode`\\_=8\\relax}')
  293. if self.verboptions:
  294. outfile.write(',' + self.verboptions)
  295. outfile.write(']\n')
  296. for ttype, value in tokensource:
  297. if ttype in Token.Comment:
  298. if self.texcomments:
  299. # Try to guess comment starting lexeme and escape it ...
  300. start = value[0:1]
  301. for i in range(1, len(value)):
  302. if start[0] != value[i]:
  303. break
  304. start += value[i]
  305. value = value[len(start):]
  306. start = escape_tex(start, cp)
  307. # ... but do not escape inside comment.
  308. value = start + value
  309. elif self.mathescape:
  310. # Only escape parts not inside a math environment.
  311. parts = value.split('$')
  312. in_math = False
  313. for i, part in enumerate(parts):
  314. if not in_math:
  315. parts[i] = escape_tex(part, cp)
  316. in_math = not in_math
  317. value = '$'.join(parts)
  318. elif self.escapeinside:
  319. text = value
  320. value = ''
  321. while text:
  322. a, sep1, text = text.partition(self.left)
  323. if sep1:
  324. b, sep2, text = text.partition(self.right)
  325. if sep2:
  326. value += escape_tex(a, cp) + b
  327. else:
  328. value += escape_tex(a + sep1 + b, cp)
  329. else:
  330. value += escape_tex(a, cp)
  331. else:
  332. value = escape_tex(value, cp)
  333. elif ttype not in Token.Escape:
  334. value = escape_tex(value, cp)
  335. styles = []
  336. while ttype is not Token:
  337. try:
  338. styles.append(t2n[ttype])
  339. except KeyError:
  340. # not in current style
  341. styles.append(_get_ttype_name(ttype))
  342. ttype = ttype.parent
  343. styleval = '+'.join(reversed(styles))
  344. if styleval:
  345. spl = value.split('\n')
  346. for line in spl[:-1]:
  347. if line:
  348. outfile.write(f"\\{cp}{{{styleval}}}{{{line}}}")
  349. outfile.write('\n')
  350. if spl[-1]:
  351. outfile.write(f"\\{cp}{{{styleval}}}{{{spl[-1]}}}")
  352. else:
  353. outfile.write(value)
  354. if not self.nowrap:
  355. outfile.write('\\end{' + self.envname + '}\n')
  356. if self.full:
  357. encoding = self.encoding or 'utf8'
  358. # map known existings encodings from LaTeX distribution
  359. encoding = {
  360. 'utf_8': 'utf8',
  361. 'latin_1': 'latin1',
  362. 'iso_8859_1': 'latin1',
  363. }.get(encoding.replace('-', '_'), encoding)
  364. realoutfile.write(DOC_TEMPLATE %
  365. dict(docclass = self.docclass,
  366. preamble = self.preamble,
  367. title = self.title,
  368. encoding = encoding,
  369. styledefs = self.get_style_defs(),
  370. code = outfile.getvalue()))
  371. class LatexEmbeddedLexer(Lexer):
  372. """
  373. This lexer takes one lexer as argument, the lexer for the language
  374. being formatted, and the left and right delimiters for escaped text.
  375. First everything is scanned using the language lexer to obtain
  376. strings and comments. All other consecutive tokens are merged and
  377. the resulting text is scanned for escaped segments, which are given
  378. the Token.Escape type. Finally text that is not escaped is scanned
  379. again with the language lexer.
  380. """
  381. def __init__(self, left, right, lang, **options):
  382. self.left = left
  383. self.right = right
  384. self.lang = lang
  385. Lexer.__init__(self, **options)
  386. def get_tokens_unprocessed(self, text):
  387. # find and remove all the escape tokens (replace with an empty string)
  388. # this is very similar to DelegatingLexer.get_tokens_unprocessed.
  389. buffered = ''
  390. insertions = []
  391. insertion_buf = []
  392. for i, t, v in self._find_safe_escape_tokens(text):
  393. if t is None:
  394. if insertion_buf:
  395. insertions.append((len(buffered), insertion_buf))
  396. insertion_buf = []
  397. buffered += v
  398. else:
  399. insertion_buf.append((i, t, v))
  400. if insertion_buf:
  401. insertions.append((len(buffered), insertion_buf))
  402. return do_insertions(insertions,
  403. self.lang.get_tokens_unprocessed(buffered))
  404. def _find_safe_escape_tokens(self, text):
  405. """ find escape tokens that are not in strings or comments """
  406. for i, t, v in self._filter_to(
  407. self.lang.get_tokens_unprocessed(text),
  408. lambda t: t in Token.Comment or t in Token.String
  409. ):
  410. if t is None:
  411. for i2, t2, v2 in self._find_escape_tokens(v):
  412. yield i + i2, t2, v2
  413. else:
  414. yield i, None, v
  415. def _filter_to(self, it, pred):
  416. """ Keep only the tokens that match `pred`, merge the others together """
  417. buf = ''
  418. idx = 0
  419. for i, t, v in it:
  420. if pred(t):
  421. if buf:
  422. yield idx, None, buf
  423. buf = ''
  424. yield i, t, v
  425. else:
  426. if not buf:
  427. idx = i
  428. buf += v
  429. if buf:
  430. yield idx, None, buf
  431. def _find_escape_tokens(self, text):
  432. """ Find escape tokens within text, give token=None otherwise """
  433. index = 0
  434. while text:
  435. a, sep1, text = text.partition(self.left)
  436. if a:
  437. yield index, None, a
  438. index += len(a)
  439. if sep1:
  440. b, sep2, text = text.partition(self.right)
  441. if sep2:
  442. yield index + len(sep1), Token.Escape, b
  443. index += len(sep1) + len(b) + len(sep2)
  444. else:
  445. yield index, Token.Error, sep1
  446. index += len(sep1)
  447. text = b