applied-ai-018 commited on
Commit
8a06feb
·
verified ·
1 Parent(s): 1ce98e3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step80/zero/12.attention.dense.weight/exp_avg.pt +3 -0
  2. ckpts/universal/global_step80/zero/12.attention.dense.weight/exp_avg_sq.pt +3 -0
  3. ckpts/universal/global_step80/zero/12.attention.dense.weight/fp32.pt +3 -0
  4. ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/exp_avg.pt +3 -0
  5. ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/exp_avg_sq.pt +3 -0
  6. ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  7. ckpts/universal/global_step80/zero/21.post_attention_layernorm.weight/exp_avg.pt +3 -0
  8. ckpts/universal/global_step80/zero/21.post_attention_layernorm.weight/exp_avg_sq.pt +3 -0
  9. ckpts/universal/global_step80/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
  10. ckpts/universal/global_step80/zero/3.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
  11. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__init__.py +83 -0
  12. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__main__.py +17 -0
  13. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-310.pyc +0 -0
  14. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/cmdline.cpython-310.pyc +0 -0
  15. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/scanner.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-310.pyc +0 -0
  19. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/unistring.cpython-310.pyc +0 -0
  20. venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-310.pyc +0 -0
  21. venv/lib/python3.10/site-packages/pip/_vendor/pygments/cmdline.py +663 -0
  22. venv/lib/python3.10/site-packages/pip/_vendor/pygments/console.py +70 -0
  23. venv/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py +71 -0
  24. venv/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__init__.py +937 -0
  25. venv/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-310.pyc +0 -0
  26. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatter.py +94 -0
  27. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py +153 -0
  28. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/groff.cpython-310.pyc +0 -0
  32. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/html.cpython-310.pyc +0 -0
  33. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/img.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/irc.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/latex.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/svg.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py +84 -0
  43. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/bbcode.py +108 -0
  44. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py +168 -0
  45. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py +983 -0
  46. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py +641 -0
  47. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/irc.py +179 -0
  48. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py +511 -0
  49. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py +161 -0
  50. venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py +83 -0
