latex.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. """
  2. pygments.formatters.latex
  3. ~~~~~~~~~~~~~~~~~~~~~~~~~
  4. Formatter for LaTeX fancyvrb output.
  5. :copyright: Copyright 2006-2021 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. The special command used here (``\PY``) and all the other macros it needs
  137. are output by the `get_style_defs` method.
  138. With the `full` option, a complete LaTeX document is output, including
  139. the command definitions in the preamble.
  140. The `get_style_defs()` method of a `LatexFormatter` returns a string
  141. containing ``\def`` commands defining the macros needed inside the
  142. ``Verbatim`` environments.
  143. Additional options accepted:
  144. `style`
  145. The style to use, can be a string or a Style subclass (default:
  146. ``'default'``).
  147. `full`
  148. Tells the formatter to output a "full" document, i.e. a complete
  149. self-contained document (default: ``False``).
  150. `title`
  151. If `full` is true, the title that should be used to caption the
  152. document (default: ``''``).
  153. `docclass`
  154. If the `full` option is enabled, this is the document class to use
  155. (default: ``'article'``).
  156. `preamble`
  157. If the `full` option is enabled, this can be further preamble commands,
  158. e.g. ``\usepackage`` (default: ``''``).
  159. `linenos`
  160. If set to ``True``, output line numbers (default: ``False``).
  161. `linenostart`
  162. The line number for the first line (default: ``1``).
  163. `linenostep`
  164. If set to a number n > 1, only every nth line number is printed.
  165. `verboptions`
  166. Additional options given to the Verbatim environment (see the *fancyvrb*
  167. docs for possible values) (default: ``''``).
  168. `commandprefix`
  169. The LaTeX commands used to produce colored output are constructed
  170. using this prefix and some letters (default: ``'PY'``).
  171. .. versionadded:: 0.7
  172. .. versionchanged:: 0.10
  173. The default is now ``'PY'`` instead of ``'C'``.
  174. `texcomments`
  175. If set to ``True``, enables LaTeX comment lines. That is, LaTex markup
  176. in comment tokens is not escaped so that LaTeX can render it (default:
  177. ``False``).
  178. .. versionadded:: 1.2
  179. `mathescape`
  180. If set to ``True``, enables LaTeX math mode escape in comments. That
  181. is, ``'$...$'`` inside a comment will trigger math mode (default:
  182. ``False``).
  183. .. versionadded:: 1.2
  184. `escapeinside`
  185. If set to a string of length 2, enables escaping to LaTeX. Text
  186. delimited by these 2 characters is read as LaTeX code and
  187. typeset accordingly. It has no effect in string literals. It has
  188. no effect in comments if `texcomments` or `mathescape` is
  189. set. (default: ``''``).
  190. .. versionadded:: 2.0
  191. `envname`
  192. Allows you to pick an alternative environment name replacing Verbatim.
  193. The alternate environment still has to support Verbatim's option syntax.
  194. (default: ``'Verbatim'``).
  195. .. versionadded:: 2.0
  196. """
  197. name = 'LaTeX'
  198. aliases = ['latex', 'tex']
  199. filenames = ['*.tex']
  200. def __init__(self, **options):
  201. Formatter.__init__(self, **options)
  202. self.docclass = options.get('docclass', 'article')
  203. self.preamble = options.get('preamble', '')
  204. self.linenos = get_bool_opt(options, 'linenos', False)
  205. self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
  206. self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
  207. self.verboptions = options.get('verboptions', '')
  208. self.nobackground = get_bool_opt(options, 'nobackground', False)
  209. self.commandprefix = options.get('commandprefix', 'PY')
  210. self.texcomments = get_bool_opt(options, 'texcomments', False)
  211. self.mathescape = get_bool_opt(options, 'mathescape', False)
  212. self.escapeinside = options.get('escapeinside', '')
  213. if len(self.escapeinside) == 2:
  214. self.left = self.escapeinside[0]
  215. self.right = self.escapeinside[1]
  216. else:
  217. self.escapeinside = ''
  218. self.envname = options.get('envname', 'Verbatim')
  219. self._create_stylesheet()
  220. def _create_stylesheet(self):
  221. t2n = self.ttype2name = {Token: ''}
  222. c2d = self.cmd2def = {}
  223. cp = self.commandprefix
  224. def rgbcolor(col):
  225. if col:
  226. return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)
  227. for i in (0, 2, 4)])
  228. else:
  229. return '1,1,1'
  230. for ttype, ndef in self.style:
  231. name = _get_ttype_name(ttype)
  232. cmndef = ''
  233. if ndef['bold']:
  234. cmndef += r'\let\$$@bf=\textbf'
  235. if ndef['italic']:
  236. cmndef += r'\let\$$@it=\textit'
  237. if ndef['underline']:
  238. cmndef += r'\let\$$@ul=\underline'
  239. if ndef['roman']:
  240. cmndef += r'\let\$$@ff=\textrm'
  241. if ndef['sans']:
  242. cmndef += r'\let\$$@ff=\textsf'
  243. if ndef['mono']:
  244. cmndef += r'\let\$$@ff=\textsf'
  245. if ndef['color']:
  246. cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
  247. rgbcolor(ndef['color']))
  248. if ndef['border']:
  249. cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{\string -\fboxrule}'
  250. r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}}' %
  251. (rgbcolor(ndef['border']),
  252. rgbcolor(ndef['bgcolor'])))
  253. elif ndef['bgcolor']:
  254. cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{0pt}'
  255. r'\colorbox[rgb]{%s}{\strut ##1}}}' %
  256. rgbcolor(ndef['bgcolor']))
  257. if cmndef == '':
  258. continue
  259. cmndef = cmndef.replace('$$', cp)
  260. t2n[ttype] = name
  261. c2d[name] = cmndef
  262. def get_style_defs(self, arg=''):
  263. """
  264. Return the command sequences needed to define the commands
  265. used to format text in the verbatim environment. ``arg`` is ignored.
  266. """
  267. cp = self.commandprefix
  268. styles = []
  269. for name, definition in self.cmd2def.items():
  270. styles.append(r'\@namedef{%s@tok@%s}{%s}' % (cp, name, definition))
  271. return STYLE_TEMPLATE % {'cp': self.commandprefix,
  272. 'styles': '\n'.join(styles)}
  273. def format_unencoded(self, tokensource, outfile):
  274. # TODO: add support for background colors
  275. t2n = self.ttype2name
  276. cp = self.commandprefix
  277. if self.full:
  278. realoutfile = outfile
  279. outfile = StringIO()
  280. outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}')
  281. if self.linenos:
  282. start, step = self.linenostart, self.linenostep
  283. outfile.write(',numbers=left' +
  284. (start and ',firstnumber=%d' % start or '') +
  285. (step and ',stepnumber=%d' % step or ''))
  286. if self.mathescape or self.texcomments or self.escapeinside:
  287. outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7'
  288. '\\catcode`\\_=8\\relax}')
  289. if self.verboptions:
  290. outfile.write(',' + self.verboptions)
  291. outfile.write(']\n')
  292. for ttype, value in tokensource:
  293. if ttype in Token.Comment:
  294. if self.texcomments:
  295. # Try to guess comment starting lexeme and escape it ...
  296. start = value[0:1]
  297. for i in range(1, len(value)):
  298. if start[0] != value[i]:
  299. break
  300. start += value[i]
  301. value = value[len(start):]
  302. start = escape_tex(start, cp)
  303. # ... but do not escape inside comment.
  304. value = start + value
  305. elif self.mathescape:
  306. # Only escape parts not inside a math environment.
  307. parts = value.split('$')
  308. in_math = False
  309. for i, part in enumerate(parts):
  310. if not in_math:
  311. parts[i] = escape_tex(part, cp)
  312. in_math = not in_math
  313. value = '$'.join(parts)
  314. elif self.escapeinside:
  315. text = value
  316. value = ''
  317. while text:
  318. a, sep1, text = text.partition(self.left)
  319. if sep1:
  320. b, sep2, text = text.partition(self.right)
  321. if sep2:
  322. value += escape_tex(a, cp) + b
  323. else:
  324. value += escape_tex(a + sep1 + b, cp)
  325. else:
  326. value += escape_tex(a, cp)
  327. else:
  328. value = escape_tex(value, cp)
  329. elif ttype not in Token.Escape:
  330. value = escape_tex(value, cp)
  331. styles = []
  332. while ttype is not Token:
  333. try:
  334. styles.append(t2n[ttype])
  335. except KeyError:
  336. # not in current style
  337. styles.append(_get_ttype_name(ttype))
  338. ttype = ttype.parent
  339. styleval = '+'.join(reversed(styles))
  340. if styleval:
  341. spl = value.split('\n')
  342. for line in spl[:-1]:
  343. if line:
  344. outfile.write("\\%s{%s}{%s}" % (cp, styleval, line))
  345. outfile.write('\n')
  346. if spl[-1]:
  347. outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1]))
  348. else:
  349. outfile.write(value)
  350. outfile.write('\\end{' + self.envname + '}\n')
  351. if self.full:
  352. encoding = self.encoding or 'utf8'
  353. # map known existings encodings from LaTeX distribution
  354. encoding = {
  355. 'utf_8': 'utf8',
  356. 'latin_1': 'latin1',
  357. 'iso_8859_1': 'latin1',
  358. }.get(encoding.replace('-', '_'), encoding)
  359. realoutfile.write(DOC_TEMPLATE %
  360. dict(docclass = self.docclass,
  361. preamble = self.preamble,
  362. title = self.title,
  363. encoding = encoding,
  364. styledefs = self.get_style_defs(),
  365. code = outfile.getvalue()))
  366. class LatexEmbeddedLexer(Lexer):
  367. """
  368. This lexer takes one lexer as argument, the lexer for the language
  369. being formatted, and the left and right delimiters for escaped text.
  370. First everything is scanned using the language lexer to obtain
  371. strings and comments. All other consecutive tokens are merged and
  372. the resulting text is scanned for escaped segments, which are given
  373. the Token.Escape type. Finally text that is not escaped is scanned
  374. again with the language lexer.
  375. """
  376. def __init__(self, left, right, lang, **options):
  377. self.left = left
  378. self.right = right
  379. self.lang = lang
  380. Lexer.__init__(self, **options)
  381. def get_tokens_unprocessed(self, text):
  382. # find and remove all the escape tokens (replace with an empty string)
  383. # this is very similar to DelegatingLexer.get_tokens_unprocessed.
  384. buffered = ''
  385. insertions = []
  386. insertion_buf = []
  387. for i, t, v in self._find_safe_escape_tokens(text):
  388. if t is None:
  389. if insertion_buf:
  390. insertions.append((len(buffered), insertion_buf))
  391. insertion_buf = []
  392. buffered += v
  393. else:
  394. insertion_buf.append((i, t, v))
  395. if insertion_buf:
  396. insertions.append((len(buffered), insertion_buf))
  397. return do_insertions(insertions,
  398. self.lang.get_tokens_unprocessed(buffered))
  399. def _find_safe_escape_tokens(self, text):
  400. """ find escape tokens that are not in strings or comments """
  401. for i, t, v in self._filter_to(
  402. self.lang.get_tokens_unprocessed(text),
  403. lambda t: t in Token.Comment or t in Token.String
  404. ):
  405. if t is None:
  406. for i2, t2, v2 in self._find_escape_tokens(v):
  407. yield i + i2, t2, v2
  408. else:
  409. yield i, None, v
  410. def _filter_to(self, it, pred):
  411. """ Keep only the tokens that match `pred`, merge the others together """
  412. buf = ''
  413. idx = 0
  414. for i, t, v in it:
  415. if pred(t):
  416. if buf:
  417. yield idx, None, buf
  418. buf = ''
  419. yield i, t, v
  420. else:
  421. if not buf:
  422. idx = i
  423. buf += v
  424. if buf:
  425. yield idx, None, buf
  426. def _find_escape_tokens(self, text):
  427. """ Find escape tokens within text, give token=None otherwise """
  428. index = 0
  429. while text:
  430. a, sep1, text = text.partition(self.left)
  431. if a:
  432. yield index, None, a
  433. index += len(a)
  434. if sep1:
  435. b, sep2, text = text.partition(self.right)
  436. if sep2:
  437. yield index + len(sep1), Token.Escape, b
  438. index += len(sep1) + len(b) + len(sep2)
  439. else:
  440. yield index, Token.Error, sep1
  441. index += len(sep1)
  442. text = b