Debian Codegraph @

texk/texlive/linked_scripts/pygmentex/pygmentex.py

raw
1 #! /usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """
5 PygmenTeX
6 ~~~~~~~~~
7
8 PygmenTeX is a converter that do syntax highlighting of snippets of
9 source code extracted from a LaTeX file.
10
11 :copyright: Copyright 2020 by José Romildo Malaquias
12 :license: BSD, see LICENSE for details
13 """
14
15 __version__ = '0.10'
16 __docformat__ = 'restructuredtext'
17
18 import sys
19 import getopt
20 import re
21 from os.path import splitext
22
23 from pygments import highlight
24 from pygments.styles import get_style_by_name
25 from pygments.lexers import get_lexer_by_name
26 from pygments.formatters.latex import LatexFormatter, escape_tex, _get_ttype_name
27 from pygments.util import get_bool_opt, get_int_opt
28 from pygments.lexer import Lexer
29 from pygments.token import Token
30 from pygments.util import guess_decode
31
32 ###################################################
33 # The following code is in >=pygments-2.0
34 ###################################################
35 class EnhancedLatexFormatter(LatexFormatter):
36 r"""
37 This is an enhanced LaTeX formatter.
38 """
39 name = 'EnhancedLaTeX'
40 aliases = []
41
42 def __init__(self, **options):
43 LatexFormatter.__init__(self, **options)
44 self.escapeinside = options.get('escapeinside', '')
45 if len(self.escapeinside) == 2:
46 self.left = self.escapeinside[0]
47 self.right = self.escapeinside[1]
48 else:
49 self.escapeinside = ''
50
51 def format_unencoded(self, tokensource, outfile):
52 # TODO: add support for background colors
53 t2n = self.ttype2name
54 cp = self.commandprefix
55
56 if self.full:
57 realoutfile = outfile
58 outfile = StringIO()
59
60 outfile.write(r'\begin{Verbatim}[commandchars=\\\{\}')
61 if self.linenos:
62 start, step = self.linenostart, self.linenostep
63 outfile.write(',numbers=left' +
64 (start and ',firstnumber=%d' % start or '') +
65 (step and ',stepnumber=%d' % step or ''))
66 if self.mathescape or self.texcomments or self.escapeinside:
67 outfile.write(r',codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8}')
68 if self.verboptions:
69 outfile.write(',' + self.verboptions)
70 outfile.write(']\n')
71
72 for ttype, value in tokensource:
73 if ttype in Token.Comment:
74 if self.texcomments:
75 # Try to guess comment starting lexeme and escape it ...
76 start = value[0:1]
77 for i in range(1, len(value)):
78 if start[0] != value[i]:
79 break
80 start += value[i]
81
82 value = value[len(start):]
83 start = escape_tex(start, self.commandprefix)
84
85 # ... but do not escape inside comment.
86 value = start + value
87 elif self.mathescape:
88 # Only escape parts not inside a math environment.
89 parts = value.split('$')
90 in_math = False
91 for i, part in enumerate(parts):
92 if not in_math:
93 parts[i] = escape_tex(part, self.commandprefix)
94 in_math = not in_math
95 value = '$'.join(parts)
96 elif self.escapeinside:
97 text = value
98 value = ''
99 while len(text) > 0:
100 a,sep1,text = text.partition(self.left)
101 if len(sep1) > 0:
102 b,sep2,text = text.partition(self.right)
103 if len(sep2) > 0:
104 value += escape_tex(a, self.commandprefix) + b
105 else:
106 value += escape_tex(a + sep1 + b, self.commandprefix)
107 else:
108 value = value + escape_tex(a, self.commandprefix)
109 else:
110 value = escape_tex(value, self.commandprefix)
111 elif ttype not in Token.Escape:
112 value = escape_tex(value, self.commandprefix)
113 styles = []
114 while ttype is not Token:
115 try:
116 styles.append(t2n[ttype])
117 except KeyError:
118 # not in current style
119 styles.append(_get_ttype_name(ttype))
120 ttype = ttype.parent
121 styleval = '+'.join(reversed(styles))
122 if styleval:
123 spl = value.split('\n')
124 for line in spl[:-1]:
125 if line:
126 outfile.write("\\%s{%s}{%s}" % (cp, styleval, line))
127 outfile.write('\n')
128 if spl[-1]:
129 outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1]))
130 else:
131 outfile.write(value)
132
133 outfile.write('\\end{Verbatim}\n')
134
135 if self.full:
136 realoutfile.write(DOC_TEMPLATE %
137 dict(docclass = self.docclass,
138 preamble = self.preamble,
139 title = self.title,
140 encoding = self.encoding or 'latin1',
141 styledefs = self.get_style_defs(),
142 code = outfile.getvalue()))
143
144 class LatexEmbeddedLexer(Lexer):
145 r"""
146
147 This lexer takes one lexer as argument, the lexer for the language
148 being formatted, and the left and right delimiters for escaped text.
149
150 First everything is scanned using the language lexer to obtain
151 strings and comments. All other consecutive tokens are merged and
152 the resulting text is scanned for escaped segments, which are given
153 the Token.Escape type. Finally text that is not escaped is scanned
154 again with the language lexer.
155 """
156 def __init__(self, left, right, lang, **options):
157 self.left = left
158 self.right = right
159 self.lang = lang
160 Lexer.__init__(self, **options)
161
162 def get_tokens_unprocessed(self, text):
163 buf = ''
164 for i, t, v in self.lang.get_tokens_unprocessed(text):
165 if t in Token.Comment or t in Token.String:
166 if buf:
167 for x in self.get_tokens_aux(idx, buf):
168 yield x
169 buf = ''
170 yield i, t, v
171 else:
172 if not buf:
173 idx = i
174 buf += v
175 if buf:
176 for x in self.get_tokens_aux(idx, buf):
177 yield x
178
179 def get_tokens_aux(self, index, text):
180 while text:
181 a, sep1, text = text.partition(self.left)
182 if a:
183 for i, t, v in self.lang.get_tokens_unprocessed(a):
184 yield index + i, t, v
185 index += len(a)
186 if sep1:
187 b, sep2, text = text.partition(self.right)
188 if sep2:
189 yield index + len(sep1), Token.Escape, b
190 index += len(sep1) + len(b) + len(sep2)
191 else:
192 yield index, Token.Error, sep1
193 index += len(sep1)
194 text = b
195 ###################################################
196
197 GENERIC_DEFINITIONS_1 = r'''% -*- mode: latex -*-
198
199 \makeatletter
200
201 \newdimen\LineNumberWidth
202 '''
203
204 GENERIC_DEFINITIONS_2 = r'''
205 \makeatother
206 '''
207
208
209 INLINE_SNIPPET_TEMPLATE = r'''
210 \expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%%
211 \pygmented@snippet@inlined{%%
212 %(body)s%%
213 }}
214 '''
215
216 DISPLAY_SNIPPET_TEMPLATE = r'''
217 \expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%%
218 \begin{pygmented@snippet@framed}%%
219 %(body)s%%
220 \end{pygmented@snippet@framed}%%
221 }
222 '''
223
224 DISPLAY_LINENOS_SNIPPET_TEMPLATE = r'''
225 \expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%%
226 \begingroup
227 \def\pygmented@alllinenos{(%(linenumbers)s)}%%
228 \begin{pygmented@snippet@framed}%%
229 %(body)s%%
230 \end{pygmented@snippet@framed}%%
231 \endgroup
232 }
233 '''
234
235
236 def pyg(outfile, outencoding, n, opts, extra_opts, text, usedstyles, inline_delim = ''):
237 try:
238 lexer = get_lexer_by_name(opts['lang'])
239 except ClassNotFound as err:
240 sys.stderr.write('Error: ')
241 sys.stderr.write(str(err))
242 return ""
243
244 # global _fmter
245 _fmter = EnhancedLatexFormatter()
246
247 escapeinside = opts.get('escapeinside', '')
248 if len(escapeinside) == 2:
249 left = escapeinside[0]
250 right = escapeinside[1]
251 _fmter.escapeinside = escapeinside
252 _fmter.left = left
253 _fmter.right = right
254 lexer = LatexEmbeddedLexer(left, right, lexer)
255
256 gobble = abs(get_int_opt(opts, 'gobble', 0))
257 if gobble:
258 lexer.add_filter('gobble', n=gobble)
259
260 tabsize = abs(get_int_opt(opts, 'tabsize', 0))
261 if tabsize:
262 lexer.tabsize = tabsize
263
264 lexer.encoding = ''
265 # _fmter.encoding = outencoding
266
267 stylename = opts['sty']
268
269 _fmter.style = get_style_by_name(stylename)
270 _fmter._create_stylesheet()
271
272 _fmter.texcomments = get_bool_opt(opts, 'texcomments', False)
273 _fmter.mathescape = get_bool_opt(opts, 'mathescape', False)
274
275 if stylename not in usedstyles:
276 styledefs = _fmter.get_style_defs() \
277 .replace('#', '##') \
278 .replace(r'\##', r'\#') \
279 .replace(r'\makeatletter', '') \
280 .replace(r'\makeatother', '') \
281 .replace('\n', '%\n')
282 outfile.write(
283 '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs))
284 usedstyles.append(stylename)
285
286 x = highlight(text, lexer, _fmter)
287
288 m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z',
289 x)
290 if m:
291 linenos = get_bool_opt(opts, 'linenos', False)
292 linenostart = abs(get_int_opt(opts, 'linenostart', 1))
293 linenostep = abs(get_int_opt(opts, 'linenostep', 1))
294 lines0 = m.group(2).split('\n')
295 numbers = []
296 lines = []
297 counter = linenostart
298 for line in lines0:
299 line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line)
300 line = re.sub(r' ', '~', line)
301 if linenos:
302 if (counter - linenostart) % linenostep == 0:
303 line = r'\pygmented@lineno@do{' + str(counter) + '}' + line
304 numbers.append(str(counter))
305 counter = counter + 1
306 lines.append(line)
307 if inline_delim:
308 outfile.write(INLINE_SNIPPET_TEMPLATE %
309 dict(number = n,
310 style = stylename,
311 options = extra_opts,
312 body = '\\newline\n'.join(lines)))
313 else:
314 if linenos:
315 template = DISPLAY_LINENOS_SNIPPET_TEMPLATE
316 else:
317 template = DISPLAY_SNIPPET_TEMPLATE
318 outfile.write(template %
319 dict(number = n,
320 style = stylename,
321 options = extra_opts,
322 linenosep = opts['linenosep'],
323 linenumbers = ','.join(numbers),
324 body = '\\newline\n'.join(lines)))
325
326
327
328 def parse_opts(basedic, opts):
329 dic = basedic.copy()
330 for opt in re.split(r'\s*,\s*', opts):
331 x = re.split(r'\s*=\s*', opt)
332 if len(x) == 2 and x[0] and x[1]:
333 dic[x[0]] = x[1]
334 elif len(x) == 1 and x[0]:
335 dic[x[0]] = True
336 return dic
337
338
339
340 _re_display = re.compile(
341 r'^<@@pygmented@display@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@display@\1$',
342 re.MULTILINE)
343
344 _re_inline = re.compile(
345 r'^<@@pygmented@inline@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@inline@\1$',
346 re.MULTILINE)
347
348 _re_input = re.compile(
349 r'^<@@pygmented@input@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@input@\1$',
350 re.MULTILINE)
351
352 def convert(code, outfile, outencoding):
353 """
354 Convert ``code``
355 """
356 outfile.write(GENERIC_DEFINITIONS_1)
357
358 opts = { 'lang' : 'c',
359 'sty' : 'default',
360 'linenosep' : '0pt',
361 'tabsize' : '8',
362 'encoding' : 'guess',
363 }
364
365 usedstyles = [ ]
366 styledefs = ''
367
368 pos = 0
369
370 while pos < len(code):
371 if code[pos].isspace():
372 pos = pos + 1
373 continue
374
375 m = _re_inline.match(code, pos)
376 if m:
377 pyg(outfile,
378 outencoding,
379 m.group(1),
380 parse_opts(opts.copy(), m.group(2)),
381 '',
382 m.group(3),
383 usedstyles,
384 True)
385 pos = m.end()
386 continue
387
388 m = _re_display.match(code, pos)
389 if m:
390 pyg(outfile,
391 outencoding,
392 m.group(1),
393 parse_opts(opts.copy(), m.group(2)),
394 '',
395 m.group(3),
396 usedstyles)
397 pos = m.end()
398 continue
399
400 m = _re_input.match(code, pos)
401 if m:
402 opts_new = parse_opts(opts, m.group(2))
403 try:
404 filecontents, inencoding = read_input(m.group(3), opts_new['encoding'])
405 except Exception as err:
406 print('Error: cannot read input file: ', err, file=sys.stderr)
407 else:
408 pyg(outfile,
409 outencoding,
410 m.group(1),
411 opts_new,
412 "",
413 filecontents,
414 usedstyles)
415 pos = m.end()
416 continue
417
418 sys.stderr.write('Error: invalid input file contents: ignoring')
419 break
420
421 outfile.write(GENERIC_DEFINITIONS_2)
422
423 def read_input(filename, encoding):
424 with open(filename, 'rb') as infp:
425 code = infp.read()
426
427 if not encoding or encoding == 'guess':
428 code, encoding = guess_decode(code)
429 else:
430 code = code.decode(encoding)
431
432 return code, encoding
433
434
435 USAGE = """\
436 Usage: %s [-o <output file name>] <input file name>
437 %s -h | -V
438
439 The input file should consist of a sequence of source code snippets, as
440 produced by the `pygmentex` LaTeX package. Each code snippet is
441 highlighted using Pygments, and a LaTeX command that expands to the
442 highlighted code snippet is written to the output file.
443
444 It also writes to the output file a set of LaTeX macro definitions the
445 Pygments styles that are used in the code snippets.
446
447 If no output file name is given, use `<input file name>.pygmented`.
448
449 The -e option enables escaping to LaTex. Text delimited by the <left>
450 and <right> characters is read as LaTeX code and typeset accordingly. It
451 has no effect in string literals. It has no effect in comments if
452 `texcomments` or `mathescape` is set.
453
454 The -h option prints this help.
455
456 The -V option prints the package version.
457 """
458
459
460 def main(args = sys.argv):
461 """
462 Main command line entry point.
463 """
464 usage = USAGE % ((args[0],) * 2)
465
466 try:
467 popts, args = getopt.getopt(args[1:], 'e:o:hV')
468 except getopt.GetoptError as err:
469 sys.stderr.write(usage)
470 return 2
471 opts = {}
472 for opt, arg in popts:
473 opts[opt] = arg
474
475 if not opts and not args:
476 print(usage)
477 return 0
478
479 if opts.pop('-h', None) is not None:
480 print(usage)
481 return 0
482
483 if opts.pop('-V', None) is not None:
484 print('PygmenTeX version %s, (c) 2020 by José Romildo.' % __version__)
485 return 0
486
487 if len(args) != 1:
488 sys.stderr.write(usage)
489 return 2
490 infn = args[0]
491 try:
492 code, inencoding = read_input(infn, "guess")
493 except Exception as err:
494 print('Error: cannot read input file: ', err, file=sys.stderr)
495 return 1
496
497 outfn = opts.pop('-o', None)
498 if not outfn:
499 root, ext = splitext(infn)
500 outfn = root + '.pygmented'
501 try:
502 outfile = open(outfn, 'w')
503 except Exception as err:
504 print('Error: cannot open output file: ', err, file=sys.stderr)
505 return 1
506
507 convert(code, outfile, inencoding)
508
509 return 0
510
511
512 if __name__ == '__main__':
513 try:
514 sys.exit(main(sys.argv))
515 except KeyboardInterrupt:
516 sys.exit(1)