ckpts/universal/global_step80/zero/12.attention.dense.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:614975d13880a74623406303c19a090d98e17f569100c87f1480bb0d2d87603f
3
+ size 16778396
ckpts/universal/global_step80/zero/12.attention.dense.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:650df97196cf613cfed221217e039936b0040fc3dbf2e7e5baf47548c7267589
3
+ size 16778411
ckpts/universal/global_step80/zero/12.attention.dense.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ded4cd8384b742a63c148faceeb911f04b4e2b8abdf9d98e7a88e4587b96449b
3
+ size 16778317
ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80e6a79b0af1310815517cd1cec68eb446df05664386c4cf52ed28fc9645fe5b
3
+ size 33555612
ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e106ff460a9fc95a29c08c1bf259aa21b38d38c01d0d6a207338d4afd230ec93
3
+ size 33555627
ckpts/universal/global_step80/zero/15.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0710a5b68c83159b1feb2f4cc894d1af3b3ef0658779d9430fa820a2d0384bda
3
+ size 33555533
ckpts/universal/global_step80/zero/21.post_attention_layernorm.weight/exp_avg.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f001aba8b1ff992e05f286c16cb1ad5ad1cd1f2f11cca7cdb3435464ea12daf3
3
+ size 9372
ckpts/universal/global_step80/zero/21.post_attention_layernorm.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:804d61758f108f7580c4738e05881985b463c0e797a1d2683b20bc2c6b8fc90b
3
+ size 9387
ckpts/universal/global_step80/zero/3.mlp.dense_4h_to_h.weight/exp_avg_sq.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25d6e7ebe3f676c5ea37055ecd9f2fe78d5d1ee3cc6cf5cc229bc4b337915983
3
+ size 33555627
ckpts/universal/global_step80/zero/3.mlp.dense_4h_to_h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:778a10589bec884fb538cfe91f7a538482fde9938d38f85dfe87fcb900006f0a
3
+ size 33555533
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__init__.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pygments
3
+ ~~~~~~~~
4
+
5
+ Pygments is a syntax highlighting package written in Python.
6
+
7
+ It is a generic syntax highlighter for general use in all kinds of software
8
+ such as forum systems, wikis or other applications that need to prettify
9
+ source code. Highlights are:
10
+
11
+ * a wide range of common languages and markup formats is supported
12
+ * special attention is paid to details, increasing quality by a fair amount
13
+ * support for new languages and formats are added easily
14
+ * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
15
+ formats that PIL supports, and ANSI sequences
16
+ * it is usable as a command-line tool and as a library
17
+ * ... and it highlights even Brainfuck!
18
+
19
+ The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.
20
+
21
+ .. _Pygments master branch:
22
+ https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev
23
+
24
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
25
+ :license: BSD, see LICENSE for details.
26
+ """
27
+ from io import StringIO, BytesIO
28
+
29
+ __version__ = '2.11.2'
30
+ __docformat__ = 'restructuredtext'
31
+
32
+ __all__ = ['lex', 'format', 'highlight']
33
+
34
+
35
+ def lex(code, lexer):
36
+ """
37
+ Lex ``code`` with ``lexer`` and return an iterable of tokens.
38
+ """
39
+ try:
40
+ return lexer.get_tokens(code)
41
+ except TypeError as err:
42
+ if (isinstance(err.args[0], str) and
43
+ ('unbound method get_tokens' in err.args[0] or
44
+ 'missing 1 required positional argument' in err.args[0])):
45
+ raise TypeError('lex() argument must be a lexer instance, '
46
+ 'not a class')
47
+ raise
48
+
49
+
50
+ def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin
51
+ """
52
+ Format a tokenlist ``tokens`` with the formatter ``formatter``.
53
+
54
+ If ``outfile`` is given and a valid file object (an object
55
+ with a ``write`` method), the result will be written to it, otherwise
56
+ it is returned as a string.
57
+ """
58
+ try:
59
+ if not outfile:
60
+ realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
61
+ formatter.format(tokens, realoutfile)
62
+ return realoutfile.getvalue()
63
+ else:
64
+ formatter.format(tokens, outfile)
65
+ except TypeError as err:
66
+ if (isinstance(err.args[0], str) and
67
+ ('unbound method format' in err.args[0] or
68
+ 'missing 1 required positional argument' in err.args[0])):
69
+ raise TypeError('format() argument must be a formatter instance, '
70
+ 'not a class')
71
+ raise
72
+
73
+
74
+ def highlight(code, lexer, formatter, outfile=None):
75
+ """
76
+ Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
77
+
78
+ If ``outfile`` is given and a valid file object (an object
79
+ with a ``write`` method), the result will be written to it, otherwise
80
+ it is returned as a string.
81
+ """
82
+ return format(lex(code, lexer), formatter, outfile)
83
+
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__main__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.__main__
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ Main entry point for ``python -m pygments``.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import sys
12
+ from pip._vendor.pygments.cmdline import main
13
+
14
+ try:
15
+ sys.exit(main(sys.argv))
16
+ except KeyboardInterrupt:
17
+ sys.exit(1)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.99 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/cmdline.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/filter.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/scanner.cpython-310.pyc ADDED
Binary file (3.55 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-310.pyc ADDED
Binary file (4.58 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/unistring.cpython-310.pyc ADDED
Binary file (31.2 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-310.pyc ADDED
Binary file (9.16 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/cmdline.py ADDED
@@ -0,0 +1,663 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.cmdline
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Command line interface.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ import shutil
14
+ import argparse
15
+ from textwrap import dedent
16
+
17
+ from pip._vendor.pygments import __version__, highlight
18
+ from pip._vendor.pygments.util import ClassNotFound, OptionError, docstring_headline, \
19
+ guess_decode, guess_decode_from_terminal, terminal_encoding, \
20
+ UnclosingTextIOWrapper
21
+ from pip._vendor.pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \
22
+ load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename
23
+ from pip._vendor.pygments.lexers.special import TextLexer
24
+ from pip._vendor.pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter
25
+ from pip._vendor.pygments.formatters import get_all_formatters, get_formatter_by_name, \
26
+ load_formatter_from_file, get_formatter_for_filename, find_formatter_class
27
+ from pip._vendor.pygments.formatters.terminal import TerminalFormatter
28
+ from pip._vendor.pygments.formatters.terminal256 import Terminal256Formatter
29
+ from pip._vendor.pygments.filters import get_all_filters, find_filter_class
30
+ from pip._vendor.pygments.styles import get_all_styles, get_style_by_name
31
+
32
+
33
+ def _parse_options(o_strs):
34
+ opts = {}
35
+ if not o_strs:
36
+ return opts
37
+ for o_str in o_strs:
38
+ if not o_str.strip():
39
+ continue
40
+ o_args = o_str.split(',')
41
+ for o_arg in o_args:
42
+ o_arg = o_arg.strip()
43
+ try:
44
+ o_key, o_val = o_arg.split('=', 1)
45
+ o_key = o_key.strip()
46
+ o_val = o_val.strip()
47
+ except ValueError:
48
+ opts[o_arg] = True
49
+ else:
50
+ opts[o_key] = o_val
51
+ return opts
52
+
53
+
54
+ def _parse_filters(f_strs):
55
+ filters = []
56
+ if not f_strs:
57
+ return filters
58
+ for f_str in f_strs:
59
+ if ':' in f_str:
60
+ fname, fopts = f_str.split(':', 1)
61
+ filters.append((fname, _parse_options([fopts])))
62
+ else:
63
+ filters.append((f_str, {}))
64
+ return filters
65
+
66
+
67
+ def _print_help(what, name):
68
+ try:
69
+ if what == 'lexer':
70
+ cls = get_lexer_by_name(name)
71
+ print("Help on the %s lexer:" % cls.name)
72
+ print(dedent(cls.__doc__))
73
+ elif what == 'formatter':
74
+ cls = find_formatter_class(name)
75
+ print("Help on the %s formatter:" % cls.name)
76
+ print(dedent(cls.__doc__))
77
+ elif what == 'filter':
78
+ cls = find_filter_class(name)
79
+ print("Help on the %s filter:" % name)
80
+ print(dedent(cls.__doc__))
81
+ return 0
82
+ except (AttributeError, ValueError):
83
+ print("%s not found!" % what, file=sys.stderr)
84
+ return 1
85
+
86
+
87
+ def _print_list(what):
88
+ if what == 'lexer':
89
+ print()
90
+ print("Lexers:")
91
+ print("~~~~~~~")
92
+
93
+ info = []
94
+ for fullname, names, exts, _ in get_all_lexers():
95
+ tup = (', '.join(names)+':', fullname,
96
+ exts and '(filenames ' + ', '.join(exts) + ')' or '')
97
+ info.append(tup)
98
+ info.sort()
99
+ for i in info:
100
+ print(('* %s\n %s %s') % i)
101
+
102
+ elif what == 'formatter':
103
+ print()
104
+ print("Formatters:")
105
+ print("~~~~~~~~~~~")
106
+
107
+ info = []
108
+ for cls in get_all_formatters():
109
+ doc = docstring_headline(cls)
110
+ tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and
111
+ '(filenames ' + ', '.join(cls.filenames) + ')' or '')
112
+ info.append(tup)
113
+ info.sort()
114
+ for i in info:
115
+ print(('* %s\n %s %s') % i)
116
+
117
+ elif what == 'filter':
118
+ print()
119
+ print("Filters:")
120
+ print("~~~~~~~~")
121
+
122
+ for name in get_all_filters():
123
+ cls = find_filter_class(name)
124
+ print("* " + name + ':')
125
+ print(" %s" % docstring_headline(cls))
126
+
127
+ elif what == 'style':
128
+ print()
129
+ print("Styles:")
130
+ print("~~~~~~~")
131
+
132
+ for name in get_all_styles():
133
+ cls = get_style_by_name(name)
134
+ print("* " + name + ':')
135
+ print(" %s" % docstring_headline(cls))
136
+
137
+
138
+ def _print_list_as_json(requested_items):
139
+ import json
140
+ result = {}
141
+ if 'lexer' in requested_items:
142
+ info = {}
143
+ for fullname, names, filenames, mimetypes in get_all_lexers():
144
+ info[fullname] = {
145
+ 'aliases': names,
146
+ 'filenames': filenames,
147
+ 'mimetypes': mimetypes
148
+ }
149
+ result['lexers'] = info
150
+
151
+ if 'formatter' in requested_items:
152
+ info = {}
153
+ for cls in get_all_formatters():
154
+ doc = docstring_headline(cls)
155
+ info[cls.name] = {
156
+ 'aliases': cls.aliases,
157
+ 'filenames': cls.filenames,
158
+ 'doc': doc
159
+ }
160
+ result['formatters'] = info
161
+
162
+ if 'filter' in requested_items:
163
+ info = {}
164
+ for name in get_all_filters():
165
+ cls = find_filter_class(name)
166
+ info[name] = {
167
+ 'doc': docstring_headline(cls)
168
+ }
169
+ result['filters'] = info
170
+
171
+ if 'style' in requested_items:
172
+ info = {}
173
+ for name in get_all_styles():
174
+ cls = get_style_by_name(name)
175
+ info[name] = {
176
+ 'doc': docstring_headline(cls)
177
+ }
178
+ result['styles'] = info
179
+
180
+ json.dump(result, sys.stdout)
181
+
182
+ def main_inner(parser, argns):
183
+ if argns.help:
184
+ parser.print_help()
185
+ return 0
186
+
187
+ if argns.V:
188
+ print('Pygments version %s, (c) 2006-2021 by Georg Brandl, Matthäus '
189
+ 'Chajdas and contributors.' % __version__)
190
+ return 0
191
+
192
+ def is_only_option(opt):
193
+ return not any(v for (k, v) in vars(argns).items() if k != opt)
194
+
195
+ # handle ``pygmentize -L``
196
+ if argns.L is not None:
197
+ arg_set = set()
198
+ for k, v in vars(argns).items():
199
+ if v:
200
+ arg_set.add(k)
201
+
202
+ arg_set.discard('L')
203
+ arg_set.discard('json')
204
+
205
+ if arg_set:
206
+ parser.print_help(sys.stderr)
207
+ return 2
208
+
209
+ # print version
210
+ if not argns.json:
211
+ main(['', '-V'])
212
+ allowed_types = {'lexer', 'formatter', 'filter', 'style'}
213
+ largs = [arg.rstrip('s') for arg in argns.L]
214
+ if any(arg not in allowed_types for arg in largs):
215
+ parser.print_help(sys.stderr)
216
+ return 0
217
+ if not largs:
218
+ largs = allowed_types
219
+ if not argns.json:
220
+ for arg in largs:
221
+ _print_list(arg)
222
+ else:
223
+ _print_list_as_json(largs)
224
+ return 0
225
+
226
+ # handle ``pygmentize -H``
227
+ if argns.H:
228
+ if not is_only_option('H'):
229
+ parser.print_help(sys.stderr)
230
+ return 2
231
+ what, name = argns.H
232
+ if what not in ('lexer', 'formatter', 'filter'):
233
+ parser.print_help(sys.stderr)
234
+ return 2
235
+ return _print_help(what, name)
236
+
237
+ # parse -O options
238
+ parsed_opts = _parse_options(argns.O or [])
239
+
240
+ # parse -P options
241
+ for p_opt in argns.P or []:
242
+ try:
243
+ name, value = p_opt.split('=', 1)
244
+ except ValueError:
245
+ parsed_opts[p_opt] = True
246
+ else:
247
+ parsed_opts[name] = value
248
+
249
+ # encodings
250
+ inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding'))
251
+ outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))
252
+
253
+ # handle ``pygmentize -N``
254
+ if argns.N:
255
+ lexer = find_lexer_class_for_filename(argns.N)
256
+ if lexer is None:
257
+ lexer = TextLexer
258
+
259
+ print(lexer.aliases[0])
260
+ return 0
261
+
262
+ # handle ``pygmentize -C``
263
+ if argns.C:
264
+ inp = sys.stdin.buffer.read()
265
+ try:
266
+ lexer = guess_lexer(inp, inencoding=inencoding)
267
+ except ClassNotFound:
268
+ lexer = TextLexer
269
+
270
+ print(lexer.aliases[0])
271
+ return 0
272
+
273
+ # handle ``pygmentize -S``
274
+ S_opt = argns.S
275
+ a_opt = argns.a
276
+ if S_opt is not None:
277
+ f_opt = argns.f
278
+ if not f_opt:
279
+ parser.print_help(sys.stderr)
280
+ return 2
281
+ if argns.l or argns.INPUTFILE:
282
+ parser.print_help(sys.stderr)
283
+ return 2
284
+
285
+ try:
286
+ parsed_opts['style'] = S_opt
287
+ fmter = get_formatter_by_name(f_opt, **parsed_opts)
288
+ except ClassNotFound as err:
289
+ print(err, file=sys.stderr)
290
+ return 1
291
+
292
+ print(fmter.get_style_defs(a_opt or ''))
293
+ return 0
294
+
295
+ # if no -S is given, -a is not allowed
296
+ if argns.a is not None:
297
+ parser.print_help(sys.stderr)
298
+ return 2
299
+
300
+ # parse -F options
301
+ F_opts = _parse_filters(argns.F or [])
302
+
303
+ # -x: allow custom (eXternal) lexers and formatters
304
+ allow_custom_lexer_formatter = bool(argns.x)
305
+
306
+ # select lexer
307
+ lexer = None
308
+
309
+ # given by name?
310
+ lexername = argns.l
311
+ if lexername:
312
+ # custom lexer, located relative to user's cwd
313
+ if allow_custom_lexer_formatter and '.py' in lexername:
314
+ try:
315
+ filename = None
316
+ name = None
317
+ if ':' in lexername:
318
+ filename, name = lexername.rsplit(':', 1)
319
+
320
+ if '.py' in name:
321
+ # This can happen on Windows: If the lexername is
322
+ # C:\lexer.py -- return to normal load path in that case
323
+ name = None
324
+
325
+ if filename and name:
326
+ lexer = load_lexer_from_file(filename, name,
327
+ **parsed_opts)
328
+ else:
329
+ lexer = load_lexer_from_file(lexername, **parsed_opts)
330
+ except ClassNotFound as err:
331
+ print('Error:', err, file=sys.stderr)
332
+ return 1
333
+ else:
334
+ try:
335
+ lexer = get_lexer_by_name(lexername, **parsed_opts)
336
+ except (OptionError, ClassNotFound) as err:
337
+ print('Error:', err, file=sys.stderr)
338
+ return 1
339
+
340
+ # read input code
341
+ code = None
342
+
343
+ if argns.INPUTFILE:
344
+ if argns.s:
345
+ print('Error: -s option not usable when input file specified',
346
+ file=sys.stderr)
347
+ return 2
348
+
349
+ infn = argns.INPUTFILE
350
+ try:
351
+ with open(infn, 'rb') as infp:
352
+ code = infp.read()
353
+ except Exception as err:
354
+ print('Error: cannot read infile:', err, file=sys.stderr)
355
+ return 1
356
+ if not inencoding:
357
+ code, inencoding = guess_decode(code)
358
+
359
+ # do we have to guess the lexer?
360
+ if not lexer:
361
+ try:
362
+ lexer = get_lexer_for_filename(infn, code, **parsed_opts)
363
+ except ClassNotFound as err:
364
+ if argns.g:
365
+ try:
366
+ lexer = guess_lexer(code, **parsed_opts)
367
+ except ClassNotFound:
368
+ lexer = TextLexer(**parsed_opts)
369
+ else:
370
+ print('Error:', err, file=sys.stderr)
371
+ return 1
372
+ except OptionError as err:
373
+ print('Error:', err, file=sys.stderr)
374
+ return 1
375
+
376
+ elif not argns.s: # treat stdin as full file (-s support is later)
377
+ # read code from terminal, always in binary mode since we want to
378
+ # decode ourselves and be tolerant with it
379
+ code = sys.stdin.buffer.read() # use .buffer to get a binary stream
380
+ if not inencoding:
381
+ code, inencoding = guess_decode_from_terminal(code, sys.stdin)
382
+ # else the lexer will do the decoding
383
+ if not lexer:
384
+ try:
385
+ lexer = guess_lexer(code, **parsed_opts)
386
+ except ClassNotFound:
387
+ lexer = TextLexer(**parsed_opts)
388
+
389
+ else: # -s option needs a lexer with -l
390
+ if not lexer:
391
+ print('Error: when using -s a lexer has to be selected with -l',
392
+ file=sys.stderr)
393
+ return 2
394
+
395
+ # process filters
396
+ for fname, fopts in F_opts:
397
+ try:
398
+ lexer.add_filter(fname, **fopts)
399
+ except ClassNotFound as err:
400
+ print('Error:', err, file=sys.stderr)
401
+ return 1
402
+
403
+ # select formatter
404
+ outfn = argns.o
405
+ fmter = argns.f
406
+ if fmter:
407
+ # custom formatter, located relative to user's cwd
408
+ if allow_custom_lexer_formatter and '.py' in fmter:
409
+ try:
410
+ filename = None
411
+ name = None
412
+ if ':' in fmter:
413
+ # Same logic as above for custom lexer
414
+ filename, name = fmter.rsplit(':', 1)
415
+
416
+ if '.py' in name:
417
+ name = None
418
+
419
+ if filename and name:
420
+ fmter = load_formatter_from_file(filename, name,
421
+ **parsed_opts)
422
+ else:
423
+ fmter = load_formatter_from_file(fmter, **parsed_opts)
424
+ except ClassNotFound as err:
425
+ print('Error:', err, file=sys.stderr)
426
+ return 1
427
+ else:
428
+ try:
429
+ fmter = get_formatter_by_name(fmter, **parsed_opts)
430
+ except (OptionError, ClassNotFound) as err:
431
+ print('Error:', err, file=sys.stderr)
432
+ return 1
433
+
434
+ if outfn:
435
+ if not fmter:
436
+ try:
437
+ fmter = get_formatter_for_filename(outfn, **parsed_opts)
438
+ except (OptionError, ClassNotFound) as err:
439
+ print('Error:', err, file=sys.stderr)
440
+ return 1
441
+ try:
442
+ outfile = open(outfn, 'wb')
443
+ except Exception as err:
444
+ print('Error: cannot open outfile:', err, file=sys.stderr)
445
+ return 1
446
+ else:
447
+ if not fmter:
448
+ if '256' in os.environ.get('TERM', ''):
449
+ fmter = Terminal256Formatter(**parsed_opts)
450
+ else:
451
+ fmter = TerminalFormatter(**parsed_opts)
452
+ outfile = sys.stdout.buffer
453
+
454
+ # determine output encoding if not explicitly selected
455
+ if not outencoding:
456
+ if outfn:
457
+ # output file? use lexer encoding for now (can still be None)
458
+ fmter.encoding = inencoding
459
+ else:
460
+ # else use terminal encoding
461
+ fmter.encoding = terminal_encoding(sys.stdout)
462
+
463
+ # provide coloring under Windows, if possible
464
+ if not outfn and sys.platform in ('win32', 'cygwin') and \
465
+ fmter.name in ('Terminal', 'Terminal256'): # pragma: no cover
466
+ # unfortunately colorama doesn't support binary streams on Py3
467
+ outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding)
468
+ fmter.encoding = None
469
+ try:
470
+ import pip._vendor.colorama.initialise as colorama_initialise
471
+ except ImportError:
472
+ pass
473
+ else:
474
+ outfile = colorama_initialise.wrap_stream(
475
+ outfile, convert=None, strip=None, autoreset=False, wrap=True)
476
+
477
+ # When using the LaTeX formatter and the option `escapeinside` is
478
+ # specified, we need a special lexer which collects escaped text
479
+ # before running the chosen language lexer.
480
+ escapeinside = parsed_opts.get('escapeinside', '')
481
+ if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter):
482
+ left = escapeinside[0]
483
+ right = escapeinside[1]
484
+ lexer = LatexEmbeddedLexer(left, right, lexer)
485
+
486
+ # ... and do it!
487
+ if not argns.s:
488
+ # process whole input as per normal...
489
+ try:
490
+ highlight(code, lexer, fmter, outfile)
491
+ finally:
492
+ if outfn:
493
+ outfile.close()
494
+ return 0
495
+ else:
496
+ # line by line processing of stdin (eg: for 'tail -f')...
497
+ try:
498
+ while 1:
499
+ line = sys.stdin.buffer.readline()
500
+ if not line:
501
+ break
502
+ if not inencoding:
503
+ line = guess_decode_from_terminal(line, sys.stdin)[0]
504
+ highlight(line, lexer, fmter, outfile)
505
+ if hasattr(outfile, 'flush'):
506
+ outfile.flush()
507
+ return 0
508
+ except KeyboardInterrupt: # pragma: no cover
509
+ return 0
510
+ finally:
511
+ if outfn:
512
+ outfile.close()
513
+
514
+
515
+ class HelpFormatter(argparse.HelpFormatter):
516
+ def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
517
+ if width is None:
518
+ try:
519
+ width = shutil.get_terminal_size().columns - 2
520
+ except Exception:
521
+ pass
522
+ argparse.HelpFormatter.__init__(self, prog, indent_increment,
523
+ max_help_position, width)
524
+
525
+
526
+ def main(args=sys.argv):
527
+ """
528
+ Main command line entry point.
529
+ """
530
+ desc = "Highlight an input file and write the result to an output file."
531
+ parser = argparse.ArgumentParser(description=desc, add_help=False,
532
+ formatter_class=HelpFormatter)
533
+
534
+ operation = parser.add_argument_group('Main operation')
535
+ lexersel = operation.add_mutually_exclusive_group()
536
+ lexersel.add_argument(
537
+ '-l', metavar='LEXER',
538
+ help='Specify the lexer to use. (Query names with -L.) If not '
539
+ 'given and -g is not present, the lexer is guessed from the filename.')
540
+ lexersel.add_argument(
541
+ '-g', action='store_true',
542
+ help='Guess the lexer from the file contents, or pass through '
543
+ 'as plain text if nothing can be guessed.')
544
+ operation.add_argument(
545
+ '-F', metavar='FILTER[:options]', action='append',
546
+ help='Add a filter to the token stream. (Query names with -L.) '
547
+ 'Filter options are given after a colon if necessary.')
548
+ operation.add_argument(
549
+ '-f', metavar='FORMATTER',
550
+ help='Specify the formatter to use. (Query names with -L.) '
551
+ 'If not given, the formatter is guessed from the output filename, '
552
+ 'and defaults to the terminal formatter if the output is to the '
553
+ 'terminal or an unknown file extension.')
554
+ operation.add_argument(
555
+ '-O', metavar='OPTION=value[,OPTION=value,...]', action='append',
556
+ help='Give options to the lexer and formatter as a comma-separated '
557
+ 'list of key-value pairs. '
558
+ 'Example: `-O bg=light,python=cool`.')
559
+ operation.add_argument(
560
+ '-P', metavar='OPTION=value', action='append',
561
+ help='Give a single option to the lexer and formatter - with this '
562
+ 'you can pass options whose value contains commas and equal signs. '
563
+ 'Example: `-P "heading=Pygments, the Python highlighter"`.')
564
+ operation.add_argument(
565
+ '-o', metavar='OUTPUTFILE',
566
+ help='Where to write the output. Defaults to standard output.')
567
+
568
+ operation.add_argument(
569
+ 'INPUTFILE', nargs='?',
570
+ help='Where to read the input. Defaults to standard input.')
571
+
572
+ flags = parser.add_argument_group('Operation flags')
573
+ flags.add_argument(
574
+ '-v', action='store_true',
575
+ help='Print a detailed traceback on unhandled exceptions, which '
576
+ 'is useful for debugging and bug reports.')
577
+ flags.add_argument(
578
+ '-s', action='store_true',
579
+ help='Process lines one at a time until EOF, rather than waiting to '
580
+ 'process the entire file. This only works for stdin, only for lexers '
581
+ 'with no line-spanning constructs, and is intended for streaming '
582
+ 'input such as you get from `tail -f`. '
583
+ 'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')
584
+ flags.add_argument(
585
+ '-x', action='store_true',
586
+ help='Allow custom lexers and formatters to be loaded from a .py file '
587
+ 'relative to the current working directory. For example, '
588
+ '`-l ./customlexer.py -x`. By default, this option expects a file '
589
+ 'with a class named CustomLexer or CustomFormatter; you can also '
590
+ 'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '
591
+ 'Users should be very careful not to use this option with untrusted '
592
+ 'files, because it will import and run them.')
593
+ flags.add_argument('--json', help='Output as JSON. This can '
594
+ 'be only used in conjunction with -L.',
595
+ default=False,
596
+ action='store_true')
597
+
598
+ special_modes_group = parser.add_argument_group(
599
+ 'Special modes - do not do any highlighting')
600
+ special_modes = special_modes_group.add_mutually_exclusive_group()
601
+ special_modes.add_argument(
602
+ '-S', metavar='STYLE -f formatter',
603
+ help='Print style definitions for STYLE for a formatter '
604
+ 'given with -f. The argument given by -a is formatter '
605
+ 'dependent.')
606
+ special_modes.add_argument(
607
+ '-L', nargs='*', metavar='WHAT',
608
+ help='List lexers, formatters, styles or filters -- '
609
+ 'give additional arguments for the thing(s) you want to list '
610
+ '(e.g. "styles"), or omit them to list everything.')
611
+ special_modes.add_argument(
612
+ '-N', metavar='FILENAME',
613
+ help='Guess and print out a lexer name based solely on the given '
614
+ 'filename. Does not take input or highlight anything. If no specific '
615
+ 'lexer can be determined, "text" is printed.')
616
+ special_modes.add_argument(
617
+ '-C', action='store_true',
618
+ help='Like -N, but print out a lexer name based solely on '
619
+ 'a given content from standard input.')
620
+ special_modes.add_argument(
621
+ '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),
622
+ help='Print detailed help for the object <name> of type <type>, '
623
+ 'where <type> is one of "lexer", "formatter" or "filter".')
624
+ special_modes.add_argument(
625
+ '-V', action='store_true',
626
+ help='Print the package version.')
627
+ special_modes.add_argument(
628
+ '-h', '--help', action='store_true',
629
+ help='Print this help.')
630
+ special_modes_group.add_argument(
631
+ '-a', metavar='ARG',
632
+ help='Formatter-specific additional argument for the -S (print '
633
+ 'style sheet) mode.')
634
+
635
+ argns = parser.parse_args(args[1:])
636
+
637
+ try:
638
+ return main_inner(parser, argns)
639
+ except Exception:
640
+ if argns.v:
641
+ print(file=sys.stderr)
642
+ print('*' * 65, file=sys.stderr)
643
+ print('An unhandled exception occurred while highlighting.',
644
+ file=sys.stderr)
645
+ print('Please report the whole traceback to the issue tracker at',
646
+ file=sys.stderr)
647
+ print('<https://github.com/pygments/pygments/issues>.',
648
+ file=sys.stderr)
649
+ print('*' * 65, file=sys.stderr)
650
+ print(file=sys.stderr)
651
+ raise
652
+ import traceback
653
+ info = traceback.format_exception(*sys.exc_info())
654
+ msg = info[-1].strip()
655
+ if len(info) >= 3:
656
+ # extract relevant file and position info
657
+ msg += '\n (f%s)' % info[-2].split('\n')[0].strip()[1:]
658
+ print(file=sys.stderr)
659
+ print('*** Error while highlighting:', file=sys.stderr)
660
+ print(msg, file=sys.stderr)
661
+ print('*** If this is a bug you want to report, please rerun with -v.',
662
+ file=sys.stderr)
663
+ return 1
venv/lib/python3.10/site-packages/pip/_vendor/pygments/console.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.console
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Format colored console output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ esc = "\x1b["
12
+
13
+ codes = {}
14
+ codes[""] = ""
15
+ codes["reset"] = esc + "39;49;00m"
16
+
17
+ codes["bold"] = esc + "01m"
18
+ codes["faint"] = esc + "02m"
19
+ codes["standout"] = esc + "03m"
20
+ codes["underline"] = esc + "04m"
21
+ codes["blink"] = esc + "05m"
22
+ codes["overline"] = esc + "06m"
23
+
24
+ dark_colors = ["black", "red", "green", "yellow", "blue",
25
+ "magenta", "cyan", "gray"]
26
+ light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
27
+ "brightmagenta", "brightcyan", "white"]
28
+
29
+ x = 30
30
+ for d, l in zip(dark_colors, light_colors):
31
+ codes[d] = esc + "%im" % x
32
+ codes[l] = esc + "%im" % (60 + x)
33
+ x += 1
34
+
35
+ del d, l, x
36
+
37
+ codes["white"] = codes["bold"]
38
+
39
+
40
+ def reset_color():
41
+ return codes["reset"]
42
+
43
+
44
+ def colorize(color_key, text):
45
+ return codes[color_key] + text + codes["reset"]
46
+
47
+
48
+ def ansiformat(attr, text):
49
+ """
50
+ Format ``text`` with a color and/or some attributes::
51
+
52
+ color normal color
53
+ *color* bold color
54
+ _color_ underlined color
55
+ +color+ blinking color
56
+ """
57
+ result = []
58
+ if attr[:1] == attr[-1:] == '+':
59
+ result.append(codes['blink'])
60
+ attr = attr[1:-1]
61
+ if attr[:1] == attr[-1:] == '*':
62
+ result.append(codes['bold'])
63
+ attr = attr[1:-1]
64
+ if attr[:1] == attr[-1:] == '_':
65
+ result.append(codes['underline'])
66
+ attr = attr[1:-1]
67
+ result.append(codes[attr])
68
+ result.append(text)
69
+ result.append(codes['reset'])
70
+ return ''.join(result)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/filter.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.filter
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ Module that implements the default filter.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+
12
+ def apply_filters(stream, filters, lexer=None):
13
+ """
14
+ Use this method to apply an iterable of filters to
15
+ a stream. If lexer is given it's forwarded to the
16
+ filter, otherwise the filter receives `None`.
17
+ """
18
+ def _apply(filter_, stream):
19
+ yield from filter_.filter(lexer, stream)
20
+ for filter_ in filters:
21
+ stream = _apply(filter_, stream)
22
+ return stream
23
+
24
+
25
+ def simplefilter(f):
26
+ """
27
+ Decorator that converts a function into a filter::
28
+
29
+ @simplefilter
30
+ def lowercase(self, lexer, stream, options):
31
+ for ttype, value in stream:
32
+ yield ttype, value.lower()
33
+ """
34
+ return type(f.__name__, (FunctionFilter,), {
35
+ '__module__': getattr(f, '__module__'),
36
+ '__doc__': f.__doc__,
37
+ 'function': f,
38
+ })
39
+
40
+
41
+ class Filter:
42
+ """
43
+ Default filter. Subclass this class or use the `simplefilter`
44
+ decorator to create own filters.
45
+ """
46
+
47
+ def __init__(self, **options):
48
+ self.options = options
49
+
50
+ def filter(self, lexer, stream):
51
+ raise NotImplementedError()
52
+
53
+
54
+ class FunctionFilter(Filter):
55
+ """
56
+ Abstract class used by `simplefilter` to create simple
57
+ function filters on the fly. The `simplefilter` decorator
58
+ automatically creates subclasses of this class for
59
+ functions passed to it.
60
+ """
61
+ function = None
62
+
63
+ def __init__(self, **options):
64
+ if not hasattr(self, 'function'):
65
+ raise TypeError('%r used without bound function' %
66
+ self.__class__.__name__)
67
+ Filter.__init__(self, **options)
68
+
69
+ def filter(self, lexer, stream):
70
+ # pylint: disable=not-callable
71
+ yield from self.function(lexer, stream, self.options)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__init__.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.filters
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Module containing filter lookup functions and default
6
+ filters.
7
+
8
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
9
+ :license: BSD, see LICENSE for details.
10
+ """
11
+
12
+ import re
13
+
14
+ from pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \
15
+ string_to_tokentype
16
+ from pip._vendor.pygments.filter import Filter
17
+ from pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \
18
+ get_choice_opt, ClassNotFound, OptionError
19
+ from pip._vendor.pygments.plugin import find_plugin_filters
20
+
21
+
22
+ def find_filter_class(filtername):
23
+ """Lookup a filter by name. Return None if not found."""
24
+ if filtername in FILTERS:
25
+ return FILTERS[filtername]
26
+ for name, cls in find_plugin_filters():
27
+ if name == filtername:
28
+ return cls
29
+ return None
30
+
31
+
32
+ def get_filter_by_name(filtername, **options):
33
+ """Return an instantiated filter.
34
+
35
+ Options are passed to the filter initializer if wanted.
36
+ Raise a ClassNotFound if not found.
37
+ """
38
+ cls = find_filter_class(filtername)
39
+ if cls:
40
+ return cls(**options)
41
+ else:
42
+ raise ClassNotFound('filter %r not found' % filtername)
43
+
44
+
45
+ def get_all_filters():
46
+ """Return a generator of all filter names."""
47
+ yield from FILTERS
48
+ for name, _ in find_plugin_filters():
49
+ yield name
50
+
51
+
52
+ def _replace_special(ttype, value, regex, specialttype,
53
+ replacefunc=lambda x: x):
54
+ last = 0
55
+ for match in regex.finditer(value):
56
+ start, end = match.start(), match.end()
57
+ if start != last:
58
+ yield ttype, value[last:start]
59
+ yield specialttype, replacefunc(value[start:end])
60
+ last = end
61
+ if last != len(value):
62
+ yield ttype, value[last:]
63
+
64
+
65
+ class CodeTagFilter(Filter):
66
+ """Highlight special code tags in comments and docstrings.
67
+
68
+ Options accepted:
69
+
70
+ `codetags` : list of strings
71
+ A list of strings that are flagged as code tags. The default is to
72
+ highlight ``XXX``, ``TODO``, ``BUG`` and ``NOTE``.
73
+ """
74
+
75
+ def __init__(self, **options):
76
+ Filter.__init__(self, **options)
77
+ tags = get_list_opt(options, 'codetags',
78
+ ['XXX', 'TODO', 'BUG', 'NOTE'])
79
+ self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([
80
+ re.escape(tag) for tag in tags if tag
81
+ ]))
82
+
83
+ def filter(self, lexer, stream):
84
+ regex = self.tag_re
85
+ for ttype, value in stream:
86
+ if ttype in String.Doc or \
87
+ ttype in Comment and \
88
+ ttype not in Comment.Preproc:
89
+ yield from _replace_special(ttype, value, regex, Comment.Special)
90
+ else:
91
+ yield ttype, value
92
+
93
+
94
+ class SymbolFilter(Filter):
95
+ """Convert mathematical symbols such as \\<longrightarrow> in Isabelle
96
+ or \\longrightarrow in LaTeX into Unicode characters.
97
+
98
+ This is mostly useful for HTML or console output when you want to
99
+ approximate the source rendering you'd see in an IDE.
100
+
101
+ Options accepted:
102
+
103
+ `lang` : string
104
+ The symbol language. Must be one of ``'isabelle'`` or
105
+ ``'latex'``. The default is ``'isabelle'``.
106
+ """
107
+
108
+ latex_symbols = {
109
+ '\\alpha' : '\U000003b1',
110
+ '\\beta' : '\U000003b2',
111
+ '\\gamma' : '\U000003b3',
112
+ '\\delta' : '\U000003b4',
113
+ '\\varepsilon' : '\U000003b5',
114
+ '\\zeta' : '\U000003b6',
115
+ '\\eta' : '\U000003b7',
116
+ '\\vartheta' : '\U000003b8',
117
+ '\\iota' : '\U000003b9',
118
+ '\\kappa' : '\U000003ba',
119
+ '\\lambda' : '\U000003bb',
120
+ '\\mu' : '\U000003bc',
121
+ '\\nu' : '\U000003bd',
122
+ '\\xi' : '\U000003be',
123
+ '\\pi' : '\U000003c0',
124
+ '\\varrho' : '\U000003c1',
125
+ '\\sigma' : '\U000003c3',
126
+ '\\tau' : '\U000003c4',
127
+ '\\upsilon' : '\U000003c5',
128
+ '\\varphi' : '\U000003c6',
129
+ '\\chi' : '\U000003c7',
130
+ '\\psi' : '\U000003c8',
131
+ '\\omega' : '\U000003c9',
132
+ '\\Gamma' : '\U00000393',
133
+ '\\Delta' : '\U00000394',
134
+ '\\Theta' : '\U00000398',
135
+ '\\Lambda' : '\U0000039b',
136
+ '\\Xi' : '\U0000039e',
137
+ '\\Pi' : '\U000003a0',
138
+ '\\Sigma' : '\U000003a3',
139
+ '\\Upsilon' : '\U000003a5',
140
+ '\\Phi' : '\U000003a6',
141
+ '\\Psi' : '\U000003a8',
142
+ '\\Omega' : '\U000003a9',
143
+ '\\leftarrow' : '\U00002190',
144
+ '\\longleftarrow' : '\U000027f5',
145
+ '\\rightarrow' : '\U00002192',
146
+ '\\longrightarrow' : '\U000027f6',
147
+ '\\Leftarrow' : '\U000021d0',
148
+ '\\Longleftarrow' : '\U000027f8',
149
+ '\\Rightarrow' : '\U000021d2',
150
+ '\\Longrightarrow' : '\U000027f9',
151
+ '\\leftrightarrow' : '\U00002194',
152
+ '\\longleftrightarrow' : '\U000027f7',
153
+ '\\Leftrightarrow' : '\U000021d4',
154
+ '\\Longleftrightarrow' : '\U000027fa',
155
+ '\\mapsto' : '\U000021a6',
156
+ '\\longmapsto' : '\U000027fc',
157
+ '\\relbar' : '\U00002500',
158
+ '\\Relbar' : '\U00002550',
159
+ '\\hookleftarrow' : '\U000021a9',
160
+ '\\hookrightarrow' : '\U000021aa',
161
+ '\\leftharpoondown' : '\U000021bd',
162
+ '\\rightharpoondown' : '\U000021c1',
163
+ '\\leftharpoonup' : '\U000021bc',
164
+ '\\rightharpoonup' : '\U000021c0',
165
+ '\\rightleftharpoons' : '\U000021cc',
166
+ '\\leadsto' : '\U0000219d',
167
+ '\\downharpoonleft' : '\U000021c3',
168
+ '\\downharpoonright' : '\U000021c2',
169
+ '\\upharpoonleft' : '\U000021bf',
170
+ '\\upharpoonright' : '\U000021be',
171
+ '\\restriction' : '\U000021be',
172
+ '\\uparrow' : '\U00002191',
173
+ '\\Uparrow' : '\U000021d1',
174
+ '\\downarrow' : '\U00002193',
175
+ '\\Downarrow' : '\U000021d3',
176
+ '\\updownarrow' : '\U00002195',
177
+ '\\Updownarrow' : '\U000021d5',
178
+ '\\langle' : '\U000027e8',
179
+ '\\rangle' : '\U000027e9',
180
+ '\\lceil' : '\U00002308',
181
+ '\\rceil' : '\U00002309',
182
+ '\\lfloor' : '\U0000230a',
183
+ '\\rfloor' : '\U0000230b',
184
+ '\\flqq' : '\U000000ab',
185
+ '\\frqq' : '\U000000bb',
186
+ '\\bot' : '\U000022a5',
187
+ '\\top' : '\U000022a4',
188
+ '\\wedge' : '\U00002227',
189
+ '\\bigwedge' : '\U000022c0',
190
+ '\\vee' : '\U00002228',
191
+ '\\bigvee' : '\U000022c1',
192
+ '\\forall' : '\U00002200',
193
+ '\\exists' : '\U00002203',
194
+ '\\nexists' : '\U00002204',
195
+ '\\neg' : '\U000000ac',
196
+ '\\Box' : '\U000025a1',
197
+ '\\Diamond' : '\U000025c7',
198
+ '\\vdash' : '\U000022a2',
199
+ '\\models' : '\U000022a8',
200
+ '\\dashv' : '\U000022a3',
201
+ '\\surd' : '\U0000221a',
202
+ '\\le' : '\U00002264',
203
+ '\\ge' : '\U00002265',
204
+ '\\ll' : '\U0000226a',
205
+ '\\gg' : '\U0000226b',
206
+ '\\lesssim' : '\U00002272',
207
+ '\\gtrsim' : '\U00002273',
208
+ '\\lessapprox' : '\U00002a85',
209
+ '\\gtrapprox' : '\U00002a86',
210
+ '\\in' : '\U00002208',
211
+ '\\notin' : '\U00002209',
212
+ '\\subset' : '\U00002282',
213
+ '\\supset' : '\U00002283',
214
+ '\\subseteq' : '\U00002286',
215
+ '\\supseteq' : '\U00002287',
216
+ '\\sqsubset' : '\U0000228f',
217
+ '\\sqsupset' : '\U00002290',
218
+ '\\sqsubseteq' : '\U00002291',
219
+ '\\sqsupseteq' : '\U00002292',
220
+ '\\cap' : '\U00002229',
221
+ '\\bigcap' : '\U000022c2',
222
+ '\\cup' : '\U0000222a',
223
+ '\\bigcup' : '\U000022c3',
224
+ '\\sqcup' : '\U00002294',
225
+ '\\bigsqcup' : '\U00002a06',
226
+ '\\sqcap' : '\U00002293',
227
+ '\\Bigsqcap' : '\U00002a05',
228
+ '\\setminus' : '\U00002216',
229
+ '\\propto' : '\U0000221d',
230
+ '\\uplus' : '\U0000228e',
231
+ '\\bigplus' : '\U00002a04',
232
+ '\\sim' : '\U0000223c',
233
+ '\\doteq' : '\U00002250',
234
+ '\\simeq' : '\U00002243',
235
+ '\\approx' : '\U00002248',
236
+ '\\asymp' : '\U0000224d',
237
+ '\\cong' : '\U00002245',
238
+ '\\equiv' : '\U00002261',
239
+ '\\Join' : '\U000022c8',
240
+ '\\bowtie' : '\U00002a1d',
241
+ '\\prec' : '\U0000227a',
242
+ '\\succ' : '\U0000227b',
243
+ '\\preceq' : '\U0000227c',
244
+ '\\succeq' : '\U0000227d',
245
+ '\\parallel' : '\U00002225',
246
+ '\\mid' : '\U000000a6',
247
+ '\\pm' : '\U000000b1',
248
+ '\\mp' : '\U00002213',
249
+ '\\times' : '\U000000d7',
250
+ '\\div' : '\U000000f7',
251
+ '\\cdot' : '\U000022c5',
252
+ '\\star' : '\U000022c6',
253
+ '\\circ' : '\U00002218',
254
+ '\\dagger' : '\U00002020',
255
+ '\\ddagger' : '\U00002021',
256
+ '\\lhd' : '\U000022b2',
257
+ '\\rhd' : '\U000022b3',
258
+ '\\unlhd' : '\U000022b4',
259
+ '\\unrhd' : '\U000022b5',
260
+ '\\triangleleft' : '\U000025c3',
261
+ '\\triangleright' : '\U000025b9',
262
+ '\\triangle' : '\U000025b3',
263
+ '\\triangleq' : '\U0000225c',
264
+ '\\oplus' : '\U00002295',
265
+ '\\bigoplus' : '\U00002a01',
266
+ '\\otimes' : '\U00002297',
267
+ '\\bigotimes' : '\U00002a02',
268
+ '\\odot' : '\U00002299',
269
+ '\\bigodot' : '\U00002a00',
270
+ '\\ominus' : '\U00002296',
271
+ '\\oslash' : '\U00002298',
272
+ '\\dots' : '\U00002026',
273
+ '\\cdots' : '\U000022ef',
274
+ '\\sum' : '\U00002211',
275
+ '\\prod' : '\U0000220f',
276
+ '\\coprod' : '\U00002210',
277
+ '\\infty' : '\U0000221e',
278
+ '\\int' : '\U0000222b',
279
+ '\\oint' : '\U0000222e',
280
+ '\\clubsuit' : '\U00002663',
281
+ '\\diamondsuit' : '\U00002662',
282
+ '\\heartsuit' : '\U00002661',
283
+ '\\spadesuit' : '\U00002660',
284
+ '\\aleph' : '\U00002135',
285
+ '\\emptyset' : '\U00002205',
286
+ '\\nabla' : '\U00002207',
287
+ '\\partial' : '\U00002202',
288
+ '\\flat' : '\U0000266d',
289
+ '\\natural' : '\U0000266e',
290
+ '\\sharp' : '\U0000266f',
291
+ '\\angle' : '\U00002220',
292
+ '\\copyright' : '\U000000a9',
293
+ '\\textregistered' : '\U000000ae',
294
+ '\\textonequarter' : '\U000000bc',
295
+ '\\textonehalf' : '\U000000bd',
296
+ '\\textthreequarters' : '\U000000be',
297
+ '\\textordfeminine' : '\U000000aa',
298
+ '\\textordmasculine' : '\U000000ba',
299
+ '\\euro' : '\U000020ac',
300
+ '\\pounds' : '\U000000a3',
301
+ '\\yen' : '\U000000a5',
302
+ '\\textcent' : '\U000000a2',
303
+ '\\textcurrency' : '\U000000a4',
304
+ '\\textdegree' : '\U000000b0',
305
+ }
306
+
307
+ isabelle_symbols = {
308
+ '\\<zero>' : '\U0001d7ec',
309
+ '\\<one>' : '\U0001d7ed',
310
+ '\\<two>' : '\U0001d7ee',
311
+ '\\<three>' : '\U0001d7ef',
312
+ '\\<four>' : '\U0001d7f0',
313
+ '\\<five>' : '\U0001d7f1',
314
+ '\\<six>' : '\U0001d7f2',
315
+ '\\<seven>' : '\U0001d7f3',
316
+ '\\<eight>' : '\U0001d7f4',
317
+ '\\<nine>' : '\U0001d7f5',
318
+ '\\<A>' : '\U0001d49c',
319
+ '\\<B>' : '\U0000212c',
320
+ '\\<C>' : '\U0001d49e',
321
+ '\\<D>' : '\U0001d49f',
322
+ '\\<E>' : '\U00002130',
323
+ '\\<F>' : '\U00002131',
324
+ '\\<G>' : '\U0001d4a2',
325
+ '\\<H>' : '\U0000210b',
326
+ '\\<I>' : '\U00002110',
327
+ '\\<J>' : '\U0001d4a5',
328
+ '\\<K>' : '\U0001d4a6',
329
+ '\\<L>' : '\U00002112',
330
+ '\\<M>' : '\U00002133',
331
+ '\\<N>' : '\U0001d4a9',
332
+ '\\<O>' : '\U0001d4aa',
333
+ '\\<P>' : '\U0001d4ab',
334
+ '\\<Q>' : '\U0001d4ac',
335
+ '\\<R>' : '\U0000211b',
336
+ '\\<S>' : '\U0001d4ae',
337
+ '\\<T>' : '\U0001d4af',
338
+ '\\<U>' : '\U0001d4b0',
339
+ '\\<V>' : '\U0001d4b1',
340
+ '\\<W>' : '\U0001d4b2',
341
+ '\\<X>' : '\U0001d4b3',
342
+ '\\<Y>' : '\U0001d4b4',
343
+ '\\<Z>' : '\U0001d4b5',
344
+ '\\<a>' : '\U0001d5ba',
345
+ '\\<b>' : '\U0001d5bb',
346
+ '\\<c>' : '\U0001d5bc',
347
+ '\\<d>' : '\U0001d5bd',
348
+ '\\<e>' : '\U0001d5be',
349
+ '\\<f>' : '\U0001d5bf',
350
+ '\\<g>' : '\U0001d5c0',
351
+ '\\<h>' : '\U0001d5c1',
352
+ '\\<i>' : '\U0001d5c2',
353
+ '\\<j>' : '\U0001d5c3',
354
+ '\\<k>' : '\U0001d5c4',
355
+ '\\<l>' : '\U0001d5c5',
356
+ '\\<m>' : '\U0001d5c6',
357
+ '\\<n>' : '\U0001d5c7',
358
+ '\\<o>' : '\U0001d5c8',
359
+ '\\<p>' : '\U0001d5c9',
360
+ '\\<q>' : '\U0001d5ca',
361
+ '\\<r>' : '\U0001d5cb',
362
+ '\\<s>' : '\U0001d5cc',
363
+ '\\<t>' : '\U0001d5cd',
364
+ '\\<u>' : '\U0001d5ce',
365
+ '\\<v>' : '\U0001d5cf',
366
+ '\\<w>' : '\U0001d5d0',
367
+ '\\<x>' : '\U0001d5d1',
368
+ '\\<y>' : '\U0001d5d2',
369
+ '\\<z>' : '\U0001d5d3',
370
+ '\\<AA>' : '\U0001d504',
371
+ '\\<BB>' : '\U0001d505',
372
+ '\\<CC>' : '\U0000212d',
373
+ '\\<DD>' : '\U0001d507',
374
+ '\\<EE>' : '\U0001d508',
375
+ '\\<FF>' : '\U0001d509',
376
+ '\\<GG>' : '\U0001d50a',
377
+ '\\<HH>' : '\U0000210c',
378
+ '\\<II>' : '\U00002111',
379
+ '\\<JJ>' : '\U0001d50d',
380
+ '\\<KK>' : '\U0001d50e',
381
+ '\\<LL>' : '\U0001d50f',
382
+ '\\<MM>' : '\U0001d510',
383
+ '\\<NN>' : '\U0001d511',
384
+ '\\<OO>' : '\U0001d512',
385
+ '\\<PP>' : '\U0001d513',
386
+ '\\<QQ>' : '\U0001d514',
387
+ '\\<RR>' : '\U0000211c',
388
+ '\\<SS>' : '\U0001d516',
389
+ '\\<TT>' : '\U0001d517',
390
+ '\\<UU>' : '\U0001d518',
391
+ '\\<VV>' : '\U0001d519',
392
+ '\\<WW>' : '\U0001d51a',
393
+ '\\<XX>' : '\U0001d51b',
394
+ '\\<YY>' : '\U0001d51c',
395
+ '\\<ZZ>' : '\U00002128',
396
+ '\\<aa>' : '\U0001d51e',
397
+ '\\<bb>' : '\U0001d51f',
398
+ '\\<cc>' : '\U0001d520',
399
+ '\\<dd>' : '\U0001d521',
400
+ '\\<ee>' : '\U0001d522',
401
+ '\\<ff>' : '\U0001d523',
402
+ '\\<gg>' : '\U0001d524',
403
+ '\\<hh>' : '\U0001d525',
404
+ '\\<ii>' : '\U0001d526',
405
+ '\\<jj>' : '\U0001d527',
406
+ '\\<kk>' : '\U0001d528',
407
+ '\\<ll>' : '\U0001d529',
408
+ '\\<mm>' : '\U0001d52a',
409
+ '\\<nn>' : '\U0001d52b',
410
+ '\\<oo>' : '\U0001d52c',
411
+ '\\<pp>' : '\U0001d52d',
412
+ '\\<qq>' : '\U0001d52e',
413
+ '\\<rr>' : '\U0001d52f',
414
+ '\\<ss>' : '\U0001d530',
415
+ '\\<tt>' : '\U0001d531',
416
+ '\\<uu>' : '\U0001d532',
417
+ '\\<vv>' : '\U0001d533',
418
+ '\\<ww>' : '\U0001d534',
419
+ '\\<xx>' : '\U0001d535',
420
+ '\\<yy>' : '\U0001d536',
421
+ '\\<zz>' : '\U0001d537',
422
+ '\\<alpha>' : '\U000003b1',
423
+ '\\<beta>' : '\U000003b2',
424
+ '\\<gamma>' : '\U000003b3',
425
+ '\\<delta>' : '\U000003b4',
426
+ '\\<epsilon>' : '\U000003b5',
427
+ '\\<zeta>' : '\U000003b6',
428
+ '\\<eta>' : '\U000003b7',
429
+ '\\<theta>' : '\U000003b8',
430
+ '\\<iota>' : '\U000003b9',
431
+ '\\<kappa>' : '\U000003ba',
432
+ '\\<lambda>' : '\U000003bb',
433
+ '\\<mu>' : '\U000003bc',
434
+ '\\<nu>' : '\U000003bd',
435
+ '\\<xi>' : '\U000003be',
436
+ '\\<pi>' : '\U000003c0',
437
+ '\\<rho>' : '\U000003c1',
438
+ '\\<sigma>' : '\U000003c3',
439
+ '\\<tau>' : '\U000003c4',
440
+ '\\<upsilon>' : '\U000003c5',
441
+ '\\<phi>' : '\U000003c6',
442
+ '\\<chi>' : '\U000003c7',
443
+ '\\<psi>' : '\U000003c8',
444
+ '\\<omega>' : '\U000003c9',
445
+ '\\<Gamma>' : '\U00000393',
446
+ '\\<Delta>' : '\U00000394',
447
+ '\\<Theta>' : '\U00000398',
448
+ '\\<Lambda>' : '\U0000039b',
449
+ '\\<Xi>' : '\U0000039e',
450
+ '\\<Pi>' : '\U000003a0',
451
+ '\\<Sigma>' : '\U000003a3',
452
+ '\\<Upsilon>' : '\U000003a5',
453
+ '\\<Phi>' : '\U000003a6',
454
+ '\\<Psi>' : '\U000003a8',
455
+ '\\<Omega>' : '\U000003a9',
456
+ '\\<bool>' : '\U0001d539',
457
+ '\\<complex>' : '\U00002102',
458
+ '\\<nat>' : '\U00002115',
459
+ '\\<rat>' : '\U0000211a',
460
+ '\\<real>' : '\U0000211d',
461
+ '\\<int>' : '\U00002124',
462
+ '\\<leftarrow>' : '\U00002190',
463
+ '\\<longleftarrow>' : '\U000027f5',
464
+ '\\<rightarrow>' : '\U00002192',
465
+ '\\<longrightarrow>' : '\U000027f6',
466
+ '\\<Leftarrow>' : '\U000021d0',
467
+ '\\<Longleftarrow>' : '\U000027f8',
468
+ '\\<Rightarrow>' : '\U000021d2',
469
+ '\\<Longrightarrow>' : '\U000027f9',
470
+ '\\<leftrightarrow>' : '\U00002194',
471
+ '\\<longleftrightarrow>' : '\U000027f7',
472
+ '\\<Leftrightarrow>' : '\U000021d4',
473
+ '\\<Longleftrightarrow>' : '\U000027fa',
474
+ '\\<mapsto>' : '\U000021a6',
475
+ '\\<longmapsto>' : '\U000027fc',
476
+ '\\<midarrow>' : '\U00002500',
477
+ '\\<Midarrow>' : '\U00002550',
478
+ '\\<hookleftarrow>' : '\U000021a9',
479
+ '\\<hookrightarrow>' : '\U000021aa',
480
+ '\\<leftharpoondown>' : '\U000021bd',
481
+ '\\<rightharpoondown>' : '\U000021c1',
482
+ '\\<leftharpoonup>' : '\U000021bc',
483
+ '\\<rightharpoonup>' : '\U000021c0',
484
+ '\\<rightleftharpoons>' : '\U000021cc',
485
+ '\\<leadsto>' : '\U0000219d',
486
+ '\\<downharpoonleft>' : '\U000021c3',
487
+ '\\<downharpoonright>' : '\U000021c2',
488
+ '\\<upharpoonleft>' : '\U000021bf',
489
+ '\\<upharpoonright>' : '\U000021be',
490
+ '\\<restriction>' : '\U000021be',
491
+ '\\<Colon>' : '\U00002237',
492
+ '\\<up>' : '\U00002191',
493
+ '\\<Up>' : '\U000021d1',
494
+ '\\<down>' : '\U00002193',
495
+ '\\<Down>' : '\U000021d3',
496
+ '\\<updown>' : '\U00002195',
497
+ '\\<Updown>' : '\U000021d5',
498
+ '\\<langle>' : '\U000027e8',
499
+ '\\<rangle>' : '\U000027e9',
500
+ '\\<lceil>' : '\U00002308',
501
+ '\\<rceil>' : '\U00002309',
502
+ '\\<lfloor>' : '\U0000230a',
503
+ '\\<rfloor>' : '\U0000230b',
504
+ '\\<lparr>' : '\U00002987',
505
+ '\\<rparr>' : '\U00002988',
506
+ '\\<lbrakk>' : '\U000027e6',
507
+ '\\<rbrakk>' : '\U000027e7',
508
+ '\\<lbrace>' : '\U00002983',
509
+ '\\<rbrace>' : '\U00002984',
510
+ '\\<guillemotleft>' : '\U000000ab',
511
+ '\\<guillemotright>' : '\U000000bb',
512
+ '\\<bottom>' : '\U000022a5',
513
+ '\\<top>' : '\U000022a4',
514
+ '\\<and>' : '\U00002227',
515
+ '\\<And>' : '\U000022c0',
516
+ '\\<or>' : '\U00002228',
517
+ '\\<Or>' : '\U000022c1',
518
+ '\\<forall>' : '\U00002200',
519
+ '\\<exists>' : '\U00002203',
520
+ '\\<nexists>' : '\U00002204',
521
+ '\\<not>' : '\U000000ac',
522
+ '\\<box>' : '\U000025a1',
523
+ '\\<diamond>' : '\U000025c7',
524
+ '\\<turnstile>' : '\U000022a2',
525
+ '\\<Turnstile>' : '\U000022a8',
526
+ '\\<tturnstile>' : '\U000022a9',
527
+ '\\<TTurnstile>' : '\U000022ab',
528
+ '\\<stileturn>' : '\U000022a3',
529
+ '\\<surd>' : '\U0000221a',
530
+ '\\<le>' : '\U00002264',
531
+ '\\<ge>' : '\U00002265',
532
+ '\\<lless>' : '\U0000226a',
533
+ '\\<ggreater>' : '\U0000226b',
534
+ '\\<lesssim>' : '\U00002272',
535
+ '\\<greatersim>' : '\U00002273',
536
+ '\\<lessapprox>' : '\U00002a85',
537
+ '\\<greaterapprox>' : '\U00002a86',
538
+ '\\<in>' : '\U00002208',
539
+ '\\<notin>' : '\U00002209',
540
+ '\\<subset>' : '\U00002282',
541
+ '\\<supset>' : '\U00002283',
542
+ '\\<subseteq>' : '\U00002286',
543
+ '\\<supseteq>' : '\U00002287',
544
+ '\\<sqsubset>' : '\U0000228f',
545
+ '\\<sqsupset>' : '\U00002290',
546
+ '\\<sqsubseteq>' : '\U00002291',
547
+ '\\<sqsupseteq>' : '\U00002292',
548
+ '\\<inter>' : '\U00002229',
549
+ '\\<Inter>' : '\U000022c2',
550
+ '\\<union>' : '\U0000222a',
551
+ '\\<Union>' : '\U000022c3',
552
+ '\\<squnion>' : '\U00002294',
553
+ '\\<Squnion>' : '\U00002a06',
554
+ '\\<sqinter>' : '\U00002293',
555
+ '\\<Sqinter>' : '\U00002a05',
556
+ '\\<setminus>' : '\U00002216',
557
+ '\\<propto>' : '\U0000221d',
558
+ '\\<uplus>' : '\U0000228e',
559
+ '\\<Uplus>' : '\U00002a04',
560
+ '\\<noteq>' : '\U00002260',
561
+ '\\<sim>' : '\U0000223c',
562
+ '\\<doteq>' : '\U00002250',
563
+ '\\<simeq>' : '\U00002243',
564
+ '\\<approx>' : '\U00002248',
565
+ '\\<asymp>' : '\U0000224d',
566
+ '\\<cong>' : '\U00002245',
567
+ '\\<smile>' : '\U00002323',
568
+ '\\<equiv>' : '\U00002261',
569
+ '\\<frown>' : '\U00002322',
570
+ '\\<Join>' : '\U000022c8',
571
+ '\\<bowtie>' : '\U00002a1d',
572
+ '\\<prec>' : '\U0000227a',
573
+ '\\<succ>' : '\U0000227b',
574
+ '\\<preceq>' : '\U0000227c',
575
+ '\\<succeq>' : '\U0000227d',
576
+ '\\<parallel>' : '\U00002225',
577
+ '\\<bar>' : '\U000000a6',
578
+ '\\<plusminus>' : '\U000000b1',
579
+ '\\<minusplus>' : '\U00002213',
580
+ '\\<times>' : '\U000000d7',
581
+ '\\<div>' : '\U000000f7',
582
+ '\\<cdot>' : '\U000022c5',
583
+ '\\<star>' : '\U000022c6',
584
+ '\\<bullet>' : '\U00002219',
585
+ '\\<circ>' : '\U00002218',
586
+ '\\<dagger>' : '\U00002020',
587
+ '\\<ddagger>' : '\U00002021',
588
+ '\\<lhd>' : '\U000022b2',
589
+ '\\<rhd>' : '\U000022b3',
590
+ '\\<unlhd>' : '\U000022b4',
591
+ '\\<unrhd>' : '\U000022b5',
592
+ '\\<triangleleft>' : '\U000025c3',
593
+ '\\<triangleright>' : '\U000025b9',
594
+ '\\<triangle>' : '\U000025b3',
595
+ '\\<triangleq>' : '\U0000225c',
596
+ '\\<oplus>' : '\U00002295',
597
+ '\\<Oplus>' : '\U00002a01',
598
+ '\\<otimes>' : '\U00002297',
599
+ '\\<Otimes>' : '\U00002a02',
600
+ '\\<odot>' : '\U00002299',
601
+ '\\<Odot>' : '\U00002a00',
602
+ '\\<ominus>' : '\U00002296',
603
+ '\\<oslash>' : '\U00002298',
604
+ '\\<dots>' : '\U00002026',
605
+ '\\<cdots>' : '\U000022ef',
606
+ '\\<Sum>' : '\U00002211',
607
+ '\\<Prod>' : '\U0000220f',
608
+ '\\<Coprod>' : '\U00002210',
609
+ '\\<infinity>' : '\U0000221e',
610
+ '\\<integral>' : '\U0000222b',
611
+ '\\<ointegral>' : '\U0000222e',
612
+ '\\<clubsuit>' : '\U00002663',
613
+ '\\<diamondsuit>' : '\U00002662',
614
+ '\\<heartsuit>' : '\U00002661',
615
+ '\\<spadesuit>' : '\U00002660',
616
+ '\\<aleph>' : '\U00002135',
617
+ '\\<emptyset>' : '\U00002205',
618
+ '\\<nabla>' : '\U00002207',
619
+ '\\<partial>' : '\U00002202',
620
+ '\\<flat>' : '\U0000266d',
621
+ '\\<natural>' : '\U0000266e',
622
+ '\\<sharp>' : '\U0000266f',
623
+ '\\<angle>' : '\U00002220',
624
+ '\\<copyright>' : '\U000000a9',
625
+ '\\<registered>' : '\U000000ae',
626
+ '\\<hyphen>' : '\U000000ad',
627
+ '\\<inverse>' : '\U000000af',
628
+ '\\<onequarter>' : '\U000000bc',
629
+ '\\<onehalf>' : '\U000000bd',
630
+ '\\<threequarters>' : '\U000000be',
631
+ '\\<ordfeminine>' : '\U000000aa',
632
+ '\\<ordmasculine>' : '\U000000ba',
633
+ '\\<section>' : '\U000000a7',
634
+ '\\<paragraph>' : '\U000000b6',
635
+ '\\<exclamdown>' : '\U000000a1',
636
+ '\\<questiondown>' : '\U000000bf',
637
+ '\\<euro>' : '\U000020ac',
638
+ '\\<pounds>' : '\U000000a3',
639
+ '\\<yen>' : '\U000000a5',
640
+ '\\<cent>' : '\U000000a2',
641
+ '\\<currency>' : '\U000000a4',
642
+ '\\<degree>' : '\U000000b0',
643
+ '\\<amalg>' : '\U00002a3f',
644
+ '\\<mho>' : '\U00002127',
645
+ '\\<lozenge>' : '\U000025ca',
646
+ '\\<wp>' : '\U00002118',
647
+ '\\<wrong>' : '\U00002240',
648
+ '\\<struct>' : '\U000022c4',
649
+ '\\<acute>' : '\U000000b4',
650
+ '\\<index>' : '\U00000131',
651
+ '\\<dieresis>' : '\U000000a8',
652
+ '\\<cedilla>' : '\U000000b8',
653
+ '\\<hungarumlaut>' : '\U000002dd',
654
+ '\\<some>' : '\U000003f5',
655
+ '\\<newline>' : '\U000023ce',
656
+ '\\<open>' : '\U00002039',
657
+ '\\<close>' : '\U0000203a',
658
+ '\\<here>' : '\U00002302',
659
+ '\\<^sub>' : '\U000021e9',
660
+ '\\<^sup>' : '\U000021e7',
661
+ '\\<^bold>' : '\U00002759',
662
+ '\\<^bsub>' : '\U000021d8',
663
+ '\\<^esub>' : '\U000021d9',
664
+ '\\<^bsup>' : '\U000021d7',
665
+ '\\<^esup>' : '\U000021d6',
666
+ }
667
+
668
+ lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols}
669
+
670
+ def __init__(self, **options):
671
+ Filter.__init__(self, **options)
672
+ lang = get_choice_opt(options, 'lang',
673
+ ['isabelle', 'latex'], 'isabelle')
674
+ self.symbols = self.lang_map[lang]
675
+
676
+ def filter(self, lexer, stream):
677
+ for ttype, value in stream:
678
+ if value in self.symbols:
679
+ yield ttype, self.symbols[value]
680
+ else:
681
+ yield ttype, value
682
+
683
+
684
+ class KeywordCaseFilter(Filter):
685
+ """Convert keywords to lowercase or uppercase or capitalize them, which
686
+ means first letter uppercase, rest lowercase.
687
+
688
+ This can be useful e.g. if you highlight Pascal code and want to adapt the
689
+ code to your styleguide.
690
+
691
+ Options accepted:
692
+
693
+ `case` : string
694
+ The casing to convert keywords to. Must be one of ``'lower'``,
695
+ ``'upper'`` or ``'capitalize'``. The default is ``'lower'``.
696
+ """
697
+
698
+ def __init__(self, **options):
699
+ Filter.__init__(self, **options)
700
+ case = get_choice_opt(options, 'case',
701
+ ['lower', 'upper', 'capitalize'], 'lower')
702
+ self.convert = getattr(str, case)
703
+
704
+ def filter(self, lexer, stream):
705
+ for ttype, value in stream:
706
+ if ttype in Keyword:
707
+ yield ttype, self.convert(value)
708
+ else:
709
+ yield ttype, value
710
+
711
+
712
+ class NameHighlightFilter(Filter):
713
+ """Highlight a normal Name (and Name.*) token with a different token type.
714
+
715
+ Example::
716
+
717
+ filter = NameHighlightFilter(
718
+ names=['foo', 'bar', 'baz'],
719
+ tokentype=Name.Function,
720
+ )
721
+
722
+ This would highlight the names "foo", "bar" and "baz"
723
+ as functions. `Name.Function` is the default token type.
724
+
725
+ Options accepted:
726
+
727
+ `names` : list of strings
728
+ A list of names that should be given the different token type.
729
+ There is no default.
730
+ `tokentype` : TokenType or string
731
+ A token type or a string containing a token type name that is
732
+ used for highlighting the strings in `names`. The default is
733
+ `Name.Function`.
734
+ """
735
+
736
+ def __init__(self, **options):
737
+ Filter.__init__(self, **options)
738
+ self.names = set(get_list_opt(options, 'names', []))
739
+ tokentype = options.get('tokentype')
740
+ if tokentype:
741
+ self.tokentype = string_to_tokentype(tokentype)
742
+ else:
743
+ self.tokentype = Name.Function
744
+
745
+ def filter(self, lexer, stream):
746
+ for ttype, value in stream:
747
+ if ttype in Name and value in self.names:
748
+ yield self.tokentype, value
749
+ else:
750
+ yield ttype, value
751
+
752
+
753
+ class ErrorToken(Exception):
754
+ pass
755
+
756
+
757
+ class RaiseOnErrorTokenFilter(Filter):
758
+ """Raise an exception when the lexer generates an error token.
759
+
760
+ Options accepted:
761
+
762
+ `excclass` : Exception class
763
+ The exception class to raise.
764
+ The default is `pygments.filters.ErrorToken`.
765
+
766
+ .. versionadded:: 0.8
767
+ """
768
+
769
+ def __init__(self, **options):
770
+ Filter.__init__(self, **options)
771
+ self.exception = options.get('excclass', ErrorToken)
772
+ try:
773
+ # issubclass() will raise TypeError if first argument is not a class
774
+ if not issubclass(self.exception, Exception):
775
+ raise TypeError
776
+ except TypeError:
777
+ raise OptionError('excclass option is not an exception class')
778
+
779
+ def filter(self, lexer, stream):
780
+ for ttype, value in stream:
781
+ if ttype is Error:
782
+ raise self.exception(value)
783
+ yield ttype, value
784
+
785
+
786
+ class VisibleWhitespaceFilter(Filter):
787
+ """Convert tabs, newlines and/or spaces to visible characters.
788
+
789
+ Options accepted:
790
+
791
+ `spaces` : string or bool
792
+ If this is a one-character string, spaces will be replaces by this string.
793
+ If it is another true value, spaces will be replaced by ``·`` (unicode
794
+ MIDDLE DOT). If it is a false value, spaces will not be replaced. The
795
+ default is ``False``.
796
+ `tabs` : string or bool
797
+ The same as for `spaces`, but the default replacement character is ``»``
798
+ (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value
799
+ is ``False``. Note: this will not work if the `tabsize` option for the
800
+ lexer is nonzero, as tabs will already have been expanded then.
801
+ `tabsize` : int
802
+ If tabs are to be replaced by this filter (see the `tabs` option), this
803
+ is the total number of characters that a tab should be expanded to.
804
+ The default is ``8``.
805
+ `newlines` : string or bool
806
+ The same as for `spaces`, but the default replacement character is ``¶``
807
+ (unicode PILCROW SIGN). The default value is ``False``.
808
+ `wstokentype` : bool
809
+ If true, give whitespace the special `Whitespace` token type. This allows
810
+ styling the visible whitespace differently (e.g. greyed out), but it can
811
+ disrupt background colors. The default is ``True``.
812
+
813
+ .. versionadded:: 0.8
814
+ """
815
+
816
+ def __init__(self, **options):
817
+ Filter.__init__(self, **options)
818
+ for name, default in [('spaces', '·'),
819
+ ('tabs', '»'),
820
+ ('newlines', '¶')]:
821
+ opt = options.get(name, False)
822
+ if isinstance(opt, str) and len(opt) == 1:
823
+ setattr(self, name, opt)
824
+ else:
825
+ setattr(self, name, (opt and default or ''))
826
+ tabsize = get_int_opt(options, 'tabsize', 8)
827
+ if self.tabs:
828
+ self.tabs += ' ' * (tabsize - 1)
829
+ if self.newlines:
830
+ self.newlines += '\n'
831
+ self.wstt = get_bool_opt(options, 'wstokentype', True)
832
+
833
+ def filter(self, lexer, stream):
834
+ if self.wstt:
835
+ spaces = self.spaces or ' '
836
+ tabs = self.tabs or '\t'
837
+ newlines = self.newlines or '\n'
838
+ regex = re.compile(r'\s')
839
+
840
+ def replacefunc(wschar):
841
+ if wschar == ' ':
842
+ return spaces
843
+ elif wschar == '\t':
844
+ return tabs
845
+ elif wschar == '\n':
846
+ return newlines
847
+ return wschar
848
+
849
+ for ttype, value in stream:
850
+ yield from _replace_special(ttype, value, regex, Whitespace,
851
+ replacefunc)
852
+ else:
853
+ spaces, tabs, newlines = self.spaces, self.tabs, self.newlines
854
+ # simpler processing
855
+ for ttype, value in stream:
856
+ if spaces:
857
+ value = value.replace(' ', spaces)
858
+ if tabs:
859
+ value = value.replace('\t', tabs)
860
+ if newlines:
861
+ value = value.replace('\n', newlines)
862
+ yield ttype, value
863
+
864
+
865
+ class GobbleFilter(Filter):
866
+ """Gobbles source code lines (eats initial characters).
867
+
868
+ This filter drops the first ``n`` characters off every line of code. This
869
+ may be useful when the source code fed to the lexer is indented by a fixed
870
+ amount of space that isn't desired in the output.
871
+
872
+ Options accepted:
873
+
874
+ `n` : int
875
+ The number of characters to gobble.
876
+
877
+ .. versionadded:: 1.2
878
+ """
879
+ def __init__(self, **options):
880
+ Filter.__init__(self, **options)
881
+ self.n = get_int_opt(options, 'n', 0)
882
+
883
+ def gobble(self, value, left):
884
+ if left < len(value):
885
+ return value[left:], 0
886
+ else:
887
+ return '', left - len(value)
888
+
889
+ def filter(self, lexer, stream):
890
+ n = self.n
891
+ left = n # How many characters left to gobble.
892
+ for ttype, value in stream:
893
+ # Remove ``left`` tokens from first line, ``n`` from all others.
894
+ parts = value.split('\n')
895
+ (parts[0], left) = self.gobble(parts[0], left)
896
+ for i in range(1, len(parts)):
897
+ (parts[i], left) = self.gobble(parts[i], n)
898
+ value = '\n'.join(parts)
899
+
900
+ if value != '':
901
+ yield ttype, value
902
+
903
+
904
+ class TokenMergeFilter(Filter):
905
+ """Merges consecutive tokens with the same token type in the output
906
+ stream of a lexer.
907
+
908
+ .. versionadded:: 1.2
909
+ """
910
+ def __init__(self, **options):
911
+ Filter.__init__(self, **options)
912
+
913
+ def filter(self, lexer, stream):
914
+ current_type = None
915
+ current_value = None
916
+ for ttype, value in stream:
917
+ if ttype is current_type:
918
+ current_value += value
919
+ else:
920
+ if current_type is not None:
921
+ yield current_type, current_value
922
+ current_type = ttype
923
+ current_value = value
924
+ if current_type is not None:
925
+ yield current_type, current_value
926
+
927
+
928
+ FILTERS = {
929
+ 'codetagify': CodeTagFilter,
930
+ 'keywordcase': KeywordCaseFilter,
931
+ 'highlight': NameHighlightFilter,
932
+ 'raiseonerror': RaiseOnErrorTokenFilter,
933
+ 'whitespace': VisibleWhitespaceFilter,
934
+ 'gobble': GobbleFilter,
935
+ 'tokenmerge': TokenMergeFilter,
936
+ 'symbols': SymbolFilter,
937
+ }
venv/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (29.5 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatter.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatter
3
+ ~~~~~~~~~~~~~~~~~~
4
+
5
+ Base formatter class.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import codecs
12
+
13
+ from pip._vendor.pygments.util import get_bool_opt
14
+ from pip._vendor.pygments.styles import get_style_by_name
15
+
16
+ __all__ = ['Formatter']
17
+
18
+
19
+ def _lookup_style(style):
20
+ if isinstance(style, str):
21
+ return get_style_by_name(style)
22
+ return style
23
+
24
+
25
+ class Formatter:
26
+ """
27
+ Converts a token stream to text.
28
+
29
+ Options accepted:
30
+
31
+ ``style``
32
+ The style to use, can be a string or a Style subclass
33
+ (default: "default"). Not used by e.g. the
34
+ TerminalFormatter.
35
+ ``full``
36
+ Tells the formatter to output a "full" document, i.e.
37
+ a complete self-contained document. This doesn't have
38
+ any effect for some formatters (default: false).
39
+ ``title``
40
+ If ``full`` is true, the title that should be used to
41
+ caption the document (default: '').
42
+ ``encoding``
43
+ If given, must be an encoding name. This will be used to
44
+ convert the Unicode token strings to byte strings in the
45
+ output. If it is "" or None, Unicode strings will be written
46
+ to the output file, which most file-like objects do not
47
+ support (default: None).
48
+ ``outencoding``
49
+ Overrides ``encoding`` if given.
50
+ """
51
+
52
+ #: Name of the formatter
53
+ name = None
54
+
55
+ #: Shortcuts for the formatter
56
+ aliases = []
57
+
58
+ #: fn match rules
59
+ filenames = []
60
+
61
+ #: If True, this formatter outputs Unicode strings when no encoding
62
+ #: option is given.
63
+ unicodeoutput = True
64
+
65
+ def __init__(self, **options):
66
+ self.style = _lookup_style(options.get('style', 'default'))
67
+ self.full = get_bool_opt(options, 'full', False)
68
+ self.title = options.get('title', '')
69
+ self.encoding = options.get('encoding', None) or None
70
+ if self.encoding in ('guess', 'chardet'):
71
+ # can happen for e.g. pygmentize -O encoding=guess
72
+ self.encoding = 'utf-8'
73
+ self.encoding = options.get('outencoding') or self.encoding
74
+ self.options = options
75
+
76
+ def get_style_defs(self, arg=''):
77
+ """
78
+ Return the style definitions for the current style as a string.
79
+
80
+ ``arg`` is an additional argument whose meaning depends on the
81
+ formatter used. Note that ``arg`` can also be a list or tuple
82
+ for some formatters like the html formatter.
83
+ """
84
+ return ''
85
+
86
+ def format(self, tokensource, outfile):
87
+ """
88
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
89
+ tuples and write it into ``outfile``.
90
+ """
91
+ if self.encoding:
92
+ # wrap the outfile in a StreamWriter
93
+ outfile = codecs.lookup(self.encoding)[3](outfile)
94
+ return self.format_unencoded(tokensource, outfile)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Pygments formatters.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+ import sys
13
+ import types
14
+ import fnmatch
15
+ from os.path import basename
16
+
17
+ from pip._vendor.pygments.formatters._mapping import FORMATTERS
18
+ from pip._vendor.pygments.plugin import find_plugin_formatters
19
+ from pip._vendor.pygments.util import ClassNotFound
20
+
21
+ __all__ = ['get_formatter_by_name', 'get_formatter_for_filename',
22
+ 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)
23
+
24
+ _formatter_cache = {} # classes by name
25
+ _pattern_cache = {}
26
+
27
+
28
+ def _fn_matches(fn, glob):
29
+ """Return whether the supplied file name fn matches pattern filename."""
30
+ if glob not in _pattern_cache:
31
+ pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
32
+ return pattern.match(fn)
33
+ return _pattern_cache[glob].match(fn)
34
+
35
+
36
+ def _load_formatters(module_name):
37
+ """Load a formatter (and all others in the module too)."""
38
+ mod = __import__(module_name, None, None, ['__all__'])
39
+ for formatter_name in mod.__all__:
40
+ cls = getattr(mod, formatter_name)
41
+ _formatter_cache[cls.name] = cls
42
+
43
+
44
+ def get_all_formatters():
45
+ """Return a generator for all formatter classes."""
46
+ # NB: this returns formatter classes, not info like get_all_lexers().
47
+ for info in FORMATTERS.values():
48
+ if info[1] not in _formatter_cache:
49
+ _load_formatters(info[0])
50
+ yield _formatter_cache[info[1]]
51
+ for _, formatter in find_plugin_formatters():
52
+ yield formatter
53
+
54
+
55
+ def find_formatter_class(alias):
56
+ """Lookup a formatter by alias.
57
+
58
+ Returns None if not found.
59
+ """
60
+ for module_name, name, aliases, _, _ in FORMATTERS.values():
61
+ if alias in aliases:
62
+ if name not in _formatter_cache:
63
+ _load_formatters(module_name)
64
+ return _formatter_cache[name]
65
+ for _, cls in find_plugin_formatters():
66
+ if alias in cls.aliases:
67
+ return cls
68
+
69
+
70
+ def get_formatter_by_name(_alias, **options):
71
+ """Lookup and instantiate a formatter by alias.
72
+
73
+ Raises ClassNotFound if not found.
74
+ """
75
+ cls = find_formatter_class(_alias)
76
+ if cls is None:
77
+ raise ClassNotFound("no formatter found for name %r" % _alias)
78
+ return cls(**options)
79
+
80
+
81
+ def load_formatter_from_file(filename, formattername="CustomFormatter",
82
+ **options):
83
+ """Load a formatter from a file.
84
+
85
+ This method expects a file located relative to the current working
86
+ directory, which contains a class named CustomFormatter. By default,
87
+ it expects the Formatter to be named CustomFormatter; you can specify
88
+ your own class name as the second argument to this function.
89
+
90
+ Users should be very careful with the input, because this method
91
+ is equivalent to running eval on the input file.
92
+
93
+ Raises ClassNotFound if there are any problems importing the Formatter.
94
+
95
+ .. versionadded:: 2.2
96
+ """
97
+ try:
98
+ # This empty dict will contain the namespace for the exec'd file
99
+ custom_namespace = {}
100
+ with open(filename, 'rb') as f:
101
+ exec(f.read(), custom_namespace)
102
+ # Retrieve the class `formattername` from that namespace
103
+ if formattername not in custom_namespace:
104
+ raise ClassNotFound('no valid %s class found in %s' %
105
+ (formattername, filename))
106
+ formatter_class = custom_namespace[formattername]
107
+ # And finally instantiate it with the options
108
+ return formatter_class(**options)
109
+ except OSError as err:
110
+ raise ClassNotFound('cannot read %s: %s' % (filename, err))
111
+ except ClassNotFound:
112
+ raise
113
+ except Exception as err:
114
+ raise ClassNotFound('error when loading custom formatter: %s' % err)
115
+
116
+
117
+ def get_formatter_for_filename(fn, **options):
118
+ """Lookup and instantiate a formatter by filename pattern.
119
+
120
+ Raises ClassNotFound if not found.
121
+ """
122
+ fn = basename(fn)
123
+ for modname, name, _, filenames, _ in FORMATTERS.values():
124
+ for filename in filenames:
125
+ if _fn_matches(fn, filename):
126
+ if name not in _formatter_cache:
127
+ _load_formatters(modname)
128
+ return _formatter_cache[name](**options)
129
+ for cls in find_plugin_formatters():
130
+ for filename in cls.filenames:
131
+ if _fn_matches(fn, filename):
132
+ return cls(**options)
133
+ raise ClassNotFound("no formatter found for file name %r" % fn)
134
+
135
+
136
+ class _automodule(types.ModuleType):
137
+ """Automatically import formatters."""
138
+
139
+ def __getattr__(self, name):
140
+ info = FORMATTERS.get(name)
141
+ if info:
142
+ _load_formatters(info[0])
143
+ cls = _formatter_cache[info[1]]
144
+ setattr(self, name, cls)
145
+ return cls
146
+ raise AttributeError(name)
147
+
148
+
149
+ oldmod = sys.modules[__name__]
150
+ newmod = _automodule(__name__)
151
+ newmod.__dict__.update(oldmod.__dict__)
152
+ sys.modules[__name__] = newmod
153
+ del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.66 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-310.pyc ADDED
Binary file (5.53 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-310.pyc ADDED
Binary file (3.08 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/groff.cpython-310.pyc ADDED
Binary file (4.35 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/html.cpython-310.pyc ADDED
Binary file (29.1 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/img.cpython-310.pyc ADDED
Binary file (17.5 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/irc.cpython-310.pyc ADDED
Binary file (4.58 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/latex.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc ADDED
Binary file (4.8 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-310.pyc ADDED
Binary file (4.13 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/svg.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc ADDED
Binary file (4 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-310.pyc ADDED
Binary file (9.25 kB). View file
 
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters._mapping
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter mapping definitions. This file is generated by itself. Everytime
6
+ you change something on a builtin formatter definition, run this script from
7
+ the formatters folder to update it.
8
+
9
+ Do not alter the FORMATTERS dictionary by hand.
10
+
11
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
12
+ :license: BSD, see LICENSE for details.
13
+ """
14
+
15
+ FORMATTERS = {
16
+ 'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'),
17
+ 'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
18
+ 'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
19
+ 'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),
20
+ 'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass` option."),
21
+ 'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),
22
+ 'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
23
+ 'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),
24
+ 'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),
25
+ 'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),
26
+ 'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),
27
+ 'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),
28
+ 'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'),
29
+ 'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file. This formatter is still experimental. Each line of code is a ``<text>`` element with explicit ``x`` and ``y`` coordinates containing ``<tspan>`` elements with the individual token styles.'),
30
+ 'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
31
+ 'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'),
32
+ 'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),
33
+ 'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.')
34
+ }
35
+
36
+ if __name__ == '__main__': # pragma: no cover
37
+ import sys
38
+ import os
39
+
40
+ # lookup formatters
41
+ found_formatters = []
42
+ imports = []
43
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
44
+ from pip._vendor.pygments.util import docstring_headline
45
+
46
+ for root, dirs, files in os.walk('.'):
47
+ for filename in files:
48
+ if filename.endswith('.py') and not filename.startswith('_'):
49
+ module_name = 'pygments.formatters%s.%s' % (
50
+ root[1:].replace('/', '.'), filename[:-3])
51
+ print(module_name)
52
+ module = __import__(module_name, None, None, [''])
53
+ for formatter_name in module.__all__:
54
+ formatter = getattr(module, formatter_name)
55
+ found_formatters.append(
56
+ '%r: %r' % (formatter_name,
57
+ (module_name,
58
+ formatter.name,
59
+ tuple(formatter.aliases),
60
+ tuple(formatter.filenames),
61
+ docstring_headline(formatter))))
62
+ # sort them to make the diff minimal
63
+ found_formatters.sort()
64
+
65
+ # extract useful sourcecode from this file
66
+ with open(__file__) as fp:
67
+ content = fp.read()
68
+ # replace crnl to nl for Windows.
69
+ #
70
+ # Note that, originally, contributers should keep nl of master
71
+ # repository, for example by using some kind of automatic
72
+ # management EOL, like `EolExtension
73
+ # <https://www.mercurial-scm.org/wiki/EolExtension>`.
74
+ content = content.replace("\r\n", "\n")
75
+ header = content[:content.find('FORMATTERS = {')]
76
+ footer = content[content.find("if __name__ == '__main__':"):]
77
+
78
+ # write new file
79
+ with open(__file__, 'w') as fp:
80
+ fp.write(header)
81
+ fp.write('FORMATTERS = {\n %s\n}\n\n' % ',\n '.join(found_formatters))
82
+ fp.write(footer)
83
+
84
+ print ('=== %d formatters processed.' % len(found_formatters))
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/bbcode.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.bbcode
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ BBcode formatter.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.util import get_bool_opt
14
+
15
+ __all__ = ['BBCodeFormatter']
16
+
17
+
18
+ class BBCodeFormatter(Formatter):
19
+ """
20
+ Format tokens with BBcodes. These formatting codes are used by many
21
+ bulletin boards, so you can highlight your sourcecode with pygments before
22
+ posting it there.
23
+
24
+ This formatter has no support for background colors and borders, as there
25
+ are no common BBcode tags for that.
26
+
27
+ Some board systems (e.g. phpBB) don't support colors in their [code] tag,
28
+ so you can't use the highlighting together with that tag.
29
+ Text in a [code] tag usually is shown with a monospace font (which this
30
+ formatter can do with the ``monofont`` option) and no spaces (which you
31
+ need for indentation) are removed.
32
+
33
+ Additional options accepted:
34
+
35
+ `style`
36
+ The style to use, can be a string or a Style subclass (default:
37
+ ``'default'``).
38
+
39
+ `codetag`
40
+ If set to true, put the output into ``[code]`` tags (default:
41
+ ``false``)
42
+
43
+ `monofont`
44
+ If set to true, add a tag to show the code with a monospace font
45
+ (default: ``false``).
46
+ """
47
+ name = 'BBCode'
48
+ aliases = ['bbcode', 'bb']
49
+ filenames = []
50
+
51
+ def __init__(self, **options):
52
+ Formatter.__init__(self, **options)
53
+ self._code = get_bool_opt(options, 'codetag', False)
54
+ self._mono = get_bool_opt(options, 'monofont', False)
55
+
56
+ self.styles = {}
57
+ self._make_styles()
58
+
59
+ def _make_styles(self):
60
+ for ttype, ndef in self.style:
61
+ start = end = ''
62
+ if ndef['color']:
63
+ start += '[color=#%s]' % ndef['color']
64
+ end = '[/color]' + end
65
+ if ndef['bold']:
66
+ start += '[b]'
67
+ end = '[/b]' + end
68
+ if ndef['italic']:
69
+ start += '[i]'
70
+ end = '[/i]' + end
71
+ if ndef['underline']:
72
+ start += '[u]'
73
+ end = '[/u]' + end
74
+ # there are no common BBcodes for background-color and border
75
+
76
+ self.styles[ttype] = start, end
77
+
78
+ def format_unencoded(self, tokensource, outfile):
79
+ if self._code:
80
+ outfile.write('[code]')
81
+ if self._mono:
82
+ outfile.write('[font=monospace]')
83
+
84
+ lastval = ''
85
+ lasttype = None
86
+
87
+ for ttype, value in tokensource:
88
+ while ttype not in self.styles:
89
+ ttype = ttype.parent
90
+ if ttype == lasttype:
91
+ lastval += value
92
+ else:
93
+ if lastval:
94
+ start, end = self.styles[lasttype]
95
+ outfile.write(''.join((start, lastval, end)))
96
+ lastval = value
97
+ lasttype = ttype
98
+
99
+ if lastval:
100
+ start, end = self.styles[lasttype]
101
+ outfile.write(''.join((start, lastval, end)))
102
+
103
+ if self._mono:
104
+ outfile.write('[/font]')
105
+ if self._code:
106
+ outfile.write('[/code]')
107
+ if self._code or self._mono:
108
+ outfile.write('\n')
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.groff
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for groff output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import math
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
14
+
15
+ __all__ = ['GroffFormatter']
16
+
17
+
18
+ class GroffFormatter(Formatter):
19
+ """
20
+ Format tokens with groff escapes to change their color and font style.
21
+
22
+ .. versionadded:: 2.11
23
+
24
+ Additional options accepted:
25
+
26
+ `style`
27
+ The style to use, can be a string or a Style subclass (default:
28
+ ``'default'``).
29
+
30
+ `monospaced`
31
+ If set to true, monospace font will be used (default: ``true``).
32
+
33
+ `linenos`
34
+ If set to true, print the line numbers (default: ``false``).
35
+
36
+ `wrap`
37
+ Wrap lines to the specified number of characters. Disabled if set to 0
38
+ (default: ``0``).
39
+ """
40
+
41
+ name = 'groff'
42
+ aliases = ['groff','troff','roff']
43
+ filenames = []
44
+
45
+ def __init__(self, **options):
46
+ Formatter.__init__(self, **options)
47
+
48
+ self.monospaced = get_bool_opt(options, 'monospaced', True)
49
+ self.linenos = get_bool_opt(options, 'linenos', False)
50
+ self._lineno = 0
51
+ self.wrap = get_int_opt(options, 'wrap', 0)
52
+ self._linelen = 0
53
+
54
+ self.styles = {}
55
+ self._make_styles()
56
+
57
+
58
+ def _make_styles(self):
59
+ regular = '\\f[CR]' if self.monospaced else '\\f[R]'
60
+ bold = '\\f[CB]' if self.monospaced else '\\f[B]'
61
+ italic = '\\f[CI]' if self.monospaced else '\\f[I]'
62
+
63
+ for ttype, ndef in self.style:
64
+ start = end = ''
65
+ if ndef['color']:
66
+ start += '\\m[%s]' % ndef['color']
67
+ end = '\\m[]' + end
68
+ if ndef['bold']:
69
+ start += bold
70
+ end = regular + end
71
+ if ndef['italic']:
72
+ start += italic
73
+ end = regular + end
74
+ if ndef['bgcolor']:
75
+ start += '\\M[%s]' % ndef['bgcolor']
76
+ end = '\\M[]' + end
77
+
78
+ self.styles[ttype] = start, end
79
+
80
+
81
+ def _define_colors(self, outfile):
82
+ colors = set()
83
+ for _, ndef in self.style:
84
+ if ndef['color'] is not None:
85
+ colors.add(ndef['color'])
86
+
87
+ for color in colors:
88
+ outfile.write('.defcolor ' + color + ' rgb #' + color + '\n')
89
+
90
+
91
+ def _write_lineno(self, outfile):
92
+ self._lineno += 1
93
+ outfile.write("%s% 4d " % (self._lineno != 1 and '\n' or '', self._lineno))
94
+
95
+
96
+ def _wrap_line(self, line):
97
+ length = len(line.rstrip('\n'))
98
+ space = ' ' if self.linenos else ''
99
+ newline = ''
100
+
101
+ if length > self.wrap:
102
+ for i in range(0, math.floor(length / self.wrap)):
103
+ chunk = line[i*self.wrap:i*self.wrap+self.wrap]
104
+ newline += (chunk + '\n' + space)
105
+ remainder = length % self.wrap
106
+ if remainder > 0:
107
+ newline += line[-remainder-1:]
108
+ self._linelen = remainder
109
+ elif self._linelen + length > self.wrap:
110
+ newline = ('\n' + space) + line
111
+ self._linelen = length
112
+ else:
113
+ newline = line
114
+ self._linelen += length
115
+
116
+ return newline
117
+
118
+
119
+ def _escape_chars(self, text):
120
+ text = text.replace('\\', '\\[u005C]'). \
121
+ replace('.', '\\[char46]'). \
122
+ replace('\'', '\\[u0027]'). \
123
+ replace('`', '\\[u0060]'). \
124
+ replace('~', '\\[u007E]')
125
+ copy = text
126
+
127
+ for char in copy:
128
+ if len(char) != len(char.encode()):
129
+ uni = char.encode('unicode_escape') \
130
+ .decode()[1:] \
131
+ .replace('x', 'u00') \
132
+ .upper()
133
+ text = text.replace(char, '\\[u' + uni[1:] + ']')
134
+
135
+ return text
136
+
137
+
138
+ def format_unencoded(self, tokensource, outfile):
139
+ self._define_colors(outfile)
140
+
141
+ outfile.write('.nf\n\\f[CR]\n')
142
+
143
+ if self.linenos:
144
+ self._write_lineno(outfile)
145
+
146
+ for ttype, value in tokensource:
147
+ start, end = self.styles[ttype]
148
+
149
+ for line in value.splitlines(True):
150
+ if self.wrap > 0:
151
+ line = self._wrap_line(line)
152
+
153
+ if start and end:
154
+ text = self._escape_chars(line.rstrip('\n'))
155
+ if text != '':
156
+ outfile.write(''.join((start, text, end)))
157
+ else:
158
+ outfile.write(self._escape_chars(line.rstrip('\n')))
159
+
160
+ if line.endswith('\n'):
161
+ if self.linenos:
162
+ self._write_lineno(outfile)
163
+ self._linelen = 0
164
+ else:
165
+ outfile.write('\n')
166
+ self._linelen = 0
167
+
168
+ outfile.write('\n.fi')
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py ADDED
@@ -0,0 +1,983 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.html
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for HTML output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import functools
12
+ import os
13
+ import sys
14
+ import os.path
15
+ from io import StringIO
16
+
17
+ from pip._vendor.pygments.formatter import Formatter
18
+ from pip._vendor.pygments.token import Token, Text, STANDARD_TYPES
19
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt
20
+
21
+ try:
22
+ import ctags
23
+ except ImportError:
24
+ ctags = None
25
+
26
+ __all__ = ['HtmlFormatter']
27
+
28
+
29
+ _escape_html_table = {
30
+ ord('&'): '&amp;',
31
+ ord('<'): '&lt;',
32
+ ord('>'): '&gt;',
33
+ ord('"'): '&quot;',
34
+ ord("'"): '&#39;',
35
+ }
36
+
37
+
38
+ def escape_html(text, table=_escape_html_table):
39
+ """Escape &, <, > as well as single and double quotes for HTML."""
40
+ return text.translate(table)
41
+
42
+
43
+ def webify(color):
44
+ if color.startswith('calc') or color.startswith('var'):
45
+ return color
46
+ else:
47
+ return '#' + color
48
+
49
+
50
+ def _get_ttype_class(ttype):
51
+ fname = STANDARD_TYPES.get(ttype)
52
+ if fname:
53
+ return fname
54
+ aname = ''
55
+ while fname is None:
56
+ aname = '-' + ttype[-1] + aname
57
+ ttype = ttype.parent
58
+ fname = STANDARD_TYPES.get(ttype)
59
+ return fname + aname
60
+
61
+
62
+ CSSFILE_TEMPLATE = '''\
63
+ /*
64
+ generated by Pygments <https://pygments.org/>
65
+ Copyright 2006-2021 by the Pygments team.
66
+ Licensed under the BSD license, see LICENSE for details.
67
+ */
68
+ %(styledefs)s
69
+ '''
70
+
71
+ DOC_HEADER = '''\
72
+ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
73
+ "http://www.w3.org/TR/html4/strict.dtd">
74
+ <!--
75
+ generated by Pygments <https://pygments.org/>
76
+ Copyright 2006-2021 by the Pygments team.
77
+ Licensed under the BSD license, see LICENSE for details.
78
+ -->
79
+ <html>
80
+ <head>
81
+ <title>%(title)s</title>
82
+ <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
83
+ <style type="text/css">
84
+ ''' + CSSFILE_TEMPLATE + '''
85
+ </style>
86
+ </head>
87
+ <body>
88
+ <h2>%(title)s</h2>
89
+
90
+ '''
91
+
92
+ DOC_HEADER_EXTERNALCSS = '''\
93
+ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
94
+ "http://www.w3.org/TR/html4/strict.dtd">
95
+
96
+ <html>
97
+ <head>
98
+ <title>%(title)s</title>
99
+ <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">
100
+ <link rel="stylesheet" href="%(cssfile)s" type="text/css">
101
+ </head>
102
+ <body>
103
+ <h2>%(title)s</h2>
104
+
105
+ '''
106
+
107
+ DOC_FOOTER = '''\
108
+ </body>
109
+ </html>
110
+ '''
111
+
112
+
113
+ class HtmlFormatter(Formatter):
114
+ r"""
115
+ Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped
116
+ in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass`
117
+ option.
118
+
119
+ If the `linenos` option is set to ``"table"``, the ``<pre>`` is
120
+ additionally wrapped inside a ``<table>`` which has one row and two
121
+ cells: one containing the line numbers and one containing the code.
122
+ Example:
123
+
124
+ .. sourcecode:: html
125
+
126
+ <div class="highlight" >
127
+ <table><tr>
128
+ <td class="linenos" title="click to toggle"
129
+ onclick="with (this.firstChild.style)
130
+ { display = (display == '') ? 'none' : '' }">
131
+ <pre>1
132
+ 2</pre>
133
+ </td>
134
+ <td class="code">
135
+ <pre><span class="Ke">def </span><span class="NaFu">foo</span>(bar):
136
+ <span class="Ke">pass</span>
137
+ </pre>
138
+ </td>
139
+ </tr></table></div>
140
+
141
+ (whitespace added to improve clarity).
142
+
143
+ Wrapping can be disabled using the `nowrap` option.
144
+
145
+ A list of lines can be specified using the `hl_lines` option to make these
146
+ lines highlighted (as of Pygments 0.11).
147
+
148
+ With the `full` option, a complete HTML 4 document is output, including
149
+ the style definitions inside a ``<style>`` tag, or in a separate file if
150
+ the `cssfile` option is given.
151
+
152
+ When `tagsfile` is set to the path of a ctags index file, it is used to
153
+ generate hyperlinks from names to their definition. You must enable
154
+ `lineanchors` and run ctags with the `-n` option for this to work. The
155
+ `python-ctags` module from PyPI must be installed to use this feature;
156
+ otherwise a `RuntimeError` will be raised.
157
+
158
+ The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string
159
+ containing CSS rules for the CSS classes used by the formatter. The
160
+ argument `arg` can be used to specify additional CSS selectors that
161
+ are prepended to the classes. A call `fmter.get_style_defs('td .code')`
162
+ would result in the following CSS classes:
163
+
164
+ .. sourcecode:: css
165
+
166
+ td .code .kw { font-weight: bold; color: #00FF00 }
167
+ td .code .cm { color: #999999 }
168
+ ...
169
+
170
+ If you have Pygments 0.6 or higher, you can also pass a list or tuple to the
171
+ `get_style_defs()` method to request multiple prefixes for the tokens:
172
+
173
+ .. sourcecode:: python
174
+
175
+ formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])
176
+
177
+ The output would then look like this:
178
+
179
+ .. sourcecode:: css
180
+
181
+ div.syntax pre .kw,
182
+ pre.syntax .kw { font-weight: bold; color: #00FF00 }
183
+ div.syntax pre .cm,
184
+ pre.syntax .cm { color: #999999 }
185
+ ...
186
+
187
+ Additional options accepted:
188
+
189
+ `nowrap`
190
+ If set to ``True``, don't wrap the tokens at all, not even inside a ``<pre>``
191
+ tag. This disables most other options (default: ``False``).
192
+
193
+ `full`
194
+ Tells the formatter to output a "full" document, i.e. a complete
195
+ self-contained document (default: ``False``).
196
+
197
+ `title`
198
+ If `full` is true, the title that should be used to caption the
199
+ document (default: ``''``).
200
+
201
+ `style`
202
+ The style to use, can be a string or a Style subclass (default:
203
+ ``'default'``). This option has no effect if the `cssfile`
204
+ and `noclobber_cssfile` option are given and the file specified in
205
+ `cssfile` exists.
206
+
207
+ `noclasses`
208
+ If set to true, token ``<span>`` tags (as well as line number elements)
209
+ will not use CSS classes, but inline styles. This is not recommended
210
+ for larger pieces of code since it increases output size by quite a bit
211
+ (default: ``False``).
212
+
213
+ `classprefix`
214
+ Since the token types use relatively short class names, they may clash
215
+ with some of your own class names. In this case you can use the
216
+ `classprefix` option to give a string to prepend to all Pygments-generated
217
+ CSS class names for token types.
218
+ Note that this option also affects the output of `get_style_defs()`.
219
+
220
+ `cssclass`
221
+ CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``).
222
+ If you set this option, the default selector for `get_style_defs()`
223
+ will be this class.
224
+
225
+ .. versionadded:: 0.9
226
+ If you select the ``'table'`` line numbers, the wrapping table will
227
+ have a CSS class of this string plus ``'table'``, the default is
228
+ accordingly ``'highlighttable'``.
229
+
230
+ `cssstyles`
231
+ Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``).
232
+
233
+ `prestyles`
234
+ Inline CSS styles for the ``<pre>`` tag (default: ``''``).
235
+
236
+ .. versionadded:: 0.11
237
+
238
+ `cssfile`
239
+ If the `full` option is true and this option is given, it must be the
240
+ name of an external file. If the filename does not include an absolute
241
+ path, the file's path will be assumed to be relative to the main output
242
+ file's path, if the latter can be found. The stylesheet is then written
243
+ to this file instead of the HTML file.
244
+
245
+ .. versionadded:: 0.6
246
+
247
+ `noclobber_cssfile`
248
+ If `cssfile` is given and the specified file exists, the css file will
249
+ not be overwritten. This allows the use of the `full` option in
250
+ combination with a user specified css file. Default is ``False``.
251
+
252
+ .. versionadded:: 1.1
253
+
254
+ `linenos`
255
+ If set to ``'table'``, output line numbers as a table with two cells,
256
+ one containing the line numbers, the other the whole code. This is
257
+ copy-and-paste-friendly, but may cause alignment problems with some
258
+ browsers or fonts. If set to ``'inline'``, the line numbers will be
259
+ integrated in the ``<pre>`` tag that contains the code (that setting
260
+ is *new in Pygments 0.8*).
261
+
262
+ For compatibility with Pygments 0.7 and earlier, every true value
263
+ except ``'inline'`` means the same as ``'table'`` (in particular, that
264
+ means also ``True``).
265
+
266
+ The default value is ``False``, which means no line numbers at all.
267
+
268
+ **Note:** with the default ("table") line number mechanism, the line
269
+ numbers and code can have different line heights in Internet Explorer
270
+ unless you give the enclosing ``<pre>`` tags an explicit ``line-height``
271
+ CSS property (you get the default line spacing with ``line-height:
272
+ 125%``).
273
+
274
+ `hl_lines`
275
+ Specify a list of lines to be highlighted. The line numbers are always
276
+ relative to the input (i.e. the first line is line 1) and are
277
+ independent of `linenostart`.
278
+
279
+ .. versionadded:: 0.11
280
+
281
+ `linenostart`
282
+ The line number for the first line (default: ``1``).
283
+
284
+ `linenostep`
285
+ If set to a number n > 1, only every nth line number is printed.
286
+
287
+ `linenospecial`
288
+ If set to a number n > 0, every nth line number is given the CSS
289
+ class ``"special"`` (default: ``0``).
290
+
291
+ `nobackground`
292
+ If set to ``True``, the formatter won't output the background color
293
+ for the wrapping element (this automatically defaults to ``False``
294
+ when there is no wrapping element [eg: no argument for the
295
+ `get_syntax_defs` method given]) (default: ``False``).
296
+
297
+ .. versionadded:: 0.6
298
+
299
+ `lineseparator`
300
+ This string is output between lines of code. It defaults to ``"\n"``,
301
+ which is enough to break a line inside ``<pre>`` tags, but you can
302
+ e.g. set it to ``"<br>"`` to get HTML line breaks.
303
+
304
+ .. versionadded:: 0.7
305
+
306
+ `lineanchors`
307
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
308
+ output line in an anchor tag with an ``id`` (and `name`) of ``foo-linenumber``.
309
+ This allows easy linking to certain lines.
310
+
311
+ .. versionadded:: 0.9
312
+
313
+ `linespans`
314
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
315
+ output line in a span tag with an ``id`` of ``foo-linenumber``.
316
+ This allows easy access to lines via javascript.
317
+
318
+ .. versionadded:: 1.6
319
+
320
+ `anchorlinenos`
321
+ If set to `True`, will wrap line numbers in <a> tags. Used in
322
+ combination with `linenos` and `lineanchors`.
323
+
324
+ `tagsfile`
325
+ If set to the path of a ctags file, wrap names in anchor tags that
326
+ link to their definitions. `lineanchors` should be used, and the
327
+ tags file should specify line numbers (see the `-n` option to ctags).
328
+
329
+ .. versionadded:: 1.6
330
+
331
+ `tagurlformat`
332
+ A string formatting pattern used to generate links to ctags definitions.
333
+ Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`.
334
+ Defaults to an empty string, resulting in just `#prefix-number` links.
335
+
336
+ .. versionadded:: 1.6
337
+
338
+ `filename`
339
+ A string used to generate a filename when rendering ``<pre>`` blocks,
340
+ for example if displaying source code. If `linenos` is set to
341
+ ``'table'`` then the filename will be rendered in an initial row
342
+ containing a single `<th>` which spans both columns.
343
+
344
+ .. versionadded:: 2.1
345
+
346
+ `wrapcode`
347
+ Wrap the code inside ``<pre>`` blocks using ``<code>``, as recommended
348
+ by the HTML5 specification.
349
+
350
+ .. versionadded:: 2.4
351
+
352
+ `debug_token_types`
353
+ Add ``title`` attributes to all token ``<span>`` tags that show the
354
+ name of the token.
355
+
356
+ .. versionadded:: 2.10
357
+
358
+
359
+ **Subclassing the HTML formatter**
360
+
361
+ .. versionadded:: 0.7
362
+
363
+ The HTML formatter is now built in a way that allows easy subclassing, thus
364
+ customizing the output HTML code. The `format()` method calls
365
+ `self._format_lines()` which returns a generator that yields tuples of ``(1,
366
+ line)``, where the ``1`` indicates that the ``line`` is a line of the
367
+ formatted source code.
368
+
369
+ If the `nowrap` option is set, the generator is the iterated over and the
370
+ resulting HTML is output.
371
+
372
+ Otherwise, `format()` calls `self.wrap()`, which wraps the generator with
373
+ other generators. These may add some HTML code to the one generated by
374
+ `_format_lines()`, either by modifying the lines generated by the latter,
375
+ then yielding them again with ``(1, line)``, and/or by yielding other HTML
376
+ code before or after the lines, with ``(0, html)``. The distinction between
377
+ source lines and other code makes it possible to wrap the generator multiple
378
+ times.
379
+
380
+ The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag.
381
+
382
+ A custom `HtmlFormatter` subclass could look like this:
383
+
384
+ .. sourcecode:: python
385
+
386
+ class CodeHtmlFormatter(HtmlFormatter):
387
+
388
+ def wrap(self, source, outfile):
389
+ return self._wrap_code(source)
390
+
391
+ def _wrap_code(self, source):
392
+ yield 0, '<code>'
393
+ for i, t in source:
394
+ if i == 1:
395
+ # it's a line of formatted code
396
+ t += '<br>'
397
+ yield i, t
398
+ yield 0, '</code>'
399
+
400
+ This results in wrapping the formatted lines with a ``<code>`` tag, where the
401
+ source lines are broken using ``<br>`` tags.
402
+
403
+ After calling `wrap()`, the `format()` method also adds the "line numbers"
404
+ and/or "full document" wrappers if the respective options are set. Then, all
405
+ HTML yielded by the wrapped generator is output.
406
+ """
407
+
408
+ name = 'HTML'
409
+ aliases = ['html']
410
+ filenames = ['*.html', '*.htm']
411
+
412
+ def __init__(self, **options):
413
+ Formatter.__init__(self, **options)
414
+ self.title = self._decodeifneeded(self.title)
415
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
416
+ self.noclasses = get_bool_opt(options, 'noclasses', False)
417
+ self.classprefix = options.get('classprefix', '')
418
+ self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))
419
+ self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
420
+ self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
421
+ self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
422
+ self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
423
+ self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
424
+ self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))
425
+ self.filename = self._decodeifneeded(options.get('filename', ''))
426
+ self.wrapcode = get_bool_opt(options, 'wrapcode', False)
427
+ self.span_element_openers = {}
428
+ self.debug_token_types = get_bool_opt(options, 'debug_token_types', False)
429
+
430
+ if self.tagsfile:
431
+ if not ctags:
432
+ raise RuntimeError('The "ctags" package must to be installed '
433
+ 'to be able to use the "tagsfile" feature.')
434
+ self._ctags = ctags.CTags(self.tagsfile)
435
+
436
+ linenos = options.get('linenos', False)
437
+ if linenos == 'inline':
438
+ self.linenos = 2
439
+ elif linenos:
440
+ # compatibility with <= 0.7
441
+ self.linenos = 1
442
+ else:
443
+ self.linenos = 0
444
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
445
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
446
+ self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
447
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
448
+ self.lineseparator = options.get('lineseparator', '\n')
449
+ self.lineanchors = options.get('lineanchors', '')
450
+ self.linespans = options.get('linespans', '')
451
+ self.anchorlinenos = get_bool_opt(options, 'anchorlinenos', False)
452
+ self.hl_lines = set()
453
+ for lineno in get_list_opt(options, 'hl_lines', []):
454
+ try:
455
+ self.hl_lines.add(int(lineno))
456
+ except ValueError:
457
+ pass
458
+
459
+ self._create_stylesheet()
460
+
461
+ def _get_css_class(self, ttype):
462
+ """Return the css class of this token type prefixed with
463
+ the classprefix option."""
464
+ ttypeclass = _get_ttype_class(ttype)
465
+ if ttypeclass:
466
+ return self.classprefix + ttypeclass
467
+ return ''
468
+
469
+ def _get_css_classes(self, ttype):
470
+ """Return the CSS classes of this token type prefixed with the classprefix option."""
471
+ cls = self._get_css_class(ttype)
472
+ while ttype not in STANDARD_TYPES:
473
+ ttype = ttype.parent
474
+ cls = self._get_css_class(ttype) + ' ' + cls
475
+ return cls or ''
476
+
477
+ def _get_css_inline_styles(self, ttype):
478
+ """Return the inline CSS styles for this token type."""
479
+ cclass = self.ttype2class.get(ttype)
480
+ while cclass is None:
481
+ ttype = ttype.parent
482
+ cclass = self.ttype2class.get(ttype)
483
+ return cclass or ''
484
+
485
+ def _create_stylesheet(self):
486
+ t2c = self.ttype2class = {Token: ''}
487
+ c2s = self.class2style = {}
488
+ for ttype, ndef in self.style:
489
+ name = self._get_css_class(ttype)
490
+ style = ''
491
+ if ndef['color']:
492
+ style += 'color: %s; ' % webify(ndef['color'])
493
+ if ndef['bold']:
494
+ style += 'font-weight: bold; '
495
+ if ndef['italic']:
496
+ style += 'font-style: italic; '
497
+ if ndef['underline']:
498
+ style += 'text-decoration: underline; '
499
+ if ndef['bgcolor']:
500
+ style += 'background-color: %s; ' % webify(ndef['bgcolor'])
501
+ if ndef['border']:
502
+ style += 'border: 1px solid %s; ' % webify(ndef['border'])
503
+ if style:
504
+ t2c[ttype] = name
505
+ # save len(ttype) to enable ordering the styles by
506
+ # hierarchy (necessary for CSS cascading rules!)
507
+ c2s[name] = (style[:-2], ttype, len(ttype))
508
+
509
+ def get_style_defs(self, arg=None):
510
+ """
511
+ Return CSS style definitions for the classes produced by the current
512
+ highlighting style. ``arg`` can be a string or list of selectors to
513
+ insert before the token type classes.
514
+ """
515
+ style_lines = []
516
+
517
+ style_lines.extend(self.get_linenos_style_defs())
518
+ style_lines.extend(self.get_background_style_defs(arg))
519
+ style_lines.extend(self.get_token_style_defs(arg))
520
+
521
+ return '\n'.join(style_lines)
522
+
523
+ def get_token_style_defs(self, arg=None):
524
+ prefix = self.get_css_prefix(arg)
525
+
526
+ styles = [
527
+ (level, ttype, cls, style)
528
+ for cls, (style, ttype, level) in self.class2style.items()
529
+ if cls and style
530
+ ]
531
+ styles.sort()
532
+
533
+ lines = [
534
+ '%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:])
535
+ for (level, ttype, cls, style) in styles
536
+ ]
537
+
538
+ return lines
539
+
540
+ def get_background_style_defs(self, arg=None):
541
+ prefix = self.get_css_prefix(arg)
542
+ bg_color = self.style.background_color
543
+ hl_color = self.style.highlight_color
544
+
545
+ lines = []
546
+
547
+ if arg and not self.nobackground and bg_color is not None:
548
+ text_style = ''
549
+ if Text in self.ttype2class:
550
+ text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
551
+ lines.insert(
552
+ 0, '%s{ background: %s;%s }' % (
553
+ prefix(''), bg_color, text_style
554
+ )
555
+ )
556
+ if hl_color is not None:
557
+ lines.insert(
558
+ 0, '%s { background-color: %s }' % (prefix('hll'), hl_color)
559
+ )
560
+
561
+ return lines
562
+
563
+ def get_linenos_style_defs(self):
564
+ lines = [
565
+ 'pre { %s }' % self._pre_style,
566
+ 'td.linenos .normal { %s }' % self._linenos_style,
567
+ 'span.linenos { %s }' % self._linenos_style,
568
+ 'td.linenos .special { %s }' % self._linenos_special_style,
569
+ 'span.linenos.special { %s }' % self._linenos_special_style,
570
+ ]
571
+
572
+ return lines
573
+
574
+ def get_css_prefix(self, arg):
575
+ if arg is None:
576
+ arg = ('cssclass' in self.options and '.'+self.cssclass or '')
577
+ if isinstance(arg, str):
578
+ args = [arg]
579
+ else:
580
+ args = list(arg)
581
+
582
+ def prefix(cls):
583
+ if cls:
584
+ cls = '.' + cls
585
+ tmp = []
586
+ for arg in args:
587
+ tmp.append((arg and arg + ' ' or '') + cls)
588
+ return ', '.join(tmp)
589
+
590
+ return prefix
591
+
592
+ @property
593
+ def _pre_style(self):
594
+ return 'line-height: 125%;'
595
+
596
+ @property
597
+ def _linenos_style(self):
598
+ return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (
599
+ self.style.line_number_color,
600
+ self.style.line_number_background_color
601
+ )
602
+
603
+ @property
604
+ def _linenos_special_style(self):
605
+ return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (
606
+ self.style.line_number_special_color,
607
+ self.style.line_number_special_background_color
608
+ )
609
+
610
+ def _decodeifneeded(self, value):
611
+ if isinstance(value, bytes):
612
+ if self.encoding:
613
+ return value.decode(self.encoding)
614
+ return value.decode()
615
+ return value
616
+
617
+ def _wrap_full(self, inner, outfile):
618
+ if self.cssfile:
619
+ if os.path.isabs(self.cssfile):
620
+ # it's an absolute filename
621
+ cssfilename = self.cssfile
622
+ else:
623
+ try:
624
+ filename = outfile.name
625
+ if not filename or filename[0] == '<':
626
+ # pseudo files, e.g. name == '<fdopen>'
627
+ raise AttributeError
628
+ cssfilename = os.path.join(os.path.dirname(filename),
629
+ self.cssfile)
630
+ except AttributeError:
631
+ print('Note: Cannot determine output file name, '
632
+ 'using current directory as base for the CSS file name',
633
+ file=sys.stderr)
634
+ cssfilename = self.cssfile
635
+ # write CSS file only if noclobber_cssfile isn't given as an option.
636
+ try:
637
+ if not os.path.exists(cssfilename) or not self.noclobber_cssfile:
638
+ with open(cssfilename, "w") as cf:
639
+ cf.write(CSSFILE_TEMPLATE %
640
+ {'styledefs': self.get_style_defs('body')})
641
+ except OSError as err:
642
+ err.strerror = 'Error writing CSS file: ' + err.strerror
643
+ raise
644
+
645
+ yield 0, (DOC_HEADER_EXTERNALCSS %
646
+ dict(title=self.title,
647
+ cssfile=self.cssfile,
648
+ encoding=self.encoding))
649
+ else:
650
+ yield 0, (DOC_HEADER %
651
+ dict(title=self.title,
652
+ styledefs=self.get_style_defs('body'),
653
+ encoding=self.encoding))
654
+
655
+ yield from inner
656
+ yield 0, DOC_FOOTER
657
+
658
+ def _wrap_tablelinenos(self, inner):
659
+ dummyoutfile = StringIO()
660
+ lncount = 0
661
+ for t, line in inner:
662
+ if t:
663
+ lncount += 1
664
+ dummyoutfile.write(line)
665
+
666
+ fl = self.linenostart
667
+ mw = len(str(lncount + fl - 1))
668
+ sp = self.linenospecial
669
+ st = self.linenostep
670
+ la = self.lineanchors
671
+ aln = self.anchorlinenos
672
+ nocls = self.noclasses
673
+
674
+ lines = []
675
+
676
+ for i in range(fl, fl+lncount):
677
+ print_line = i % st == 0
678
+ special_line = sp and i % sp == 0
679
+
680
+ if print_line:
681
+ line = '%*d' % (mw, i)
682
+ if aln:
683
+ line = '<a href="#%s-%d">%s</a>' % (la, i, line)
684
+ else:
685
+ line = ' ' * mw
686
+
687
+ if nocls:
688
+ if special_line:
689
+ style = ' style="%s"' % self._linenos_special_style
690
+ else:
691
+ style = ' style="%s"' % self._linenos_style
692
+ else:
693
+ if special_line:
694
+ style = ' class="special"'
695
+ else:
696
+ style = ' class="normal"'
697
+
698
+ if style:
699
+ line = '<span%s>%s</span>' % (style, line)
700
+
701
+ lines.append(line)
702
+
703
+ ls = '\n'.join(lines)
704
+
705
+ # If a filename was specified, we can't put it into the code table as it
706
+ # would misalign the line numbers. Hence we emit a separate row for it.
707
+ filename_tr = ""
708
+ if self.filename:
709
+ filename_tr = (
710
+ '<tr><th colspan="2" class="filename"><div class="highlight">'
711
+ '<span class="filename">' + self.filename + '</span></div>'
712
+ '</th></tr>')
713
+
714
+ # in case you wonder about the seemingly redundant <div> here: since the
715
+ # content in the other cell also is wrapped in a div, some browsers in
716
+ # some configurations seem to mess up the formatting...
717
+ yield 0, (
718
+ '<table class="%stable">' % self.cssclass + filename_tr +
719
+ '<tr><td class="linenos"><div class="linenodiv"><pre>' +
720
+ ls + '</pre></div></td><td class="code">'
721
+ )
722
+ yield 0, dummyoutfile.getvalue()
723
+ yield 0, '</td></tr></table>'
724
+
725
+ def _wrap_inlinelinenos(self, inner):
726
+ # need a list of lines since we need the width of a single number :(
727
+ inner_lines = list(inner)
728
+ sp = self.linenospecial
729
+ st = self.linenostep
730
+ num = self.linenostart
731
+ mw = len(str(len(inner_lines) + num - 1))
732
+ la = self.lineanchors
733
+ aln = self.anchorlinenos
734
+ nocls = self.noclasses
735
+
736
+ for _, inner_line in inner_lines:
737
+ print_line = num % st == 0
738
+ special_line = sp and num % sp == 0
739
+
740
+ if print_line:
741
+ line = '%*d' % (mw, num)
742
+ else:
743
+ line = ' ' * mw
744
+
745
+ if nocls:
746
+ if special_line:
747
+ style = ' style="%s"' % self._linenos_special_style
748
+ else:
749
+ style = ' style="%s"' % self._linenos_style
750
+ else:
751
+ if special_line:
752
+ style = ' class="linenos special"'
753
+ else:
754
+ style = ' class="linenos"'
755
+
756
+ if style:
757
+ linenos = '<span%s>%s</span>' % (style, line)
758
+ else:
759
+ linenos = line
760
+
761
+ if aln:
762
+ yield 1, ('<a href="#%s-%d">%s</a>' % (la, num, linenos) +
763
+ inner_line)
764
+ else:
765
+ yield 1, linenos + inner_line
766
+ num += 1
767
+
768
+ def _wrap_lineanchors(self, inner):
769
+ s = self.lineanchors
770
+ # subtract 1 since we have to increment i *before* yielding
771
+ i = self.linenostart - 1
772
+ for t, line in inner:
773
+ if t:
774
+ i += 1
775
+ href = "" if self.linenos else ' href="#%s-%d"' % (s, i)
776
+ yield 1, '<a id="%s-%d" name="%s-%d"%s></a>' % (s, i, s, i, href) + line
777
+ else:
778
+ yield 0, line
779
+
780
+ def _wrap_linespans(self, inner):
781
+ s = self.linespans
782
+ i = self.linenostart - 1
783
+ for t, line in inner:
784
+ if t:
785
+ i += 1
786
+ yield 1, '<span id="%s-%d">%s</span>' % (s, i, line)
787
+ else:
788
+ yield 0, line
789
+
790
+ def _wrap_div(self, inner):
791
+ style = []
792
+ if (self.noclasses and not self.nobackground and
793
+ self.style.background_color is not None):
794
+ style.append('background: %s' % (self.style.background_color,))
795
+ if self.cssstyles:
796
+ style.append(self.cssstyles)
797
+ style = '; '.join(style)
798
+
799
+ yield 0, ('<div' + (self.cssclass and ' class="%s"' % self.cssclass) +
800
+ (style and (' style="%s"' % style)) + '>')
801
+ yield from inner
802
+ yield 0, '</div>\n'
803
+
804
+ def _wrap_pre(self, inner):
805
+ style = []
806
+ if self.prestyles:
807
+ style.append(self.prestyles)
808
+ if self.noclasses:
809
+ style.append(self._pre_style)
810
+ style = '; '.join(style)
811
+
812
+ if self.filename and self.linenos != 1:
813
+ yield 0, ('<span class="filename">' + self.filename + '</span>')
814
+
815
+ # the empty span here is to keep leading empty lines from being
816
+ # ignored by HTML parsers
817
+ yield 0, ('<pre' + (style and ' style="%s"' % style) + '><span></span>')
818
+ yield from inner
819
+ yield 0, '</pre>'
820
+
821
+ def _wrap_code(self, inner):
822
+ yield 0, '<code>'
823
+ yield from inner
824
+ yield 0, '</code>'
825
+
826
+ @functools.lru_cache(maxsize=100)
827
+ def _translate_parts(self, value):
828
+ """HTML-escape a value and split it by newlines."""
829
+ return value.translate(_escape_html_table).split('\n')
830
+
831
+ def _format_lines(self, tokensource):
832
+ """
833
+ Just format the tokens, without any wrapping tags.
834
+ Yield individual lines.
835
+ """
836
+ nocls = self.noclasses
837
+ lsep = self.lineseparator
838
+ tagsfile = self.tagsfile
839
+
840
+ lspan = ''
841
+ line = []
842
+ for ttype, value in tokensource:
843
+ try:
844
+ cspan = self.span_element_openers[ttype]
845
+ except KeyError:
846
+ title = ' title="%s"' % '.'.join(ttype) if self.debug_token_types else ''
847
+ if nocls:
848
+ css_style = self._get_css_inline_styles(ttype)
849
+ if css_style:
850
+ css_style = self.class2style[css_style][0]
851
+ cspan = '<span style="%s"%s>' % (css_style, title)
852
+ else:
853
+ cspan = ''
854
+ else:
855
+ css_class = self._get_css_classes(ttype)
856
+ if css_class:
857
+ cspan = '<span class="%s"%s>' % (css_class, title)
858
+ else:
859
+ cspan = ''
860
+ self.span_element_openers[ttype] = cspan
861
+
862
+ parts = self._translate_parts(value)
863
+
864
+ if tagsfile and ttype in Token.Name:
865
+ filename, linenumber = self._lookup_ctag(value)
866
+ if linenumber:
867
+ base, filename = os.path.split(filename)
868
+ if base:
869
+ base += '/'
870
+ filename, extension = os.path.splitext(filename)
871
+ url = self.tagurlformat % {'path': base, 'fname': filename,
872
+ 'fext': extension}
873
+ parts[0] = "<a href=\"%s#%s-%d\">%s" % \
874
+ (url, self.lineanchors, linenumber, parts[0])
875
+ parts[-1] = parts[-1] + "</a>"
876
+
877
+ # for all but the last line
878
+ for part in parts[:-1]:
879
+ if line:
880
+ if lspan != cspan:
881
+ line.extend(((lspan and '</span>'), cspan, part,
882
+ (cspan and '</span>'), lsep))
883
+ else: # both are the same
884
+ line.extend((part, (lspan and '</span>'), lsep))
885
+ yield 1, ''.join(line)
886
+ line = []
887
+ elif part:
888
+ yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))
889
+ else:
890
+ yield 1, lsep
891
+ # for the last line
892
+ if line and parts[-1]:
893
+ if lspan != cspan:
894
+ line.extend(((lspan and '</span>'), cspan, parts[-1]))
895
+ lspan = cspan
896
+ else:
897
+ line.append(parts[-1])
898
+ elif parts[-1]:
899
+ line = [cspan, parts[-1]]
900
+ lspan = cspan
901
+ # else we neither have to open a new span nor set lspan
902
+
903
+ if line:
904
+ line.extend(((lspan and '</span>'), lsep))
905
+ yield 1, ''.join(line)
906
+
907
+ def _lookup_ctag(self, token):
908
+ entry = ctags.TagEntry()
909
+ if self._ctags.find(entry, token.encode(), 0):
910
+ return entry['file'], entry['lineNumber']
911
+ else:
912
+ return None, None
913
+
914
+ def _highlight_lines(self, tokensource):
915
+ """
916
+ Highlighted the lines specified in the `hl_lines` option by
917
+ post-processing the token stream coming from `_format_lines`.
918
+ """
919
+ hls = self.hl_lines
920
+
921
+ for i, (t, value) in enumerate(tokensource):
922
+ if t != 1:
923
+ yield t, value
924
+ if i + 1 in hls: # i + 1 because Python indexes start at 0
925
+ if self.noclasses:
926
+ style = ''
927
+ if self.style.highlight_color is not None:
928
+ style = (' style="background-color: %s"' %
929
+ (self.style.highlight_color,))
930
+ yield 1, '<span%s>%s</span>' % (style, value)
931
+ else:
932
+ yield 1, '<span class="hll">%s</span>' % value
933
+ else:
934
+ yield 1, value
935
+
936
+ def wrap(self, source, outfile):
937
+ """
938
+ Wrap the ``source``, which is a generator yielding
939
+ individual lines, in custom generators. See docstring
940
+ for `format`. Can be overridden.
941
+ """
942
+ if self.wrapcode:
943
+ return self._wrap_div(self._wrap_pre(self._wrap_code(source)))
944
+ else:
945
+ return self._wrap_div(self._wrap_pre(source))
946
+
947
+ def format_unencoded(self, tokensource, outfile):
948
+ """
949
+ The formatting process uses several nested generators; which of
950
+ them are used is determined by the user's options.
951
+
952
+ Each generator should take at least one argument, ``inner``,
953
+ and wrap the pieces of text generated by this.
954
+
955
+ Always yield 2-tuples: (code, text). If "code" is 1, the text
956
+ is part of the original tokensource being highlighted, if it's
957
+ 0, the text is some piece of wrapping. This makes it possible to
958
+ use several different wrappers that process the original source
959
+ linewise, e.g. line number generators.
960
+ """
961
+ source = self._format_lines(tokensource)
962
+
963
+ # As a special case, we wrap line numbers before line highlighting
964
+ # so the line numbers get wrapped in the highlighting tag.
965
+ if not self.nowrap and self.linenos == 2:
966
+ source = self._wrap_inlinelinenos(source)
967
+
968
+ if self.hl_lines:
969
+ source = self._highlight_lines(source)
970
+
971
+ if not self.nowrap:
972
+ if self.lineanchors:
973
+ source = self._wrap_lineanchors(source)
974
+ if self.linespans:
975
+ source = self._wrap_linespans(source)
976
+ source = self.wrap(source, outfile)
977
+ if self.linenos == 1:
978
+ source = self._wrap_tablelinenos(source)
979
+ if self.full:
980
+ source = self._wrap_full(source, outfile)
981
+
982
+ for t, piece in source:
983
+ outfile.write(piece)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.img
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for Pixmap output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import os
12
+ import sys
13
+
14
+ from pip._vendor.pygments.formatter import Formatter
15
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
16
+ get_choice_opt
17
+
18
+ import subprocess
19
+
20
+ # Import this carefully
21
+ try:
22
+ from PIL import Image, ImageDraw, ImageFont
23
+ pil_available = True
24
+ except ImportError:
25
+ pil_available = False
26
+
27
+ try:
28
+ import _winreg
29
+ except ImportError:
30
+ try:
31
+ import winreg as _winreg
32
+ except ImportError:
33
+ _winreg = None
34
+
35
+ __all__ = ['ImageFormatter', 'GifImageFormatter', 'JpgImageFormatter',
36
+ 'BmpImageFormatter']
37
+
38
+
39
+ # For some unknown reason every font calls it something different
40
+ STYLES = {
41
+ 'NORMAL': ['', 'Roman', 'Book', 'Normal', 'Regular', 'Medium'],
42
+ 'ITALIC': ['Oblique', 'Italic'],
43
+ 'BOLD': ['Bold'],
44
+ 'BOLDITALIC': ['Bold Oblique', 'Bold Italic'],
45
+ }
46
+
47
+ # A sane default for modern systems
48
+ DEFAULT_FONT_NAME_NIX = 'DejaVu Sans Mono'
49
+ DEFAULT_FONT_NAME_WIN = 'Courier New'
50
+ DEFAULT_FONT_NAME_MAC = 'Menlo'
51
+
52
+
53
+ class PilNotAvailable(ImportError):
54
+ """When Python imaging library is not available"""
55
+
56
+
57
+ class FontNotFound(Exception):
58
+ """When there are no usable fonts specified"""
59
+
60
+
61
+ class FontManager:
62
+ """
63
+ Manages a set of fonts: normal, italic, bold, etc...
64
+ """
65
+
66
+ def __init__(self, font_name, font_size=14):
67
+ self.font_name = font_name
68
+ self.font_size = font_size
69
+ self.fonts = {}
70
+ self.encoding = None
71
+ if sys.platform.startswith('win'):
72
+ if not font_name:
73
+ self.font_name = DEFAULT_FONT_NAME_WIN
74
+ self._create_win()
75
+ elif sys.platform.startswith('darwin'):
76
+ if not font_name:
77
+ self.font_name = DEFAULT_FONT_NAME_MAC
78
+ self._create_mac()
79
+ else:
80
+ if not font_name:
81
+ self.font_name = DEFAULT_FONT_NAME_NIX
82
+ self._create_nix()
83
+
84
+ def _get_nix_font_path(self, name, style):
85
+ proc = subprocess.Popen(['fc-list', "%s:style=%s" % (name, style), 'file'],
86
+ stdout=subprocess.PIPE, stderr=None)
87
+ stdout, _ = proc.communicate()
88
+ if proc.returncode == 0:
89
+ lines = stdout.splitlines()
90
+ for line in lines:
91
+ if line.startswith(b'Fontconfig warning:'):
92
+ continue
93
+ path = line.decode().strip().strip(':')
94
+ if path:
95
+ return path
96
+ return None
97
+
98
+ def _create_nix(self):
99
+ for name in STYLES['NORMAL']:
100
+ path = self._get_nix_font_path(self.font_name, name)
101
+ if path is not None:
102
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
103
+ break
104
+ else:
105
+ raise FontNotFound('No usable fonts named: "%s"' %
106
+ self.font_name)
107
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
108
+ for stylename in STYLES[style]:
109
+ path = self._get_nix_font_path(self.font_name, stylename)
110
+ if path is not None:
111
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
112
+ break
113
+ else:
114
+ if style == 'BOLDITALIC':
115
+ self.fonts[style] = self.fonts['BOLD']
116
+ else:
117
+ self.fonts[style] = self.fonts['NORMAL']
118
+
119
+ def _get_mac_font_path(self, font_map, name, style):
120
+ return font_map.get((name + ' ' + style).strip().lower())
121
+
122
+ def _create_mac(self):
123
+ font_map = {}
124
+ for font_dir in (os.path.join(os.getenv("HOME"), 'Library/Fonts/'),
125
+ '/Library/Fonts/', '/System/Library/Fonts/'):
126
+ font_map.update(
127
+ (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))
128
+ for f in os.listdir(font_dir)
129
+ if f.lower().endswith(('ttf', 'ttc')))
130
+
131
+ for name in STYLES['NORMAL']:
132
+ path = self._get_mac_font_path(font_map, self.font_name, name)
133
+ if path is not None:
134
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
135
+ break
136
+ else:
137
+ raise FontNotFound('No usable fonts named: "%s"' %
138
+ self.font_name)
139
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
140
+ for stylename in STYLES[style]:
141
+ path = self._get_mac_font_path(font_map, self.font_name, stylename)
142
+ if path is not None:
143
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
144
+ break
145
+ else:
146
+ if style == 'BOLDITALIC':
147
+ self.fonts[style] = self.fonts['BOLD']
148
+ else:
149
+ self.fonts[style] = self.fonts['NORMAL']
150
+
151
+ def _lookup_win(self, key, basename, styles, fail=False):
152
+ for suffix in ('', ' (TrueType)'):
153
+ for style in styles:
154
+ try:
155
+ valname = '%s%s%s' % (basename, style and ' '+style, suffix)
156
+ val, _ = _winreg.QueryValueEx(key, valname)
157
+ return val
158
+ except OSError:
159
+ continue
160
+ else:
161
+ if fail:
162
+ raise FontNotFound('Font %s (%s) not found in registry' %
163
+ (basename, styles[0]))
164
+ return None
165
+
166
+ def _create_win(self):
167
+ lookuperror = None
168
+ keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
169
+ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Fonts'),
170
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
171
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') ]
172
+ for keyname in keynames:
173
+ try:
174
+ key = _winreg.OpenKey(*keyname)
175
+ try:
176
+ path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
177
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
178
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
179
+ path = self._lookup_win(key, self.font_name, STYLES[style])
180
+ if path:
181
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
182
+ else:
183
+ if style == 'BOLDITALIC':
184
+ self.fonts[style] = self.fonts['BOLD']
185
+ else:
186
+ self.fonts[style] = self.fonts['NORMAL']
187
+ return
188
+ except FontNotFound as err:
189
+ lookuperror = err
190
+ finally:
191
+ _winreg.CloseKey(key)
192
+ except OSError:
193
+ pass
194
+ else:
195
+ # If we get here, we checked all registry keys and had no luck
196
+ # We can be in one of two situations now:
197
+ # * All key lookups failed. In this case lookuperror is None and we
198
+ # will raise a generic error
199
+ # * At least one lookup failed with a FontNotFound error. In this
200
+ # case, we will raise that as a more specific error
201
+ if lookuperror:
202
+ raise lookuperror
203
+ raise FontNotFound('Can\'t open Windows font registry key')
204
+
205
+ def get_char_size(self):
206
+ """
207
+ Get the character size.
208
+ """
209
+ return self.fonts['NORMAL'].getsize('M')
210
+
211
+ def get_text_size(self, text):
212
+ """
213
+ Get the text size(width, height).
214
+ """
215
+ return self.fonts['NORMAL'].getsize(text)
216
+
217
+ def get_font(self, bold, oblique):
218
+ """
219
+ Get the font based on bold and italic flags.
220
+ """
221
+ if bold and oblique:
222
+ return self.fonts['BOLDITALIC']
223
+ elif bold:
224
+ return self.fonts['BOLD']
225
+ elif oblique:
226
+ return self.fonts['ITALIC']
227
+ else:
228
+ return self.fonts['NORMAL']
229
+
230
+
231
+ class ImageFormatter(Formatter):
232
+ """
233
+ Create a PNG image from source code. This uses the Python Imaging Library to
234
+ generate a pixmap from the source code.
235
+
236
+ .. versionadded:: 0.10
237
+
238
+ Additional options accepted:
239
+
240
+ `image_format`
241
+ An image format to output to that is recognised by PIL, these include:
242
+
243
+ * "PNG" (default)
244
+ * "JPEG"
245
+ * "BMP"
246
+ * "GIF"
247
+
248
+ `line_pad`
249
+ The extra spacing (in pixels) between each line of text.
250
+
251
+ Default: 2
252
+
253
+ `font_name`
254
+ The font name to be used as the base font from which others, such as
255
+ bold and italic fonts will be generated. This really should be a
256
+ monospace font to look sane.
257
+
258
+ Default: "Courier New" on Windows, "Menlo" on Mac OS, and
259
+ "DejaVu Sans Mono" on \\*nix
260
+
261
+ `font_size`
262
+ The font size in points to be used.
263
+
264
+ Default: 14
265
+
266
+ `image_pad`
267
+ The padding, in pixels to be used at each edge of the resulting image.
268
+
269
+ Default: 10
270
+
271
+ `line_numbers`
272
+ Whether line numbers should be shown: True/False
273
+
274
+ Default: True
275
+
276
+ `line_number_start`
277
+ The line number of the first line.
278
+
279
+ Default: 1
280
+
281
+ `line_number_step`
282
+ The step used when printing line numbers.
283
+
284
+ Default: 1
285
+
286
+ `line_number_bg`
287
+ The background colour (in "#123456" format) of the line number bar, or
288
+ None to use the style background color.
289
+
290
+ Default: "#eed"
291
+
292
+ `line_number_fg`
293
+ The text color of the line numbers (in "#123456"-like format).
294
+
295
+ Default: "#886"
296
+
297
+ `line_number_chars`
298
+ The number of columns of line numbers allowable in the line number
299
+ margin.
300
+
301
+ Default: 2
302
+
303
+ `line_number_bold`
304
+ Whether line numbers will be bold: True/False
305
+
306
+ Default: False
307
+
308
+ `line_number_italic`
309
+ Whether line numbers will be italicized: True/False
310
+
311
+ Default: False
312
+
313
+ `line_number_separator`
314
+ Whether a line will be drawn between the line number area and the
315
+ source code area: True/False
316
+
317
+ Default: True
318
+
319
+ `line_number_pad`
320
+ The horizontal padding (in pixels) between the line number margin, and
321
+ the source code area.
322
+
323
+ Default: 6
324
+
325
+ `hl_lines`
326
+ Specify a list of lines to be highlighted.
327
+
328
+ .. versionadded:: 1.2
329
+
330
+ Default: empty list
331
+
332
+ `hl_color`
333
+ Specify the color for highlighting lines.
334
+
335
+ .. versionadded:: 1.2
336
+
337
+ Default: highlight color of the selected style
338
+ """
339
+
340
+ # Required by the pygments mapper
341
+ name = 'img'
342
+ aliases = ['img', 'IMG', 'png']
343
+ filenames = ['*.png']
344
+
345
+ unicodeoutput = False
346
+
347
+ default_image_format = 'png'
348
+
349
+ def __init__(self, **options):
350
+ """
351
+ See the class docstring for explanation of options.
352
+ """
353
+ if not pil_available:
354
+ raise PilNotAvailable(
355
+ 'Python Imaging Library is required for this formatter')
356
+ Formatter.__init__(self, **options)
357
+ self.encoding = 'latin1' # let pygments.format() do the right thing
358
+ # Read the style
359
+ self.styles = dict(self.style)
360
+ if self.style.background_color is None:
361
+ self.background_color = '#fff'
362
+ else:
363
+ self.background_color = self.style.background_color
364
+ # Image options
365
+ self.image_format = get_choice_opt(
366
+ options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
367
+ self.default_image_format, normcase=True)
368
+ self.image_pad = get_int_opt(options, 'image_pad', 10)
369
+ self.line_pad = get_int_opt(options, 'line_pad', 2)
370
+ # The fonts
371
+ fontsize = get_int_opt(options, 'font_size', 14)
372
+ self.fonts = FontManager(options.get('font_name', ''), fontsize)
373
+ self.fontw, self.fonth = self.fonts.get_char_size()
374
+ # Line number options
375
+ self.line_number_fg = options.get('line_number_fg', '#886')
376
+ self.line_number_bg = options.get('line_number_bg', '#eed')
377
+ self.line_number_chars = get_int_opt(options,
378
+ 'line_number_chars', 2)
379
+ self.line_number_bold = get_bool_opt(options,
380
+ 'line_number_bold', False)
381
+ self.line_number_italic = get_bool_opt(options,
382
+ 'line_number_italic', False)
383
+ self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
384
+ self.line_numbers = get_bool_opt(options, 'line_numbers', True)
385
+ self.line_number_separator = get_bool_opt(options,
386
+ 'line_number_separator', True)
387
+ self.line_number_step = get_int_opt(options, 'line_number_step', 1)
388
+ self.line_number_start = get_int_opt(options, 'line_number_start', 1)
389
+ if self.line_numbers:
390
+ self.line_number_width = (self.fontw * self.line_number_chars +
391
+ self.line_number_pad * 2)
392
+ else:
393
+ self.line_number_width = 0
394
+ self.hl_lines = []
395
+ hl_lines_str = get_list_opt(options, 'hl_lines', [])
396
+ for line in hl_lines_str:
397
+ try:
398
+ self.hl_lines.append(int(line))
399
+ except ValueError:
400
+ pass
401
+ self.hl_color = options.get('hl_color',
402
+ self.style.highlight_color) or '#f90'
403
+ self.drawables = []
404
+
405
+ def get_style_defs(self, arg=''):
406
+ raise NotImplementedError('The -S option is meaningless for the image '
407
+ 'formatter. Use -O style=<stylename> instead.')
408
+
409
+ def _get_line_height(self):
410
+ """
411
+ Get the height of a line.
412
+ """
413
+ return self.fonth + self.line_pad
414
+
415
+ def _get_line_y(self, lineno):
416
+ """
417
+ Get the Y coordinate of a line number.
418
+ """
419
+ return lineno * self._get_line_height() + self.image_pad
420
+
421
+ def _get_char_width(self):
422
+ """
423
+ Get the width of a character.
424
+ """
425
+ return self.fontw
426
+
427
+ def _get_char_x(self, linelength):
428
+ """
429
+ Get the X coordinate of a character position.
430
+ """
431
+ return linelength + self.image_pad + self.line_number_width
432
+
433
+ def _get_text_pos(self, linelength, lineno):
434
+ """
435
+ Get the actual position for a character and line position.
436
+ """
437
+ return self._get_char_x(linelength), self._get_line_y(lineno)
438
+
439
+ def _get_linenumber_pos(self, lineno):
440
+ """
441
+ Get the actual position for the start of a line number.
442
+ """
443
+ return (self.image_pad, self._get_line_y(lineno))
444
+
445
+ def _get_text_color(self, style):
446
+ """
447
+ Get the correct color for the token from the style.
448
+ """
449
+ if style['color'] is not None:
450
+ fill = '#' + style['color']
451
+ else:
452
+ fill = '#000'
453
+ return fill
454
+
455
+ def _get_text_bg_color(self, style):
456
+ """
457
+ Get the correct background color for the token from the style.
458
+ """
459
+ if style['bgcolor'] is not None:
460
+ bg_color = '#' + style['bgcolor']
461
+ else:
462
+ bg_color = None
463
+ return bg_color
464
+
465
+ def _get_style_font(self, style):
466
+ """
467
+ Get the correct font for the style.
468
+ """
469
+ return self.fonts.get_font(style['bold'], style['italic'])
470
+
471
+ def _get_image_size(self, maxlinelength, maxlineno):
472
+ """
473
+ Get the required image size.
474
+ """
475
+ return (self._get_char_x(maxlinelength) + self.image_pad,
476
+ self._get_line_y(maxlineno + 0) + self.image_pad)
477
+
478
+ def _draw_linenumber(self, posno, lineno):
479
+ """
480
+ Remember a line number drawable to paint later.
481
+ """
482
+ self._draw_text(
483
+ self._get_linenumber_pos(posno),
484
+ str(lineno).rjust(self.line_number_chars),
485
+ font=self.fonts.get_font(self.line_number_bold,
486
+ self.line_number_italic),
487
+ text_fg=self.line_number_fg,
488
+ text_bg=None,
489
+ )
490
+
491
+ def _draw_text(self, pos, text, font, text_fg, text_bg):
492
+ """
493
+ Remember a single drawable tuple to paint later.
494
+ """
495
+ self.drawables.append((pos, text, font, text_fg, text_bg))
496
+
497
+ def _create_drawables(self, tokensource):
498
+ """
499
+ Create drawables for the token content.
500
+ """
501
+ lineno = charno = maxcharno = 0
502
+ maxlinelength = linelength = 0
503
+ for ttype, value in tokensource:
504
+ while ttype not in self.styles:
505
+ ttype = ttype.parent
506
+ style = self.styles[ttype]
507
+ # TODO: make sure tab expansion happens earlier in the chain. It
508
+ # really ought to be done on the input, as to do it right here is
509
+ # quite complex.
510
+ value = value.expandtabs(4)
511
+ lines = value.splitlines(True)
512
+ # print lines
513
+ for i, line in enumerate(lines):
514
+ temp = line.rstrip('\n')
515
+ if temp:
516
+ self._draw_text(
517
+ self._get_text_pos(linelength, lineno),
518
+ temp,
519
+ font = self._get_style_font(style),
520
+ text_fg = self._get_text_color(style),
521
+ text_bg = self._get_text_bg_color(style),
522
+ )
523
+ temp_width, temp_hight = self.fonts.get_text_size(temp)
524
+ linelength += temp_width
525
+ maxlinelength = max(maxlinelength, linelength)
526
+ charno += len(temp)
527
+ maxcharno = max(maxcharno, charno)
528
+ if line.endswith('\n'):
529
+ # add a line for each extra line in the value
530
+ linelength = 0
531
+ charno = 0
532
+ lineno += 1
533
+ self.maxlinelength = maxlinelength
534
+ self.maxcharno = maxcharno
535
+ self.maxlineno = lineno
536
+
537
+ def _draw_line_numbers(self):
538
+ """
539
+ Create drawables for the line numbers.
540
+ """
541
+ if not self.line_numbers:
542
+ return
543
+ for p in range(self.maxlineno):
544
+ n = p + self.line_number_start
545
+ if (n % self.line_number_step) == 0:
546
+ self._draw_linenumber(p, n)
547
+
548
+ def _paint_line_number_bg(self, im):
549
+ """
550
+ Paint the line number background on the image.
551
+ """
552
+ if not self.line_numbers:
553
+ return
554
+ if self.line_number_fg is None:
555
+ return
556
+ draw = ImageDraw.Draw(im)
557
+ recth = im.size[-1]
558
+ rectw = self.image_pad + self.line_number_width - self.line_number_pad
559
+ draw.rectangle([(0, 0), (rectw, recth)],
560
+ fill=self.line_number_bg)
561
+ if self.line_number_separator:
562
+ draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
563
+ del draw
564
+
565
+ def format(self, tokensource, outfile):
566
+ """
567
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
568
+ tuples and write it into ``outfile``.
569
+
570
+ This implementation calculates where it should draw each token on the
571
+ pixmap, then calculates the required pixmap size and draws the items.
572
+ """
573
+ self._create_drawables(tokensource)
574
+ self._draw_line_numbers()
575
+ im = Image.new(
576
+ 'RGB',
577
+ self._get_image_size(self.maxlinelength, self.maxlineno),
578
+ self.background_color
579
+ )
580
+ self._paint_line_number_bg(im)
581
+ draw = ImageDraw.Draw(im)
582
+ # Highlight
583
+ if self.hl_lines:
584
+ x = self.image_pad + self.line_number_width - self.line_number_pad + 1
585
+ recth = self._get_line_height()
586
+ rectw = im.size[0] - x
587
+ for linenumber in self.hl_lines:
588
+ y = self._get_line_y(linenumber - 1)
589
+ draw.rectangle([(x, y), (x + rectw, y + recth)],
590
+ fill=self.hl_color)
591
+ for pos, value, font, text_fg, text_bg in self.drawables:
592
+ if text_bg:
593
+ text_size = draw.textsize(text=value, font=font)
594
+ draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)
595
+ draw.text(pos, value, font=font, fill=text_fg)
596
+ im.save(outfile, self.image_format.upper())
597
+
598
+
599
+ # Add one formatter per format, so that the "-f gif" option gives the correct result
600
+ # when used in pygmentize.
601
+
602
+ class GifImageFormatter(ImageFormatter):
603
+ """
604
+ Create a GIF image from source code. This uses the Python Imaging Library to
605
+ generate a pixmap from the source code.
606
+
607
+ .. versionadded:: 1.0
608
+ """
609
+
610
+ name = 'img_gif'
611
+ aliases = ['gif']
612
+ filenames = ['*.gif']
613
+ default_image_format = 'gif'
614
+
615
+
616
+ class JpgImageFormatter(ImageFormatter):
617
+ """
618
+ Create a JPEG image from source code. This uses the Python Imaging Library to
619
+ generate a pixmap from the source code.
620
+
621
+ .. versionadded:: 1.0
622
+ """
623
+
624
+ name = 'img_jpg'
625
+ aliases = ['jpg', 'jpeg']
626
+ filenames = ['*.jpg']
627
+ default_image_format = 'jpeg'
628
+
629
+
630
+ class BmpImageFormatter(ImageFormatter):
631
+ """
632
+ Create a bitmap image from source code. This uses the Python Imaging Library to
633
+ generate a pixmap from the source code.
634
+
635
+ .. versionadded:: 1.0
636
+ """
637
+
638
+ name = 'img_bmp'
639
+ aliases = ['bmp', 'bitmap']
640
+ filenames = ['*.bmp']
641
+ default_image_format = 'bmp'
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/irc.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.irc
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for IRC output
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+ from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
13
+ Number, Operator, Generic, Token, Whitespace
14
+ from pip._vendor.pygments.util import get_choice_opt
15
+
16
+
17
+ __all__ = ['IRCFormatter']
18
+
19
+
20
+ #: Map token types to a tuple of color values for light and dark
21
+ #: backgrounds.
22
+ IRC_COLORS = {
23
+ Token: ('', ''),
24
+
25
+ Whitespace: ('gray', 'brightblack'),
26
+ Comment: ('gray', 'brightblack'),
27
+ Comment.Preproc: ('cyan', 'brightcyan'),
28
+ Keyword: ('blue', 'brightblue'),
29
+ Keyword.Type: ('cyan', 'brightcyan'),
30
+ Operator.Word: ('magenta', 'brightcyan'),
31
+ Name.Builtin: ('cyan', 'brightcyan'),
32
+ Name.Function: ('green', 'brightgreen'),
33
+ Name.Namespace: ('_cyan_', '_brightcyan_'),
34
+ Name.Class: ('_green_', '_brightgreen_'),
35
+ Name.Exception: ('cyan', 'brightcyan'),
36
+ Name.Decorator: ('brightblack', 'gray'),
37
+ Name.Variable: ('red', 'brightred'),
38
+ Name.Constant: ('red', 'brightred'),
39
+ Name.Attribute: ('cyan', 'brightcyan'),
40
+ Name.Tag: ('brightblue', 'brightblue'),
41
+ String: ('yellow', 'yellow'),
42
+ Number: ('blue', 'brightblue'),
43
+
44
+ Generic.Deleted: ('brightred', 'brightred'),
45
+ Generic.Inserted: ('green', 'brightgreen'),
46
+ Generic.Heading: ('**', '**'),
47
+ Generic.Subheading: ('*magenta*', '*brightmagenta*'),
48
+ Generic.Error: ('brightred', 'brightred'),
49
+
50
+ Error: ('_brightred_', '_brightred_'),
51
+ }
52
+
53
+
54
+ IRC_COLOR_MAP = {
55
+ 'white': 0,
56
+ 'black': 1,
57
+ 'blue': 2,
58
+ 'brightgreen': 3,
59
+ 'brightred': 4,
60
+ 'yellow': 5,
61
+ 'magenta': 6,
62
+ 'orange': 7,
63
+ 'green': 7, #compat w/ ansi
64
+ 'brightyellow': 8,
65
+ 'lightgreen': 9,
66
+ 'brightcyan': 9, # compat w/ ansi
67
+ 'cyan': 10,
68
+ 'lightblue': 11,
69
+ 'red': 11, # compat w/ ansi
70
+ 'brightblue': 12,
71
+ 'brightmagenta': 13,
72
+ 'brightblack': 14,
73
+ 'gray': 15,
74
+ }
75
+
76
+ def ircformat(color, text):
77
+ if len(color) < 1:
78
+ return text
79
+ add = sub = ''
80
+ if '_' in color: # italic
81
+ add += '\x1D'
82
+ sub = '\x1D' + sub
83
+ color = color.strip('_')
84
+ if '*' in color: # bold
85
+ add += '\x02'
86
+ sub = '\x02' + sub
87
+ color = color.strip('*')
88
+ # underline (\x1F) not supported
89
+ # backgrounds (\x03FF,BB) not supported
90
+ if len(color) > 0: # actual color - may have issues with ircformat("red", "blah")+"10" type stuff
91
+ add += '\x03' + str(IRC_COLOR_MAP[color]).zfill(2)
92
+ sub = '\x03' + sub
93
+ return add + text + sub
94
+ return '<'+add+'>'+text+'</'+sub+'>'
95
+
96
+
97
+ class IRCFormatter(Formatter):
98
+ r"""
99
+ Format tokens with IRC color sequences
100
+
101
+ The `get_style_defs()` method doesn't do anything special since there is
102
+ no support for common styles.
103
+
104
+ Options accepted:
105
+
106
+ `bg`
107
+ Set to ``"light"`` or ``"dark"`` depending on the terminal's background
108
+ (default: ``"light"``).
109
+
110
+ `colorscheme`
111
+ A dictionary mapping token types to (lightbg, darkbg) color names or
112
+ ``None`` (default: ``None`` = use builtin colorscheme).
113
+
114
+ `linenos`
115
+ Set to ``True`` to have line numbers in the output as well
116
+ (default: ``False`` = no line numbers).
117
+ """
118
+ name = 'IRC'
119
+ aliases = ['irc', 'IRC']
120
+ filenames = []
121
+
122
+ def __init__(self, **options):
123
+ Formatter.__init__(self, **options)
124
+ self.darkbg = get_choice_opt(options, 'bg',
125
+ ['light', 'dark'], 'light') == 'dark'
126
+ self.colorscheme = options.get('colorscheme', None) or IRC_COLORS
127
+ self.linenos = options.get('linenos', False)
128
+ self._lineno = 0
129
+
130
+ def _write_lineno(self, outfile):
131
+ self._lineno += 1
132
+ outfile.write("\n%04d: " % self._lineno)
133
+
134
+ def _format_unencoded_with_lineno(self, tokensource, outfile):
135
+ self._write_lineno(outfile)
136
+
137
+ for ttype, value in tokensource:
138
+ if value.endswith("\n"):
139
+ self._write_lineno(outfile)
140
+ value = value[:-1]
141
+ color = self.colorscheme.get(ttype)
142
+ while color is None:
143
+ ttype = ttype.parent
144
+ color = self.colorscheme.get(ttype)
145
+ if color:
146
+ color = color[self.darkbg]
147
+ spl = value.split('\n')
148
+ for line in spl[:-1]:
149
+ self._write_lineno(outfile)
150
+ if line:
151
+ outfile.write(ircformat(color, line[:-1]))
152
+ if spl[-1]:
153
+ outfile.write(ircformat(color, spl[-1]))
154
+ else:
155
+ outfile.write(value)
156
+
157
+ outfile.write("\n")
158
+
159
+ def format_unencoded(self, tokensource, outfile):
160
+ if self.linenos:
161
+ self._format_unencoded_with_lineno(tokensource, outfile)
162
+ return
163
+
164
+ for ttype, value in tokensource:
165
+ color = self.colorscheme.get(ttype)
166
+ while color is None:
167
+ ttype = ttype[:-1]
168
+ color = self.colorscheme.get(ttype)
169
+ if color:
170
+ color = color[self.darkbg]
171
+ spl = value.split('\n')
172
+ for line in spl[:-1]:
173
+ if line:
174
+ outfile.write(ircformat(color, line))
175
+ outfile.write('\n')
176
+ if spl[-1]:
177
+ outfile.write(ircformat(color, spl[-1]))
178
+ else:
179
+ outfile.write(value)
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.latex
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for LaTeX fancyvrb output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from io import StringIO
12
+
13
+ from pip._vendor.pygments.formatter import Formatter
14
+ from pip._vendor.pygments.lexer import Lexer, do_insertions
15
+ from pip._vendor.pygments.token import Token, STANDARD_TYPES
16
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
17
+
18
+
19
+ __all__ = ['LatexFormatter']
20
+
21
+
22
+ def escape_tex(text, commandprefix):
23
+ return text.replace('\\', '\x00'). \
24
+ replace('{', '\x01'). \
25
+ replace('}', '\x02'). \
26
+ replace('\x00', r'\%sZbs{}' % commandprefix). \
27
+ replace('\x01', r'\%sZob{}' % commandprefix). \
28
+ replace('\x02', r'\%sZcb{}' % commandprefix). \
29
+ replace('^', r'\%sZca{}' % commandprefix). \
30
+ replace('_', r'\%sZus{}' % commandprefix). \
31
+ replace('&', r'\%sZam{}' % commandprefix). \
32
+ replace('<', r'\%sZlt{}' % commandprefix). \
33
+ replace('>', r'\%sZgt{}' % commandprefix). \
34
+ replace('#', r'\%sZsh{}' % commandprefix). \
35
+ replace('%', r'\%sZpc{}' % commandprefix). \
36
+ replace('$', r'\%sZdl{}' % commandprefix). \
37
+ replace('-', r'\%sZhy{}' % commandprefix). \
38
+ replace("'", r'\%sZsq{}' % commandprefix). \
39
+ replace('"', r'\%sZdq{}' % commandprefix). \
40
+ replace('~', r'\%sZti{}' % commandprefix)
41
+
42
+
43
+ DOC_TEMPLATE = r'''
44
+ \documentclass{%(docclass)s}
45
+ \usepackage{fancyvrb}
46
+ \usepackage{color}
47
+ \usepackage[%(encoding)s]{inputenc}
48
+ %(preamble)s
49
+
50
+ %(styledefs)s
51
+
52
+ \begin{document}
53
+
54
+ \section*{%(title)s}
55
+
56
+ %(code)s
57
+ \end{document}
58
+ '''
59
+
60
+ ## Small explanation of the mess below :)
61
+ #
62
+ # The previous version of the LaTeX formatter just assigned a command to
63
+ # each token type defined in the current style. That obviously is
64
+ # problematic if the highlighted code is produced for a different style
65
+ # than the style commands themselves.
66
+ #
67
+ # This version works much like the HTML formatter which assigns multiple
68
+ # CSS classes to each <span> tag, from the most specific to the least
69
+ # specific token type, thus falling back to the parent token type if one
70
+ # is not defined. Here, the classes are there too and use the same short
71
+ # forms given in token.STANDARD_TYPES.
72
+ #
73
+ # Highlighted code now only uses one custom command, which by default is
74
+ # \PY and selectable by the commandprefix option (and in addition the
75
+ # escapes \PYZat, \PYZlb and \PYZrb which haven't been renamed for
76
+ # backwards compatibility purposes).
77
+ #
78
+ # \PY has two arguments: the classes, separated by +, and the text to
79
+ # render in that style. The classes are resolved into the respective
80
+ # style commands by magic, which serves to ignore unknown classes.
81
+ #
82
+ # The magic macros are:
83
+ # * \PY@it, \PY@bf, etc. are unconditionally wrapped around the text
84
+ # to render in \PY@do. Their definition determines the style.
85
+ # * \PY@reset resets \PY@it etc. to do nothing.
86
+ # * \PY@toks parses the list of classes, using magic inspired by the
87
+ # keyval package (but modified to use plusses instead of commas
88
+ # because fancyvrb redefines commas inside its environments).
89
+ # * \PY@tok processes one class, calling the \PY@tok@classname command
90
+ # if it exists.
91
+ # * \PY@tok@classname sets the \PY@it etc. to reflect the chosen style
92
+ # for its class.
93
+ # * \PY resets the style, parses the classnames and then calls \PY@do.
94
+ #
95
+ # Tip: to read this code, print it out in substituted form using e.g.
96
+ # >>> print STYLE_TEMPLATE % {'cp': 'PY'}
97
+
98
+ STYLE_TEMPLATE = r'''
99
+ \makeatletter
100
+ \def\%(cp)s@reset{\let\%(cp)s@it=\relax \let\%(cp)s@bf=\relax%%
101
+ \let\%(cp)s@ul=\relax \let\%(cp)s@tc=\relax%%
102
+ \let\%(cp)s@bc=\relax \let\%(cp)s@ff=\relax}
103
+ \def\%(cp)s@tok#1{\csname %(cp)s@tok@#1\endcsname}
104
+ \def\%(cp)s@toks#1+{\ifx\relax#1\empty\else%%
105
+ \%(cp)s@tok{#1}\expandafter\%(cp)s@toks\fi}
106
+ \def\%(cp)s@do#1{\%(cp)s@bc{\%(cp)s@tc{\%(cp)s@ul{%%
107
+ \%(cp)s@it{\%(cp)s@bf{\%(cp)s@ff{#1}}}}}}}
108
+ \def\%(cp)s#1#2{\%(cp)s@reset\%(cp)s@toks#1+\relax+\%(cp)s@do{#2}}
109
+
110
+ %(styles)s
111
+
112
+ \def\%(cp)sZbs{\char`\\}
113
+ \def\%(cp)sZus{\char`\_}
114
+ \def\%(cp)sZob{\char`\{}
115
+ \def\%(cp)sZcb{\char`\}}
116
+ \def\%(cp)sZca{\char`\^}
117
+ \def\%(cp)sZam{\char`\&}
118
+ \def\%(cp)sZlt{\char`\<}
119
+ \def\%(cp)sZgt{\char`\>}
120
+ \def\%(cp)sZsh{\char`\#}
121
+ \def\%(cp)sZpc{\char`\%%}
122
+ \def\%(cp)sZdl{\char`\$}
123
+ \def\%(cp)sZhy{\char`\-}
124
+ \def\%(cp)sZsq{\char`\'}
125
+ \def\%(cp)sZdq{\char`\"}
126
+ \def\%(cp)sZti{\char`\~}
127
+ %% for compatibility with earlier versions
128
+ \def\%(cp)sZat{@}
129
+ \def\%(cp)sZlb{[}
130
+ \def\%(cp)sZrb{]}
131
+ \makeatother
132
+ '''
133
+
134
+
135
+ def _get_ttype_name(ttype):
136
+ fname = STANDARD_TYPES.get(ttype)
137
+ if fname:
138
+ return fname
139
+ aname = ''
140
+ while fname is None:
141
+ aname = ttype[-1] + aname
142
+ ttype = ttype.parent
143
+ fname = STANDARD_TYPES.get(ttype)
144
+ return fname + aname
145
+
146
+
147
+ class LatexFormatter(Formatter):
148
+ r"""
149
+ Format tokens as LaTeX code. This needs the `fancyvrb` and `color`
150
+ standard packages.
151
+
152
+ Without the `full` option, code is formatted as one ``Verbatim``
153
+ environment, like this:
154
+
155
+ .. sourcecode:: latex
156
+
157
+ \begin{Verbatim}[commandchars=\\\{\}]
158
+ \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}):
159
+ \PY{k}{pass}
160
+ \end{Verbatim}
161
+
162
+ The special command used here (``\PY``) and all the other macros it needs
163
+ are output by the `get_style_defs` method.
164
+
165
+ With the `full` option, a complete LaTeX document is output, including
166
+ the command definitions in the preamble.
167
+
168
+ The `get_style_defs()` method of a `LatexFormatter` returns a string
169
+ containing ``\def`` commands defining the macros needed inside the
170
+ ``Verbatim`` environments.
171
+
172
+ Additional options accepted:
173
+
174
+ `style`
175
+ The style to use, can be a string or a Style subclass (default:
176
+ ``'default'``).
177
+
178
+ `full`
179
+ Tells the formatter to output a "full" document, i.e. a complete
180
+ self-contained document (default: ``False``).
181
+
182
+ `title`
183
+ If `full` is true, the title that should be used to caption the
184
+ document (default: ``''``).
185
+
186
+ `docclass`
187
+ If the `full` option is enabled, this is the document class to use
188
+ (default: ``'article'``).
189
+
190
+ `preamble`
191
+ If the `full` option is enabled, this can be further preamble commands,
192
+ e.g. ``\usepackage`` (default: ``''``).
193
+
194
+ `linenos`
195
+ If set to ``True``, output line numbers (default: ``False``).
196
+
197
+ `linenostart`
198
+ The line number for the first line (default: ``1``).
199
+
200
+ `linenostep`
201
+ If set to a number n > 1, only every nth line number is printed.
202
+
203
+ `verboptions`
204
+ Additional options given to the Verbatim environment (see the *fancyvrb*
205
+ docs for possible values) (default: ``''``).
206
+
207
+ `commandprefix`
208
+ The LaTeX commands used to produce colored output are constructed
209
+ using this prefix and some letters (default: ``'PY'``).
210
+
211
+ .. versionadded:: 0.7
212
+ .. versionchanged:: 0.10
213
+ The default is now ``'PY'`` instead of ``'C'``.
214
+
215
+ `texcomments`
216
+ If set to ``True``, enables LaTeX comment lines. That is, LaTex markup
217
+ in comment tokens is not escaped so that LaTeX can render it (default:
218
+ ``False``).
219
+
220
+ .. versionadded:: 1.2
221
+
222
+ `mathescape`
223
+ If set to ``True``, enables LaTeX math mode escape in comments. That
224
+ is, ``'$...$'`` inside a comment will trigger math mode (default:
225
+ ``False``).
226
+
227
+ .. versionadded:: 1.2
228
+
229
+ `escapeinside`
230
+ If set to a string of length 2, enables escaping to LaTeX. Text
231
+ delimited by these 2 characters is read as LaTeX code and
232
+ typeset accordingly. It has no effect in string literals. It has
233
+ no effect in comments if `texcomments` or `mathescape` is
234
+ set. (default: ``''``).
235
+
236
+ .. versionadded:: 2.0
237
+
238
+ `envname`
239
+ Allows you to pick an alternative environment name replacing Verbatim.
240
+ The alternate environment still has to support Verbatim's option syntax.
241
+ (default: ``'Verbatim'``).
242
+
243
+ .. versionadded:: 2.0
244
+ """
245
+ name = 'LaTeX'
246
+ aliases = ['latex', 'tex']
247
+ filenames = ['*.tex']
248
+
249
+ def __init__(self, **options):
250
+ Formatter.__init__(self, **options)
251
+ self.docclass = options.get('docclass', 'article')
252
+ self.preamble = options.get('preamble', '')
253
+ self.linenos = get_bool_opt(options, 'linenos', False)
254
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
255
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
256
+ self.verboptions = options.get('verboptions', '')
257
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
258
+ self.commandprefix = options.get('commandprefix', 'PY')
259
+ self.texcomments = get_bool_opt(options, 'texcomments', False)
260
+ self.mathescape = get_bool_opt(options, 'mathescape', False)
261
+ self.escapeinside = options.get('escapeinside', '')
262
+ if len(self.escapeinside) == 2:
263
+ self.left = self.escapeinside[0]
264
+ self.right = self.escapeinside[1]
265
+ else:
266
+ self.escapeinside = ''
267
+ self.envname = options.get('envname', 'Verbatim')
268
+
269
+ self._create_stylesheet()
270
+
271
+ def _create_stylesheet(self):
272
+ t2n = self.ttype2name = {Token: ''}
273
+ c2d = self.cmd2def = {}
274
+ cp = self.commandprefix
275
+
276
+ def rgbcolor(col):
277
+ if col:
278
+ return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)
279
+ for i in (0, 2, 4)])
280
+ else:
281
+ return '1,1,1'
282
+
283
+ for ttype, ndef in self.style:
284
+ name = _get_ttype_name(ttype)
285
+ cmndef = ''
286
+ if ndef['bold']:
287
+ cmndef += r'\let\$$@bf=\textbf'
288
+ if ndef['italic']:
289
+ cmndef += r'\let\$$@it=\textit'
290
+ if ndef['underline']:
291
+ cmndef += r'\let\$$@ul=\underline'
292
+ if ndef['roman']:
293
+ cmndef += r'\let\$$@ff=\textrm'
294
+ if ndef['sans']:
295
+ cmndef += r'\let\$$@ff=\textsf'
296
+ if ndef['mono']:
297
+ cmndef += r'\let\$$@ff=\textsf'
298
+ if ndef['color']:
299
+ cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
300
+ rgbcolor(ndef['color']))
301
+ if ndef['border']:
302
+ cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{\string -\fboxrule}'
303
+ r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}}' %
304
+ (rgbcolor(ndef['border']),
305
+ rgbcolor(ndef['bgcolor'])))
306
+ elif ndef['bgcolor']:
307
+ cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{0pt}'
308
+ r'\colorbox[rgb]{%s}{\strut ##1}}}' %
309
+ rgbcolor(ndef['bgcolor']))
310
+ if cmndef == '':
311
+ continue
312
+ cmndef = cmndef.replace('$$', cp)
313
+ t2n[ttype] = name
314
+ c2d[name] = cmndef
315
+
316
+ def get_style_defs(self, arg=''):
317
+ """
318
+ Return the command sequences needed to define the commands
319
+ used to format text in the verbatim environment. ``arg`` is ignored.
320
+ """
321
+ cp = self.commandprefix
322
+ styles = []
323
+ for name, definition in self.cmd2def.items():
324
+ styles.append(r'\@namedef{%s@tok@%s}{%s}' % (cp, name, definition))
325
+ return STYLE_TEMPLATE % {'cp': self.commandprefix,
326
+ 'styles': '\n'.join(styles)}
327
+
328
+ def format_unencoded(self, tokensource, outfile):
329
+ # TODO: add support for background colors
330
+ t2n = self.ttype2name
331
+ cp = self.commandprefix
332
+
333
+ if self.full:
334
+ realoutfile = outfile
335
+ outfile = StringIO()
336
+
337
+ outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}')
338
+ if self.linenos:
339
+ start, step = self.linenostart, self.linenostep
340
+ outfile.write(',numbers=left' +
341
+ (start and ',firstnumber=%d' % start or '') +
342
+ (step and ',stepnumber=%d' % step or ''))
343
+ if self.mathescape or self.texcomments or self.escapeinside:
344
+ outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7'
345
+ '\\catcode`\\_=8\\relax}')
346
+ if self.verboptions:
347
+ outfile.write(',' + self.verboptions)
348
+ outfile.write(']\n')
349
+
350
+ for ttype, value in tokensource:
351
+ if ttype in Token.Comment:
352
+ if self.texcomments:
353
+ # Try to guess comment starting lexeme and escape it ...
354
+ start = value[0:1]
355
+ for i in range(1, len(value)):
356
+ if start[0] != value[i]:
357
+ break
358
+ start += value[i]
359
+
360
+ value = value[len(start):]
361
+ start = escape_tex(start, cp)
362
+
363
+ # ... but do not escape inside comment.
364
+ value = start + value
365
+ elif self.mathescape:
366
+ # Only escape parts not inside a math environment.
367
+ parts = value.split('$')
368
+ in_math = False
369
+ for i, part in enumerate(parts):
370
+ if not in_math:
371
+ parts[i] = escape_tex(part, cp)
372
+ in_math = not in_math
373
+ value = '$'.join(parts)
374
+ elif self.escapeinside:
375
+ text = value
376
+ value = ''
377
+ while text:
378
+ a, sep1, text = text.partition(self.left)
379
+ if sep1:
380
+ b, sep2, text = text.partition(self.right)
381
+ if sep2:
382
+ value += escape_tex(a, cp) + b
383
+ else:
384
+ value += escape_tex(a + sep1 + b, cp)
385
+ else:
386
+ value += escape_tex(a, cp)
387
+ else:
388
+ value = escape_tex(value, cp)
389
+ elif ttype not in Token.Escape:
390
+ value = escape_tex(value, cp)
391
+ styles = []
392
+ while ttype is not Token:
393
+ try:
394
+ styles.append(t2n[ttype])
395
+ except KeyError:
396
+ # not in current style
397
+ styles.append(_get_ttype_name(ttype))
398
+ ttype = ttype.parent
399
+ styleval = '+'.join(reversed(styles))
400
+ if styleval:
401
+ spl = value.split('\n')
402
+ for line in spl[:-1]:
403
+ if line:
404
+ outfile.write("\\%s{%s}{%s}" % (cp, styleval, line))
405
+ outfile.write('\n')
406
+ if spl[-1]:
407
+ outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1]))
408
+ else:
409
+ outfile.write(value)
410
+
411
+ outfile.write('\\end{' + self.envname + '}\n')
412
+
413
+ if self.full:
414
+ encoding = self.encoding or 'utf8'
415
+ # map known existings encodings from LaTeX distribution
416
+ encoding = {
417
+ 'utf_8': 'utf8',
418
+ 'latin_1': 'latin1',
419
+ 'iso_8859_1': 'latin1',
420
+ }.get(encoding.replace('-', '_'), encoding)
421
+ realoutfile.write(DOC_TEMPLATE %
422
+ dict(docclass = self.docclass,
423
+ preamble = self.preamble,
424
+ title = self.title,
425
+ encoding = encoding,
426
+ styledefs = self.get_style_defs(),
427
+ code = outfile.getvalue()))
428
+
429
+
430
+ class LatexEmbeddedLexer(Lexer):
431
+ """
432
+ This lexer takes one lexer as argument, the lexer for the language
433
+ being formatted, and the left and right delimiters for escaped text.
434
+
435
+ First everything is scanned using the language lexer to obtain
436
+ strings and comments. All other consecutive tokens are merged and
437
+ the resulting text is scanned for escaped segments, which are given
438
+ the Token.Escape type. Finally text that is not escaped is scanned
439
+ again with the language lexer.
440
+ """
441
+ def __init__(self, left, right, lang, **options):
442
+ self.left = left
443
+ self.right = right
444
+ self.lang = lang
445
+ Lexer.__init__(self, **options)
446
+
447
+ def get_tokens_unprocessed(self, text):
448
+ # find and remove all the escape tokens (replace with an empty string)
449
+ # this is very similar to DelegatingLexer.get_tokens_unprocessed.
450
+ buffered = ''
451
+ insertions = []
452
+ insertion_buf = []
453
+ for i, t, v in self._find_safe_escape_tokens(text):
454
+ if t is None:
455
+ if insertion_buf:
456
+ insertions.append((len(buffered), insertion_buf))
457
+ insertion_buf = []
458
+ buffered += v
459
+ else:
460
+ insertion_buf.append((i, t, v))
461
+ if insertion_buf:
462
+ insertions.append((len(buffered), insertion_buf))
463
+ return do_insertions(insertions,
464
+ self.lang.get_tokens_unprocessed(buffered))
465
+
466
+ def _find_safe_escape_tokens(self, text):
467
+ """ find escape tokens that are not in strings or comments """
468
+ for i, t, v in self._filter_to(
469
+ self.lang.get_tokens_unprocessed(text),
470
+ lambda t: t in Token.Comment or t in Token.String
471
+ ):
472
+ if t is None:
473
+ for i2, t2, v2 in self._find_escape_tokens(v):
474
+ yield i + i2, t2, v2
475
+ else:
476
+ yield i, None, v
477
+
478
+ def _filter_to(self, it, pred):
479
+ """ Keep only the tokens that match `pred`, merge the others together """
480
+ buf = ''
481
+ idx = 0
482
+ for i, t, v in it:
483
+ if pred(t):
484
+ if buf:
485
+ yield idx, None, buf
486
+ buf = ''
487
+ yield i, t, v
488
+ else:
489
+ if not buf:
490
+ idx = i
491
+ buf += v
492
+ if buf:
493
+ yield idx, None, buf
494
+
495
+ def _find_escape_tokens(self, text):
496
+ """ Find escape tokens within text, give token=None otherwise """
497
+ index = 0
498
+ while text:
499
+ a, sep1, text = text.partition(self.left)
500
+ if a:
501
+ yield index, None, a
502
+ index += len(a)
503
+ if sep1:
504
+ b, sep2, text = text.partition(self.right)
505
+ if sep2:
506
+ yield index + len(sep1), Token.Escape, b
507
+ index += len(sep1) + len(b) + len(sep2)
508
+ else:
509
+ yield index, Token.Error, sep1
510
+ index += len(sep1)
511
+ text = b
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.other
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Other formatters: NullFormatter, RawTokenFormatter.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+ from pip._vendor.pygments.util import get_choice_opt
13
+ from pip._vendor.pygments.token import Token
14
+ from pip._vendor.pygments.console import colorize
15
+
16
+ __all__ = ['NullFormatter', 'RawTokenFormatter', 'TestcaseFormatter']
17
+
18
+
19
+ class NullFormatter(Formatter):
20
+ """
21
+ Output the text unchanged without any formatting.
22
+ """
23
+ name = 'Text only'
24
+ aliases = ['text', 'null']
25
+ filenames = ['*.txt']
26
+
27
+ def format(self, tokensource, outfile):
28
+ enc = self.encoding
29
+ for ttype, value in tokensource:
30
+ if enc:
31
+ outfile.write(value.encode(enc))
32
+ else:
33
+ outfile.write(value)
34
+
35
+
36
+ class RawTokenFormatter(Formatter):
37
+ r"""
38
+ Format tokens as a raw representation for storing token streams.
39
+
40
+ The format is ``tokentype<TAB>repr(tokenstring)\n``. The output can later
41
+ be converted to a token stream with the `RawTokenLexer`, described in the
42
+ :doc:`lexer list <lexers>`.
43
+
44
+ Only two options are accepted:
45
+
46
+ `compress`
47
+ If set to ``'gz'`` or ``'bz2'``, compress the output with the given
48
+ compression algorithm after encoding (default: ``''``).
49
+ `error_color`
50
+ If set to a color name, highlight error tokens using that color. If
51
+ set but with no value, defaults to ``'red'``.
52
+
53
+ .. versionadded:: 0.11
54
+
55
+ """
56
+ name = 'Raw tokens'
57
+ aliases = ['raw', 'tokens']
58
+ filenames = ['*.raw']
59
+
60
+ unicodeoutput = False
61
+
62
+ def __init__(self, **options):
63
+ Formatter.__init__(self, **options)
64
+ # We ignore self.encoding if it is set, since it gets set for lexer
65
+ # and formatter if given with -Oencoding on the command line.
66
+ # The RawTokenFormatter outputs only ASCII. Override here.
67
+ self.encoding = 'ascii' # let pygments.format() do the right thing
68
+ self.compress = get_choice_opt(options, 'compress',
69
+ ['', 'none', 'gz', 'bz2'], '')
70
+ self.error_color = options.get('error_color', None)
71
+ if self.error_color is True:
72
+ self.error_color = 'red'
73
+ if self.error_color is not None:
74
+ try:
75
+ colorize(self.error_color, '')
76
+ except KeyError:
77
+ raise ValueError("Invalid color %r specified" %
78
+ self.error_color)
79
+
80
+ def format(self, tokensource, outfile):
81
+ try:
82
+ outfile.write(b'')
83
+ except TypeError:
84
+ raise TypeError('The raw tokens formatter needs a binary '
85
+ 'output file')
86
+ if self.compress == 'gz':
87
+ import gzip
88
+ outfile = gzip.GzipFile('', 'wb', 9, outfile)
89
+
90
+ write = outfile.write
91
+ flush = outfile.close
92
+ elif self.compress == 'bz2':
93
+ import bz2
94
+ compressor = bz2.BZ2Compressor(9)
95
+
96
+ def write(text):
97
+ outfile.write(compressor.compress(text))
98
+
99
+ def flush():
100
+ outfile.write(compressor.flush())
101
+ outfile.flush()
102
+ else:
103
+ write = outfile.write
104
+ flush = outfile.flush
105
+
106
+ if self.error_color:
107
+ for ttype, value in tokensource:
108
+ line = b"%r\t%r\n" % (ttype, value)
109
+ if ttype is Token.Error:
110
+ write(colorize(self.error_color, line))
111
+ else:
112
+ write(line)
113
+ else:
114
+ for ttype, value in tokensource:
115
+ write(b"%r\t%r\n" % (ttype, value))
116
+ flush()
117
+
118
+
119
+ TESTCASE_BEFORE = '''\
120
+ def testNeedsName(lexer):
121
+ fragment = %r
122
+ tokens = [
123
+ '''
124
+ TESTCASE_AFTER = '''\
125
+ ]
126
+ assert list(lexer.get_tokens(fragment)) == tokens
127
+ '''
128
+
129
+
130
+ class TestcaseFormatter(Formatter):
131
+ """
132
+ Format tokens as appropriate for a new testcase.
133
+
134
+ .. versionadded:: 2.0
135
+ """
136
+ name = 'Testcase'
137
+ aliases = ['testcase']
138
+
139
+ def __init__(self, **options):
140
+ Formatter.__init__(self, **options)
141
+ if self.encoding is not None and self.encoding != 'utf-8':
142
+ raise ValueError("Only None and utf-8 are allowed encodings.")
143
+
144
+ def format(self, tokensource, outfile):
145
+ indentation = ' ' * 12
146
+ rawbuf = []
147
+ outbuf = []
148
+ for ttype, value in tokensource:
149
+ rawbuf.append(value)
150
+ outbuf.append('%s(%s, %r),\n' % (indentation, ttype, value))
151
+
152
+ before = TESTCASE_BEFORE % (''.join(rawbuf),)
153
+ during = ''.join(outbuf)
154
+ after = TESTCASE_AFTER
155
+ if self.encoding is None:
156
+ outfile.write(before + during + after)
157
+ else:
158
+ outfile.write(before.encode('utf-8'))
159
+ outfile.write(during.encode('utf-8'))
160
+ outfile.write(after.encode('utf-8'))
161
+ outfile.flush()
venv/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.pangomarkup
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for Pango markup output.
6
+
7
+ :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pip._vendor.pygments.formatter import Formatter
12
+
13
+
14
+ __all__ = ['PangoMarkupFormatter']
15
+
16
+
17
+ _escape_table = {
18
+ ord('&'): '&amp;',
19
+ ord('<'): '&lt;',
20
+ }
21
+
22
+
23
+ def escape_special_chars(text, table=_escape_table):
24
+ """Escape & and < for Pango Markup."""
25
+ return text.translate(table)
26
+
27
+
28
+ class PangoMarkupFormatter(Formatter):
29
+ """
30
+ Format tokens as Pango Markup code. It can then be rendered to an SVG.
31
+
32
+ .. versionadded:: 2.9
33
+ """
34
+
35
+ name = 'Pango Markup'
36
+ aliases = ['pango', 'pangomarkup']
37
+ filenames = []
38
+
39
+ def __init__(self, **options):
40
+ Formatter.__init__(self, **options)
41
+
42
+ self.styles = {}
43
+
44
+ for token, style in self.style:
45
+ start = ''
46
+ end = ''
47
+ if style['color']:
48
+ start += '<span fgcolor="#%s">' % style['color']
49
+ end = '</span>' + end
50
+ if style['bold']:
51
+ start += '<b>'
52
+ end = '</b>' + end
53
+ if style['italic']:
54
+ start += '<i>'
55
+ end = '</i>' + end
56
+ if style['underline']:
57
+ start += '<u>'
58
+ end = '</u>' + end
59
+ self.styles[token] = (start, end)
60
+
61
+ def format_unencoded(self, tokensource, outfile):
62
+ lastval = ''
63
+ lasttype = None
64
+
65
+ outfile.write('<tt>')
66
+
67
+ for ttype, value in tokensource:
68
+ while ttype not in self.styles:
69
+ ttype = ttype.parent
70
+ if ttype == lasttype:
71
+ lastval += escape_special_chars(value)
72
+ else:
73
+ if lastval:
74
+ stylebegin, styleend = self.styles[lasttype]
75
+ outfile.write(stylebegin + lastval + styleend)
76
+ lastval = escape_special_chars(value)
77
+ lasttype = ttype
78
+
79
+ if lastval:
80
+ stylebegin, styleend = self.styles[lasttype]
81
+ outfile.write(stylebegin + lastval + styleend)
82
+
83
+ outfile.write('</tt>')