diff options
42 files changed, 2469 insertions, 1 deletions
diff --git a/Build/source/texk/texlive/linked_scripts/Makefile.am b/Build/source/texk/texlive/linked_scripts/Makefile.am index 616d8dece47..033eb06b2eb 100644 --- a/Build/source/texk/texlive/linked_scripts/Makefile.am +++ b/Build/source/texk/texlive/linked_scripts/Makefile.am @@ -146,6 +146,7 @@ texmf_other_scripts = \ pst2pdf/pst2pdf.pl \ ptex2pdf/ptex2pdf.lua \ purifyeps/purifyeps \ + pygmentex/pygmentex.py \ pythontex/pythontex.py \ pythontex/depythontex.py \ rubik/rubikrotation.pl \ diff --git a/Build/source/texk/texlive/linked_scripts/Makefile.in b/Build/source/texk/texlive/linked_scripts/Makefile.in index 0d65fb3c6a2..ba63d1db542 100644 --- a/Build/source/texk/texlive/linked_scripts/Makefile.in +++ b/Build/source/texk/texlive/linked_scripts/Makefile.in @@ -354,6 +354,7 @@ texmf_other_scripts = \ pst2pdf/pst2pdf.pl \ ptex2pdf/ptex2pdf.lua \ purifyeps/purifyeps \ + pygmentex/pygmentex.py \ pythontex/pythontex.py \ pythontex/depythontex.py \ rubik/rubikrotation.pl \ diff --git a/Build/source/texk/texlive/linked_scripts/pygmentex/pygmentex.py b/Build/source/texk/texlive/linked_scripts/pygmentex/pygmentex.py new file mode 100755 index 00000000000..42cef96faea --- /dev/null +++ b/Build/source/texk/texlive/linked_scripts/pygmentex/pygmentex.py @@ -0,0 +1,523 @@ +#! /usr/bin/env python2 +# -*- coding: utf-8 -*- + +""" + PygmenTeX + ~~~~~~~~~ + + PygmenTeX is a converter that do syntax highlighting of snippets of + source code extracted from a LaTeX file. + + :copyright: Copyright 2014 by José Romildo Malaquias + :license: BSD, see LICENSE for details +""" + +__version__ = '0.8' +__docformat__ = 'restructuredtext' + +import sys +import getopt +import re +from os.path import splitext + +from pygments import highlight +from pygments.styles import get_style_by_name +from pygments.lexers import get_lexer_by_name +from pygments.formatters.latex import LatexFormatter, escape_tex, _get_ttype_name +from pygments.util import get_bool_opt, get_int_opt +from pygments.lexer import Lexer +from pygments.token import Token + +################################################### +# The following code is in >=pygments-2.0 +################################################### +class EnhancedLatexFormatter(LatexFormatter): + r""" + This is an enhanced LaTeX formatter. + """ + name = 'EnhancedLaTeX' + aliases = [] + + def __init__(self, **options): + LatexFormatter.__init__(self, **options) + self.escapeinside = options.get('escapeinside', '') + if len(self.escapeinside) == 2: + self.left = self.escapeinside[0] + self.right = self.escapeinside[1] + else: + self.escapeinside = '' + + def format_unencoded(self, tokensource, outfile): + # TODO: add support for background colors + t2n = self.ttype2name + cp = self.commandprefix + + if self.full: + realoutfile = outfile + outfile = StringIO() + + outfile.write(u'\\begin{Verbatim}[commandchars=\\\\\\{\\}') + if self.linenos: + start, step = self.linenostart, self.linenostep + outfile.write(u',numbers=left' + + (start and u',firstnumber=%d' % start or u'') + + (step and u',stepnumber=%d' % step or u'')) + if self.mathescape or self.texcomments or self.escapeinside: + outfile.write(u',codes={\\catcode`\\$=3\\catcode`\\^=7\\catcode`\\_=8}') + if self.verboptions: + outfile.write(u',' + self.verboptions) + outfile.write(u']\n') + + for ttype, value in tokensource: + if ttype in Token.Comment: + if self.texcomments: + # Try to guess comment starting lexeme and escape it ... + start = value[0:1] + for i in xrange(1, len(value)): + if start[0] != value[i]: + break + start += value[i] + + value = value[len(start):] + start = escape_tex(start, self.commandprefix) + + # ... but do not escape inside comment. + value = start + value + elif self.mathescape: + # Only escape parts not inside a math environment. + parts = value.split('$') + in_math = False + for i, part in enumerate(parts): + if not in_math: + parts[i] = escape_tex(part, self.commandprefix) + in_math = not in_math + value = '$'.join(parts) + elif self.escapeinside: + text = value + value = '' + while len(text) > 0: + a,sep1,text = text.partition(self.left) + if len(sep1) > 0: + b,sep2,text = text.partition(self.right) + if len(sep2) > 0: + value += escape_tex(a, self.commandprefix) + b + else: + value += escape_tex(a + sep1 + b, self.commandprefix) + else: + value = value + escape_tex(a, self.commandprefix) + else: + value = escape_tex(value, self.commandprefix) + elif ttype not in Token.Escape: + value = escape_tex(value, self.commandprefix) + styles = [] + while ttype is not Token: + try: + styles.append(t2n[ttype]) + except KeyError: + # not in current style + styles.append(_get_ttype_name(ttype)) + ttype = ttype.parent + styleval = '+'.join(reversed(styles)) + if styleval: + spl = value.split('\n') + for line in spl[:-1]: + if line: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, line)) + outfile.write('\n') + if spl[-1]: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1])) + else: + outfile.write(value) + + outfile.write(u'\\end{Verbatim}\n') + + if self.full: + realoutfile.write(DOC_TEMPLATE % + dict(docclass = self.docclass, + preamble = self.preamble, + title = self.title, + encoding = self.encoding or 'latin1', + styledefs = self.get_style_defs(), + code = outfile.getvalue())) + +class LatexEmbeddedLexer(Lexer): + r""" + + This lexer takes one lexer as argument, the lexer for the language + being formatted, and the left and right delimiters for escaped text. + + First everything is scanned using the language lexer to obtain + strings and comments. All other consecutive tokens are merged and + the resulting text is scanned for escaped segments, which are given + the Token.Escape type. Finally text that is not escaped is scanned + again with the language lexer. + """ + def __init__(self, left, right, lang, **options): + self.left = left + self.right = right + self.lang = lang + Lexer.__init__(self, **options) + + def get_tokens_unprocessed(self, text): + buf = '' + for i, t, v in self.lang.get_tokens_unprocessed(text): + if t in Token.Comment or t in Token.String: + if buf: + for x in self.get_tokens_aux(idx, buf): + yield x + buf = '' + yield i, t, v + else: + if not buf: + idx = i + buf += v + if buf: + for x in self.get_tokens_aux(idx, buf): + yield x + + def get_tokens_aux(self, index, text): + while text: + a, sep1, text = text.partition(self.left) + if a: + for i, t, v in self.lang.get_tokens_unprocessed(a): + yield index + i, t, v + index += len(a) + if sep1: + b, sep2, text = text.partition(self.right) + if sep2: + yield index + len(sep1), Token.Escape, b + index += len(sep1) + len(b) + len(sep2) + else: + yield index, Token.Error, sep1 + index += len(sep1) + text = b +################################################### + +GENERIC_DEFINITIONS_1 = r'''% -*- mode: latex -*- + +\makeatletter + +\newdimen\LineNumberWidth +''' + +GENERIC_DEFINITIONS_2 = r''' +\makeatother +''' + + +INLINE_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \pygmented@snippet@inlined{%% +%(body)s%% +}} +''' + +DISPLAY_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \begin{pygmented@snippet@framed}%% +%(body)s%% + \end{pygmented@snippet@framed}%% +} +''' + +DISPLAY_LINENOS_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \begingroup + \def\pygmented@alllinenos{(%(linenumbers)s)}%% + \begin{pygmented@snippet@framed}%% +%(body)s%% + \end{pygmented@snippet@framed}%% + \endgroup +} +''' + + +def pyg(outfile, n, opts, extra_opts, text, usedstyles, inline_delim = ''): + try: + lexer = get_lexer_by_name(opts['lang']) + except ClassNotFound as err: + sys.stderr.write('Error: ') + sys.stderr.write(str(err)) + return "" + + # global _fmter + _fmter = EnhancedLatexFormatter() + + escapeinside = opts.get('escapeinside', '') + if len(escapeinside) == 2: + left = escapeinside[0] + right = escapeinside[1] + _fmter.escapeinside = escapeinside + _fmter.left = left + _fmter.right = right + lexer = LatexEmbeddedLexer(left, right, lexer) + + gobble = abs(get_int_opt(opts, 'gobble', 0)) + if gobble: + lexer.add_filter('gobble', n=gobble) + + tabsize = abs(get_int_opt(opts, 'tabsize', 0)) + if tabsize: + lexer.tabsize = tabsize + + encoding = opts['encoding'] + if encoding == 'guess': + try: + import chardet + except ImportError: + try: + text = text.decode('utf-8') + if text.startswith(u'\ufeff'): + text = text[len(u'\ufeff'):] + encoding = 'utf-8' + except UnicodeDecodeError: + text = text.decode('latin1') + encoding = 'latin1' + else: + encoding = chardet.detect(text)['encoding'] + text = text.decode(encoding) + else: + text = text.decode(encoding) + + lexer.encoding = '' + _fmter.encoding = encoding + + stylename = opts['sty'] + + _fmter.style = get_style_by_name(stylename) + _fmter._create_stylesheet() + + _fmter.texcomments = get_bool_opt(opts, 'texcomments', False) + _fmter.mathescape = get_bool_opt(opts, 'mathescape', False) + + if stylename not in usedstyles: + styledefs = _fmter.get_style_defs() \ + .replace('#', '##') \ + .replace(r'\##', r'\#') \ + .replace(r'\makeatletter', '') \ + .replace(r'\makeatother', '') \ + .replace('\n', '%\n') + outfile.write( + '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs)) + usedstyles.append(stylename) + + x = highlight(text, lexer, _fmter) + + m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z', + x) + if m: + linenos = get_bool_opt(opts, 'linenos', False) + linenostart = abs(get_int_opt(opts, 'linenostart', 1)) + linenostep = abs(get_int_opt(opts, 'linenostep', 1)) + lines0 = m.group(2).split('\n') + numbers = [] + lines = [] + counter = linenostart + for line in lines0: + line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line) + line = re.sub(r' ', '~', line) + if linenos: + if (counter - linenostart) % linenostep == 0: + line = r'\pygmented@lineno@do{' + str(counter) + '}' + line + numbers.append(str(counter)) + counter = counter + 1 + lines.append(line) + if inline_delim: + outfile.write(INLINE_SNIPPET_TEMPLATE % + dict(number = n, + style = stylename, + options = extra_opts, + body = '\\newline\n'.join(lines))) + else: + if linenos: + template = DISPLAY_LINENOS_SNIPPET_TEMPLATE + else: + template = DISPLAY_SNIPPET_TEMPLATE + outfile.write(template % + dict(number = n, + style = stylename, + options = extra_opts, + linenosep = opts['linenosep'], + linenumbers = ','.join(numbers), + body = '\\newline\n'.join(lines))) + + + +def parse_opts(basedic, opts): + dic = basedic.copy() + for opt in re.split(r'\s*,\s*', opts): + x = re.split(r'\s*=\s*', opt) + if len(x) == 2 and x[0] and x[1]: + dic[x[0]] = x[1] + elif len(x) == 1 and x[0]: + dic[x[0]] = True + return dic + + + +_re_display = re.compile( + r'^<@@pygmented@display@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@display@\1$', + re.MULTILINE) + +_re_inline = re.compile( + r'^<@@pygmented@inline@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@inline@\1$', + re.MULTILINE) + +_re_input = re.compile( + r'^<@@pygmented@input@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@input@\1$', + re.MULTILINE) + +def convert(code, outfile): + """ + Convert ``code`` + """ + outfile.write(GENERIC_DEFINITIONS_1) + + opts = { 'lang' : 'c', + 'sty' : 'default', + 'linenosep' : '0pt', + 'tabsize' : '8', + 'encoding' : 'guess', + } + + usedstyles = [ ] + styledefs = '' + + pos = 0 + + while pos < len(code): + if code[pos].isspace(): + pos = pos + 1 + continue + + m = _re_inline.match(code, pos) + if m: + pyg(outfile, + m.group(1), + parse_opts(opts.copy(), m.group(2)), + '', + m.group(3), + usedstyles, + True) + pos = m.end() + continue + + m = _re_display.match(code, pos) + if m: + pyg(outfile, + m.group(1), + parse_opts(opts.copy(), m.group(2)), + '', + m.group(3), + usedstyles) + pos = m.end() + continue + + m = _re_input.match(code, pos) + if m: + try: + filecontents = open(m.group(3), 'rb').read() + except Exception as err: + sys.stderr.write('Error: cannot read input file: ') + sys.stderr.write(str(err)) + else: + pyg(outfile, + m.group(1), + parse_opts(opts, m.group(2)), + "", + filecontents, + usedstyles) + pos = m.end() + continue + + sys.stderr.write('Error: invalid input file contents: ignoring') + break + + outfile.write(GENERIC_DEFINITIONS_2) + + + +USAGE = """\ +Usage: %s [-o <output file name>] <input file name> + %s -h | -V + +The input file should consist of a sequence of source code snippets, as +produced by the `pygmentex` LaTeX package. Each code snippet is +highlighted using Pygments, and a LaTeX command that expands to the +highlighted code snippet is written to the output file. + +It also writes to the output file a set of LaTeX macro definitions the +Pygments styles that are used in the code snippets. + +If no output file name is given, use `<input file name>.pygmented`. + +The -e option enables escaping to LaTex. Text delimited by the <left> +and <right> characters is read as LaTeX code and typeset accordingly. It +has no effect in string literals. It has no effect in comments if +`texcomments` or `mathescape` is set. + +The -h option prints this help. + +The -V option prints the package version. +""" + + +def main(args = sys.argv): + """ + Main command line entry point. + """ + usage = USAGE % ((args[0],) * 2) + + try: + popts, args = getopt.getopt(args[1:], 'e:o:hV') + except getopt.GetoptError as err: + sys.stderr.write(usage) + return 2 + opts = {} + for opt, arg in popts: + opts[opt] = arg + + if not opts and not args: + print(usage) + return 0 + + if opts.pop('-h', None) is not None: + print(usage) + return 0 + + if opts.pop('-V', None) is not None: + print('PygmenTeX version %s, (c) 2010 by José Romildo.' % __version__) + return 0 + + if len(args) != 1: + sys.stderr.write(usage) + return 2 + infn = args[0] + try: + code = open(infn, 'rb').read() + except Exception as err: + sys.stderr.write('Error: cannot read input file: ') + sys.stderr.write(str(err)) + return 1 + + outfn = opts.pop('-o', None) + if not outfn: + root, ext = splitext(infn) + outfn = root + '.pygmented' + try: + outfile = open(outfn, 'w') + except Exception as err: + sys.stderr.write('Error: cannot open output file: ') + sys.stderr.write(str(err)) + return 1 + + convert(code, outfile) + + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main(sys.argv)) + except KeyboardInterrupt: + sys.exit(1) diff --git a/Build/source/texk/texlive/linked_scripts/scripts.lst b/Build/source/texk/texlive/linked_scripts/scripts.lst index afa4e961fea..e2017247032 100644 --- a/Build/source/texk/texlive/linked_scripts/scripts.lst +++ b/Build/source/texk/texlive/linked_scripts/scripts.lst @@ -96,6 +96,7 @@ pmxchords/pmxchords.lua pst2pdf/pst2pdf.pl ptex2pdf/ptex2pdf.lua purifyeps/purifyeps +pygmentex/pygmentex.py pythontex/pythontex.py pythontex/depythontex.py rubik/rubikrotation.pl diff --git a/Master/bin/alpha-linux/pygmentex b/Master/bin/alpha-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/alpha-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/amd64-freebsd/pygmentex b/Master/bin/amd64-freebsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/amd64-freebsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/amd64-kfreebsd/pygmentex b/Master/bin/amd64-kfreebsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/amd64-kfreebsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/amd64-netbsd/pygmentex b/Master/bin/amd64-netbsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/amd64-netbsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/armel-linux/pygmentex b/Master/bin/armel-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/armel-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/armhf-linux/pygmentex b/Master/bin/armhf-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/armhf-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-cygwin/pygmentex b/Master/bin/i386-cygwin/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-cygwin/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-freebsd/pygmentex b/Master/bin/i386-freebsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-freebsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-kfreebsd/pygmentex b/Master/bin/i386-kfreebsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-kfreebsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-linux/pygmentex b/Master/bin/i386-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-netbsd/pygmentex b/Master/bin/i386-netbsd/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-netbsd/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/i386-solaris/pygmentex b/Master/bin/i386-solaris/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/i386-solaris/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/mipsel-linux/pygmentex b/Master/bin/mipsel-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/mipsel-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/powerpc-linux/pygmentex b/Master/bin/powerpc-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/powerpc-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/sparc-solaris/pygmentex b/Master/bin/sparc-solaris/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/sparc-solaris/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/universal-darwin/pygmentex b/Master/bin/universal-darwin/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/universal-darwin/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/win32/pygmentex.exe b/Master/bin/win32/pygmentex.exe Binary files differnew file mode 100755 index 00000000000..5777d90a17a --- /dev/null +++ b/Master/bin/win32/pygmentex.exe diff --git a/Master/bin/x86_64-cygwin/pygmentex b/Master/bin/x86_64-cygwin/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/x86_64-cygwin/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/x86_64-darwin/pygmentex b/Master/bin/x86_64-darwin/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/x86_64-darwin/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/x86_64-linux/pygmentex b/Master/bin/x86_64-linux/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/x86_64-linux/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/bin/x86_64-solaris/pygmentex b/Master/bin/x86_64-solaris/pygmentex new file mode 120000 index 00000000000..049b6fd454b --- /dev/null +++ b/Master/bin/x86_64-solaris/pygmentex @@ -0,0 +1 @@ +../../texmf-dist/scripts/pygmentex/pygmentex.py
\ No newline at end of file diff --git a/Master/texmf-dist/doc/latex/pygmentex/Factorial.java b/Master/texmf-dist/doc/latex/pygmentex/Factorial.java new file mode 100644 index 00000000000..aea3cb5c8c3 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/Factorial.java @@ -0,0 +1,12 @@ +public class Factorial +{ + public static void main(String[] args) + { + int number = 5; + int factorial = 1; + for (int i = 1; i <= number; i++) + factorial = factorial * i; + System.out.println("Factorial of " + number + + " is " + factorial); + } +} diff --git a/Master/texmf-dist/doc/latex/pygmentex/README b/Master/texmf-dist/doc/latex/pygmentex/README new file mode 100644 index 00000000000..41d8062a18c --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/README @@ -0,0 +1,20 @@ +PygmenTeX is a Python-based LaTeX package that can be used for +typesetting code listings in a LaTeX document using Pygments. + +Pygments is a generic syntax highlighter for general use in all kinds of +software such as forum systems, wikis or other applications that need to +prettify source code. + +In order to use PygmenTeX you need to have Pygments installed. If you +need instructions on installing it, please refer to its home page at +http://pygments.org/. + +The file pygmentex.py should be installed as an executable file in a +directory in the PATH. + +The file pygmentex.sty should be installed in a directory where TeX +searches for input files. + +The file demo.pdf demonstrates the use of the package. + +PygmenTeX is licensed under Latex Project Public License (version 1.3). diff --git a/Master/texmf-dist/doc/latex/pygmentex/blueshade.png b/Master/texmf-dist/doc/latex/pygmentex/blueshade.png Binary files differnew file mode 100644 index 00000000000..4b1713e657c --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/blueshade.png diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.c b/Master/texmf-dist/doc/latex/pygmentex/demo.c new file mode 100644 index 00000000000..1d739f5edf3 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.c @@ -0,0 +1,22 @@ +// test.cpp + +#include <iostream> + +using namespace std; + +void greetings() +{ + string name; + cout << "What is your name? "; + cin >> name; + cout << "Hello, " + << name + << '!' + << endl; +} + +int main() +{ + greetings(); + return 0; +} diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.delphi b/Master/texmf-dist/doc/latex/pygmentex/demo.delphi new file mode 100644 index 00000000000..71e38129746 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.delphi @@ -0,0 +1,8 @@ +procedure example(a: integer); +const + A = 'jeja'; +var + sMessage: string; +begin + ShowMessage(sMessage + A); +end; diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.hs b/Master/texmf-dist/doc/latex/pygmentex/demo.hs new file mode 100644 index 00000000000..b784c890a5c --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.hs @@ -0,0 +1,7 @@ +module Main where + +-- the main IO action +main = do { putStr "What is your name? " + , name''' <- read + , putStrLn ("Hello, " ++ name''') + } diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.java b/Master/texmf-dist/doc/latex/pygmentex/demo.java new file mode 100644 index 00000000000..bda5bb322f6 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.java @@ -0,0 +1,68 @@ +import java.io.IOException; +import java.io.Reader; +import java.util.Hashtable; +import java.util.Map; + +public class Lexer +{ + private Reader in; + private int x; + + private Map<String,Token.T> reserved = + new Hashtable<String,Token.T>(); + + public Lexer(Reader in) throws IOException + { + this.in = in; + x = in.read(); + reserved.put("let", Token.T.LET); + // acrescentar demais palavras reservadas + // ... + } + + public Token get() throws IOException + { + // retornar o próximo símbolo léxico do programa + + while (Character.isWhitespace(x)) + x = in.read(); + + if (x == -1) + return new Token(Token.T.EOF); + + if ((char)x == ',') + { + x = in.read(); + return new Token(Token.T.COMMA); + } + + if (Character.isDigit(x)) + { + StringBuilder builder = new StringBuilder(); + builder.append((char)x); + while (Character.isDigit((x = in.read()))) + builder.append((char)x); + return new Token(Token.T.INT, new Long(builder.toString())); + } + + if (Character.isAlphabetic(x)) + { + StringBuilder builder = new StringBuilder(); + builder.append((char)x); + while (Character.isAlphabetic(x = in.read()) || + Character.isDigit(x) || (char)x == '_') + builder.append((char)x); + String s = builder.toString(); + Token.T t = reserved.get(s); + if (t == null) + return new Token(Token.T.ID, s); + return new Token(t); + } + + // completar demais tokens + + System.out.println("unexpectec char: <" + (char)x + ">"); + x = in.read(); + return get(); + } +} diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.pas b/Master/texmf-dist/doc/latex/pygmentex/demo.pas new file mode 100644 index 00000000000..5d63cc6e2d2 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.pas @@ -0,0 +1,7 @@ +Program HelloWorld(output) +var + msg : String +begin + msg = 'Hello, world!'; + Writeln(msg) +end. diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.pdf b/Master/texmf-dist/doc/latex/pygmentex/demo.pdf Binary files differnew file mode 100644 index 00000000000..ccebf5004ad --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.pdf diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.py b/Master/texmf-dist/doc/latex/pygmentex/demo.py new file mode 100644 index 00000000000..a5fa60eed43 --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- + +def parse_opts(dic, opts): + for opt in re.split(r'\s*,\s*', opts): + x = re.split(r'\s*=\s*', opt) + if len(x) == 2 and x[0] and x[1]: + dic[x[0]] = x[1] + elif len(x) == 1 and x[0]: + dic[x[0]] = True + return dic diff --git a/Master/texmf-dist/doc/latex/pygmentex/demo.tex b/Master/texmf-dist/doc/latex/pygmentex/demo.tex new file mode 100644 index 00000000000..03fe3ac0a1b --- /dev/null +++ b/Master/texmf-dist/doc/latex/pygmentex/demo.tex @@ -0,0 +1,852 @@ +\documentclass[10pt,a4paper]{article} + +%\usepackage[margin=13mm]{geometry} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage[font=normalsize,format=plain,labelfont=bf,up,textfont=it,up]{caption} +\usepackage{xcolor} +\usepackage{hyperref} +\usepackage[framemethod=tikz]{mdframed} +\usepackage{tcolorbox} +\usepackage{fvrb-ex} +\usepackage{tikz} +\usepackage{calc} +\usepackage{pygmentex} +\usepackage{lipsum} + +\fvset{gobble=0,showtabs,tabsize=1,frame=lines,framerule=1pt,numbers=left,fontsize=\scriptsize} + +\tcbuselibrary{skins,breakable} + +\definecolor{shadecolor}{rgb}{0.9,0.9,0.9} +\definecolor{lightgreen}{rgb}{0.8,0.95,0.8} + +\begin{document} + +\title{Testing the Pygmen\TeX{} package} +\author{José Romildo Malaquias} +\maketitle + +\section{The Pygmen\TeX{} package} + +This document demonstrates how to use the Pygment\TeX{} package to +typeset code listings with \LaTeX{} and +Pygments\footnote{\url{http://pygments.org/}}. + +Pygments is a generic syntax highlighter for general use in all kinds of +software such as forum systems, wikis or other applications that need to +prettify source code. + +Pygmen\TeX{} provides an environment and two commands for typesetting code +listings in a \LaTeX{} document: +\begin{itemize} + \item the \verb|pygmented| environment typesets its contents as a + source code listing, + \item the \verb|includepygmented| command typesets the contents of a + file, including the result in the \LaTeX{} document, and + \item the \verb|\pyginline| command typesets its contents, keeping the + result in the same line. +\end{itemize} +They accept many options that allow the user to configure the listing in +many ways. + +Read the remaining of this document to have an idea of what the package +is capable of. + +\section{How to use the package} + +In order to use the package, start by putting +\begin{verbatim} +\usepackage{pygmentex} +\end{verbatim} +in the preamble of the document. + +Use the environment or commands mentioned previously to include source +code listings on your document. + +When compiling the document (with \texttt{pdflatex}, for instance), all +the source code listings in the document wil be collected and saved in a +temporary file with the extension \texttt{.snippets} in its name. Then +the auxiliary program \texttt{pygmentex} (a Python application +distributed with the Pygmen\TeX{} package) should be run taking this +file as input. It will produce another temporary file with the extension +\texttt{.pygmented}, containing \LaTeX{} code for the code listings +previously collected. The next time the document is compiled, they are +included to produce the final typeset document. + +The programming language of the listing code can be specified using the +\verb|lang| option. + +To get a list of all available languages, execute the following command +on the command line: +\begin{verbatim} +$ pygmentize -L lexers +\end{verbatim} + +\section{First examples} + +The followig C program reads two integers and calculates their sum. + +\begin{Example} +\begin{pygmented}[lang=c] +#include <stdio.h> +int main(void) +{ + int a, b, c; + printf("Enter two numbers to add: "); + scanf("%d%d", &a, &b); + c = a + b; + printf("Sum of entered numbers = %d\n", c); + return 0; +} +\end{pygmented} +\end{Example} + +\begin{Example} + In this program, \pyginline[lang=c]|int| is a type and + \pyginline[lang=c]|"Enter two numbers to add: "| is a literal string. +\end{Example} + +Next you can see a Java program to calculate the factorial of a number. + +\begin{Example} +\inputpygmented[lang=java]{Factorial.java} +\end{Example} + +\section{Choosing different Pygments styles} + +Instead of using the default style you may choose another stylesheet +provided by Pygments by its name using the \verb|sty| option. + +To get a list of all available stylesheets, execute the following +command on the command line: +\begin{verbatim} +$ pygmentize -L styles +\end{verbatim} + +Creating your own styles is also very easy. Just follow the instructions +provided on the website. + +As examples you can see a C program typeset with different styles. + +\begin{Example} +\noindent +\begin{minipage}[t]{0.49\linewidth} + \begin{pygmented}[lang=c,gobble=4,sty=murphy] + #include<stdio.h> + main() + { int n; + printf("Enter a number: "); + scanf("%d",&n); + if ( n%2 == 0 ) + printf("Even\n"); + else + printf("Odd\n"); + return 0; + } + \end{pygmented} +\end{minipage} +\hfil +\begin{minipage}[t]{0.49\linewidth} + \begin{pygmented}[lang=c,gobble=4,sty=trac] + #include<stdio.h> + main() + { int n; + printf("Enter a number: "); + scanf("%d",&n); + if ( n%2 == 0 ) + printf("Even\n"); + else + printf("Odd\n"); + return 0; + } + \end{pygmented} +\end{minipage} +\end{Example} + +\section{Choosing a font} + +The value of the option \verb|font| is typeset before the content of the +listing. Usualy it is used to specify a font to be used. See the +following example. + +\begin{Example} +\begin{pygmented}[lang=scala,font=\rmfamily\scshape\large] +object bigint extends Application { + def factorial(n: BigInt): BigInt = + if (n == 0) 1 else n * factorial(n-1) + + val f50 = factorial(50); val f49 = factorial(49) + println("50! = " + f50) + println("49! = " + f49) + println("50!/49! = " + (f50 / f49)) +} +\end{pygmented} +\end{Example} + +\section{Changing the background color} + +The option \verb|colback| can be used to choose a background color, as +is shown in the folowing example. + +\begin{Example} +\begin{pygmented}[lang=fsharp,colback=green!25] +let rec factorial n = + if n = 0 + then 1 + else n * factorial (n - 1) +System.Console.WriteLine(factorial anInt) +\end{pygmented} +\end{Example} + + +\section{Supressing initial characters} + +The option \verb|gobble| specifies the number of characters to suppress +at the beginning of each line (up to a maximum of 9). This is mainly +useful when environments are indented (Default: empty — no character +suppressed). + +\begin{Example} +A code snippet inside a minipage: +\begin{minipage}[t]{.5\linewidth} + \begin{pygmented}[lang=d,gobble=8] + ulong fact(ulong n) + { + if(n < 2) + return 1; + else + return n * fact(n - 1); + } + \end{pygmented} +\end{minipage} +\end{Example} + + +\section{Size of tabulator} + +The option \verb|tabsize| specifies the number of of spaces given by a +tab character (Default: 8). + +\begin{Verbatim}[showtabs,tabsize=1] +\begin{pygmented}[lang=common-lisp,tabsize=4] +;; Triple the value of a number +(defun triple (X) + "Compute three times X." + (* 3 X)) +\end{pygmented} +\end{Verbatim} + +\begin{pygmented}[lang=common-lisp,tabsize=4] +;; Triple the value of a number +(defun triple (X) + "Compute three times X." + (* 3 X)) +\end{pygmented} + + +\section{Numbering lines} + +The lines of a listing can be numbered. The followig options control +numbering of lines. +\begin{itemize} + \item Line numbering is enabled or disable with the \verb|linenos| + boolean option. + \item The number used for the first line can be set with the option + \verb|linenostart|. + \item The step between numbered lines can be set with the option + \verb|linenostep|. + \item The space between the line number and the line of the listing + can be set with the option \verb|linenosep|. +\end{itemize} + +In the followig listing you can see a Scheme function to calculate the +factorial of a number. + +\begin{Example} +\begin{pygmented}[lang=scheme,linenos,linenostart=1001,linenostep=2,linenosep=5mm] +;; Building a list of squares from 0 to 9. +;; Note: loop is simply an arbitrary symbol used as +;; a label. Any symbol will do. + +(define (list-of-squares n) + (let loop ((i n) (res '())) + (if (< i 0) + res + (loop (- i 1) (cons (* i i) res))))) +\end{pygmented} +\end{Example} + +\section{Captioning} + +The option \verb|caption| can be used to set a caption for the listing. +The option \verb|label| allows the assignment of a label to the listing. + +Here is an example: + +\begin{Example} +\begin{pygmented}[lang=c++,label=lst:test,caption=A \textbf{C++} example] +// This program adds two numbers and prints their sum. +#include <iostream> +int main() +{ + int a; + int b; + int sum; + sum = a + b; + std::cout << "The sum of " << a << " and " << b + << " is " << sum << "\n"; + return 0; +} +\end{pygmented} +\end{Example} + +\begin{Example} + Listing \ref{lst:test} is a C++ program. +\end{Example} + +\section{Escaping to \LaTeX{} inside a code snippet} + +The option \verb|texcomments|, if set to \texttt{true}, enables \LaTeX{} +comment lines. That is, LaTex markup in comment tokens is not escaped +so that \LaTeX{} can render it. + +The \verb|mathescape|, if set to \texttt{true}, enables \LaTeX{} math +mode escape in comments. That is, \verb|$...$| inside a comment will +trigger math mode. + +The option \verb|escapeinside|, if set to a string of length two, +enables escaping to \LaTeX{}. Text delimited by these two characters +is read as \LaTeX{} code and typeset accordingly. It has no effect in +string literals. It has no effect in comments if \verb|texcomments| or +\verb|mathescape| is set. + +Some examples follows. + +\begin{Example} +\begin{pygmented}[lang=c++,texcomments] +#include <iostream> +using namespace std; +main() +{ + cout << "Hello World"; // prints \underline{Hello World} + return 0; +} +\end{pygmented} +\end{Example} + +\begin{Example} +\begin{pygmented}[lang=python,mathescape] +# Returns $\sum_{i=1}^{n}i$ +def sum_from_one_to(n): + r = range(1, n + 1) + return sum(r) +\end{pygmented} +\end{Example} + +\begin{Example} +\begin{pygmented}[lang=c,escapeinside=||] + +if (|\textit{condition}|) + |\textit{command$_1$}| +else + |\textit{command$_2$}| +\end{pygmented} +\end{Example} + + +\section{Enclosing command and environment} + +After being prettified by Pygments, the listings are enclosed in a +command (for \verb|\pyginline|) or in an environment (for +\verb|pygmented| and \verb|includepygmented|). By default +\verb|\pyginline| uses the command \verb|\efbox| from the \texttt{efbox} +package, and \verb|pygmented| and \verb|includepygmented| use the +environment \verb|mdframed| from the \texttt{mdframed} package. + +The enclosing command or environment should be configurable using a list +of key-value pairs written between square brackets. + +The enclosing command for +\verb|\pyginline| can be changed with the option +\verb|inline method|. For instance, in the following the command +\verb|\tcbox| from the \verb|tcolorbox| package is used: + +\begin{Example} + In the previous Java program, + \pyginline[lang=java,inline method=tcbox]|"Factorial of "| is a + literal string. +\end{Example} + +The enclosing environment for \verb|pygmented| and +\verb|includepygmented| can be changed with the option +\verb|boxing method|. For instance, here is a hello world program in +C\#, enclosed in a \verb|tcolorbox| environment: + +\begin{Example} +\begin{pygmented}[lang=csharp,boxing method=tcolorbox] +using System; +class Program +{ + public static void Main(string[] args) + { + Console.WriteLine("Hello, world!"); + } +} +\end{pygmented} +\end{Example} + +Any option unknown to Pygmen\TeX{} are passed to the enclosing command +or environment. + +For instance: + +\begin{Example} +\begin{pygmented}[lang=xml,boxing method=tcolorbox,colframe=red,boxrule=2mm] +<!-- This is a note --> +<note> + <to>Tove</to> + <from>Jani</from> + <heading>Reminder</heading> + <body>Don't forget me this weekend!</body> +</note> +\end{pygmented} +\end{Example} + +\section{Setting global options for Pygmen\TeX{}} + +Global options can be setting using the \verb|setpygmented| command. +See the examples that follows. + +\begin{Example} +\setpygmented{lang=haskell, colback=red!30, font=\ttfamily\small} + +\begin{pygmented}[] +sum :: Num a => [a] -> a +sum [] = 0 +sum (x:xs) = x + sum xs +\end{pygmented} +\end{Example} + +\begin{Example} +\begin{pygmented}[colback=blue!20, boxing method=tcolorbox] +elem :: Eq a => a -> [a] -> Bool +elem _ [] = False +elem x (y:ys) = x == y || elem x ys +\end{pygmented} +\end{Example} + +\begin{Example} +\setpygmented{lang=snobol} + +\begin{pygmented}[] + OUTPUT = "What is your name?" + Username = INPUT + OUTPUT = "Thank you, " Username +END +\end{pygmented} +\end{Example} + +\begin{Example} +\setpygmented{test/.style={colback=yellow!33,boxing method=tcolorbox,colframe=blue}} + +\begin{pygmented}[test, lang=vbnet] +Module Module1 + Sub Main() + Console.WriteLine("Hello, world!") + End Sub +End Module +\end{pygmented} +\end{Example} + +\begin{Example} +\begin{pygmented}[lang=tcl] +puts "Hello, world!" +\end{pygmented} +\end{Example} + +\section{More examples of inline code snippets} + +\begin{Example} + An inline source code snippet: + \pyginline[lang=c]|const double alfa = 3.14159;|. + This is a C declaration with initialization. +\end{Example} + +\begin{Example} + \pyginline[lang=prolog,colback=yellow]=avo(A,B) :- pai(A,X), pai(X,B).= + is a Prolog clause. Its head is + \pyginline[lang=prolog,sty=emacs,colback=yellow,linecolor=red]=avo(A,B)= + and its body is + \pyginline[lang=prolog,sty=vim,colback=black,hidealllines]=pai(A,X), pai(X,B)=. +\end{Example} + +\begin{Example} + See the identifier \pyginline[inline method=efbox,colback=green!25]|variable|, + which names something. String literals in C looks like + \pyginline[lang=c,inline method=tcbox,colback=blue!20,boxrule=2pt]|"hello, world!\n"|. +\end{Example} + +\setpygmented{colback=shadecolor} + +\begin{Example} + This one + \pyginline[lang=ocaml,font=\ttfamily\scriptsize,topline=false]:let x = [1;2;3] in length x: + is an OCaml expression with local bindings. With OCaml one can do + imperative, functional and object oriented programming. +\end{Example} + +\begin{Example} + Now some Java code: + \pyginline[lang=java,sty=colorful,font=\ttfamily\itshape,linewidth=1pt]|public int f(double x)|. + This is a method header. +\end{Example} + +\section{More examples of displayed code snippets} + +\setpygmented{lang=scheme,colback=shadecolor,sty=emacs} + +In listing \ref{lst:fact} you can see a function definition in the +Scheme language. This function computes the factorial of a natural +number. +\newline\rule{\linewidth}{2pt} +\begin{pygmented}[ + sty=emacs, + linenos, + label=lst:fact, + caption=A Scheme function. + ] +(define fact + (lambda (n) + (if (= n 0) + 1 + (* n (fact (- n 1)))))) +\end{pygmented} + +Here you have some more code to further testing the package. Listing +\ref{lst:haskell} is a Haskell program. When run this program interacts +with the user asking the user name, reading a line input by the user, +and showing a greeting message to the user. + +\inputpygmented[% + lang=haskell, + linenos, + linenostart=79831, + innerlinecolor=yellow, innerlinewidth=6pt, + middlelinecolor=blue, middlelinewidth=10pt, + outerlinecolor=green, outerlinewidth=12pt, + roundcorner=4, + colback=shadecolor, + caption=A haskell interactive program, + label=lst:haskell, + ]{demo.hs} + +This is a rule: + +\noindent\rule{\linewidth}{2pt} + +Now a Pascal procedure: + +\inputpygmented[ + lang=delphi, + linewidth=1.5pt, + font=\ttfamily\sffamily\large, + colback=yellow + ]{demo.delphi} +and a Pascal program +\inputpygmented[lang=pascal,linenos,linenostart=5801]{demo.pas} + +A Python code snippet: + +\inputpygmented[ + lang=python, + sty=emacs, + linenos, + linenostep=3, + linewidth=1pt, + colback=lightgreen + ]{demo.py} + +\section{Using code snippets in environments} + +The following is a \textbf{description} environment. + +\begin{description} + \item[An item] \lipsum[31] + \begin{pygmented}[lang=scala,colback=yellow, + % title=Item A + ] +def qsort(xs: List[Int]): List[Int] = + xs match { + case Nil => + Nil + case pivot :: tail => + qsort(tail filter { _ < pivot }) ::: + pivot :: qsort(tail filter { _ >= pivot }) + } + \end{pygmented} + \lipsum[32] + + \item[Another item] \lipsum[33] + \begin{pygmented}[lang=lua,colback=yellow] +function entry0 (o) + N=N + 1 + local title = o.title or '(no title)' + fwrite('<LI><A HREF="#%d">%s</A>\n', N, title) +end + \end{pygmented} + \lipsum[34] +\end{description} + +\section{A long program} + +Here you can read the source code for a hand written lexical analyser +for the \emph{straight-line} programming language that I have developed +in Java. + +\inputpygmented[boxing method=mdframed,lang=java,sty=autumn,colback=red!8,font=\ttfamily\small,tabsize=2,frametitle=\emph{Ad hoc} lexical analyser]{demo.java} + +\section{Some fancy examples using \texttt{tcolorbox}} + +The followig example uses \texttt{tcolorbox} to typeset the code +listing. + +\newcounter{example} +\newlength{\examlen} +\colorlet{colexam}{red!75!black} + +\begin{pygmented}[boxing method=tcolorbox,lang=scala, + title=Example \arabic{example}: hello from \texttt{Scala}, + code={\refstepcounter{example}% + \settowidth{\examlen}{\Large\bfseries Example \arabic{example}}},% + coltitle=colexam,fonttitle=\Large\bfseries, + enhanced,breakable, + before=\par\medskip, + parbox=false, + frame hidden,interior hidden,segmentation hidden, + boxsep=0pt,left=0pt,right=3mm,toptitle=2mm,pad at break=0mm, + overlay unbroken={\draw[colexam,line width=1pt] (frame.north west) + --([xshift=-0.5pt]frame.north east)--([xshift=-0.5pt]frame.south east) + --(frame.south west); + \draw[colexam,line width=2pt] ([yshift=0.5pt]frame.north west) + -- +(\examlen,0pt);}, + overlay first={\draw[colexam,line width=1pt] (frame.north west) + --([xshift=-0.5pt]frame.north east)--([xshift=-0.5pt]frame.south east); + \draw[red!75!black,line width=2pt] ([yshift=0.5pt]frame.north west) + -- +(\examlen,0pt);}, + overlay middle={\draw[colexam,line width=1pt] ([xshift=-0.5pt]frame.north east) + --([xshift=-0.5pt]frame.south east); }, + overlay last={\draw[colexam,line width=1pt] ([xshift=-0.5pt]frame.north east) + --([xshift=-0.5pt]frame.south east)--(frame.south west);}% + ] +object HelloWorld extends App { + println("Hello, world!") +}\end{pygmented} + +\begin{pygmented}[boxing method=tcolorbox,lang=java, + enhanced,colback=blue!10!white,colframe=orange,top=4mm, + enlarge top by=\baselineskip/2+1mm, + enlarge top at break by=0mm,pad at break=2mm, + fontupper=\normalsize, + overlay unbroken and first={% + \node[rectangle,rounded corners,draw=black,fill=blue!20!white, + inner sep=1mm,anchor=west,font=\small] + at ([xshift=4.5mm]frame.north west) {\strut\textbf{My fancy title}};}, + ] +public class Hello { + public static void main(String[] args) { + System.out.println("Hello, world!") + } +} +\end{pygmented} + +\begin{pygmented}[boxing method=tcolorbox,lang=haskell, + enhanced,sharp corners=uphill, + colback=blue!25!white,colframe=blue!25!black,coltext=blue!90!black, + fontupper=\Large\bfseries,arc=6mm,boxrule=2mm,boxsep=5mm, + borderline={0.3mm}{0.3mm}{white} + ] +module Main (main) where + +main :: IO () +main = putStrLn "Hello, world!" +\end{pygmented} + +\begin{pygmented}[boxing method=tcolorbox,lang=c++, + enhanced,frame style image=blueshade.png, + opacityback=0.75,opacitybacktitle=0.25, + colback=blue!5!white,colframe=blue!75!black, + title=My title + ] +#include <iostream> +using namespace std; +int main(int argc, char** argv) { + cout << "Hello, world!" << endl; + return 0; +} +\end{pygmented} + +\begin{pygmented}[boxing method=tcolorbox,lang=d, + enhanced,attach boxed title to top center={yshift=-3mm,yshifttext=-1mm}, + colback=blue!5!white,colframe=blue!75!black,colbacktitle=red!80!black, + title=My title,fonttitle=\bfseries, + boxed title style={size=small,colframe=red!50!black} + ] +/* This program prints a + hello world message + to the console. */ + +import std.stdio; + +void main() +{ + writeln("Hello, World!"); +} +\end{pygmented} + + +\section{Some fancy examples using \texttt{mdframed}} + +The followig example uses \texttt{mdframed} to typeset the code listing. + +\global\mdfdefinestyle{exampledefault}{% + linecolor=red,linewidth=3pt,% + leftmargin=1cm,rightmargin=1cm +} + +\begin{pygmented}[boxing method=mdframed,lang=ada,style=exampledefault] +with Ada.Text_IO; + +procedure Hello_World is + use Ada.Text_IO; +begin + Put_Line("Hello, world!"); +end; +\end{pygmented} + +\global\mdfapptodefinestyle{exampledefault}{% + topline=false,bottomline=false, +} + +\begin{pygmented}[boxing method=mdframed,lang=pascal,style=exampledefault,frametitle={Saying \emph{hello} from Pascal}] +program HelloWorld; + +begin + WriteLn('Hello, world!'); +end. +\end{pygmented} + +\global\mdfdefinestyle{separateheader}{% + frametitle={% + \tikz[baseline=(current bounding box.east),outer sep=0pt] + \node[anchor=east,rectangle,fill=blue!20] + {\strut Saying \emph{hello} in Modula-2};}, + innertopmargin=10pt,linecolor=blue!20,% + linewidth=2pt,topline=true, + frametitleaboveskip=\dimexpr-\ht\strutbox\relax, + frametitlerule=false, + backgroundcolor=white, +} + +\begin{pygmented}[boxing method=mdframed,lang=modula2,style=separateheader] +MODULE Hello; +FROM STextIO IMPORT WriteString; +BEGIN + WriteString("Hello World!"); +END Hello. +\end{pygmented} + + +\tikzset{titregris/.style = + {draw=gray, thick, fill=white, shading = exersicetitle, % + text=gray, rectangle, rounded corners, right,minimum height=.7cm}} +\pgfdeclarehorizontalshading{exersicebackground}{100bp} + {color(0bp)=(green!40); color(100bp)=(black!5)} +\pgfdeclarehorizontalshading{exersicetitle}{100bp} + {color(0bp)=(red!40);color(100bp)=(black!5)} +\newcounter{exercise} +\renewcommand*\theexercise{Exercise~n\arabic{exercise}} +\makeatletter +\def\mdf@@exercisepoints{}%new mdframed key: +\define@key{mdf}{exercisepoints}{% + \def\mdf@@exercisepoints{#1} +} +\mdfdefinestyle{exercisestyle}{% + outerlinewidth=1em,outerlinecolor=white,% + leftmargin=-1em,rightmargin=-1em,% + middlelinewidth=1.2pt,roundcorner=5pt,linecolor=gray, + apptotikzsetting={\tikzset{mdfbackground/.append style ={% + shading = exersicebackground}}}, + innertopmargin=1.2\baselineskip, + skipabove={\dimexpr0.5\baselineskip+\topskip\relax}, + skipbelow={-1em}, + needspace=3\baselineskip, + frametitlefont=\sffamily\bfseries, + settings={\global\stepcounter{exercise}}, + singleextra={% + \node[titregris,xshift=1cm] at (P-|O) % + {~\mdf@frametitlefont{\theexercise}\hbox{~}}; + \ifdefempty{\mdf@@exercisepoints}% + {}% + {\node[titregris,left,xshift=-1cm] at (P)% + {~\mdf@frametitlefont{\mdf@@exercisepoints points}\hbox{~}};}% + }, + firstextra={% + \node[titregris,xshift=1cm] at (P-|O) % + {~\mdf@frametitlefont{\theexercise}\hbox{~}}; + \ifdefempty{\mdf@@exercisepoints}% + {}% + {\node[titregris,left,xshift=-1cm] at (P)% + {~\mdf@frametitlefont{\mdf@@exercisepoints points}\hbox{~}};}% + }, +} +\makeatother + +\begin{pygmented}[boxing method=mdframed,lang=go,style=exercisestyle] +// hello world in 'go' +package main + +import "fmt" + +func main() { + fmt.Println("Hello, world!") +} +\end{pygmented} + +\begin{pygmented}[boxing method=mdframed,lang=objective-c,style=exercisestyle,exercisepoints=10] +/* hello from objective-c */ + +#import <stdio.h> +#import <Foundation/Foundation.h> + +int main(void) +{ + NSLog(@"Hello, world!\n"); + return 0; +} +\end{pygmented} + +\mdfdefinestyle{another}{% + linecolor=red,middlelinewidth=2pt,% + frametitlerule=true,% + apptotikzsetting={\tikzset{mdfframetitlebackground/.append style={% + shade,left color=white, right color=blue!20}}}, + frametitlerulecolor=green!60, + frametitlerulewidth=1pt, + innertopmargin=\topskip, +} + +\begin{pygmented}[boxing method=mdframed,lang=c,style=another,frametitle={Hello from C}] +#include <stdio.h> +int main(int argc, char **argv) { + printf("Hello, world!\n"); + return 0; +} +\end{pygmented} + + +\section{Conclusion} + +That is all. + +\end{document} diff --git a/Master/texmf-dist/scripts/pygmentex/pygmentex.py b/Master/texmf-dist/scripts/pygmentex/pygmentex.py new file mode 100755 index 00000000000..42cef96faea --- /dev/null +++ b/Master/texmf-dist/scripts/pygmentex/pygmentex.py @@ -0,0 +1,523 @@ +#! /usr/bin/env python2 +# -*- coding: utf-8 -*- + +""" + PygmenTeX + ~~~~~~~~~ + + PygmenTeX is a converter that do syntax highlighting of snippets of + source code extracted from a LaTeX file. + + :copyright: Copyright 2014 by José Romildo Malaquias + :license: BSD, see LICENSE for details +""" + +__version__ = '0.8' +__docformat__ = 'restructuredtext' + +import sys +import getopt +import re +from os.path import splitext + +from pygments import highlight +from pygments.styles import get_style_by_name +from pygments.lexers import get_lexer_by_name +from pygments.formatters.latex import LatexFormatter, escape_tex, _get_ttype_name +from pygments.util import get_bool_opt, get_int_opt +from pygments.lexer import Lexer +from pygments.token import Token + +################################################### +# The following code is in >=pygments-2.0 +################################################### +class EnhancedLatexFormatter(LatexFormatter): + r""" + This is an enhanced LaTeX formatter. + """ + name = 'EnhancedLaTeX' + aliases = [] + + def __init__(self, **options): + LatexFormatter.__init__(self, **options) + self.escapeinside = options.get('escapeinside', '') + if len(self.escapeinside) == 2: + self.left = self.escapeinside[0] + self.right = self.escapeinside[1] + else: + self.escapeinside = '' + + def format_unencoded(self, tokensource, outfile): + # TODO: add support for background colors + t2n = self.ttype2name + cp = self.commandprefix + + if self.full: + realoutfile = outfile + outfile = StringIO() + + outfile.write(u'\\begin{Verbatim}[commandchars=\\\\\\{\\}') + if self.linenos: + start, step = self.linenostart, self.linenostep + outfile.write(u',numbers=left' + + (start and u',firstnumber=%d' % start or u'') + + (step and u',stepnumber=%d' % step or u'')) + if self.mathescape or self.texcomments or self.escapeinside: + outfile.write(u',codes={\\catcode`\\$=3\\catcode`\\^=7\\catcode`\\_=8}') + if self.verboptions: + outfile.write(u',' + self.verboptions) + outfile.write(u']\n') + + for ttype, value in tokensource: + if ttype in Token.Comment: + if self.texcomments: + # Try to guess comment starting lexeme and escape it ... + start = value[0:1] + for i in xrange(1, len(value)): + if start[0] != value[i]: + break + start += value[i] + + value = value[len(start):] + start = escape_tex(start, self.commandprefix) + + # ... but do not escape inside comment. + value = start + value + elif self.mathescape: + # Only escape parts not inside a math environment. + parts = value.split('$') + in_math = False + for i, part in enumerate(parts): + if not in_math: + parts[i] = escape_tex(part, self.commandprefix) + in_math = not in_math + value = '$'.join(parts) + elif self.escapeinside: + text = value + value = '' + while len(text) > 0: + a,sep1,text = text.partition(self.left) + if len(sep1) > 0: + b,sep2,text = text.partition(self.right) + if len(sep2) > 0: + value += escape_tex(a, self.commandprefix) + b + else: + value += escape_tex(a + sep1 + b, self.commandprefix) + else: + value = value + escape_tex(a, self.commandprefix) + else: + value = escape_tex(value, self.commandprefix) + elif ttype not in Token.Escape: + value = escape_tex(value, self.commandprefix) + styles = [] + while ttype is not Token: + try: + styles.append(t2n[ttype]) + except KeyError: + # not in current style + styles.append(_get_ttype_name(ttype)) + ttype = ttype.parent + styleval = '+'.join(reversed(styles)) + if styleval: + spl = value.split('\n') + for line in spl[:-1]: + if line: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, line)) + outfile.write('\n') + if spl[-1]: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1])) + else: + outfile.write(value) + + outfile.write(u'\\end{Verbatim}\n') + + if self.full: + realoutfile.write(DOC_TEMPLATE % + dict(docclass = self.docclass, + preamble = self.preamble, + title = self.title, + encoding = self.encoding or 'latin1', + styledefs = self.get_style_defs(), + code = outfile.getvalue())) + +class LatexEmbeddedLexer(Lexer): + r""" + + This lexer takes one lexer as argument, the lexer for the language + being formatted, and the left and right delimiters for escaped text. + + First everything is scanned using the language lexer to obtain + strings and comments. All other consecutive tokens are merged and + the resulting text is scanned for escaped segments, which are given + the Token.Escape type. Finally text that is not escaped is scanned + again with the language lexer. + """ + def __init__(self, left, right, lang, **options): + self.left = left + self.right = right + self.lang = lang + Lexer.__init__(self, **options) + + def get_tokens_unprocessed(self, text): + buf = '' + for i, t, v in self.lang.get_tokens_unprocessed(text): + if t in Token.Comment or t in Token.String: + if buf: + for x in self.get_tokens_aux(idx, buf): + yield x + buf = '' + yield i, t, v + else: + if not buf: + idx = i + buf += v + if buf: + for x in self.get_tokens_aux(idx, buf): + yield x + + def get_tokens_aux(self, index, text): + while text: + a, sep1, text = text.partition(self.left) + if a: + for i, t, v in self.lang.get_tokens_unprocessed(a): + yield index + i, t, v + index += len(a) + if sep1: + b, sep2, text = text.partition(self.right) + if sep2: + yield index + len(sep1), Token.Escape, b + index += len(sep1) + len(b) + len(sep2) + else: + yield index, Token.Error, sep1 + index += len(sep1) + text = b +################################################### + +GENERIC_DEFINITIONS_1 = r'''% -*- mode: latex -*- + +\makeatletter + +\newdimen\LineNumberWidth +''' + +GENERIC_DEFINITIONS_2 = r''' +\makeatother +''' + + +INLINE_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \pygmented@snippet@inlined{%% +%(body)s%% +}} +''' + +DISPLAY_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \begin{pygmented@snippet@framed}%% +%(body)s%% + \end{pygmented@snippet@framed}%% +} +''' + +DISPLAY_LINENOS_SNIPPET_TEMPLATE = r''' +\expandafter\def\csname pygmented@snippet@%(number)s\endcsname{%% + \begingroup + \def\pygmented@alllinenos{(%(linenumbers)s)}%% + \begin{pygmented@snippet@framed}%% +%(body)s%% + \end{pygmented@snippet@framed}%% + \endgroup +} +''' + + +def pyg(outfile, n, opts, extra_opts, text, usedstyles, inline_delim = ''): + try: + lexer = get_lexer_by_name(opts['lang']) + except ClassNotFound as err: + sys.stderr.write('Error: ') + sys.stderr.write(str(err)) + return "" + + # global _fmter + _fmter = EnhancedLatexFormatter() + + escapeinside = opts.get('escapeinside', '') + if len(escapeinside) == 2: + left = escapeinside[0] + right = escapeinside[1] + _fmter.escapeinside = escapeinside + _fmter.left = left + _fmter.right = right + lexer = LatexEmbeddedLexer(left, right, lexer) + + gobble = abs(get_int_opt(opts, 'gobble', 0)) + if gobble: + lexer.add_filter('gobble', n=gobble) + + tabsize = abs(get_int_opt(opts, 'tabsize', 0)) + if tabsize: + lexer.tabsize = tabsize + + encoding = opts['encoding'] + if encoding == 'guess': + try: + import chardet + except ImportError: + try: + text = text.decode('utf-8') + if text.startswith(u'\ufeff'): + text = text[len(u'\ufeff'):] + encoding = 'utf-8' + except UnicodeDecodeError: + text = text.decode('latin1') + encoding = 'latin1' + else: + encoding = chardet.detect(text)['encoding'] + text = text.decode(encoding) + else: + text = text.decode(encoding) + + lexer.encoding = '' + _fmter.encoding = encoding + + stylename = opts['sty'] + + _fmter.style = get_style_by_name(stylename) + _fmter._create_stylesheet() + + _fmter.texcomments = get_bool_opt(opts, 'texcomments', False) + _fmter.mathescape = get_bool_opt(opts, 'mathescape', False) + + if stylename not in usedstyles: + styledefs = _fmter.get_style_defs() \ + .replace('#', '##') \ + .replace(r'\##', r'\#') \ + .replace(r'\makeatletter', '') \ + .replace(r'\makeatother', '') \ + .replace('\n', '%\n') + outfile.write( + '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs)) + usedstyles.append(stylename) + + x = highlight(text, lexer, _fmter) + + m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z', + x) + if m: + linenos = get_bool_opt(opts, 'linenos', False) + linenostart = abs(get_int_opt(opts, 'linenostart', 1)) + linenostep = abs(get_int_opt(opts, 'linenostep', 1)) + lines0 = m.group(2).split('\n') + numbers = [] + lines = [] + counter = linenostart + for line in lines0: + line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line) + line = re.sub(r' ', '~', line) + if linenos: + if (counter - linenostart) % linenostep == 0: + line = r'\pygmented@lineno@do{' + str(counter) + '}' + line + numbers.append(str(counter)) + counter = counter + 1 + lines.append(line) + if inline_delim: + outfile.write(INLINE_SNIPPET_TEMPLATE % + dict(number = n, + style = stylename, + options = extra_opts, + body = '\\newline\n'.join(lines))) + else: + if linenos: + template = DISPLAY_LINENOS_SNIPPET_TEMPLATE + else: + template = DISPLAY_SNIPPET_TEMPLATE + outfile.write(template % + dict(number = n, + style = stylename, + options = extra_opts, + linenosep = opts['linenosep'], + linenumbers = ','.join(numbers), + body = '\\newline\n'.join(lines))) + + + +def parse_opts(basedic, opts): + dic = basedic.copy() + for opt in re.split(r'\s*,\s*', opts): + x = re.split(r'\s*=\s*', opt) + if len(x) == 2 and x[0] and x[1]: + dic[x[0]] = x[1] + elif len(x) == 1 and x[0]: + dic[x[0]] = True + return dic + + + +_re_display = re.compile( + r'^<@@pygmented@display@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@display@\1$', + re.MULTILINE) + +_re_inline = re.compile( + r'^<@@pygmented@inline@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@inline@\1$', + re.MULTILINE) + +_re_input = re.compile( + r'^<@@pygmented@input@(\d+)\n(.*)\n([\s\S]*?)\n>@@pygmented@input@\1$', + re.MULTILINE) + +def convert(code, outfile): + """ + Convert ``code`` + """ + outfile.write(GENERIC_DEFINITIONS_1) + + opts = { 'lang' : 'c', + 'sty' : 'default', + 'linenosep' : '0pt', + 'tabsize' : '8', + 'encoding' : 'guess', + } + + usedstyles = [ ] + styledefs = '' + + pos = 0 + + while pos < len(code): + if code[pos].isspace(): + pos = pos + 1 + continue + + m = _re_inline.match(code, pos) + if m: + pyg(outfile, + m.group(1), + parse_opts(opts.copy(), m.group(2)), + '', + m.group(3), + usedstyles, + True) + pos = m.end() + continue + + m = _re_display.match(code, pos) + if m: + pyg(outfile, + m.group(1), + parse_opts(opts.copy(), m.group(2)), + '', + m.group(3), + usedstyles) + pos = m.end() + continue + + m = _re_input.match(code, pos) + if m: + try: + filecontents = open(m.group(3), 'rb').read() + except Exception as err: + sys.stderr.write('Error: cannot read input file: ') + sys.stderr.write(str(err)) + else: + pyg(outfile, + m.group(1), + parse_opts(opts, m.group(2)), + "", + filecontents, + usedstyles) + pos = m.end() + continue + + sys.stderr.write('Error: invalid input file contents: ignoring') + break + + outfile.write(GENERIC_DEFINITIONS_2) + + + +USAGE = """\ +Usage: %s [-o <output file name>] <input file name> + %s -h | -V + +The input file should consist of a sequence of source code snippets, as +produced by the `pygmentex` LaTeX package. Each code snippet is +highlighted using Pygments, and a LaTeX command that expands to the +highlighted code snippet is written to the output file. + +It also writes to the output file a set of LaTeX macro definitions the +Pygments styles that are used in the code snippets. + +If no output file name is given, use `<input file name>.pygmented`. + +The -e option enables escaping to LaTex. Text delimited by the <left> +and <right> characters is read as LaTeX code and typeset accordingly. It +has no effect in string literals. It has no effect in comments if +`texcomments` or `mathescape` is set. + +The -h option prints this help. + +The -V option prints the package version. +""" + + +def main(args = sys.argv): + """ + Main command line entry point. + """ + usage = USAGE % ((args[0],) * 2) + + try: + popts, args = getopt.getopt(args[1:], 'e:o:hV') + except getopt.GetoptError as err: + sys.stderr.write(usage) + return 2 + opts = {} + for opt, arg in popts: + opts[opt] = arg + + if not opts and not args: + print(usage) + return 0 + + if opts.pop('-h', None) is not None: + print(usage) + return 0 + + if opts.pop('-V', None) is not None: + print('PygmenTeX version %s, (c) 2010 by José Romildo.' % __version__) + return 0 + + if len(args) != 1: + sys.stderr.write(usage) + return 2 + infn = args[0] + try: + code = open(infn, 'rb').read() + except Exception as err: + sys.stderr.write('Error: cannot read input file: ') + sys.stderr.write(str(err)) + return 1 + + outfn = opts.pop('-o', None) + if not outfn: + root, ext = splitext(infn) + outfn = root + '.pygmented' + try: + outfile = open(outfn, 'w') + except Exception as err: + sys.stderr.write('Error: cannot open output file: ') + sys.stderr.write(str(err)) + return 1 + + convert(code, outfile) + + return 0 + + +if __name__ == '__main__': + try: + sys.exit(main(sys.argv)) + except KeyboardInterrupt: + sys.exit(1) diff --git a/Master/texmf-dist/tex/latex/pygmentex/pygmentex.sty b/Master/texmf-dist/tex/latex/pygmentex/pygmentex.sty new file mode 100644 index 00000000000..a0ddd911b8d --- /dev/null +++ b/Master/texmf-dist/tex/latex/pygmentex/pygmentex.sty @@ -0,0 +1,389 @@ +% pygmentex.sty + +\NeedsTeXFormat{LaTeX2e} + +\ProvidesPackage{pygmentex}[2014/08/12 v0.8 A Pygmentex layer for LaTeX] + +\RequirePackage{fancyvrb} +\RequirePackage{color} +\RequirePackage{ifthen} +%\RequirePackage[font=small,format=plain,labelfont=bf,up,textfont=it,up]{caption} +\RequirePackage{caption} +\RequirePackage{pgfkeys} +\RequirePackage{efbox} +\RequirePackage[framemethod=tikz]{mdframed} + +%\DeclareCaptionType[within=chapter]{code}[Listagem][Lista de listagens] +\DeclareCaptionType{code}[Listagem][Lista de listagens] +\captionsetup[code]{position=top} + +% ========================================================= +% Auxiliary: +% finding the widest string in a comma +% separated list of strings delimited by parenthesis +% ========================================================= + +% arguments: +% #1) text: a comma separeted list of strings +% #2) formatter: a macro to format each string +% #3) dimension: will hold the result + +\def\widest(#1)#2#3{% + \begingroup + \def\widest@end{\widest@end}% + \def\widest@helper##1,{% + \ifx\widest@end##1\relax + \else + \settowidth\dimen@{#2{##1}}% + \ifdim#3<\dimen@ + \global#3=\dimen@ + \else + \fi + \expandafter\widest@helper + \fi + }% + \widest@helper#1,\widest@end,% + \endgroup +} + +% ========================================================= +% fancyvrb new commands to append to a file +% ========================================================= + +% See http://tex.stackexchange.com/questions/47462/inputenc-error-with-unicode-chars-and-verbatim +\long\def\unexpanded@write#1#2{\write#1{\unexpanded{#2}}} + +\def\VerbatimOutAppend{\FV@Environment{}{VerbatimOutAppend}} + +\def\FVB@VerbatimOutAppend#1{% + \@bsphack + \begingroup + \FV@UseKeyValues + \FV@DefineWhiteSpace + \def\FV@Space{\space}% + \FV@DefineTabOut + \def\FV@ProcessLine{\immediate\unexpanded@write#1}% + \let\FV@FontScanPrep\relax + \let\@noligs\relax + \FV@Scan +} + +\def\FVE@VerbatimOutAppend{% + \endgroup + \@esphack +} + +\DefineVerbatimEnvironment{VerbatimOutAppend}{VerbatimOutAppend}{} + +% ========================================================= +% Main options +% ========================================================= + +\newif\ifpygmented@opt@texcomments +\newif\ifpygmented@opt@mathescape +\newif\ifpygmented@opt@linenos +\newif\ifpygmented@left +\newif\ifpygmented@right + +% some settings used by fancyvrb: +% * for line numbering: +% numbers, numbersep, firstnumber, stepnumber, numberblanklines +% * for selection of lines to print: +% firstline, lastline, + +\pgfkeys{% + /pygmented/.cd, + % + boxing method/.store in = \pygmented@opt@boxing@method, + inline method/.store in = \pygmented@opt@inline@method, + % + lang/.store in = \pygmented@opt@lang, + sty/.store in = \pygmented@opt@style, + escapeinside/.store in = \pygmented@opt@escapeinside, + texcomments/.is if = pygmented@opt@texcomments, + mathescape/.is if = pygmented@opt@mathescape, + % + label/.store in = \pygmented@opt@label, + caption/.store in = \pygmented@opt@caption, + % + gobble/.store in = \pygmented@opt@gobble, + tabsize/.store in = \pygmented@opt@tabsize, + % + linenos/.is if = pygmented@opt@linenos, + linenostart/.store in = \pygmented@opt@linenostart, + linenostep/.store in = \pygmented@opt@linenostep, + linenosep/.store in = \pygmented@opt@linenosep, + % + colback/.store in = \pygmented@opt@colback, + font/.store in = \pygmented@opt@font, + % + texcomments/.default = true, + mathescape/.default = true, + linenos/.default = true, +} + +\pgfqkeys{/pygmented}{ + boxing method = mdframed, + inline method = efbox, + sty = default, + linenos = false, + linenosep = 2pt, + font = \ttfamily, + tabsize = 0, +} + +% ========================================================= +% pygmented commands and environments +% ========================================================= + +\newwrite\pygmented@outfile + +\newcount\pygmented@counter + +\newcommand\pygmented@process@options[1]{% + \pgfkeys{% + /pgf/key filters/defined/.install key filter,% + /pgf/key filter handlers/append filtered to/.install key filter handler=\remainingglobaloptions + }% + \def\remainingglobaloptions{}% + \pgfkeysalsofilteredfrom{\pygmented@global@options}% + \pgfkeysalso{% + /pgf/key filter handlers/append filtered to/.install key filter handler=\remaininguseroptions + }% + \def\remaininguseroptions{}% + \pgfqkeysfiltered{/pygmented}{#1}% + % %%%%%%% DEBUGING + % \typeout{}% + % \typeout{\string\pygmented@global@options:}\typeout{\meaning\pygmented@global@options}% + % \typeout{\string\remainingglobaloptions:}\typeout{\meaning\remainingglobaloptions}% + % \typeout{\string\remaininguseroptions:}\typeout{\meaning\remaininguseroptions}% + % + \fvset{gobble=0,tabsize=0}% +} + +\newcommand\pygmented@process@adicional@options[1]{% + \pgfkeysalso{% + /pgf/key filters/false/.install key filter,% + /pgf/key filter handlers/append filtered to/.install key filter handler=\remainingoptions + }% + \def\remainingoptions{}% + \pgfkeysalsofilteredfrom{\remainingglobaloptions}% + \edef\pygmented@saved@{% + \ifcsname pygmented@#1@additional@options\endcsname + \csname pygmented@#1@additional@options\endcsname,% + \fi + }% + \pgfkeysalsofilteredfrom{\pygmented@saved@}% + \pgfkeysalsofilteredfrom{\remaininguseroptions}% + % %%%%%%% DEBUGING + % \typeout{}% + % \typeout{\string\remainingoptions:}% + % \typeout{\meaning\remainingoptions}% +} + +\newcommand\inputpygmented[2][]{% + \begingroup + \pygmented@process@options{#1}% + \immediate\write\pygmented@outfile{<@@pygmented@input@\the\pygmented@counter}% + \immediate\write\pygmented@outfile{\detokenize\expandafter{\pygmented@global@options},\detokenize{#1}}% + \immediate\write\pygmented@outfile{#2}% + \immediate\write\pygmented@outfile{>@@pygmented@input@\the\pygmented@counter}% + % + \csname pygmented@snippet@\the\pygmented@counter\endcsname + \global\advance\pygmented@counter by 1\relax + \endgroup +} + +\newenvironment{pygmented}[1][]{% + \pygmented@process@options{#1}% + \immediate\write\pygmented@outfile{<@@pygmented@display@\the\pygmented@counter}% + \immediate\write\pygmented@outfile{\detokenize\expandafter{\pygmented@global@options},\detokenize{#1}}% + \VerbatimEnvironment + \begin{VerbatimOutAppend}{\pygmented@outfile}% +}{% + \end{VerbatimOutAppend}% + \immediate\write\pygmented@outfile{>@@pygmented@display@\the\pygmented@counter}% + \csname pygmented@snippet@\the\pygmented@counter\endcsname + \global\advance\pygmented@counter by 1\relax +} + +\newcommand\pyginline[2][]{% + \begingroup + \pygmented@process@options{#1}% + \immediate\write\pygmented@outfile{<@@pygmented@inline@\the\pygmented@counter}% + \immediate\write\pygmented@outfile{\detokenize\expandafter{\pygmented@global@options},\detokenize{#1}}% + \DefineShortVerb{#2}% + \SaveVerb + [aftersave={% + \UndefineShortVerb{#2}% + \immediate\write\pygmented@outfile{\FV@SV@pygmented@verb}% + \immediate\write\pygmented@outfile{>@@pygmented@inline@\the\pygmented@counter}% + % + \csname pygmented@snippet@\the\pygmented@counter\endcsname + \global\advance\pygmented@counter by 1\relax + \endgroup + }]% + {pygmented@verb}#2% +} + + +\newcommand\pygmented@snippet@inlined[1]{% + \begingroup + \csname PYstyle\pygmented@opt@style\endcsname + \pygmented@opt@font + \pygmented@process@adicional@options{\pygmented@opt@inline@method}% + \expandafter\expandafter\csname \pygmented@opt@inline@method \endcsname\expandafter[\remainingoptions]{#1}% + \endgroup +} + +\newenvironment{pygmented@snippet@framed}{% + \begingroup + \pygmented@leftmargin\z@ + \ifpygmented@opt@linenos + \expandafter\widest\pygmented@alllinenos{\FormatLineNumber}{\pygmented@leftmargin}% + \advance\pygmented@leftmargin\pygmented@opt@linenosep + \fi + % + \ifdefined\pygmented@opt@label + \def\pygmented@title{% + \captionof{code}{\label{\pygmented@opt@label}\pygmented@opt@caption}% + % \nopagebreak + \vskip -0.7\baselineskip + }% + \else + \ifdefined\pygmented@opt@caption + \def\pygmented@title{% + \captionof{code}{\pygmented@opt@caption}% + % \nopagebreak + \vskip -0.7\baselineskip + }% + \fi + \fi + \ifdefined\pygmented@title + % \nopagebreak[0]% + \pygmented@title + % \nopagebreak + \fi + % + \pygmented@process@adicional@options{\pygmented@opt@boxing@method}% + \expandafter\begin\expandafter{\expandafter\pygmented@opt@boxing@method\expandafter}\expandafter[% + \remainingoptions + ]% + \csname PYstyle\pygmented@opt@style\endcsname + \pygmented@opt@font + % + \noindent + }{% + \end{\pygmented@opt@boxing@method}% + \endgroup +} + + +\newcommand\pygmented@inlined[1]{% + \expandafter\efbox\expandafter[\remainingoptions]{#1}% +} + + + +\def\FormatLineNumber#1{{\rmfamily\tiny#1}} + + +\newdimen\pygmented@leftmargin +\newdimen\pygmented@linenosep + +\def\pygmented@lineno@do#1{% + \pygmented@linenosep 0pt% + \csname pygmented@\pygmented@opt@boxing@method @margin\endcsname + \advance \pygmented@linenosep \pygmented@opt@linenosep + \makebox[0pt][r]{% + \FormatLineNumber{#1}% + \hspace*{\pygmented@linenosep}}% +} + +\newcommand\pygmented@tcbox@additional@options{% + nobeforeafter,% + tcbox raise base,% + left=0mm,% + right=0mm,% + top=0mm,% + bottom=0mm,% + boxsep=2pt,% + arc=1pt,% + boxrule=0pt,% + \ifcsname pygmented@opt@colback\endcsname + colback=\pygmented@opt@colback,% + \fi +} + +\newcommand\pygmented@efbox@additional@options{% + \ifcsname pygmented@opt@colback\endcsname + backgroundcolor=\pygmented@opt@colback,% + \fi +} + +\newcommand\pygmented@mdframed@additional@options{% + leftmargin=\pygmented@leftmargin,% + frametitlerule=true,% + \ifcsname pygmented@opt@colback\endcsname + backgroundcolor=\pygmented@opt@colback,% + \fi +} + +\newcommand\pygmented@tcolorbox@additional@options{% + grow to left by=-\pygmented@leftmargin,% + \ifcsname pygmented@opt@colback\endcsname + colback=\pygmented@opt@colback,% + \fi +} + +\newcommand\pygmented@boite@additional@options{% + leftmargin=\pygmented@leftmargin,% + \ifcsname pygmented@opt@colback\endcsname + colback=\pygmented@opt@colback,% + \fi +} + + +\newcommand\pygmented@mdframed@margin{% + \advance \pygmented@linenosep \mdflength{outerlinewidth}% + \advance \pygmented@linenosep \mdflength{middlelinewidth}% + \advance \pygmented@linenosep \mdflength{innerlinewidth}% + \advance \pygmented@linenosep \mdflength{innerleftmargin}% +} + +\newcommand\pygmented@tcolorbox@margin{% + \advance \pygmented@linenosep \kvtcb@left@rule + \advance \pygmented@linenosep \kvtcb@leftupper + \advance \pygmented@linenosep \kvtcb@boxsep +} + +\newcommand\pygmented@boite@margin{% + \advance \pygmented@linenosep \boite@leftrule + \advance \pygmented@linenosep \boite@boxsep +} + +\def\pygmented@global@options{} + +\newcommand\setpygmented[1]{% + \def\pygmented@global@options{/pygmented/.cd,#1}% +} + + +% ========================================================= +% final actions +% ========================================================= + +\AtEndOfPackage{% + \IfFileExists{\jobname.pygmented}{% + \input{\jobname.pygmented}% + }{% + \PackageWarning{pygmentex}{File `\jobname.pygmented' not found.}% + }% + \immediate\openout\pygmented@outfile\jobname.snippets% +} + +\AtEndDocument{% + \closeout\pygmented@outfile% +} + +\endinput diff --git a/Master/tlpkg/bin/tlpkg-ctan-check b/Master/tlpkg/bin/tlpkg-ctan-check index e422920b8b8..0c2b60bdaaf 100755 --- a/Master/tlpkg/bin/tlpkg-ctan-check +++ b/Master/tlpkg/bin/tlpkg-ctan-check @@ -414,7 +414,7 @@ my @TLP_working = qw( pstricks-examples-en pstricks_calcnotes psu-thesis ptex2pdf ptext ptptex punk punk-latex punknova purifyeps pxbase pxchfon pxcjkcat pxfonts pxgreeks pxjahyper - pxpgfmark pxrubrica pxtxalfa python pythontex + pxpgfmark pxrubrica pxtxalfa pygmentex python pythontex quattrocento qcircuit qcm qobitree qstest qsymbols qtree quotchap quoting quotmark r_und_s raleway ran_toks randbild randomwalk randtext diff --git a/Master/tlpkg/libexec/ctan2tds b/Master/tlpkg/libexec/ctan2tds index bbc595494af..8e1a70f5026 100755 --- a/Master/tlpkg/libexec/ctan2tds +++ b/Master/tlpkg/libexec/ctan2tds @@ -2079,6 +2079,7 @@ $standardsource='\.(bat|c|drv|dtx|fea|fdd|ins|sfd)$|configure.*|install-sh'; 'patch', '\.doc', 'pdfx', 'rvdtx\.sty|' . $standardsource, 'poetrytex', 'Makefile|' . $standardsource, + 'pygmentex', 'NULL', # keep together 'rcs', 'rcs.el|src|' . $standardsource, 'ruhyphen', '^[^.]*$|README.ru|hyphen.rules', 'selnolig', 'NULL', # not .fea @@ -2544,6 +2545,7 @@ $standardxmt='\.xmt'; 'pst2pdf' => 'pst2pdf\.pl$', 'ptex2pdf' => 'ptex2pdf\.lua$', 'purifyeps' => 'purifyeps$', + 'pygmentex', => 'pygmentex\.py$', 'pythontex' => '(de)?pythontex\.py$', 'rubik' => '\.pl$', 'splitindex' => 'splitindex\.pl$', diff --git a/Master/tlpkg/tlpsrc/collection-science.tlpsrc b/Master/tlpkg/tlpsrc/collection-science.tlpsrc index 39d496d9977..0fbfd290c38 100644 --- a/Master/tlpkg/tlpsrc/collection-science.tlpsrc +++ b/Master/tlpkg/tlpsrc/collection-science.tlpsrc @@ -55,6 +55,7 @@ depend objectz depend physics depend physymb depend pseudocode +depend pygmentex depend sasnrdisplay depend sciposter depend sfg diff --git a/Master/tlpkg/tlpsrc/pygmentex.tlpsrc b/Master/tlpkg/tlpsrc/pygmentex.tlpsrc new file mode 100644 index 00000000000..dca338c719c --- /dev/null +++ b/Master/tlpkg/tlpsrc/pygmentex.tlpsrc @@ -0,0 +1 @@ +binpattern f bin/${ARCH}/${PKGNAME} |