latex.py 17 KB

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