ZTWHHH commited on
Commit
c4a45fd
·
verified ·
1 Parent(s): ccfa07a

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. vllm/lib/python3.10/site-packages/pip/_vendor/distro/__pycache__/__init__.cpython-310.pyc +0 -0
  2. vllm/lib/python3.10/site-packages/pip/_vendor/distro/distro.py +1403 -0
  3. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__init__.py +82 -0
  4. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__main__.py +17 -0
  5. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/__main__.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/cmdline.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/formatter.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-310.pyc +0 -0
  9. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/scanner.cpython-310.pyc +0 -0
  10. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-310.pyc +0 -0
  11. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-310.pyc +0 -0
  12. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-310.pyc +0 -0
  13. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/cmdline.py +668 -0
  14. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/console.py +70 -0
  15. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__init__.py +940 -0
  16. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatter.py +129 -0
  18. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py +157 -0
  19. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-310.pyc +0 -0
  20. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/groff.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/html.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/img.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/irc.cpython-310.pyc +0 -0
  26. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/latex.cpython-310.pyc +0 -0
  27. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc +0 -0
  28. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc +0 -0
  29. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/svg.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py +23 -0
  34. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/bbcode.py +108 -0
  35. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py +170 -0
  36. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py +987 -0
  37. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py +685 -0
  38. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/irc.py +154 -0
  39. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py +518 -0
  40. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py +160 -0
  41. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py +83 -0
  42. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/rtf.py +349 -0
  43. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/svg.py +185 -0
  44. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal.py +127 -0
  45. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal256.py +338 -0
  46. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexer.py +963 -0
  47. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__init__.py +362 -0
  48. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-310.pyc +0 -0
  49. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/python.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/pip/_vendor/distro/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (893 Bytes). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/distro/distro.py ADDED
@@ -0,0 +1,1403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2015-2021 Nir Cohen
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """
17
+ The ``distro`` package (``distro`` stands for Linux Distribution) provides
18
+ information about the Linux distribution it runs on, such as a reliable
19
+ machine-readable distro ID, or version information.
20
+
21
+ It is the recommended replacement for Python's original
22
+ :py:func:`platform.linux_distribution` function, but it provides much more
23
+ functionality. An alternative implementation became necessary because Python
24
+ 3.5 deprecated this function, and Python 3.8 removed it altogether. Its
25
+ predecessor function :py:func:`platform.dist` was already deprecated since
26
+ Python 2.6 and removed in Python 3.8. Still, there are many cases in which
27
+ access to OS distribution information is needed. See `Python issue 1322
28
+ <https://bugs.python.org/issue1322>`_ for more information.
29
+ """
30
+
31
+ import argparse
32
+ import json
33
+ import logging
34
+ import os
35
+ import re
36
+ import shlex
37
+ import subprocess
38
+ import sys
39
+ import warnings
40
+ from typing import (
41
+ Any,
42
+ Callable,
43
+ Dict,
44
+ Iterable,
45
+ Optional,
46
+ Sequence,
47
+ TextIO,
48
+ Tuple,
49
+ Type,
50
+ )
51
+
52
+ try:
53
+ from typing import TypedDict
54
+ except ImportError:
55
+ # Python 3.7
56
+ TypedDict = dict
57
+
58
+ __version__ = "1.9.0"
59
+
60
+
61
+ class VersionDict(TypedDict):
62
+ major: str
63
+ minor: str
64
+ build_number: str
65
+
66
+
67
+ class InfoDict(TypedDict):
68
+ id: str
69
+ version: str
70
+ version_parts: VersionDict
71
+ like: str
72
+ codename: str
73
+
74
+
75
+ _UNIXCONFDIR = os.environ.get("UNIXCONFDIR", "/etc")
76
+ _UNIXUSRLIBDIR = os.environ.get("UNIXUSRLIBDIR", "/usr/lib")
77
+ _OS_RELEASE_BASENAME = "os-release"
78
+
79
+ #: Translation table for normalizing the "ID" attribute defined in os-release
80
+ #: files, for use by the :func:`distro.id` method.
81
+ #:
82
+ #: * Key: Value as defined in the os-release file, translated to lower case,
83
+ #: with blanks translated to underscores.
84
+ #:
85
+ #: * Value: Normalized value.
86
+ NORMALIZED_OS_ID = {
87
+ "ol": "oracle", # Oracle Linux
88
+ "opensuse-leap": "opensuse", # Newer versions of OpenSuSE report as opensuse-leap
89
+ }
90
+
91
+ #: Translation table for normalizing the "Distributor ID" attribute returned by
92
+ #: the lsb_release command, for use by the :func:`distro.id` method.
93
+ #:
94
+ #: * Key: Value as returned by the lsb_release command, translated to lower
95
+ #: case, with blanks translated to underscores.
96
+ #:
97
+ #: * Value: Normalized value.
98
+ NORMALIZED_LSB_ID = {
99
+ "enterpriseenterpriseas": "oracle", # Oracle Enterprise Linux 4
100
+ "enterpriseenterpriseserver": "oracle", # Oracle Linux 5
101
+ "redhatenterpriseworkstation": "rhel", # RHEL 6, 7 Workstation
102
+ "redhatenterpriseserver": "rhel", # RHEL 6, 7 Server
103
+ "redhatenterprisecomputenode": "rhel", # RHEL 6 ComputeNode
104
+ }
105
+
106
+ #: Translation table for normalizing the distro ID derived from the file name
107
+ #: of distro release files, for use by the :func:`distro.id` method.
108
+ #:
109
+ #: * Key: Value as derived from the file name of a distro release file,
110
+ #: translated to lower case, with blanks translated to underscores.
111
+ #:
112
+ #: * Value: Normalized value.
113
+ NORMALIZED_DISTRO_ID = {
114
+ "redhat": "rhel", # RHEL 6.x, 7.x
115
+ }
116
+
117
+ # Pattern for content of distro release file (reversed)
118
+ _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(
119
+ r"(?:[^)]*\)(.*)\()? *(?:STL )?([\d.+\-a-z]*\d) *(?:esaeler *)?(.+)"
120
+ )
121
+
122
+ # Pattern for base file name of distro release file
123
+ _DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r"(\w+)[-_](release|version)$")
124
+
125
+ # Base file names to be looked up for if _UNIXCONFDIR is not readable.
126
+ _DISTRO_RELEASE_BASENAMES = [
127
+ "SuSE-release",
128
+ "altlinux-release",
129
+ "arch-release",
130
+ "base-release",
131
+ "centos-release",
132
+ "fedora-release",
133
+ "gentoo-release",
134
+ "mageia-release",
135
+ "mandrake-release",
136
+ "mandriva-release",
137
+ "mandrivalinux-release",
138
+ "manjaro-release",
139
+ "oracle-release",
140
+ "redhat-release",
141
+ "rocky-release",
142
+ "sl-release",
143
+ "slackware-version",
144
+ ]
145
+
146
+ # Base file names to be ignored when searching for distro release file
147
+ _DISTRO_RELEASE_IGNORE_BASENAMES = (
148
+ "debian_version",
149
+ "lsb-release",
150
+ "oem-release",
151
+ _OS_RELEASE_BASENAME,
152
+ "system-release",
153
+ "plesk-release",
154
+ "iredmail-release",
155
+ "board-release",
156
+ "ec2_version",
157
+ )
158
+
159
+
160
+ def linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:
161
+ """
162
+ .. deprecated:: 1.6.0
163
+
164
+ :func:`distro.linux_distribution()` is deprecated. It should only be
165
+ used as a compatibility shim with Python's
166
+ :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,
167
+ :func:`distro.version` and :func:`distro.name` instead.
168
+
169
+ Return information about the current OS distribution as a tuple
170
+ ``(id_name, version, codename)`` with items as follows:
171
+
172
+ * ``id_name``: If *full_distribution_name* is false, the result of
173
+ :func:`distro.id`. Otherwise, the result of :func:`distro.name`.
174
+
175
+ * ``version``: The result of :func:`distro.version`.
176
+
177
+ * ``codename``: The extra item (usually in parentheses) after the
178
+ os-release version number, or the result of :func:`distro.codename`.
179
+
180
+ The interface of this function is compatible with the original
181
+ :py:func:`platform.linux_distribution` function, supporting a subset of
182
+ its parameters.
183
+
184
+ The data it returns may not exactly be the same, because it uses more data
185
+ sources than the original function, and that may lead to different data if
186
+ the OS distribution is not consistent across multiple data sources it
187
+ provides (there are indeed such distributions ...).
188
+
189
+ Another reason for differences is the fact that the :func:`distro.id`
190
+ method normalizes the distro ID string to a reliable machine-readable value
191
+ for a number of popular OS distributions.
192
+ """
193
+ warnings.warn(
194
+ "distro.linux_distribution() is deprecated. It should only be used as a "
195
+ "compatibility shim with Python's platform.linux_distribution(). Please use "
196
+ "distro.id(), distro.version() and distro.name() instead.",
197
+ DeprecationWarning,
198
+ stacklevel=2,
199
+ )
200
+ return _distro.linux_distribution(full_distribution_name)
201
+
202
+
203
+ def id() -> str:
204
+ """
205
+ Return the distro ID of the current distribution, as a
206
+ machine-readable string.
207
+
208
+ For a number of OS distributions, the returned distro ID value is
209
+ *reliable*, in the sense that it is documented and that it does not change
210
+ across releases of the distribution.
211
+
212
+ This package maintains the following reliable distro ID values:
213
+
214
+ ============== =========================================
215
+ Distro ID Distribution
216
+ ============== =========================================
217
+ "ubuntu" Ubuntu
218
+ "debian" Debian
219
+ "rhel" RedHat Enterprise Linux
220
+ "centos" CentOS
221
+ "fedora" Fedora
222
+ "sles" SUSE Linux Enterprise Server
223
+ "opensuse" openSUSE
224
+ "amzn" Amazon Linux
225
+ "arch" Arch Linux
226
+ "buildroot" Buildroot
227
+ "cloudlinux" CloudLinux OS
228
+ "exherbo" Exherbo Linux
229
+ "gentoo" GenToo Linux
230
+ "ibm_powerkvm" IBM PowerKVM
231
+ "kvmibm" KVM for IBM z Systems
232
+ "linuxmint" Linux Mint
233
+ "mageia" Mageia
234
+ "mandriva" Mandriva Linux
235
+ "parallels" Parallels
236
+ "pidora" Pidora
237
+ "raspbian" Raspbian
238
+ "oracle" Oracle Linux (and Oracle Enterprise Linux)
239
+ "scientific" Scientific Linux
240
+ "slackware" Slackware
241
+ "xenserver" XenServer
242
+ "openbsd" OpenBSD
243
+ "netbsd" NetBSD
244
+ "freebsd" FreeBSD
245
+ "midnightbsd" MidnightBSD
246
+ "rocky" Rocky Linux
247
+ "aix" AIX
248
+ "guix" Guix System
249
+ "altlinux" ALT Linux
250
+ ============== =========================================
251
+
252
+ If you have a need to get distros for reliable IDs added into this set,
253
+ or if you find that the :func:`distro.id` function returns a different
254
+ distro ID for one of the listed distros, please create an issue in the
255
+ `distro issue tracker`_.
256
+
257
+ **Lookup hierarchy and transformations:**
258
+
259
+ First, the ID is obtained from the following sources, in the specified
260
+ order. The first available and non-empty value is used:
261
+
262
+ * the value of the "ID" attribute of the os-release file,
263
+
264
+ * the value of the "Distributor ID" attribute returned by the lsb_release
265
+ command,
266
+
267
+ * the first part of the file name of the distro release file,
268
+
269
+ The so determined ID value then passes the following transformations,
270
+ before it is returned by this method:
271
+
272
+ * it is translated to lower case,
273
+
274
+ * blanks (which should not be there anyway) are translated to underscores,
275
+
276
+ * a normalization of the ID is performed, based upon
277
+ `normalization tables`_. The purpose of this normalization is to ensure
278
+ that the ID is as reliable as possible, even across incompatible changes
279
+ in the OS distributions. A common reason for an incompatible change is
280
+ the addition of an os-release file, or the addition of the lsb_release
281
+ command, with ID values that differ from what was previously determined
282
+ from the distro release file name.
283
+ """
284
+ return _distro.id()
285
+
286
+
287
+ def name(pretty: bool = False) -> str:
288
+ """
289
+ Return the name of the current OS distribution, as a human-readable
290
+ string.
291
+
292
+ If *pretty* is false, the name is returned without version or codename.
293
+ (e.g. "CentOS Linux")
294
+
295
+ If *pretty* is true, the version and codename are appended.
296
+ (e.g. "CentOS Linux 7.1.1503 (Core)")
297
+
298
+ **Lookup hierarchy:**
299
+
300
+ The name is obtained from the following sources, in the specified order.
301
+ The first available and non-empty value is used:
302
+
303
+ * If *pretty* is false:
304
+
305
+ - the value of the "NAME" attribute of the os-release file,
306
+
307
+ - the value of the "Distributor ID" attribute returned by the lsb_release
308
+ command,
309
+
310
+ - the value of the "<name>" field of the distro release file.
311
+
312
+ * If *pretty* is true:
313
+
314
+ - the value of the "PRETTY_NAME" attribute of the os-release file,
315
+
316
+ - the value of the "Description" attribute returned by the lsb_release
317
+ command,
318
+
319
+ - the value of the "<name>" field of the distro release file, appended
320
+ with the value of the pretty version ("<version_id>" and "<codename>"
321
+ fields) of the distro release file, if available.
322
+ """
323
+ return _distro.name(pretty)
324
+
325
+
326
+ def version(pretty: bool = False, best: bool = False) -> str:
327
+ """
328
+ Return the version of the current OS distribution, as a human-readable
329
+ string.
330
+
331
+ If *pretty* is false, the version is returned without codename (e.g.
332
+ "7.0").
333
+
334
+ If *pretty* is true, the codename in parenthesis is appended, if the
335
+ codename is non-empty (e.g. "7.0 (Maipo)").
336
+
337
+ Some distributions provide version numbers with different precisions in
338
+ the different sources of distribution information. Examining the different
339
+ sources in a fixed priority order does not always yield the most precise
340
+ version (e.g. for Debian 8.2, or CentOS 7.1).
341
+
342
+ Some other distributions may not provide this kind of information. In these
343
+ cases, an empty string would be returned. This behavior can be observed
344
+ with rolling releases distributions (e.g. Arch Linux).
345
+
346
+ The *best* parameter can be used to control the approach for the returned
347
+ version:
348
+
349
+ If *best* is false, the first non-empty version number in priority order of
350
+ the examined sources is returned.
351
+
352
+ If *best* is true, the most precise version number out of all examined
353
+ sources is returned.
354
+
355
+ **Lookup hierarchy:**
356
+
357
+ In all cases, the version number is obtained from the following sources.
358
+ If *best* is false, this order represents the priority order:
359
+
360
+ * the value of the "VERSION_ID" attribute of the os-release file,
361
+ * the value of the "Release" attribute returned by the lsb_release
362
+ command,
363
+ * the version number parsed from the "<version_id>" field of the first line
364
+ of the distro release file,
365
+ * the version number parsed from the "PRETTY_NAME" attribute of the
366
+ os-release file, if it follows the format of the distro release files.
367
+ * the version number parsed from the "Description" attribute returned by
368
+ the lsb_release command, if it follows the format of the distro release
369
+ files.
370
+ """
371
+ return _distro.version(pretty, best)
372
+
373
+
374
+ def version_parts(best: bool = False) -> Tuple[str, str, str]:
375
+ """
376
+ Return the version of the current OS distribution as a tuple
377
+ ``(major, minor, build_number)`` with items as follows:
378
+
379
+ * ``major``: The result of :func:`distro.major_version`.
380
+
381
+ * ``minor``: The result of :func:`distro.minor_version`.
382
+
383
+ * ``build_number``: The result of :func:`distro.build_number`.
384
+
385
+ For a description of the *best* parameter, see the :func:`distro.version`
386
+ method.
387
+ """
388
+ return _distro.version_parts(best)
389
+
390
+
391
+ def major_version(best: bool = False) -> str:
392
+ """
393
+ Return the major version of the current OS distribution, as a string,
394
+ if provided.
395
+ Otherwise, the empty string is returned. The major version is the first
396
+ part of the dot-separated version string.
397
+
398
+ For a description of the *best* parameter, see the :func:`distro.version`
399
+ method.
400
+ """
401
+ return _distro.major_version(best)
402
+
403
+
404
+ def minor_version(best: bool = False) -> str:
405
+ """
406
+ Return the minor version of the current OS distribution, as a string,
407
+ if provided.
408
+ Otherwise, the empty string is returned. The minor version is the second
409
+ part of the dot-separated version string.
410
+
411
+ For a description of the *best* parameter, see the :func:`distro.version`
412
+ method.
413
+ """
414
+ return _distro.minor_version(best)
415
+
416
+
417
+ def build_number(best: bool = False) -> str:
418
+ """
419
+ Return the build number of the current OS distribution, as a string,
420
+ if provided.
421
+ Otherwise, the empty string is returned. The build number is the third part
422
+ of the dot-separated version string.
423
+
424
+ For a description of the *best* parameter, see the :func:`distro.version`
425
+ method.
426
+ """
427
+ return _distro.build_number(best)
428
+
429
+
430
+ def like() -> str:
431
+ """
432
+ Return a space-separated list of distro IDs of distributions that are
433
+ closely related to the current OS distribution in regards to packaging
434
+ and programming interfaces, for example distributions the current
435
+ distribution is a derivative from.
436
+
437
+ **Lookup hierarchy:**
438
+
439
+ This information item is only provided by the os-release file.
440
+ For details, see the description of the "ID_LIKE" attribute in the
441
+ `os-release man page
442
+ <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.
443
+ """
444
+ return _distro.like()
445
+
446
+
447
+ def codename() -> str:
448
+ """
449
+ Return the codename for the release of the current OS distribution,
450
+ as a string.
451
+
452
+ If the distribution does not have a codename, an empty string is returned.
453
+
454
+ Note that the returned codename is not always really a codename. For
455
+ example, openSUSE returns "x86_64". This function does not handle such
456
+ cases in any special way and just returns the string it finds, if any.
457
+
458
+ **Lookup hierarchy:**
459
+
460
+ * the codename within the "VERSION" attribute of the os-release file, if
461
+ provided,
462
+
463
+ * the value of the "Codename" attribute returned by the lsb_release
464
+ command,
465
+
466
+ * the value of the "<codename>" field of the distro release file.
467
+ """
468
+ return _distro.codename()
469
+
470
+
471
+ def info(pretty: bool = False, best: bool = False) -> InfoDict:
472
+ """
473
+ Return certain machine-readable information items about the current OS
474
+ distribution in a dictionary, as shown in the following example:
475
+
476
+ .. sourcecode:: python
477
+
478
+ {
479
+ 'id': 'rhel',
480
+ 'version': '7.0',
481
+ 'version_parts': {
482
+ 'major': '7',
483
+ 'minor': '0',
484
+ 'build_number': ''
485
+ },
486
+ 'like': 'fedora',
487
+ 'codename': 'Maipo'
488
+ }
489
+
490
+ The dictionary structure and keys are always the same, regardless of which
491
+ information items are available in the underlying data sources. The values
492
+ for the various keys are as follows:
493
+
494
+ * ``id``: The result of :func:`distro.id`.
495
+
496
+ * ``version``: The result of :func:`distro.version`.
497
+
498
+ * ``version_parts -> major``: The result of :func:`distro.major_version`.
499
+
500
+ * ``version_parts -> minor``: The result of :func:`distro.minor_version`.
501
+
502
+ * ``version_parts -> build_number``: The result of
503
+ :func:`distro.build_number`.
504
+
505
+ * ``like``: The result of :func:`distro.like`.
506
+
507
+ * ``codename``: The result of :func:`distro.codename`.
508
+
509
+ For a description of the *pretty* and *best* parameters, see the
510
+ :func:`distro.version` method.
511
+ """
512
+ return _distro.info(pretty, best)
513
+
514
+
515
+ def os_release_info() -> Dict[str, str]:
516
+ """
517
+ Return a dictionary containing key-value pairs for the information items
518
+ from the os-release file data source of the current OS distribution.
519
+
520
+ See `os-release file`_ for details about these information items.
521
+ """
522
+ return _distro.os_release_info()
523
+
524
+
525
+ def lsb_release_info() -> Dict[str, str]:
526
+ """
527
+ Return a dictionary containing key-value pairs for the information items
528
+ from the lsb_release command data source of the current OS distribution.
529
+
530
+ See `lsb_release command output`_ for details about these information
531
+ items.
532
+ """
533
+ return _distro.lsb_release_info()
534
+
535
+
536
+ def distro_release_info() -> Dict[str, str]:
537
+ """
538
+ Return a dictionary containing key-value pairs for the information items
539
+ from the distro release file data source of the current OS distribution.
540
+
541
+ See `distro release file`_ for details about these information items.
542
+ """
543
+ return _distro.distro_release_info()
544
+
545
+
546
+ def uname_info() -> Dict[str, str]:
547
+ """
548
+ Return a dictionary containing key-value pairs for the information items
549
+ from the distro release file data source of the current OS distribution.
550
+ """
551
+ return _distro.uname_info()
552
+
553
+
554
+ def os_release_attr(attribute: str) -> str:
555
+ """
556
+ Return a single named information item from the os-release file data source
557
+ of the current OS distribution.
558
+
559
+ Parameters:
560
+
561
+ * ``attribute`` (string): Key of the information item.
562
+
563
+ Returns:
564
+
565
+ * (string): Value of the information item, if the item exists.
566
+ The empty string, if the item does not exist.
567
+
568
+ See `os-release file`_ for details about these information items.
569
+ """
570
+ return _distro.os_release_attr(attribute)
571
+
572
+
573
+ def lsb_release_attr(attribute: str) -> str:
574
+ """
575
+ Return a single named information item from the lsb_release command output
576
+ data source of the current OS distribution.
577
+
578
+ Parameters:
579
+
580
+ * ``attribute`` (string): Key of the information item.
581
+
582
+ Returns:
583
+
584
+ * (string): Value of the information item, if the item exists.
585
+ The empty string, if the item does not exist.
586
+
587
+ See `lsb_release command output`_ for details about these information
588
+ items.
589
+ """
590
+ return _distro.lsb_release_attr(attribute)
591
+
592
+
593
+ def distro_release_attr(attribute: str) -> str:
594
+ """
595
+ Return a single named information item from the distro release file
596
+ data source of the current OS distribution.
597
+
598
+ Parameters:
599
+
600
+ * ``attribute`` (string): Key of the information item.
601
+
602
+ Returns:
603
+
604
+ * (string): Value of the information item, if the item exists.
605
+ The empty string, if the item does not exist.
606
+
607
+ See `distro release file`_ for details about these information items.
608
+ """
609
+ return _distro.distro_release_attr(attribute)
610
+
611
+
612
+ def uname_attr(attribute: str) -> str:
613
+ """
614
+ Return a single named information item from the distro release file
615
+ data source of the current OS distribution.
616
+
617
+ Parameters:
618
+
619
+ * ``attribute`` (string): Key of the information item.
620
+
621
+ Returns:
622
+
623
+ * (string): Value of the information item, if the item exists.
624
+ The empty string, if the item does not exist.
625
+ """
626
+ return _distro.uname_attr(attribute)
627
+
628
+
629
+ try:
630
+ from functools import cached_property
631
+ except ImportError:
632
+ # Python < 3.8
633
+ class cached_property: # type: ignore
634
+ """A version of @property which caches the value. On access, it calls the
635
+ underlying function and sets the value in `__dict__` so future accesses
636
+ will not re-call the property.
637
+ """
638
+
639
+ def __init__(self, f: Callable[[Any], Any]) -> None:
640
+ self._fname = f.__name__
641
+ self._f = f
642
+
643
+ def __get__(self, obj: Any, owner: Type[Any]) -> Any:
644
+ assert obj is not None, f"call {self._fname} on an instance"
645
+ ret = obj.__dict__[self._fname] = self._f(obj)
646
+ return ret
647
+
648
+
649
+ class LinuxDistribution:
650
+ """
651
+ Provides information about a OS distribution.
652
+
653
+ This package creates a private module-global instance of this class with
654
+ default initialization arguments, that is used by the
655
+ `consolidated accessor functions`_ and `single source accessor functions`_.
656
+ By using default initialization arguments, that module-global instance
657
+ returns data about the current OS distribution (i.e. the distro this
658
+ package runs on).
659
+
660
+ Normally, it is not necessary to create additional instances of this class.
661
+ However, in situations where control is needed over the exact data sources
662
+ that are used, instances of this class can be created with a specific
663
+ distro release file, or a specific os-release file, or without invoking the
664
+ lsb_release command.
665
+ """
666
+
667
+ def __init__(
668
+ self,
669
+ include_lsb: Optional[bool] = None,
670
+ os_release_file: str = "",
671
+ distro_release_file: str = "",
672
+ include_uname: Optional[bool] = None,
673
+ root_dir: Optional[str] = None,
674
+ include_oslevel: Optional[bool] = None,
675
+ ) -> None:
676
+ """
677
+ The initialization method of this class gathers information from the
678
+ available data sources, and stores that in private instance attributes.
679
+ Subsequent access to the information items uses these private instance
680
+ attributes, so that the data sources are read only once.
681
+
682
+ Parameters:
683
+
684
+ * ``include_lsb`` (bool): Controls whether the
685
+ `lsb_release command output`_ is included as a data source.
686
+
687
+ If the lsb_release command is not available in the program execution
688
+ path, the data source for the lsb_release command will be empty.
689
+
690
+ * ``os_release_file`` (string): The path name of the
691
+ `os-release file`_ that is to be used as a data source.
692
+
693
+ An empty string (the default) will cause the default path name to
694
+ be used (see `os-release file`_ for details).
695
+
696
+ If the specified or defaulted os-release file does not exist, the
697
+ data source for the os-release file will be empty.
698
+
699
+ * ``distro_release_file`` (string): The path name of the
700
+ `distro release file`_ that is to be used as a data source.
701
+
702
+ An empty string (the default) will cause a default search algorithm
703
+ to be used (see `distro release file`_ for details).
704
+
705
+ If the specified distro release file does not exist, or if no default
706
+ distro release file can be found, the data source for the distro
707
+ release file will be empty.
708
+
709
+ * ``include_uname`` (bool): Controls whether uname command output is
710
+ included as a data source. If the uname command is not available in
711
+ the program execution path the data source for the uname command will
712
+ be empty.
713
+
714
+ * ``root_dir`` (string): The absolute path to the root directory to use
715
+ to find distro-related information files. Note that ``include_*``
716
+ parameters must not be enabled in combination with ``root_dir``.
717
+
718
+ * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command
719
+ output is included as a data source. If the oslevel command is not
720
+ available in the program execution path the data source will be
721
+ empty.
722
+
723
+ Public instance attributes:
724
+
725
+ * ``os_release_file`` (string): The path name of the
726
+ `os-release file`_ that is actually used as a data source. The
727
+ empty string if no distro release file is used as a data source.
728
+
729
+ * ``distro_release_file`` (string): The path name of the
730
+ `distro release file`_ that is actually used as a data source. The
731
+ empty string if no distro release file is used as a data source.
732
+
733
+ * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.
734
+ This controls whether the lsb information will be loaded.
735
+
736
+ * ``include_uname`` (bool): The result of the ``include_uname``
737
+ parameter. This controls whether the uname information will
738
+ be loaded.
739
+
740
+ * ``include_oslevel`` (bool): The result of the ``include_oslevel``
741
+ parameter. This controls whether (AIX) oslevel information will be
742
+ loaded.
743
+
744
+ * ``root_dir`` (string): The result of the ``root_dir`` parameter.
745
+ The absolute path to the root directory to use to find distro-related
746
+ information files.
747
+
748
+ Raises:
749
+
750
+ * :py:exc:`ValueError`: Initialization parameters combination is not
751
+ supported.
752
+
753
+ * :py:exc:`OSError`: Some I/O issue with an os-release file or distro
754
+ release file.
755
+
756
+ * :py:exc:`UnicodeError`: A data source has unexpected characters or
757
+ uses an unexpected encoding.
758
+ """
759
+ self.root_dir = root_dir
760
+ self.etc_dir = os.path.join(root_dir, "etc") if root_dir else _UNIXCONFDIR
761
+ self.usr_lib_dir = (
762
+ os.path.join(root_dir, "usr/lib") if root_dir else _UNIXUSRLIBDIR
763
+ )
764
+
765
+ if os_release_file:
766
+ self.os_release_file = os_release_file
767
+ else:
768
+ etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)
769
+ usr_lib_os_release_file = os.path.join(
770
+ self.usr_lib_dir, _OS_RELEASE_BASENAME
771
+ )
772
+
773
+ # NOTE: The idea is to respect order **and** have it set
774
+ # at all times for API backwards compatibility.
775
+ if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(
776
+ usr_lib_os_release_file
777
+ ):
778
+ self.os_release_file = etc_dir_os_release_file
779
+ else:
780
+ self.os_release_file = usr_lib_os_release_file
781
+
782
+ self.distro_release_file = distro_release_file or "" # updated later
783
+
784
+ is_root_dir_defined = root_dir is not None
785
+ if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):
786
+ raise ValueError(
787
+ "Including subprocess data sources from specific root_dir is disallowed"
788
+ " to prevent false information"
789
+ )
790
+ self.include_lsb = (
791
+ include_lsb if include_lsb is not None else not is_root_dir_defined
792
+ )
793
+ self.include_uname = (
794
+ include_uname if include_uname is not None else not is_root_dir_defined
795
+ )
796
+ self.include_oslevel = (
797
+ include_oslevel if include_oslevel is not None else not is_root_dir_defined
798
+ )
799
+
800
+ def __repr__(self) -> str:
801
+ """Return repr of all info"""
802
+ return (
803
+ "LinuxDistribution("
804
+ "os_release_file={self.os_release_file!r}, "
805
+ "distro_release_file={self.distro_release_file!r}, "
806
+ "include_lsb={self.include_lsb!r}, "
807
+ "include_uname={self.include_uname!r}, "
808
+ "include_oslevel={self.include_oslevel!r}, "
809
+ "root_dir={self.root_dir!r}, "
810
+ "_os_release_info={self._os_release_info!r}, "
811
+ "_lsb_release_info={self._lsb_release_info!r}, "
812
+ "_distro_release_info={self._distro_release_info!r}, "
813
+ "_uname_info={self._uname_info!r}, "
814
+ "_oslevel_info={self._oslevel_info!r})".format(self=self)
815
+ )
816
+
817
+ def linux_distribution(
818
+ self, full_distribution_name: bool = True
819
+ ) -> Tuple[str, str, str]:
820
+ """
821
+ Return information about the OS distribution that is compatible
822
+ with Python's :func:`platform.linux_distribution`, supporting a subset
823
+ of its parameters.
824
+
825
+ For details, see :func:`distro.linux_distribution`.
826
+ """
827
+ return (
828
+ self.name() if full_distribution_name else self.id(),
829
+ self.version(),
830
+ self._os_release_info.get("release_codename") or self.codename(),
831
+ )
832
+
833
+ def id(self) -> str:
834
+ """Return the distro ID of the OS distribution, as a string.
835
+
836
+ For details, see :func:`distro.id`.
837
+ """
838
+
839
+ def normalize(distro_id: str, table: Dict[str, str]) -> str:
840
+ distro_id = distro_id.lower().replace(" ", "_")
841
+ return table.get(distro_id, distro_id)
842
+
843
+ distro_id = self.os_release_attr("id")
844
+ if distro_id:
845
+ return normalize(distro_id, NORMALIZED_OS_ID)
846
+
847
+ distro_id = self.lsb_release_attr("distributor_id")
848
+ if distro_id:
849
+ return normalize(distro_id, NORMALIZED_LSB_ID)
850
+
851
+ distro_id = self.distro_release_attr("id")
852
+ if distro_id:
853
+ return normalize(distro_id, NORMALIZED_DISTRO_ID)
854
+
855
+ distro_id = self.uname_attr("id")
856
+ if distro_id:
857
+ return normalize(distro_id, NORMALIZED_DISTRO_ID)
858
+
859
+ return ""
860
+
861
+ def name(self, pretty: bool = False) -> str:
862
+ """
863
+ Return the name of the OS distribution, as a string.
864
+
865
+ For details, see :func:`distro.name`.
866
+ """
867
+ name = (
868
+ self.os_release_attr("name")
869
+ or self.lsb_release_attr("distributor_id")
870
+ or self.distro_release_attr("name")
871
+ or self.uname_attr("name")
872
+ )
873
+ if pretty:
874
+ name = self.os_release_attr("pretty_name") or self.lsb_release_attr(
875
+ "description"
876
+ )
877
+ if not name:
878
+ name = self.distro_release_attr("name") or self.uname_attr("name")
879
+ version = self.version(pretty=True)
880
+ if version:
881
+ name = f"{name} {version}"
882
+ return name or ""
883
+
884
+ def version(self, pretty: bool = False, best: bool = False) -> str:
885
+ """
886
+ Return the version of the OS distribution, as a string.
887
+
888
+ For details, see :func:`distro.version`.
889
+ """
890
+ versions = [
891
+ self.os_release_attr("version_id"),
892
+ self.lsb_release_attr("release"),
893
+ self.distro_release_attr("version_id"),
894
+ self._parse_distro_release_content(self.os_release_attr("pretty_name")).get(
895
+ "version_id", ""
896
+ ),
897
+ self._parse_distro_release_content(
898
+ self.lsb_release_attr("description")
899
+ ).get("version_id", ""),
900
+ self.uname_attr("release"),
901
+ ]
902
+ if self.uname_attr("id").startswith("aix"):
903
+ # On AIX platforms, prefer oslevel command output.
904
+ versions.insert(0, self.oslevel_info())
905
+ elif self.id() == "debian" or "debian" in self.like().split():
906
+ # On Debian-like, add debian_version file content to candidates list.
907
+ versions.append(self._debian_version)
908
+ version = ""
909
+ if best:
910
+ # This algorithm uses the last version in priority order that has
911
+ # the best precision. If the versions are not in conflict, that
912
+ # does not matter; otherwise, using the last one instead of the
913
+ # first one might be considered a surprise.
914
+ for v in versions:
915
+ if v.count(".") > version.count(".") or version == "":
916
+ version = v
917
+ else:
918
+ for v in versions:
919
+ if v != "":
920
+ version = v
921
+ break
922
+ if pretty and version and self.codename():
923
+ version = f"{version} ({self.codename()})"
924
+ return version
925
+
926
+ def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
927
+ """
928
+ Return the version of the OS distribution, as a tuple of version
929
+ numbers.
930
+
931
+ For details, see :func:`distro.version_parts`.
932
+ """
933
+ version_str = self.version(best=best)
934
+ if version_str:
935
+ version_regex = re.compile(r"(\d+)\.?(\d+)?\.?(\d+)?")
936
+ matches = version_regex.match(version_str)
937
+ if matches:
938
+ major, minor, build_number = matches.groups()
939
+ return major, minor or "", build_number or ""
940
+ return "", "", ""
941
+
942
+ def major_version(self, best: bool = False) -> str:
943
+ """
944
+ Return the major version number of the current distribution.
945
+
946
+ For details, see :func:`distro.major_version`.
947
+ """
948
+ return self.version_parts(best)[0]
949
+
950
+ def minor_version(self, best: bool = False) -> str:
951
+ """
952
+ Return the minor version number of the current distribution.
953
+
954
+ For details, see :func:`distro.minor_version`.
955
+ """
956
+ return self.version_parts(best)[1]
957
+
958
+ def build_number(self, best: bool = False) -> str:
959
+ """
960
+ Return the build number of the current distribution.
961
+
962
+ For details, see :func:`distro.build_number`.
963
+ """
964
+ return self.version_parts(best)[2]
965
+
966
+ def like(self) -> str:
967
+ """
968
+ Return the IDs of distributions that are like the OS distribution.
969
+
970
+ For details, see :func:`distro.like`.
971
+ """
972
+ return self.os_release_attr("id_like") or ""
973
+
974
+ def codename(self) -> str:
975
+ """
976
+ Return the codename of the OS distribution.
977
+
978
+ For details, see :func:`distro.codename`.
979
+ """
980
+ try:
981
+ # Handle os_release specially since distros might purposefully set
982
+ # this to empty string to have no codename
983
+ return self._os_release_info["codename"]
984
+ except KeyError:
985
+ return (
986
+ self.lsb_release_attr("codename")
987
+ or self.distro_release_attr("codename")
988
+ or ""
989
+ )
990
+
991
+ def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
992
+ """
993
+ Return certain machine-readable information about the OS
994
+ distribution.
995
+
996
+ For details, see :func:`distro.info`.
997
+ """
998
+ return InfoDict(
999
+ id=self.id(),
1000
+ version=self.version(pretty, best),
1001
+ version_parts=VersionDict(
1002
+ major=self.major_version(best),
1003
+ minor=self.minor_version(best),
1004
+ build_number=self.build_number(best),
1005
+ ),
1006
+ like=self.like(),
1007
+ codename=self.codename(),
1008
+ )
1009
+
1010
+ def os_release_info(self) -> Dict[str, str]:
1011
+ """
1012
+ Return a dictionary containing key-value pairs for the information
1013
+ items from the os-release file data source of the OS distribution.
1014
+
1015
+ For details, see :func:`distro.os_release_info`.
1016
+ """
1017
+ return self._os_release_info
1018
+
1019
+ def lsb_release_info(self) -> Dict[str, str]:
1020
+ """
1021
+ Return a dictionary containing key-value pairs for the information
1022
+ items from the lsb_release command data source of the OS
1023
+ distribution.
1024
+
1025
+ For details, see :func:`distro.lsb_release_info`.
1026
+ """
1027
+ return self._lsb_release_info
1028
+
1029
+ def distro_release_info(self) -> Dict[str, str]:
1030
+ """
1031
+ Return a dictionary containing key-value pairs for the information
1032
+ items from the distro release file data source of the OS
1033
+ distribution.
1034
+
1035
+ For details, see :func:`distro.distro_release_info`.
1036
+ """
1037
+ return self._distro_release_info
1038
+
1039
+ def uname_info(self) -> Dict[str, str]:
1040
+ """
1041
+ Return a dictionary containing key-value pairs for the information
1042
+ items from the uname command data source of the OS distribution.
1043
+
1044
+ For details, see :func:`distro.uname_info`.
1045
+ """
1046
+ return self._uname_info
1047
+
1048
+ def oslevel_info(self) -> str:
1049
+ """
1050
+ Return AIX' oslevel command output.
1051
+ """
1052
+ return self._oslevel_info
1053
+
1054
+ def os_release_attr(self, attribute: str) -> str:
1055
+ """
1056
+ Return a single named information item from the os-release file data
1057
+ source of the OS distribution.
1058
+
1059
+ For details, see :func:`distro.os_release_attr`.
1060
+ """
1061
+ return self._os_release_info.get(attribute, "")
1062
+
1063
+ def lsb_release_attr(self, attribute: str) -> str:
1064
+ """
1065
+ Return a single named information item from the lsb_release command
1066
+ output data source of the OS distribution.
1067
+
1068
+ For details, see :func:`distro.lsb_release_attr`.
1069
+ """
1070
+ return self._lsb_release_info.get(attribute, "")
1071
+
1072
+ def distro_release_attr(self, attribute: str) -> str:
1073
+ """
1074
+ Return a single named information item from the distro release file
1075
+ data source of the OS distribution.
1076
+
1077
+ For details, see :func:`distro.distro_release_attr`.
1078
+ """
1079
+ return self._distro_release_info.get(attribute, "")
1080
+
1081
+ def uname_attr(self, attribute: str) -> str:
1082
+ """
1083
+ Return a single named information item from the uname command
1084
+ output data source of the OS distribution.
1085
+
1086
+ For details, see :func:`distro.uname_attr`.
1087
+ """
1088
+ return self._uname_info.get(attribute, "")
1089
+
1090
+ @cached_property
1091
+ def _os_release_info(self) -> Dict[str, str]:
1092
+ """
1093
+ Get the information items from the specified os-release file.
1094
+
1095
+ Returns:
1096
+ A dictionary containing all information items.
1097
+ """
1098
+ if os.path.isfile(self.os_release_file):
1099
+ with open(self.os_release_file, encoding="utf-8") as release_file:
1100
+ return self._parse_os_release_content(release_file)
1101
+ return {}
1102
+
1103
+ @staticmethod
1104
+ def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:
1105
+ """
1106
+ Parse the lines of an os-release file.
1107
+
1108
+ Parameters:
1109
+
1110
+ * lines: Iterable through the lines in the os-release file.
1111
+ Each line must be a unicode string or a UTF-8 encoded byte
1112
+ string.
1113
+
1114
+ Returns:
1115
+ A dictionary containing all information items.
1116
+ """
1117
+ props = {}
1118
+ lexer = shlex.shlex(lines, posix=True)
1119
+ lexer.whitespace_split = True
1120
+
1121
+ tokens = list(lexer)
1122
+ for token in tokens:
1123
+ # At this point, all shell-like parsing has been done (i.e.
1124
+ # comments processed, quotes and backslash escape sequences
1125
+ # processed, multi-line values assembled, trailing newlines
1126
+ # stripped, etc.), so the tokens are now either:
1127
+ # * variable assignments: var=value
1128
+ # * commands or their arguments (not allowed in os-release)
1129
+ # Ignore any tokens that are not variable assignments
1130
+ if "=" in token:
1131
+ k, v = token.split("=", 1)
1132
+ props[k.lower()] = v
1133
+
1134
+ if "version" in props:
1135
+ # extract release codename (if any) from version attribute
1136
+ match = re.search(r"\((\D+)\)|,\s*(\D+)", props["version"])
1137
+ if match:
1138
+ release_codename = match.group(1) or match.group(2)
1139
+ props["codename"] = props["release_codename"] = release_codename
1140
+
1141
+ if "version_codename" in props:
1142
+ # os-release added a version_codename field. Use that in
1143
+ # preference to anything else Note that some distros purposefully
1144
+ # do not have code names. They should be setting
1145
+ # version_codename=""
1146
+ props["codename"] = props["version_codename"]
1147
+ elif "ubuntu_codename" in props:
1148
+ # Same as above but a non-standard field name used on older Ubuntus
1149
+ props["codename"] = props["ubuntu_codename"]
1150
+
1151
+ return props
1152
+
1153
+ @cached_property
1154
+ def _lsb_release_info(self) -> Dict[str, str]:
1155
+ """
1156
+ Get the information items from the lsb_release command output.
1157
+
1158
+ Returns:
1159
+ A dictionary containing all information items.
1160
+ """
1161
+ if not self.include_lsb:
1162
+ return {}
1163
+ try:
1164
+ cmd = ("lsb_release", "-a")
1165
+ stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1166
+ # Command not found or lsb_release returned error
1167
+ except (OSError, subprocess.CalledProcessError):
1168
+ return {}
1169
+ content = self._to_str(stdout).splitlines()
1170
+ return self._parse_lsb_release_content(content)
1171
+
1172
+ @staticmethod
1173
+ def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:
1174
+ """
1175
+ Parse the output of the lsb_release command.
1176
+
1177
+ Parameters:
1178
+
1179
+ * lines: Iterable through the lines of the lsb_release output.
1180
+ Each line must be a unicode string or a UTF-8 encoded byte
1181
+ string.
1182
+
1183
+ Returns:
1184
+ A dictionary containing all information items.
1185
+ """
1186
+ props = {}
1187
+ for line in lines:
1188
+ kv = line.strip("\n").split(":", 1)
1189
+ if len(kv) != 2:
1190
+ # Ignore lines without colon.
1191
+ continue
1192
+ k, v = kv
1193
+ props.update({k.replace(" ", "_").lower(): v.strip()})
1194
+ return props
1195
+
1196
+ @cached_property
1197
+ def _uname_info(self) -> Dict[str, str]:
1198
+ if not self.include_uname:
1199
+ return {}
1200
+ try:
1201
+ cmd = ("uname", "-rs")
1202
+ stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
1203
+ except OSError:
1204
+ return {}
1205
+ content = self._to_str(stdout).splitlines()
1206
+ return self._parse_uname_content(content)
1207
+
1208
+ @cached_property
1209
+ def _oslevel_info(self) -> str:
1210
+ if not self.include_oslevel:
1211
+ return ""
1212
+ try:
1213
+ stdout = subprocess.check_output("oslevel", stderr=subprocess.DEVNULL)
1214
+ except (OSError, subprocess.CalledProcessError):
1215
+ return ""
1216
+ return self._to_str(stdout).strip()
1217
+
1218
+ @cached_property
1219
+ def _debian_version(self) -> str:
1220
+ try:
1221
+ with open(
1222
+ os.path.join(self.etc_dir, "debian_version"), encoding="ascii"
1223
+ ) as fp:
1224
+ return fp.readline().rstrip()
1225
+ except FileNotFoundError:
1226
+ return ""
1227
+
1228
+ @staticmethod
1229
+ def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:
1230
+ if not lines:
1231
+ return {}
1232
+ props = {}
1233
+ match = re.search(r"^([^\s]+)\s+([\d\.]+)", lines[0].strip())
1234
+ if match:
1235
+ name, version = match.groups()
1236
+
1237
+ # This is to prevent the Linux kernel version from
1238
+ # appearing as the 'best' version on otherwise
1239
+ # identifiable distributions.
1240
+ if name == "Linux":
1241
+ return {}
1242
+ props["id"] = name.lower()
1243
+ props["name"] = name
1244
+ props["release"] = version
1245
+ return props
1246
+
1247
+ @staticmethod
1248
+ def _to_str(bytestring: bytes) -> str:
1249
+ encoding = sys.getfilesystemencoding()
1250
+ return bytestring.decode(encoding)
1251
+
1252
+ @cached_property
1253
+ def _distro_release_info(self) -> Dict[str, str]:
1254
+ """
1255
+ Get the information items from the specified distro release file.
1256
+
1257
+ Returns:
1258
+ A dictionary containing all information items.
1259
+ """
1260
+ if self.distro_release_file:
1261
+ # If it was specified, we use it and parse what we can, even if
1262
+ # its file name or content does not match the expected pattern.
1263
+ distro_info = self._parse_distro_release_file(self.distro_release_file)
1264
+ basename = os.path.basename(self.distro_release_file)
1265
+ # The file name pattern for user-specified distro release files
1266
+ # is somewhat more tolerant (compared to when searching for the
1267
+ # file), because we want to use what was specified as best as
1268
+ # possible.
1269
+ match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1270
+ else:
1271
+ try:
1272
+ basenames = [
1273
+ basename
1274
+ for basename in os.listdir(self.etc_dir)
1275
+ if basename not in _DISTRO_RELEASE_IGNORE_BASENAMES
1276
+ and os.path.isfile(os.path.join(self.etc_dir, basename))
1277
+ ]
1278
+ # We sort for repeatability in cases where there are multiple
1279
+ # distro specific files; e.g. CentOS, Oracle, Enterprise all
1280
+ # containing `redhat-release` on top of their own.
1281
+ basenames.sort()
1282
+ except OSError:
1283
+ # This may occur when /etc is not readable but we can't be
1284
+ # sure about the *-release files. Check common entries of
1285
+ # /etc for information. If they turn out to not be there the
1286
+ # error is handled in `_parse_distro_release_file()`.
1287
+ basenames = _DISTRO_RELEASE_BASENAMES
1288
+ for basename in basenames:
1289
+ match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)
1290
+ if match is None:
1291
+ continue
1292
+ filepath = os.path.join(self.etc_dir, basename)
1293
+ distro_info = self._parse_distro_release_file(filepath)
1294
+ # The name is always present if the pattern matches.
1295
+ if "name" not in distro_info:
1296
+ continue
1297
+ self.distro_release_file = filepath
1298
+ break
1299
+ else: # the loop didn't "break": no candidate.
1300
+ return {}
1301
+
1302
+ if match is not None:
1303
+ distro_info["id"] = match.group(1)
1304
+
1305
+ # CloudLinux < 7: manually enrich info with proper id.
1306
+ if "cloudlinux" in distro_info.get("name", "").lower():
1307
+ distro_info["id"] = "cloudlinux"
1308
+
1309
+ return distro_info
1310
+
1311
+ def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:
1312
+ """
1313
+ Parse a distro release file.
1314
+
1315
+ Parameters:
1316
+
1317
+ * filepath: Path name of the distro release file.
1318
+
1319
+ Returns:
1320
+ A dictionary containing all information items.
1321
+ """
1322
+ try:
1323
+ with open(filepath, encoding="utf-8") as fp:
1324
+ # Only parse the first line. For instance, on SLES there
1325
+ # are multiple lines. We don't want them...
1326
+ return self._parse_distro_release_content(fp.readline())
1327
+ except OSError:
1328
+ # Ignore not being able to read a specific, seemingly version
1329
+ # related file.
1330
+ # See https://github.com/python-distro/distro/issues/162
1331
+ return {}
1332
+
1333
+ @staticmethod
1334
+ def _parse_distro_release_content(line: str) -> Dict[str, str]:
1335
+ """
1336
+ Parse a line from a distro release file.
1337
+
1338
+ Parameters:
1339
+ * line: Line from the distro release file. Must be a unicode string
1340
+ or a UTF-8 encoded byte string.
1341
+
1342
+ Returns:
1343
+ A dictionary containing all information items.
1344
+ """
1345
+ matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
1346
+ distro_info = {}
1347
+ if matches:
1348
+ # regexp ensures non-None
1349
+ distro_info["name"] = matches.group(3)[::-1]
1350
+ if matches.group(2):
1351
+ distro_info["version_id"] = matches.group(2)[::-1]
1352
+ if matches.group(1):
1353
+ distro_info["codename"] = matches.group(1)[::-1]
1354
+ elif line:
1355
+ distro_info["name"] = line.strip()
1356
+ return distro_info
1357
+
1358
+
1359
+ _distro = LinuxDistribution()
1360
+
1361
+
1362
+ def main() -> None:
1363
+ logger = logging.getLogger(__name__)
1364
+ logger.setLevel(logging.DEBUG)
1365
+ logger.addHandler(logging.StreamHandler(sys.stdout))
1366
+
1367
+ parser = argparse.ArgumentParser(description="OS distro info tool")
1368
+ parser.add_argument(
1369
+ "--json", "-j", help="Output in machine readable format", action="store_true"
1370
+ )
1371
+
1372
+ parser.add_argument(
1373
+ "--root-dir",
1374
+ "-r",
1375
+ type=str,
1376
+ dest="root_dir",
1377
+ help="Path to the root filesystem directory (defaults to /)",
1378
+ )
1379
+
1380
+ args = parser.parse_args()
1381
+
1382
+ if args.root_dir:
1383
+ dist = LinuxDistribution(
1384
+ include_lsb=False,
1385
+ include_uname=False,
1386
+ include_oslevel=False,
1387
+ root_dir=args.root_dir,
1388
+ )
1389
+ else:
1390
+ dist = _distro
1391
+
1392
+ if args.json:
1393
+ logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))
1394
+ else:
1395
+ logger.info("Name: %s", dist.name(pretty=True))
1396
+ distribution_version = dist.version(pretty=True)
1397
+ logger.info("Version: %s", distribution_version)
1398
+ distribution_codename = dist.codename()
1399
+ logger.info("Codename: %s", distribution_codename)
1400
+
1401
+
1402
+ if __name__ == "__main__":
1403
+ main()
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__init__.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-2024 by the Pygments team, see AUTHORS.
25
+ :license: BSD, see LICENSE for details.
26
+ """
27
+ from io import StringIO, BytesIO
28
+
29
+ __version__ = '2.18.0'
30
+ __docformat__ = 'restructuredtext'
31
+
32
+ __all__ = ['lex', 'format', 'highlight']
33
+
34
+
35
+ def lex(code, lexer):
36
+ """
37
+ Lex `code` with the `lexer` (must be a `Lexer` instance)
38
+ and return an iterable of tokens. Currently, this only calls
39
+ `lexer.get_tokens()`.
40
+ """
41
+ try:
42
+ return lexer.get_tokens(code)
43
+ except TypeError:
44
+ # Heuristic to catch a common mistake.
45
+ from pip._vendor.pygments.lexer import RegexLexer
46
+ if isinstance(lexer, type) and issubclass(lexer, RegexLexer):
47
+ raise TypeError('lex() argument must be a lexer instance, '
48
+ 'not a class')
49
+ raise
50
+
51
+
52
+ def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin
53
+ """
54
+ Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``
55
+ (a `Formatter` instance).
56
+
57
+ If ``outfile`` is given and a valid file object (an object with a
58
+ ``write`` method), the result will be written to it, otherwise it
59
+ is returned as a string.
60
+ """
61
+ try:
62
+ if not outfile:
63
+ realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
64
+ formatter.format(tokens, realoutfile)
65
+ return realoutfile.getvalue()
66
+ else:
67
+ formatter.format(tokens, outfile)
68
+ except TypeError:
69
+ # Heuristic to catch a common mistake.
70
+ from pip._vendor.pygments.formatter import Formatter
71
+ if isinstance(formatter, type) and issubclass(formatter, Formatter):
72
+ raise TypeError('format() argument must be a formatter instance, '
73
+ 'not a class')
74
+ raise
75
+
76
+
77
+ def highlight(code, lexer, formatter, outfile=None):
78
+ """
79
+ This is the most high-level highlighting function. It combines `lex` and
80
+ `format` in one function.
81
+ """
82
+ return format(lex(code, lexer), formatter, outfile)
vllm/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-2024 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)
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (566 Bytes). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/cmdline.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/formatter.cpython-310.pyc ADDED
Binary file (4.08 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/modeline.cpython-310.pyc ADDED
Binary file (1.17 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/scanner.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/style.cpython-310.pyc ADDED
Binary file (4.59 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/token.cpython-310.pyc ADDED
Binary file (4.67 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/__pycache__/util.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/cmdline.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.cmdline
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Command line interface.
6
+
7
+ :copyright: Copyright 2006-2024 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, TerminalTrueColorFormatter
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(f"Help on the {cls.name} lexer:")
72
+ print(dedent(cls.__doc__))
73
+ elif what == 'formatter':
74
+ cls = find_formatter_class(name)
75
+ print(f"Help on the {cls.name} formatter:")
76
+ print(dedent(cls.__doc__))
77
+ elif what == 'filter':
78
+ cls = find_filter_class(name)
79
+ print(f"Help on the {name} filter:")
80
+ print(dedent(cls.__doc__))
81
+ return 0
82
+ except (AttributeError, ValueError):
83
+ print(f"{what} not found!", 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(('* {}\n {} {}').format(*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(('* {}\n {} {}').format(*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(f" {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(f" {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(f'Pygments version {__version__}, (c) 2006-2024 by Georg Brandl, Matthäus '
189
+ 'Chajdas and contributors.')
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 os.environ.get('COLORTERM','') in ('truecolor', '24bit'):
449
+ fmter = TerminalTrueColorFormatter(**parsed_opts)
450
+ elif '256' in os.environ.get('TERM', ''):
451
+ fmter = Terminal256Formatter(**parsed_opts)
452
+ else:
453
+ fmter = TerminalFormatter(**parsed_opts)
454
+ outfile = sys.stdout.buffer
455
+
456
+ # determine output encoding if not explicitly selected
457
+ if not outencoding:
458
+ if outfn:
459
+ # output file? use lexer encoding for now (can still be None)
460
+ fmter.encoding = inencoding
461
+ else:
462
+ # else use terminal encoding
463
+ fmter.encoding = terminal_encoding(sys.stdout)
464
+
465
+ # provide coloring under Windows, if possible
466
+ if not outfn and sys.platform in ('win32', 'cygwin') and \
467
+ fmter.name in ('Terminal', 'Terminal256'): # pragma: no cover
468
+ # unfortunately colorama doesn't support binary streams on Py3
469
+ outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding)
470
+ fmter.encoding = None
471
+ try:
472
+ import colorama.initialise
473
+ except ImportError:
474
+ pass
475
+ else:
476
+ outfile = colorama.initialise.wrap_stream(
477
+ outfile, convert=None, strip=None, autoreset=False, wrap=True)
478
+
479
+ # When using the LaTeX formatter and the option `escapeinside` is
480
+ # specified, we need a special lexer which collects escaped text
481
+ # before running the chosen language lexer.
482
+ escapeinside = parsed_opts.get('escapeinside', '')
483
+ if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter):
484
+ left = escapeinside[0]
485
+ right = escapeinside[1]
486
+ lexer = LatexEmbeddedLexer(left, right, lexer)
487
+
488
+ # ... and do it!
489
+ if not argns.s:
490
+ # process whole input as per normal...
491
+ try:
492
+ highlight(code, lexer, fmter, outfile)
493
+ finally:
494
+ if outfn:
495
+ outfile.close()
496
+ return 0
497
+ else:
498
+ # line by line processing of stdin (eg: for 'tail -f')...
499
+ try:
500
+ while 1:
501
+ line = sys.stdin.buffer.readline()
502
+ if not line:
503
+ break
504
+ if not inencoding:
505
+ line = guess_decode_from_terminal(line, sys.stdin)[0]
506
+ highlight(line, lexer, fmter, outfile)
507
+ if hasattr(outfile, 'flush'):
508
+ outfile.flush()
509
+ return 0
510
+ except KeyboardInterrupt: # pragma: no cover
511
+ return 0
512
+ finally:
513
+ if outfn:
514
+ outfile.close()
515
+
516
+
517
+ class HelpFormatter(argparse.HelpFormatter):
518
+ def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
519
+ if width is None:
520
+ try:
521
+ width = shutil.get_terminal_size().columns - 2
522
+ except Exception:
523
+ pass
524
+ argparse.HelpFormatter.__init__(self, prog, indent_increment,
525
+ max_help_position, width)
526
+
527
+
528
+ def main(args=sys.argv):
529
+ """
530
+ Main command line entry point.
531
+ """
532
+ desc = "Highlight an input file and write the result to an output file."
533
+ parser = argparse.ArgumentParser(description=desc, add_help=False,
534
+ formatter_class=HelpFormatter)
535
+
536
+ operation = parser.add_argument_group('Main operation')
537
+ lexersel = operation.add_mutually_exclusive_group()
538
+ lexersel.add_argument(
539
+ '-l', metavar='LEXER',
540
+ help='Specify the lexer to use. (Query names with -L.) If not '
541
+ 'given and -g is not present, the lexer is guessed from the filename.')
542
+ lexersel.add_argument(
543
+ '-g', action='store_true',
544
+ help='Guess the lexer from the file contents, or pass through '
545
+ 'as plain text if nothing can be guessed.')
546
+ operation.add_argument(
547
+ '-F', metavar='FILTER[:options]', action='append',
548
+ help='Add a filter to the token stream. (Query names with -L.) '
549
+ 'Filter options are given after a colon if necessary.')
550
+ operation.add_argument(
551
+ '-f', metavar='FORMATTER',
552
+ help='Specify the formatter to use. (Query names with -L.) '
553
+ 'If not given, the formatter is guessed from the output filename, '
554
+ 'and defaults to the terminal formatter if the output is to the '
555
+ 'terminal or an unknown file extension.')
556
+ operation.add_argument(
557
+ '-O', metavar='OPTION=value[,OPTION=value,...]', action='append',
558
+ help='Give options to the lexer and formatter as a comma-separated '
559
+ 'list of key-value pairs. '
560
+ 'Example: `-O bg=light,python=cool`.')
561
+ operation.add_argument(
562
+ '-P', metavar='OPTION=value', action='append',
563
+ help='Give a single option to the lexer and formatter - with this '
564
+ 'you can pass options whose value contains commas and equal signs. '
565
+ 'Example: `-P "heading=Pygments, the Python highlighter"`.')
566
+ operation.add_argument(
567
+ '-o', metavar='OUTPUTFILE',
568
+ help='Where to write the output. Defaults to standard output.')
569
+
570
+ operation.add_argument(
571
+ 'INPUTFILE', nargs='?',
572
+ help='Where to read the input. Defaults to standard input.')
573
+
574
+ flags = parser.add_argument_group('Operation flags')
575
+ flags.add_argument(
576
+ '-v', action='store_true',
577
+ help='Print a detailed traceback on unhandled exceptions, which '
578
+ 'is useful for debugging and bug reports.')
579
+ flags.add_argument(
580
+ '-s', action='store_true',
581
+ help='Process lines one at a time until EOF, rather than waiting to '
582
+ 'process the entire file. This only works for stdin, only for lexers '
583
+ 'with no line-spanning constructs, and is intended for streaming '
584
+ 'input such as you get from `tail -f`. '
585
+ 'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')
586
+ flags.add_argument(
587
+ '-x', action='store_true',
588
+ help='Allow custom lexers and formatters to be loaded from a .py file '
589
+ 'relative to the current working directory. For example, '
590
+ '`-l ./customlexer.py -x`. By default, this option expects a file '
591
+ 'with a class named CustomLexer or CustomFormatter; you can also '
592
+ 'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '
593
+ 'Users should be very careful not to use this option with untrusted '
594
+ 'files, because it will import and run them.')
595
+ flags.add_argument('--json', help='Output as JSON. This can '
596
+ 'be only used in conjunction with -L.',
597
+ default=False,
598
+ action='store_true')
599
+
600
+ special_modes_group = parser.add_argument_group(
601
+ 'Special modes - do not do any highlighting')
602
+ special_modes = special_modes_group.add_mutually_exclusive_group()
603
+ special_modes.add_argument(
604
+ '-S', metavar='STYLE -f formatter',
605
+ help='Print style definitions for STYLE for a formatter '
606
+ 'given with -f. The argument given by -a is formatter '
607
+ 'dependent.')
608
+ special_modes.add_argument(
609
+ '-L', nargs='*', metavar='WHAT',
610
+ help='List lexers, formatters, styles or filters -- '
611
+ 'give additional arguments for the thing(s) you want to list '
612
+ '(e.g. "styles"), or omit them to list everything.')
613
+ special_modes.add_argument(
614
+ '-N', metavar='FILENAME',
615
+ help='Guess and print out a lexer name based solely on the given '
616
+ 'filename. Does not take input or highlight anything. If no specific '
617
+ 'lexer can be determined, "text" is printed.')
618
+ special_modes.add_argument(
619
+ '-C', action='store_true',
620
+ help='Like -N, but print out a lexer name based solely on '
621
+ 'a given content from standard input.')
622
+ special_modes.add_argument(
623
+ '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),
624
+ help='Print detailed help for the object <name> of type <type>, '
625
+ 'where <type> is one of "lexer", "formatter" or "filter".')
626
+ special_modes.add_argument(
627
+ '-V', action='store_true',
628
+ help='Print the package version.')
629
+ special_modes.add_argument(
630
+ '-h', '--help', action='store_true',
631
+ help='Print this help.')
632
+ special_modes_group.add_argument(
633
+ '-a', metavar='ARG',
634
+ help='Formatter-specific additional argument for the -S (print '
635
+ 'style sheet) mode.')
636
+
637
+ argns = parser.parse_args(args[1:])
638
+
639
+ try:
640
+ return main_inner(parser, argns)
641
+ except BrokenPipeError:
642
+ # someone closed our stdout, e.g. by quitting a pager.
643
+ return 0
644
+ except Exception:
645
+ if argns.v:
646
+ print(file=sys.stderr)
647
+ print('*' * 65, file=sys.stderr)
648
+ print('An unhandled exception occurred while highlighting.',
649
+ file=sys.stderr)
650
+ print('Please report the whole traceback to the issue tracker at',
651
+ file=sys.stderr)
652
+ print('<https://github.com/pygments/pygments/issues>.',
653
+ file=sys.stderr)
654
+ print('*' * 65, file=sys.stderr)
655
+ print(file=sys.stderr)
656
+ raise
657
+ import traceback
658
+ info = traceback.format_exception(*sys.exc_info())
659
+ msg = info[-1].strip()
660
+ if len(info) >= 3:
661
+ # extract relevant file and position info
662
+ msg += '\n (f{})'.format(info[-2].split('\n')[0].strip()[1:])
663
+ print(file=sys.stderr)
664
+ print('*** Error while highlighting:', file=sys.stderr)
665
+ print(msg, file=sys.stderr)
666
+ print('*** If this is a bug you want to report, please rerun with -v.',
667
+ file=sys.stderr)
668
+ return 1
vllm/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-2024 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 dark, light in zip(dark_colors, light_colors):
31
+ codes[dark] = esc + "%im" % x
32
+ codes[light] = esc + "%im" % (60 + x)
33
+ x += 1
34
+
35
+ del dark, light, 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)
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__init__.py ADDED
@@ -0,0 +1,940 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.filters
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Module containing filter lookup functions and default
6
+ filters.
7
+
8
+ :copyright: Copyright 2006-2024 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(f'filter {filtername!r} not found')
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``, ``FIXME``, ``BUG`` and ``NOTE``.
73
+
74
+ .. versionchanged:: 2.13
75
+ Now recognizes ``FIXME`` by default.
76
+ """
77
+
78
+ def __init__(self, **options):
79
+ Filter.__init__(self, **options)
80
+ tags = get_list_opt(options, 'codetags',
81
+ ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])
82
+ self.tag_re = re.compile(r'\b({})\b'.format('|'.join([
83
+ re.escape(tag) for tag in tags if tag
84
+ ])))
85
+
86
+ def filter(self, lexer, stream):
87
+ regex = self.tag_re
88
+ for ttype, value in stream:
89
+ if ttype in String.Doc or \
90
+ ttype in Comment and \
91
+ ttype not in Comment.Preproc:
92
+ yield from _replace_special(ttype, value, regex, Comment.Special)
93
+ else:
94
+ yield ttype, value
95
+
96
+
97
+ class SymbolFilter(Filter):
98
+ """Convert mathematical symbols such as \\<longrightarrow> in Isabelle
99
+ or \\longrightarrow in LaTeX into Unicode characters.
100
+
101
+ This is mostly useful for HTML or console output when you want to
102
+ approximate the source rendering you'd see in an IDE.
103
+
104
+ Options accepted:
105
+
106
+ `lang` : string
107
+ The symbol language. Must be one of ``'isabelle'`` or
108
+ ``'latex'``. The default is ``'isabelle'``.
109
+ """
110
+
111
+ latex_symbols = {
112
+ '\\alpha' : '\U000003b1',
113
+ '\\beta' : '\U000003b2',
114
+ '\\gamma' : '\U000003b3',
115
+ '\\delta' : '\U000003b4',
116
+ '\\varepsilon' : '\U000003b5',
117
+ '\\zeta' : '\U000003b6',
118
+ '\\eta' : '\U000003b7',
119
+ '\\vartheta' : '\U000003b8',
120
+ '\\iota' : '\U000003b9',
121
+ '\\kappa' : '\U000003ba',
122
+ '\\lambda' : '\U000003bb',
123
+ '\\mu' : '\U000003bc',
124
+ '\\nu' : '\U000003bd',
125
+ '\\xi' : '\U000003be',
126
+ '\\pi' : '\U000003c0',
127
+ '\\varrho' : '\U000003c1',
128
+ '\\sigma' : '\U000003c3',
129
+ '\\tau' : '\U000003c4',
130
+ '\\upsilon' : '\U000003c5',
131
+ '\\varphi' : '\U000003c6',
132
+ '\\chi' : '\U000003c7',
133
+ '\\psi' : '\U000003c8',
134
+ '\\omega' : '\U000003c9',
135
+ '\\Gamma' : '\U00000393',
136
+ '\\Delta' : '\U00000394',
137
+ '\\Theta' : '\U00000398',
138
+ '\\Lambda' : '\U0000039b',
139
+ '\\Xi' : '\U0000039e',
140
+ '\\Pi' : '\U000003a0',
141
+ '\\Sigma' : '\U000003a3',
142
+ '\\Upsilon' : '\U000003a5',
143
+ '\\Phi' : '\U000003a6',
144
+ '\\Psi' : '\U000003a8',
145
+ '\\Omega' : '\U000003a9',
146
+ '\\leftarrow' : '\U00002190',
147
+ '\\longleftarrow' : '\U000027f5',
148
+ '\\rightarrow' : '\U00002192',
149
+ '\\longrightarrow' : '\U000027f6',
150
+ '\\Leftarrow' : '\U000021d0',
151
+ '\\Longleftarrow' : '\U000027f8',
152
+ '\\Rightarrow' : '\U000021d2',
153
+ '\\Longrightarrow' : '\U000027f9',
154
+ '\\leftrightarrow' : '\U00002194',
155
+ '\\longleftrightarrow' : '\U000027f7',
156
+ '\\Leftrightarrow' : '\U000021d4',
157
+ '\\Longleftrightarrow' : '\U000027fa',
158
+ '\\mapsto' : '\U000021a6',
159
+ '\\longmapsto' : '\U000027fc',
160
+ '\\relbar' : '\U00002500',
161
+ '\\Relbar' : '\U00002550',
162
+ '\\hookleftarrow' : '\U000021a9',
163
+ '\\hookrightarrow' : '\U000021aa',
164
+ '\\leftharpoondown' : '\U000021bd',
165
+ '\\rightharpoondown' : '\U000021c1',
166
+ '\\leftharpoonup' : '\U000021bc',
167
+ '\\rightharpoonup' : '\U000021c0',
168
+ '\\rightleftharpoons' : '\U000021cc',
169
+ '\\leadsto' : '\U0000219d',
170
+ '\\downharpoonleft' : '\U000021c3',
171
+ '\\downharpoonright' : '\U000021c2',
172
+ '\\upharpoonleft' : '\U000021bf',
173
+ '\\upharpoonright' : '\U000021be',
174
+ '\\restriction' : '\U000021be',
175
+ '\\uparrow' : '\U00002191',
176
+ '\\Uparrow' : '\U000021d1',
177
+ '\\downarrow' : '\U00002193',
178
+ '\\Downarrow' : '\U000021d3',
179
+ '\\updownarrow' : '\U00002195',
180
+ '\\Updownarrow' : '\U000021d5',
181
+ '\\langle' : '\U000027e8',
182
+ '\\rangle' : '\U000027e9',
183
+ '\\lceil' : '\U00002308',
184
+ '\\rceil' : '\U00002309',
185
+ '\\lfloor' : '\U0000230a',
186
+ '\\rfloor' : '\U0000230b',
187
+ '\\flqq' : '\U000000ab',
188
+ '\\frqq' : '\U000000bb',
189
+ '\\bot' : '\U000022a5',
190
+ '\\top' : '\U000022a4',
191
+ '\\wedge' : '\U00002227',
192
+ '\\bigwedge' : '\U000022c0',
193
+ '\\vee' : '\U00002228',
194
+ '\\bigvee' : '\U000022c1',
195
+ '\\forall' : '\U00002200',
196
+ '\\exists' : '\U00002203',
197
+ '\\nexists' : '\U00002204',
198
+ '\\neg' : '\U000000ac',
199
+ '\\Box' : '\U000025a1',
200
+ '\\Diamond' : '\U000025c7',
201
+ '\\vdash' : '\U000022a2',
202
+ '\\models' : '\U000022a8',
203
+ '\\dashv' : '\U000022a3',
204
+ '\\surd' : '\U0000221a',
205
+ '\\le' : '\U00002264',
206
+ '\\ge' : '\U00002265',
207
+ '\\ll' : '\U0000226a',
208
+ '\\gg' : '\U0000226b',
209
+ '\\lesssim' : '\U00002272',
210
+ '\\gtrsim' : '\U00002273',
211
+ '\\lessapprox' : '\U00002a85',
212
+ '\\gtrapprox' : '\U00002a86',
213
+ '\\in' : '\U00002208',
214
+ '\\notin' : '\U00002209',
215
+ '\\subset' : '\U00002282',
216
+ '\\supset' : '\U00002283',
217
+ '\\subseteq' : '\U00002286',
218
+ '\\supseteq' : '\U00002287',
219
+ '\\sqsubset' : '\U0000228f',
220
+ '\\sqsupset' : '\U00002290',
221
+ '\\sqsubseteq' : '\U00002291',
222
+ '\\sqsupseteq' : '\U00002292',
223
+ '\\cap' : '\U00002229',
224
+ '\\bigcap' : '\U000022c2',
225
+ '\\cup' : '\U0000222a',
226
+ '\\bigcup' : '\U000022c3',
227
+ '\\sqcup' : '\U00002294',
228
+ '\\bigsqcup' : '\U00002a06',
229
+ '\\sqcap' : '\U00002293',
230
+ '\\Bigsqcap' : '\U00002a05',
231
+ '\\setminus' : '\U00002216',
232
+ '\\propto' : '\U0000221d',
233
+ '\\uplus' : '\U0000228e',
234
+ '\\bigplus' : '\U00002a04',
235
+ '\\sim' : '\U0000223c',
236
+ '\\doteq' : '\U00002250',
237
+ '\\simeq' : '\U00002243',
238
+ '\\approx' : '\U00002248',
239
+ '\\asymp' : '\U0000224d',
240
+ '\\cong' : '\U00002245',
241
+ '\\equiv' : '\U00002261',
242
+ '\\Join' : '\U000022c8',
243
+ '\\bowtie' : '\U00002a1d',
244
+ '\\prec' : '\U0000227a',
245
+ '\\succ' : '\U0000227b',
246
+ '\\preceq' : '\U0000227c',
247
+ '\\succeq' : '\U0000227d',
248
+ '\\parallel' : '\U00002225',
249
+ '\\mid' : '\U000000a6',
250
+ '\\pm' : '\U000000b1',
251
+ '\\mp' : '\U00002213',
252
+ '\\times' : '\U000000d7',
253
+ '\\div' : '\U000000f7',
254
+ '\\cdot' : '\U000022c5',
255
+ '\\star' : '\U000022c6',
256
+ '\\circ' : '\U00002218',
257
+ '\\dagger' : '\U00002020',
258
+ '\\ddagger' : '\U00002021',
259
+ '\\lhd' : '\U000022b2',
260
+ '\\rhd' : '\U000022b3',
261
+ '\\unlhd' : '\U000022b4',
262
+ '\\unrhd' : '\U000022b5',
263
+ '\\triangleleft' : '\U000025c3',
264
+ '\\triangleright' : '\U000025b9',
265
+ '\\triangle' : '\U000025b3',
266
+ '\\triangleq' : '\U0000225c',
267
+ '\\oplus' : '\U00002295',
268
+ '\\bigoplus' : '\U00002a01',
269
+ '\\otimes' : '\U00002297',
270
+ '\\bigotimes' : '\U00002a02',
271
+ '\\odot' : '\U00002299',
272
+ '\\bigodot' : '\U00002a00',
273
+ '\\ominus' : '\U00002296',
274
+ '\\oslash' : '\U00002298',
275
+ '\\dots' : '\U00002026',
276
+ '\\cdots' : '\U000022ef',
277
+ '\\sum' : '\U00002211',
278
+ '\\prod' : '\U0000220f',
279
+ '\\coprod' : '\U00002210',
280
+ '\\infty' : '\U0000221e',
281
+ '\\int' : '\U0000222b',
282
+ '\\oint' : '\U0000222e',
283
+ '\\clubsuit' : '\U00002663',
284
+ '\\diamondsuit' : '\U00002662',
285
+ '\\heartsuit' : '\U00002661',
286
+ '\\spadesuit' : '\U00002660',
287
+ '\\aleph' : '\U00002135',
288
+ '\\emptyset' : '\U00002205',
289
+ '\\nabla' : '\U00002207',
290
+ '\\partial' : '\U00002202',
291
+ '\\flat' : '\U0000266d',
292
+ '\\natural' : '\U0000266e',
293
+ '\\sharp' : '\U0000266f',
294
+ '\\angle' : '\U00002220',
295
+ '\\copyright' : '\U000000a9',
296
+ '\\textregistered' : '\U000000ae',
297
+ '\\textonequarter' : '\U000000bc',
298
+ '\\textonehalf' : '\U000000bd',
299
+ '\\textthreequarters' : '\U000000be',
300
+ '\\textordfeminine' : '\U000000aa',
301
+ '\\textordmasculine' : '\U000000ba',
302
+ '\\euro' : '\U000020ac',
303
+ '\\pounds' : '\U000000a3',
304
+ '\\yen' : '\U000000a5',
305
+ '\\textcent' : '\U000000a2',
306
+ '\\textcurrency' : '\U000000a4',
307
+ '\\textdegree' : '\U000000b0',
308
+ }
309
+
310
+ isabelle_symbols = {
311
+ '\\<zero>' : '\U0001d7ec',
312
+ '\\<one>' : '\U0001d7ed',
313
+ '\\<two>' : '\U0001d7ee',
314
+ '\\<three>' : '\U0001d7ef',
315
+ '\\<four>' : '\U0001d7f0',
316
+ '\\<five>' : '\U0001d7f1',
317
+ '\\<six>' : '\U0001d7f2',
318
+ '\\<seven>' : '\U0001d7f3',
319
+ '\\<eight>' : '\U0001d7f4',
320
+ '\\<nine>' : '\U0001d7f5',
321
+ '\\<A>' : '\U0001d49c',
322
+ '\\<B>' : '\U0000212c',
323
+ '\\<C>' : '\U0001d49e',
324
+ '\\<D>' : '\U0001d49f',
325
+ '\\<E>' : '\U00002130',
326
+ '\\<F>' : '\U00002131',
327
+ '\\<G>' : '\U0001d4a2',
328
+ '\\<H>' : '\U0000210b',
329
+ '\\<I>' : '\U00002110',
330
+ '\\<J>' : '\U0001d4a5',
331
+ '\\<K>' : '\U0001d4a6',
332
+ '\\<L>' : '\U00002112',
333
+ '\\<M>' : '\U00002133',
334
+ '\\<N>' : '\U0001d4a9',
335
+ '\\<O>' : '\U0001d4aa',
336
+ '\\<P>' : '\U0001d4ab',
337
+ '\\<Q>' : '\U0001d4ac',
338
+ '\\<R>' : '\U0000211b',
339
+ '\\<S>' : '\U0001d4ae',
340
+ '\\<T>' : '\U0001d4af',
341
+ '\\<U>' : '\U0001d4b0',
342
+ '\\<V>' : '\U0001d4b1',
343
+ '\\<W>' : '\U0001d4b2',
344
+ '\\<X>' : '\U0001d4b3',
345
+ '\\<Y>' : '\U0001d4b4',
346
+ '\\<Z>' : '\U0001d4b5',
347
+ '\\<a>' : '\U0001d5ba',
348
+ '\\<b>' : '\U0001d5bb',
349
+ '\\<c>' : '\U0001d5bc',
350
+ '\\<d>' : '\U0001d5bd',
351
+ '\\<e>' : '\U0001d5be',
352
+ '\\<f>' : '\U0001d5bf',
353
+ '\\<g>' : '\U0001d5c0',
354
+ '\\<h>' : '\U0001d5c1',
355
+ '\\<i>' : '\U0001d5c2',
356
+ '\\<j>' : '\U0001d5c3',
357
+ '\\<k>' : '\U0001d5c4',
358
+ '\\<l>' : '\U0001d5c5',
359
+ '\\<m>' : '\U0001d5c6',
360
+ '\\<n>' : '\U0001d5c7',
361
+ '\\<o>' : '\U0001d5c8',
362
+ '\\<p>' : '\U0001d5c9',
363
+ '\\<q>' : '\U0001d5ca',
364
+ '\\<r>' : '\U0001d5cb',
365
+ '\\<s>' : '\U0001d5cc',
366
+ '\\<t>' : '\U0001d5cd',
367
+ '\\<u>' : '\U0001d5ce',
368
+ '\\<v>' : '\U0001d5cf',
369
+ '\\<w>' : '\U0001d5d0',
370
+ '\\<x>' : '\U0001d5d1',
371
+ '\\<y>' : '\U0001d5d2',
372
+ '\\<z>' : '\U0001d5d3',
373
+ '\\<AA>' : '\U0001d504',
374
+ '\\<BB>' : '\U0001d505',
375
+ '\\<CC>' : '\U0000212d',
376
+ '\\<DD>' : '\U0001d507',
377
+ '\\<EE>' : '\U0001d508',
378
+ '\\<FF>' : '\U0001d509',
379
+ '\\<GG>' : '\U0001d50a',
380
+ '\\<HH>' : '\U0000210c',
381
+ '\\<II>' : '\U00002111',
382
+ '\\<JJ>' : '\U0001d50d',
383
+ '\\<KK>' : '\U0001d50e',
384
+ '\\<LL>' : '\U0001d50f',
385
+ '\\<MM>' : '\U0001d510',
386
+ '\\<NN>' : '\U0001d511',
387
+ '\\<OO>' : '\U0001d512',
388
+ '\\<PP>' : '\U0001d513',
389
+ '\\<QQ>' : '\U0001d514',
390
+ '\\<RR>' : '\U0000211c',
391
+ '\\<SS>' : '\U0001d516',
392
+ '\\<TT>' : '\U0001d517',
393
+ '\\<UU>' : '\U0001d518',
394
+ '\\<VV>' : '\U0001d519',
395
+ '\\<WW>' : '\U0001d51a',
396
+ '\\<XX>' : '\U0001d51b',
397
+ '\\<YY>' : '\U0001d51c',
398
+ '\\<ZZ>' : '\U00002128',
399
+ '\\<aa>' : '\U0001d51e',
400
+ '\\<bb>' : '\U0001d51f',
401
+ '\\<cc>' : '\U0001d520',
402
+ '\\<dd>' : '\U0001d521',
403
+ '\\<ee>' : '\U0001d522',
404
+ '\\<ff>' : '\U0001d523',
405
+ '\\<gg>' : '\U0001d524',
406
+ '\\<hh>' : '\U0001d525',
407
+ '\\<ii>' : '\U0001d526',
408
+ '\\<jj>' : '\U0001d527',
409
+ '\\<kk>' : '\U0001d528',
410
+ '\\<ll>' : '\U0001d529',
411
+ '\\<mm>' : '\U0001d52a',
412
+ '\\<nn>' : '\U0001d52b',
413
+ '\\<oo>' : '\U0001d52c',
414
+ '\\<pp>' : '\U0001d52d',
415
+ '\\<qq>' : '\U0001d52e',
416
+ '\\<rr>' : '\U0001d52f',
417
+ '\\<ss>' : '\U0001d530',
418
+ '\\<tt>' : '\U0001d531',
419
+ '\\<uu>' : '\U0001d532',
420
+ '\\<vv>' : '\U0001d533',
421
+ '\\<ww>' : '\U0001d534',
422
+ '\\<xx>' : '\U0001d535',
423
+ '\\<yy>' : '\U0001d536',
424
+ '\\<zz>' : '\U0001d537',
425
+ '\\<alpha>' : '\U000003b1',
426
+ '\\<beta>' : '\U000003b2',
427
+ '\\<gamma>' : '\U000003b3',
428
+ '\\<delta>' : '\U000003b4',
429
+ '\\<epsilon>' : '\U000003b5',
430
+ '\\<zeta>' : '\U000003b6',
431
+ '\\<eta>' : '\U000003b7',
432
+ '\\<theta>' : '\U000003b8',
433
+ '\\<iota>' : '\U000003b9',
434
+ '\\<kappa>' : '\U000003ba',
435
+ '\\<lambda>' : '\U000003bb',
436
+ '\\<mu>' : '\U000003bc',
437
+ '\\<nu>' : '\U000003bd',
438
+ '\\<xi>' : '\U000003be',
439
+ '\\<pi>' : '\U000003c0',
440
+ '\\<rho>' : '\U000003c1',
441
+ '\\<sigma>' : '\U000003c3',
442
+ '\\<tau>' : '\U000003c4',
443
+ '\\<upsilon>' : '\U000003c5',
444
+ '\\<phi>' : '\U000003c6',
445
+ '\\<chi>' : '\U000003c7',
446
+ '\\<psi>' : '\U000003c8',
447
+ '\\<omega>' : '\U000003c9',
448
+ '\\<Gamma>' : '\U00000393',
449
+ '\\<Delta>' : '\U00000394',
450
+ '\\<Theta>' : '\U00000398',
451
+ '\\<Lambda>' : '\U0000039b',
452
+ '\\<Xi>' : '\U0000039e',
453
+ '\\<Pi>' : '\U000003a0',
454
+ '\\<Sigma>' : '\U000003a3',
455
+ '\\<Upsilon>' : '\U000003a5',
456
+ '\\<Phi>' : '\U000003a6',
457
+ '\\<Psi>' : '\U000003a8',
458
+ '\\<Omega>' : '\U000003a9',
459
+ '\\<bool>' : '\U0001d539',
460
+ '\\<complex>' : '\U00002102',
461
+ '\\<nat>' : '\U00002115',
462
+ '\\<rat>' : '\U0000211a',
463
+ '\\<real>' : '\U0000211d',
464
+ '\\<int>' : '\U00002124',
465
+ '\\<leftarrow>' : '\U00002190',
466
+ '\\<longleftarrow>' : '\U000027f5',
467
+ '\\<rightarrow>' : '\U00002192',
468
+ '\\<longrightarrow>' : '\U000027f6',
469
+ '\\<Leftarrow>' : '\U000021d0',
470
+ '\\<Longleftarrow>' : '\U000027f8',
471
+ '\\<Rightarrow>' : '\U000021d2',
472
+ '\\<Longrightarrow>' : '\U000027f9',
473
+ '\\<leftrightarrow>' : '\U00002194',
474
+ '\\<longleftrightarrow>' : '\U000027f7',
475
+ '\\<Leftrightarrow>' : '\U000021d4',
476
+ '\\<Longleftrightarrow>' : '\U000027fa',
477
+ '\\<mapsto>' : '\U000021a6',
478
+ '\\<longmapsto>' : '\U000027fc',
479
+ '\\<midarrow>' : '\U00002500',
480
+ '\\<Midarrow>' : '\U00002550',
481
+ '\\<hookleftarrow>' : '\U000021a9',
482
+ '\\<hookrightarrow>' : '\U000021aa',
483
+ '\\<leftharpoondown>' : '\U000021bd',
484
+ '\\<rightharpoondown>' : '\U000021c1',
485
+ '\\<leftharpoonup>' : '\U000021bc',
486
+ '\\<rightharpoonup>' : '\U000021c0',
487
+ '\\<rightleftharpoons>' : '\U000021cc',
488
+ '\\<leadsto>' : '\U0000219d',
489
+ '\\<downharpoonleft>' : '\U000021c3',
490
+ '\\<downharpoonright>' : '\U000021c2',
491
+ '\\<upharpoonleft>' : '\U000021bf',
492
+ '\\<upharpoonright>' : '\U000021be',
493
+ '\\<restriction>' : '\U000021be',
494
+ '\\<Colon>' : '\U00002237',
495
+ '\\<up>' : '\U00002191',
496
+ '\\<Up>' : '\U000021d1',
497
+ '\\<down>' : '\U00002193',
498
+ '\\<Down>' : '\U000021d3',
499
+ '\\<updown>' : '\U00002195',
500
+ '\\<Updown>' : '\U000021d5',
501
+ '\\<langle>' : '\U000027e8',
502
+ '\\<rangle>' : '\U000027e9',
503
+ '\\<lceil>' : '\U00002308',
504
+ '\\<rceil>' : '\U00002309',
505
+ '\\<lfloor>' : '\U0000230a',
506
+ '\\<rfloor>' : '\U0000230b',
507
+ '\\<lparr>' : '\U00002987',
508
+ '\\<rparr>' : '\U00002988',
509
+ '\\<lbrakk>' : '\U000027e6',
510
+ '\\<rbrakk>' : '\U000027e7',
511
+ '\\<lbrace>' : '\U00002983',
512
+ '\\<rbrace>' : '\U00002984',
513
+ '\\<guillemotleft>' : '\U000000ab',
514
+ '\\<guillemotright>' : '\U000000bb',
515
+ '\\<bottom>' : '\U000022a5',
516
+ '\\<top>' : '\U000022a4',
517
+ '\\<and>' : '\U00002227',
518
+ '\\<And>' : '\U000022c0',
519
+ '\\<or>' : '\U00002228',
520
+ '\\<Or>' : '\U000022c1',
521
+ '\\<forall>' : '\U00002200',
522
+ '\\<exists>' : '\U00002203',
523
+ '\\<nexists>' : '\U00002204',
524
+ '\\<not>' : '\U000000ac',
525
+ '\\<box>' : '\U000025a1',
526
+ '\\<diamond>' : '\U000025c7',
527
+ '\\<turnstile>' : '\U000022a2',
528
+ '\\<Turnstile>' : '\U000022a8',
529
+ '\\<tturnstile>' : '\U000022a9',
530
+ '\\<TTurnstile>' : '\U000022ab',
531
+ '\\<stileturn>' : '\U000022a3',
532
+ '\\<surd>' : '\U0000221a',
533
+ '\\<le>' : '\U00002264',
534
+ '\\<ge>' : '\U00002265',
535
+ '\\<lless>' : '\U0000226a',
536
+ '\\<ggreater>' : '\U0000226b',
537
+ '\\<lesssim>' : '\U00002272',
538
+ '\\<greatersim>' : '\U00002273',
539
+ '\\<lessapprox>' : '\U00002a85',
540
+ '\\<greaterapprox>' : '\U00002a86',
541
+ '\\<in>' : '\U00002208',
542
+ '\\<notin>' : '\U00002209',
543
+ '\\<subset>' : '\U00002282',
544
+ '\\<supset>' : '\U00002283',
545
+ '\\<subseteq>' : '\U00002286',
546
+ '\\<supseteq>' : '\U00002287',
547
+ '\\<sqsubset>' : '\U0000228f',
548
+ '\\<sqsupset>' : '\U00002290',
549
+ '\\<sqsubseteq>' : '\U00002291',
550
+ '\\<sqsupseteq>' : '\U00002292',
551
+ '\\<inter>' : '\U00002229',
552
+ '\\<Inter>' : '\U000022c2',
553
+ '\\<union>' : '\U0000222a',
554
+ '\\<Union>' : '\U000022c3',
555
+ '\\<squnion>' : '\U00002294',
556
+ '\\<Squnion>' : '\U00002a06',
557
+ '\\<sqinter>' : '\U00002293',
558
+ '\\<Sqinter>' : '\U00002a05',
559
+ '\\<setminus>' : '\U00002216',
560
+ '\\<propto>' : '\U0000221d',
561
+ '\\<uplus>' : '\U0000228e',
562
+ '\\<Uplus>' : '\U00002a04',
563
+ '\\<noteq>' : '\U00002260',
564
+ '\\<sim>' : '\U0000223c',
565
+ '\\<doteq>' : '\U00002250',
566
+ '\\<simeq>' : '\U00002243',
567
+ '\\<approx>' : '\U00002248',
568
+ '\\<asymp>' : '\U0000224d',
569
+ '\\<cong>' : '\U00002245',
570
+ '\\<smile>' : '\U00002323',
571
+ '\\<equiv>' : '\U00002261',
572
+ '\\<frown>' : '\U00002322',
573
+ '\\<Join>' : '\U000022c8',
574
+ '\\<bowtie>' : '\U00002a1d',
575
+ '\\<prec>' : '\U0000227a',
576
+ '\\<succ>' : '\U0000227b',
577
+ '\\<preceq>' : '\U0000227c',
578
+ '\\<succeq>' : '\U0000227d',
579
+ '\\<parallel>' : '\U00002225',
580
+ '\\<bar>' : '\U000000a6',
581
+ '\\<plusminus>' : '\U000000b1',
582
+ '\\<minusplus>' : '\U00002213',
583
+ '\\<times>' : '\U000000d7',
584
+ '\\<div>' : '\U000000f7',
585
+ '\\<cdot>' : '\U000022c5',
586
+ '\\<star>' : '\U000022c6',
587
+ '\\<bullet>' : '\U00002219',
588
+ '\\<circ>' : '\U00002218',
589
+ '\\<dagger>' : '\U00002020',
590
+ '\\<ddagger>' : '\U00002021',
591
+ '\\<lhd>' : '\U000022b2',
592
+ '\\<rhd>' : '\U000022b3',
593
+ '\\<unlhd>' : '\U000022b4',
594
+ '\\<unrhd>' : '\U000022b5',
595
+ '\\<triangleleft>' : '\U000025c3',
596
+ '\\<triangleright>' : '\U000025b9',
597
+ '\\<triangle>' : '\U000025b3',
598
+ '\\<triangleq>' : '\U0000225c',
599
+ '\\<oplus>' : '\U00002295',
600
+ '\\<Oplus>' : '\U00002a01',
601
+ '\\<otimes>' : '\U00002297',
602
+ '\\<Otimes>' : '\U00002a02',
603
+ '\\<odot>' : '\U00002299',
604
+ '\\<Odot>' : '\U00002a00',
605
+ '\\<ominus>' : '\U00002296',
606
+ '\\<oslash>' : '\U00002298',
607
+ '\\<dots>' : '\U00002026',
608
+ '\\<cdots>' : '\U000022ef',
609
+ '\\<Sum>' : '\U00002211',
610
+ '\\<Prod>' : '\U0000220f',
611
+ '\\<Coprod>' : '\U00002210',
612
+ '\\<infinity>' : '\U0000221e',
613
+ '\\<integral>' : '\U0000222b',
614
+ '\\<ointegral>' : '\U0000222e',
615
+ '\\<clubsuit>' : '\U00002663',
616
+ '\\<diamondsuit>' : '\U00002662',
617
+ '\\<heartsuit>' : '\U00002661',
618
+ '\\<spadesuit>' : '\U00002660',
619
+ '\\<aleph>' : '\U00002135',
620
+ '\\<emptyset>' : '\U00002205',
621
+ '\\<nabla>' : '\U00002207',
622
+ '\\<partial>' : '\U00002202',
623
+ '\\<flat>' : '\U0000266d',
624
+ '\\<natural>' : '\U0000266e',
625
+ '\\<sharp>' : '\U0000266f',
626
+ '\\<angle>' : '\U00002220',
627
+ '\\<copyright>' : '\U000000a9',
628
+ '\\<registered>' : '\U000000ae',
629
+ '\\<hyphen>' : '\U000000ad',
630
+ '\\<inverse>' : '\U000000af',
631
+ '\\<onequarter>' : '\U000000bc',
632
+ '\\<onehalf>' : '\U000000bd',
633
+ '\\<threequarters>' : '\U000000be',
634
+ '\\<ordfeminine>' : '\U000000aa',
635
+ '\\<ordmasculine>' : '\U000000ba',
636
+ '\\<section>' : '\U000000a7',
637
+ '\\<paragraph>' : '\U000000b6',
638
+ '\\<exclamdown>' : '\U000000a1',
639
+ '\\<questiondown>' : '\U000000bf',
640
+ '\\<euro>' : '\U000020ac',
641
+ '\\<pounds>' : '\U000000a3',
642
+ '\\<yen>' : '\U000000a5',
643
+ '\\<cent>' : '\U000000a2',
644
+ '\\<currency>' : '\U000000a4',
645
+ '\\<degree>' : '\U000000b0',
646
+ '\\<amalg>' : '\U00002a3f',
647
+ '\\<mho>' : '\U00002127',
648
+ '\\<lozenge>' : '\U000025ca',
649
+ '\\<wp>' : '\U00002118',
650
+ '\\<wrong>' : '\U00002240',
651
+ '\\<struct>' : '\U000022c4',
652
+ '\\<acute>' : '\U000000b4',
653
+ '\\<index>' : '\U00000131',
654
+ '\\<dieresis>' : '\U000000a8',
655
+ '\\<cedilla>' : '\U000000b8',
656
+ '\\<hungarumlaut>' : '\U000002dd',
657
+ '\\<some>' : '\U000003f5',
658
+ '\\<newline>' : '\U000023ce',
659
+ '\\<open>' : '\U00002039',
660
+ '\\<close>' : '\U0000203a',
661
+ '\\<here>' : '\U00002302',
662
+ '\\<^sub>' : '\U000021e9',
663
+ '\\<^sup>' : '\U000021e7',
664
+ '\\<^bold>' : '\U00002759',
665
+ '\\<^bsub>' : '\U000021d8',
666
+ '\\<^esub>' : '\U000021d9',
667
+ '\\<^bsup>' : '\U000021d7',
668
+ '\\<^esup>' : '\U000021d6',
669
+ }
670
+
671
+ lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols}
672
+
673
+ def __init__(self, **options):
674
+ Filter.__init__(self, **options)
675
+ lang = get_choice_opt(options, 'lang',
676
+ ['isabelle', 'latex'], 'isabelle')
677
+ self.symbols = self.lang_map[lang]
678
+
679
+ def filter(self, lexer, stream):
680
+ for ttype, value in stream:
681
+ if value in self.symbols:
682
+ yield ttype, self.symbols[value]
683
+ else:
684
+ yield ttype, value
685
+
686
+
687
+ class KeywordCaseFilter(Filter):
688
+ """Convert keywords to lowercase or uppercase or capitalize them, which
689
+ means first letter uppercase, rest lowercase.
690
+
691
+ This can be useful e.g. if you highlight Pascal code and want to adapt the
692
+ code to your styleguide.
693
+
694
+ Options accepted:
695
+
696
+ `case` : string
697
+ The casing to convert keywords to. Must be one of ``'lower'``,
698
+ ``'upper'`` or ``'capitalize'``. The default is ``'lower'``.
699
+ """
700
+
701
+ def __init__(self, **options):
702
+ Filter.__init__(self, **options)
703
+ case = get_choice_opt(options, 'case',
704
+ ['lower', 'upper', 'capitalize'], 'lower')
705
+ self.convert = getattr(str, case)
706
+
707
+ def filter(self, lexer, stream):
708
+ for ttype, value in stream:
709
+ if ttype in Keyword:
710
+ yield ttype, self.convert(value)
711
+ else:
712
+ yield ttype, value
713
+
714
+
715
+ class NameHighlightFilter(Filter):
716
+ """Highlight a normal Name (and Name.*) token with a different token type.
717
+
718
+ Example::
719
+
720
+ filter = NameHighlightFilter(
721
+ names=['foo', 'bar', 'baz'],
722
+ tokentype=Name.Function,
723
+ )
724
+
725
+ This would highlight the names "foo", "bar" and "baz"
726
+ as functions. `Name.Function` is the default token type.
727
+
728
+ Options accepted:
729
+
730
+ `names` : list of strings
731
+ A list of names that should be given the different token type.
732
+ There is no default.
733
+ `tokentype` : TokenType or string
734
+ A token type or a string containing a token type name that is
735
+ used for highlighting the strings in `names`. The default is
736
+ `Name.Function`.
737
+ """
738
+
739
+ def __init__(self, **options):
740
+ Filter.__init__(self, **options)
741
+ self.names = set(get_list_opt(options, 'names', []))
742
+ tokentype = options.get('tokentype')
743
+ if tokentype:
744
+ self.tokentype = string_to_tokentype(tokentype)
745
+ else:
746
+ self.tokentype = Name.Function
747
+
748
+ def filter(self, lexer, stream):
749
+ for ttype, value in stream:
750
+ if ttype in Name and value in self.names:
751
+ yield self.tokentype, value
752
+ else:
753
+ yield ttype, value
754
+
755
+
756
+ class ErrorToken(Exception):
757
+ pass
758
+
759
+
760
+ class RaiseOnErrorTokenFilter(Filter):
761
+ """Raise an exception when the lexer generates an error token.
762
+
763
+ Options accepted:
764
+
765
+ `excclass` : Exception class
766
+ The exception class to raise.
767
+ The default is `pygments.filters.ErrorToken`.
768
+
769
+ .. versionadded:: 0.8
770
+ """
771
+
772
+ def __init__(self, **options):
773
+ Filter.__init__(self, **options)
774
+ self.exception = options.get('excclass', ErrorToken)
775
+ try:
776
+ # issubclass() will raise TypeError if first argument is not a class
777
+ if not issubclass(self.exception, Exception):
778
+ raise TypeError
779
+ except TypeError:
780
+ raise OptionError('excclass option is not an exception class')
781
+
782
+ def filter(self, lexer, stream):
783
+ for ttype, value in stream:
784
+ if ttype is Error:
785
+ raise self.exception(value)
786
+ yield ttype, value
787
+
788
+
789
+ class VisibleWhitespaceFilter(Filter):
790
+ """Convert tabs, newlines and/or spaces to visible characters.
791
+
792
+ Options accepted:
793
+
794
+ `spaces` : string or bool
795
+ If this is a one-character string, spaces will be replaces by this string.
796
+ If it is another true value, spaces will be replaced by ``·`` (unicode
797
+ MIDDLE DOT). If it is a false value, spaces will not be replaced. The
798
+ default is ``False``.
799
+ `tabs` : string or bool
800
+ The same as for `spaces`, but the default replacement character is ``»``
801
+ (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK). The default value
802
+ is ``False``. Note: this will not work if the `tabsize` option for the
803
+ lexer is nonzero, as tabs will already have been expanded then.
804
+ `tabsize` : int
805
+ If tabs are to be replaced by this filter (see the `tabs` option), this
806
+ is the total number of characters that a tab should be expanded to.
807
+ The default is ``8``.
808
+ `newlines` : string or bool
809
+ The same as for `spaces`, but the default replacement character is ``¶``
810
+ (unicode PILCROW SIGN). The default value is ``False``.
811
+ `wstokentype` : bool
812
+ If true, give whitespace the special `Whitespace` token type. This allows
813
+ styling the visible whitespace differently (e.g. greyed out), but it can
814
+ disrupt background colors. The default is ``True``.
815
+
816
+ .. versionadded:: 0.8
817
+ """
818
+
819
+ def __init__(self, **options):
820
+ Filter.__init__(self, **options)
821
+ for name, default in [('spaces', '·'),
822
+ ('tabs', '»'),
823
+ ('newlines', '¶')]:
824
+ opt = options.get(name, False)
825
+ if isinstance(opt, str) and len(opt) == 1:
826
+ setattr(self, name, opt)
827
+ else:
828
+ setattr(self, name, (opt and default or ''))
829
+ tabsize = get_int_opt(options, 'tabsize', 8)
830
+ if self.tabs:
831
+ self.tabs += ' ' * (tabsize - 1)
832
+ if self.newlines:
833
+ self.newlines += '\n'
834
+ self.wstt = get_bool_opt(options, 'wstokentype', True)
835
+
836
+ def filter(self, lexer, stream):
837
+ if self.wstt:
838
+ spaces = self.spaces or ' '
839
+ tabs = self.tabs or '\t'
840
+ newlines = self.newlines or '\n'
841
+ regex = re.compile(r'\s')
842
+
843
+ def replacefunc(wschar):
844
+ if wschar == ' ':
845
+ return spaces
846
+ elif wschar == '\t':
847
+ return tabs
848
+ elif wschar == '\n':
849
+ return newlines
850
+ return wschar
851
+
852
+ for ttype, value in stream:
853
+ yield from _replace_special(ttype, value, regex, Whitespace,
854
+ replacefunc)
855
+ else:
856
+ spaces, tabs, newlines = self.spaces, self.tabs, self.newlines
857
+ # simpler processing
858
+ for ttype, value in stream:
859
+ if spaces:
860
+ value = value.replace(' ', spaces)
861
+ if tabs:
862
+ value = value.replace('\t', tabs)
863
+ if newlines:
864
+ value = value.replace('\n', newlines)
865
+ yield ttype, value
866
+
867
+
868
+ class GobbleFilter(Filter):
869
+ """Gobbles source code lines (eats initial characters).
870
+
871
+ This filter drops the first ``n`` characters off every line of code. This
872
+ may be useful when the source code fed to the lexer is indented by a fixed
873
+ amount of space that isn't desired in the output.
874
+
875
+ Options accepted:
876
+
877
+ `n` : int
878
+ The number of characters to gobble.
879
+
880
+ .. versionadded:: 1.2
881
+ """
882
+ def __init__(self, **options):
883
+ Filter.__init__(self, **options)
884
+ self.n = get_int_opt(options, 'n', 0)
885
+
886
+ def gobble(self, value, left):
887
+ if left < len(value):
888
+ return value[left:], 0
889
+ else:
890
+ return '', left - len(value)
891
+
892
+ def filter(self, lexer, stream):
893
+ n = self.n
894
+ left = n # How many characters left to gobble.
895
+ for ttype, value in stream:
896
+ # Remove ``left`` tokens from first line, ``n`` from all others.
897
+ parts = value.split('\n')
898
+ (parts[0], left) = self.gobble(parts[0], left)
899
+ for i in range(1, len(parts)):
900
+ (parts[i], left) = self.gobble(parts[i], n)
901
+ value = '\n'.join(parts)
902
+
903
+ if value != '':
904
+ yield ttype, value
905
+
906
+
907
+ class TokenMergeFilter(Filter):
908
+ """Merges consecutive tokens with the same token type in the output
909
+ stream of a lexer.
910
+
911
+ .. versionadded:: 1.2
912
+ """
913
+ def __init__(self, **options):
914
+ Filter.__init__(self, **options)
915
+
916
+ def filter(self, lexer, stream):
917
+ current_type = None
918
+ current_value = None
919
+ for ttype, value in stream:
920
+ if ttype is current_type:
921
+ current_value += value
922
+ else:
923
+ if current_type is not None:
924
+ yield current_type, current_value
925
+ current_type = ttype
926
+ current_value = value
927
+ if current_type is not None:
928
+ yield current_type, current_value
929
+
930
+
931
+ FILTERS = {
932
+ 'codetagify': CodeTagFilter,
933
+ 'keywordcase': KeywordCaseFilter,
934
+ 'highlight': NameHighlightFilter,
935
+ 'raiseonerror': RaiseOnErrorTokenFilter,
936
+ 'whitespace': VisibleWhitespaceFilter,
937
+ 'gobble': GobbleFilter,
938
+ 'tokenmerge': TokenMergeFilter,
939
+ 'symbols': SymbolFilter,
940
+ }
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/filters/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (29.6 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatter.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatter
3
+ ~~~~~~~~~~~~~~~~~~
4
+
5
+ Base formatter class.
6
+
7
+ :copyright: Copyright 2006-2024 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
+ Formatters should have attributes to help selecting them. These
30
+ are similar to the corresponding :class:`~pygments.lexer.Lexer`
31
+ attributes.
32
+
33
+ .. autoattribute:: name
34
+ :no-value:
35
+
36
+ .. autoattribute:: aliases
37
+ :no-value:
38
+
39
+ .. autoattribute:: filenames
40
+ :no-value:
41
+
42
+ You can pass options as keyword arguments to the constructor.
43
+ All formatters accept these basic options:
44
+
45
+ ``style``
46
+ The style to use, can be a string or a Style subclass
47
+ (default: "default"). Not used by e.g. the
48
+ TerminalFormatter.
49
+ ``full``
50
+ Tells the formatter to output a "full" document, i.e.
51
+ a complete self-contained document. This doesn't have
52
+ any effect for some formatters (default: false).
53
+ ``title``
54
+ If ``full`` is true, the title that should be used to
55
+ caption the document (default: '').
56
+ ``encoding``
57
+ If given, must be an encoding name. This will be used to
58
+ convert the Unicode token strings to byte strings in the
59
+ output. If it is "" or None, Unicode strings will be written
60
+ to the output file, which most file-like objects do not
61
+ support (default: None).
62
+ ``outencoding``
63
+ Overrides ``encoding`` if given.
64
+
65
+ """
66
+
67
+ #: Full name for the formatter, in human-readable form.
68
+ name = None
69
+
70
+ #: A list of short, unique identifiers that can be used to lookup
71
+ #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`.
72
+ aliases = []
73
+
74
+ #: A list of fnmatch patterns that match filenames for which this
75
+ #: formatter can produce output. The patterns in this list should be unique
76
+ #: among all formatters.
77
+ filenames = []
78
+
79
+ #: If True, this formatter outputs Unicode strings when no encoding
80
+ #: option is given.
81
+ unicodeoutput = True
82
+
83
+ def __init__(self, **options):
84
+ """
85
+ As with lexers, this constructor takes arbitrary optional arguments,
86
+ and if you override it, you should first process your own options, then
87
+ call the base class implementation.
88
+ """
89
+ self.style = _lookup_style(options.get('style', 'default'))
90
+ self.full = get_bool_opt(options, 'full', False)
91
+ self.title = options.get('title', '')
92
+ self.encoding = options.get('encoding', None) or None
93
+ if self.encoding in ('guess', 'chardet'):
94
+ # can happen for e.g. pygmentize -O encoding=guess
95
+ self.encoding = 'utf-8'
96
+ self.encoding = options.get('outencoding') or self.encoding
97
+ self.options = options
98
+
99
+ def get_style_defs(self, arg=''):
100
+ """
101
+ This method must return statements or declarations suitable to define
102
+ the current style for subsequent highlighted text (e.g. CSS classes
103
+ in the `HTMLFormatter`).
104
+
105
+ The optional argument `arg` can be used to modify the generation and
106
+ is formatter dependent (it is standardized because it can be given on
107
+ the command line).
108
+
109
+ This method is called by the ``-S`` :doc:`command-line option <cmdline>`,
110
+ the `arg` is then given by the ``-a`` option.
111
+ """
112
+ return ''
113
+
114
+ def format(self, tokensource, outfile):
115
+ """
116
+ This method must format the tokens from the `tokensource` iterable and
117
+ write the formatted version to the file object `outfile`.
118
+
119
+ Formatter options can control how exactly the tokens are converted.
120
+ """
121
+ if self.encoding:
122
+ # wrap the outfile in a StreamWriter
123
+ outfile = codecs.lookup(self.encoding)[3](outfile)
124
+ return self.format_unencoded(tokensource, outfile)
125
+
126
+ # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to
127
+ # Formatter. This helps when using third-party type stubs from typeshed.
128
+ def __class_getitem__(cls, name):
129
+ return cls
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__init__.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Pygments formatters.
6
+
7
+ :copyright: Copyright 2006-2024 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
+ """
72
+ Return an instance of a :class:`.Formatter` subclass that has `alias` in its
73
+ aliases list. The formatter is given the `options` at its instantiation.
74
+
75
+ Will raise :exc:`pygments.util.ClassNotFound` if no formatter with that
76
+ alias is found.
77
+ """
78
+ cls = find_formatter_class(_alias)
79
+ if cls is None:
80
+ raise ClassNotFound(f"no formatter found for name {_alias!r}")
81
+ return cls(**options)
82
+
83
+
84
+ def load_formatter_from_file(filename, formattername="CustomFormatter", **options):
85
+ """
86
+ Return a `Formatter` subclass instance loaded from the provided file, relative
87
+ to the current directory.
88
+
89
+ The file is expected to contain a Formatter class named ``formattername``
90
+ (by default, CustomFormatter). Users should be very careful with the input, because
91
+ this method is equivalent to running ``eval()`` on the input file. The formatter is
92
+ given the `options` at its instantiation.
93
+
94
+ :exc:`pygments.util.ClassNotFound` is raised if there are any errors loading
95
+ the formatter.
96
+
97
+ .. versionadded:: 2.2
98
+ """
99
+ try:
100
+ # This empty dict will contain the namespace for the exec'd file
101
+ custom_namespace = {}
102
+ with open(filename, 'rb') as f:
103
+ exec(f.read(), custom_namespace)
104
+ # Retrieve the class `formattername` from that namespace
105
+ if formattername not in custom_namespace:
106
+ raise ClassNotFound(f'no valid {formattername} class found in {filename}')
107
+ formatter_class = custom_namespace[formattername]
108
+ # And finally instantiate it with the options
109
+ return formatter_class(**options)
110
+ except OSError as err:
111
+ raise ClassNotFound(f'cannot read {filename}: {err}')
112
+ except ClassNotFound:
113
+ raise
114
+ except Exception as err:
115
+ raise ClassNotFound(f'error when loading custom formatter: {err}')
116
+
117
+
118
+ def get_formatter_for_filename(fn, **options):
119
+ """
120
+ Return a :class:`.Formatter` subclass instance that has a filename pattern
121
+ matching `fn`. The formatter is given the `options` at its instantiation.
122
+
123
+ Will raise :exc:`pygments.util.ClassNotFound` if no formatter for that filename
124
+ is found.
125
+ """
126
+ fn = basename(fn)
127
+ for modname, name, _, filenames, _ in FORMATTERS.values():
128
+ for filename in filenames:
129
+ if _fn_matches(fn, filename):
130
+ if name not in _formatter_cache:
131
+ _load_formatters(modname)
132
+ return _formatter_cache[name](**options)
133
+ for _name, cls in find_plugin_formatters():
134
+ for filename in cls.filenames:
135
+ if _fn_matches(fn, filename):
136
+ return cls(**options)
137
+ raise ClassNotFound(f"no formatter found for file name {fn!r}")
138
+
139
+
140
+ class _automodule(types.ModuleType):
141
+ """Automatically import formatters."""
142
+
143
+ def __getattr__(self, name):
144
+ info = FORMATTERS.get(name)
145
+ if info:
146
+ _load_formatters(info[0])
147
+ cls = _formatter_cache[info[1]]
148
+ setattr(self, name, cls)
149
+ return cls
150
+ raise AttributeError(name)
151
+
152
+
153
+ oldmod = sys.modules[__name__]
154
+ newmod = _automodule(__name__)
155
+ newmod.__dict__.update(oldmod.__dict__)
156
+ sys.modules[__name__] = newmod
157
+ del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/_mapping.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/bbcode.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/groff.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/html.cpython-310.pyc ADDED
Binary file (29.4 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/img.cpython-310.pyc ADDED
Binary file (18.4 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/irc.cpython-310.pyc ADDED
Binary file (4.08 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/latex.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/other.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/pangomarkup.cpython-310.pyc ADDED
Binary file (2.09 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/rtf.cpython-310.pyc ADDED
Binary file (8.84 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/svg.cpython-310.pyc ADDED
Binary file (6.3 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/__pycache__/terminal256.cpython-310.pyc ADDED
Binary file (9.23 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/_mapping.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Automatically generated by scripts/gen_mapfiles.py.
2
+ # DO NOT EDIT BY HAND; run `tox -e mapfiles` instead.
3
+
4
+ FORMATTERS = {
5
+ '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.'),
6
+ '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.'),
7
+ '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.'),
8
+ 'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),
9
+ 'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), "Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option). The ``<div>``'s CSS class can be set by the `cssclass` option."),
10
+ 'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),
11
+ '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.'),
12
+ '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.'),
13
+ 'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),
14
+ 'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),
15
+ 'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),
16
+ 'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),
17
+ '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.'),
18
+ '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.'),
19
+ '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.'),
20
+ '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.'),
21
+ '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.'),
22
+ 'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'),
23
+ }
vllm/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-2024 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=#{}]'.format(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')
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/groff.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.groff
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for groff output.
6
+
7
+ :copyright: Copyright 2006-2024 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[{}]'.format(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[{}]'.format(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 sorted(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
+ while ttype not in self.styles:
148
+ ttype = ttype.parent
149
+ start, end = self.styles[ttype]
150
+
151
+ for line in value.splitlines(True):
152
+ if self.wrap > 0:
153
+ line = self._wrap_line(line)
154
+
155
+ if start and end:
156
+ text = self._escape_chars(line.rstrip('\n'))
157
+ if text != '':
158
+ outfile.write(''.join((start, text, end)))
159
+ else:
160
+ outfile.write(self._escape_chars(line.rstrip('\n')))
161
+
162
+ if line.endswith('\n'):
163
+ if self.linenos:
164
+ self._write_lineno(outfile)
165
+ self._linelen = 0
166
+ else:
167
+ outfile.write('\n')
168
+ self._linelen = 0
169
+
170
+ outfile.write('\n.fi')
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/html.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.html
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for HTML output.
6
+
7
+ :copyright: Copyright 2006-2024 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-2024 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-2024 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. By default, the content is enclosed
116
+ in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option).
117
+ The ``<div>``'s CSS class can be set by the `cssclass` 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
+ A list of lines can be specified using the `hl_lines` option to make these
144
+ lines highlighted (as of Pygments 0.11).
145
+
146
+ With the `full` option, a complete HTML 4 document is output, including
147
+ the style definitions inside a ``<style>`` tag, or in a separate file if
148
+ the `cssfile` option is given.
149
+
150
+ When `tagsfile` is set to the path of a ctags index file, it is used to
151
+ generate hyperlinks from names to their definition. You must enable
152
+ `lineanchors` and run ctags with the `-n` option for this to work. The
153
+ `python-ctags` module from PyPI must be installed to use this feature;
154
+ otherwise a `RuntimeError` will be raised.
155
+
156
+ The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string
157
+ containing CSS rules for the CSS classes used by the formatter. The
158
+ argument `arg` can be used to specify additional CSS selectors that
159
+ are prepended to the classes. A call `fmter.get_style_defs('td .code')`
160
+ would result in the following CSS classes:
161
+
162
+ .. sourcecode:: css
163
+
164
+ td .code .kw { font-weight: bold; color: #00FF00 }
165
+ td .code .cm { color: #999999 }
166
+ ...
167
+
168
+ If you have Pygments 0.6 or higher, you can also pass a list or tuple to the
169
+ `get_style_defs()` method to request multiple prefixes for the tokens:
170
+
171
+ .. sourcecode:: python
172
+
173
+ formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])
174
+
175
+ The output would then look like this:
176
+
177
+ .. sourcecode:: css
178
+
179
+ div.syntax pre .kw,
180
+ pre.syntax .kw { font-weight: bold; color: #00FF00 }
181
+ div.syntax pre .cm,
182
+ pre.syntax .cm { color: #999999 }
183
+ ...
184
+
185
+ Additional options accepted:
186
+
187
+ `nowrap`
188
+ If set to ``True``, don't add a ``<pre>`` and a ``<div>`` tag
189
+ around the tokens. This disables most other options (default: ``False``).
190
+
191
+ `full`
192
+ Tells the formatter to output a "full" document, i.e. a complete
193
+ self-contained document (default: ``False``).
194
+
195
+ `title`
196
+ If `full` is true, the title that should be used to caption the
197
+ document (default: ``''``).
198
+
199
+ `style`
200
+ The style to use, can be a string or a Style subclass (default:
201
+ ``'default'``). This option has no effect if the `cssfile`
202
+ and `noclobber_cssfile` option are given and the file specified in
203
+ `cssfile` exists.
204
+
205
+ `noclasses`
206
+ If set to true, token ``<span>`` tags (as well as line number elements)
207
+ will not use CSS classes, but inline styles. This is not recommended
208
+ for larger pieces of code since it increases output size by quite a bit
209
+ (default: ``False``).
210
+
211
+ `classprefix`
212
+ Since the token types use relatively short class names, they may clash
213
+ with some of your own class names. In this case you can use the
214
+ `classprefix` option to give a string to prepend to all Pygments-generated
215
+ CSS class names for token types.
216
+ Note that this option also affects the output of `get_style_defs()`.
217
+
218
+ `cssclass`
219
+ CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``).
220
+ If you set this option, the default selector for `get_style_defs()`
221
+ will be this class.
222
+
223
+ .. versionadded:: 0.9
224
+ If you select the ``'table'`` line numbers, the wrapping table will
225
+ have a CSS class of this string plus ``'table'``, the default is
226
+ accordingly ``'highlighttable'``.
227
+
228
+ `cssstyles`
229
+ Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``).
230
+
231
+ `prestyles`
232
+ Inline CSS styles for the ``<pre>`` tag (default: ``''``).
233
+
234
+ .. versionadded:: 0.11
235
+
236
+ `cssfile`
237
+ If the `full` option is true and this option is given, it must be the
238
+ name of an external file. If the filename does not include an absolute
239
+ path, the file's path will be assumed to be relative to the main output
240
+ file's path, if the latter can be found. The stylesheet is then written
241
+ to this file instead of the HTML file.
242
+
243
+ .. versionadded:: 0.6
244
+
245
+ `noclobber_cssfile`
246
+ If `cssfile` is given and the specified file exists, the css file will
247
+ not be overwritten. This allows the use of the `full` option in
248
+ combination with a user specified css file. Default is ``False``.
249
+
250
+ .. versionadded:: 1.1
251
+
252
+ `linenos`
253
+ If set to ``'table'``, output line numbers as a table with two cells,
254
+ one containing the line numbers, the other the whole code. This is
255
+ copy-and-paste-friendly, but may cause alignment problems with some
256
+ browsers or fonts. If set to ``'inline'``, the line numbers will be
257
+ integrated in the ``<pre>`` tag that contains the code (that setting
258
+ is *new in Pygments 0.8*).
259
+
260
+ For compatibility with Pygments 0.7 and earlier, every true value
261
+ except ``'inline'`` means the same as ``'table'`` (in particular, that
262
+ means also ``True``).
263
+
264
+ The default value is ``False``, which means no line numbers at all.
265
+
266
+ **Note:** with the default ("table") line number mechanism, the line
267
+ numbers and code can have different line heights in Internet Explorer
268
+ unless you give the enclosing ``<pre>`` tags an explicit ``line-height``
269
+ CSS property (you get the default line spacing with ``line-height:
270
+ 125%``).
271
+
272
+ `hl_lines`
273
+ Specify a list of lines to be highlighted. The line numbers are always
274
+ relative to the input (i.e. the first line is line 1) and are
275
+ independent of `linenostart`.
276
+
277
+ .. versionadded:: 0.11
278
+
279
+ `linenostart`
280
+ The line number for the first line (default: ``1``).
281
+
282
+ `linenostep`
283
+ If set to a number n > 1, only every nth line number is printed.
284
+
285
+ `linenospecial`
286
+ If set to a number n > 0, every nth line number is given the CSS
287
+ class ``"special"`` (default: ``0``).
288
+
289
+ `nobackground`
290
+ If set to ``True``, the formatter won't output the background color
291
+ for the wrapping element (this automatically defaults to ``False``
292
+ when there is no wrapping element [eg: no argument for the
293
+ `get_syntax_defs` method given]) (default: ``False``).
294
+
295
+ .. versionadded:: 0.6
296
+
297
+ `lineseparator`
298
+ This string is output between lines of code. It defaults to ``"\n"``,
299
+ which is enough to break a line inside ``<pre>`` tags, but you can
300
+ e.g. set it to ``"<br>"`` to get HTML line breaks.
301
+
302
+ .. versionadded:: 0.7
303
+
304
+ `lineanchors`
305
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
306
+ output line in an anchor tag with an ``id`` (and `name`) of ``foo-linenumber``.
307
+ This allows easy linking to certain lines.
308
+
309
+ .. versionadded:: 0.9
310
+
311
+ `linespans`
312
+ If set to a nonempty string, e.g. ``foo``, the formatter will wrap each
313
+ output line in a span tag with an ``id`` of ``foo-linenumber``.
314
+ This allows easy access to lines via javascript.
315
+
316
+ .. versionadded:: 1.6
317
+
318
+ `anchorlinenos`
319
+ If set to `True`, will wrap line numbers in <a> tags. Used in
320
+ combination with `linenos` and `lineanchors`.
321
+
322
+ `tagsfile`
323
+ If set to the path of a ctags file, wrap names in anchor tags that
324
+ link to their definitions. `lineanchors` should be used, and the
325
+ tags file should specify line numbers (see the `-n` option to ctags).
326
+ The tags file is assumed to be encoded in UTF-8.
327
+
328
+ .. versionadded:: 1.6
329
+
330
+ `tagurlformat`
331
+ A string formatting pattern used to generate links to ctags definitions.
332
+ Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`.
333
+ Defaults to an empty string, resulting in just `#prefix-number` links.
334
+
335
+ .. versionadded:: 1.6
336
+
337
+ `filename`
338
+ A string used to generate a filename when rendering ``<pre>`` blocks,
339
+ for example if displaying source code. If `linenos` is set to
340
+ ``'table'`` then the filename will be rendered in an initial row
341
+ containing a single `<th>` which spans both columns.
342
+
343
+ .. versionadded:: 2.1
344
+
345
+ `wrapcode`
346
+ Wrap the code inside ``<pre>`` blocks using ``<code>``, as recommended
347
+ by the HTML5 specification.
348
+
349
+ .. versionadded:: 2.4
350
+
351
+ `debug_token_types`
352
+ Add ``title`` attributes to all token ``<span>`` tags that show the
353
+ name of the token.
354
+
355
+ .. versionadded:: 2.10
356
+
357
+
358
+ **Subclassing the HTML formatter**
359
+
360
+ .. versionadded:: 0.7
361
+
362
+ The HTML formatter is now built in a way that allows easy subclassing, thus
363
+ customizing the output HTML code. The `format()` method calls
364
+ `self._format_lines()` which returns a generator that yields tuples of ``(1,
365
+ line)``, where the ``1`` indicates that the ``line`` is a line of the
366
+ formatted source code.
367
+
368
+ If the `nowrap` option is set, the generator is the iterated over and the
369
+ resulting HTML is output.
370
+
371
+ Otherwise, `format()` calls `self.wrap()`, which wraps the generator with
372
+ other generators. These may add some HTML code to the one generated by
373
+ `_format_lines()`, either by modifying the lines generated by the latter,
374
+ then yielding them again with ``(1, line)``, and/or by yielding other HTML
375
+ code before or after the lines, with ``(0, html)``. The distinction between
376
+ source lines and other code makes it possible to wrap the generator multiple
377
+ times.
378
+
379
+ The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag.
380
+
381
+ A custom `HtmlFormatter` subclass could look like this:
382
+
383
+ .. sourcecode:: python
384
+
385
+ class CodeHtmlFormatter(HtmlFormatter):
386
+
387
+ def wrap(self, source, *, include_div):
388
+ return self._wrap_code(source)
389
+
390
+ def _wrap_code(self, source):
391
+ yield 0, '<code>'
392
+ for i, t in source:
393
+ if i == 1:
394
+ # it's a line of formatted code
395
+ t += '<br>'
396
+ yield i, t
397
+ yield 0, '</code>'
398
+
399
+ This results in wrapping the formatted lines with a ``<code>`` tag, where the
400
+ source lines are broken using ``<br>`` tags.
401
+
402
+ After calling `wrap()`, the `format()` method also adds the "line numbers"
403
+ and/or "full document" wrappers if the respective options are set. Then, all
404
+ HTML yielded by the wrapped generator is output.
405
+ """
406
+
407
+ name = 'HTML'
408
+ aliases = ['html']
409
+ filenames = ['*.html', '*.htm']
410
+
411
+ def __init__(self, **options):
412
+ Formatter.__init__(self, **options)
413
+ self.title = self._decodeifneeded(self.title)
414
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
415
+ self.noclasses = get_bool_opt(options, 'noclasses', False)
416
+ self.classprefix = options.get('classprefix', '')
417
+ self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))
418
+ self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
419
+ self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
420
+ self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
421
+ self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
422
+ self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
423
+ self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))
424
+ self.filename = self._decodeifneeded(options.get('filename', ''))
425
+ self.wrapcode = get_bool_opt(options, 'wrapcode', False)
426
+ self.span_element_openers = {}
427
+ self.debug_token_types = get_bool_opt(options, 'debug_token_types', False)
428
+
429
+ if self.tagsfile:
430
+ if not ctags:
431
+ raise RuntimeError('The "ctags" package must to be installed '
432
+ 'to be able to use the "tagsfile" feature.')
433
+ self._ctags = ctags.CTags(self.tagsfile)
434
+
435
+ linenos = options.get('linenos', False)
436
+ if linenos == 'inline':
437
+ self.linenos = 2
438
+ elif linenos:
439
+ # compatibility with <= 0.7
440
+ self.linenos = 1
441
+ else:
442
+ self.linenos = 0
443
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
444
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
445
+ self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
446
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
447
+ self.lineseparator = options.get('lineseparator', '\n')
448
+ self.lineanchors = options.get('lineanchors', '')
449
+ self.linespans = options.get('linespans', '')
450
+ self.anchorlinenos = get_bool_opt(options, 'anchorlinenos', False)
451
+ self.hl_lines = set()
452
+ for lineno in get_list_opt(options, 'hl_lines', []):
453
+ try:
454
+ self.hl_lines.add(int(lineno))
455
+ except ValueError:
456
+ pass
457
+
458
+ self._create_stylesheet()
459
+
460
+ def _get_css_class(self, ttype):
461
+ """Return the css class of this token type prefixed with
462
+ the classprefix option."""
463
+ ttypeclass = _get_ttype_class(ttype)
464
+ if ttypeclass:
465
+ return self.classprefix + ttypeclass
466
+ return ''
467
+
468
+ def _get_css_classes(self, ttype):
469
+ """Return the CSS classes of this token type prefixed with the classprefix option."""
470
+ cls = self._get_css_class(ttype)
471
+ while ttype not in STANDARD_TYPES:
472
+ ttype = ttype.parent
473
+ cls = self._get_css_class(ttype) + ' ' + cls
474
+ return cls or ''
475
+
476
+ def _get_css_inline_styles(self, ttype):
477
+ """Return the inline CSS styles for this token type."""
478
+ cclass = self.ttype2class.get(ttype)
479
+ while cclass is None:
480
+ ttype = ttype.parent
481
+ cclass = self.ttype2class.get(ttype)
482
+ return cclass or ''
483
+
484
+ def _create_stylesheet(self):
485
+ t2c = self.ttype2class = {Token: ''}
486
+ c2s = self.class2style = {}
487
+ for ttype, ndef in self.style:
488
+ name = self._get_css_class(ttype)
489
+ style = ''
490
+ if ndef['color']:
491
+ style += 'color: {}; '.format(webify(ndef['color']))
492
+ if ndef['bold']:
493
+ style += 'font-weight: bold; '
494
+ if ndef['italic']:
495
+ style += 'font-style: italic; '
496
+ if ndef['underline']:
497
+ style += 'text-decoration: underline; '
498
+ if ndef['bgcolor']:
499
+ style += 'background-color: {}; '.format(webify(ndef['bgcolor']))
500
+ if ndef['border']:
501
+ style += 'border: 1px solid {}; '.format(webify(ndef['border']))
502
+ if style:
503
+ t2c[ttype] = name
504
+ # save len(ttype) to enable ordering the styles by
505
+ # hierarchy (necessary for CSS cascading rules!)
506
+ c2s[name] = (style[:-2], ttype, len(ttype))
507
+
508
+ def get_style_defs(self, arg=None):
509
+ """
510
+ Return CSS style definitions for the classes produced by the current
511
+ highlighting style. ``arg`` can be a string or list of selectors to
512
+ insert before the token type classes.
513
+ """
514
+ style_lines = []
515
+
516
+ style_lines.extend(self.get_linenos_style_defs())
517
+ style_lines.extend(self.get_background_style_defs(arg))
518
+ style_lines.extend(self.get_token_style_defs(arg))
519
+
520
+ return '\n'.join(style_lines)
521
+
522
+ def get_token_style_defs(self, arg=None):
523
+ prefix = self.get_css_prefix(arg)
524
+
525
+ styles = [
526
+ (level, ttype, cls, style)
527
+ for cls, (style, ttype, level) in self.class2style.items()
528
+ if cls and style
529
+ ]
530
+ styles.sort()
531
+
532
+ lines = [
533
+ f'{prefix(cls)} {{ {style} }} /* {repr(ttype)[6:]} */'
534
+ for (level, ttype, cls, style) in styles
535
+ ]
536
+
537
+ return lines
538
+
539
+ def get_background_style_defs(self, arg=None):
540
+ prefix = self.get_css_prefix(arg)
541
+ bg_color = self.style.background_color
542
+ hl_color = self.style.highlight_color
543
+
544
+ lines = []
545
+
546
+ if arg and not self.nobackground and bg_color is not None:
547
+ text_style = ''
548
+ if Text in self.ttype2class:
549
+ text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
550
+ lines.insert(
551
+ 0, '{}{{ background: {};{} }}'.format(
552
+ prefix(''), bg_color, text_style
553
+ )
554
+ )
555
+ if hl_color is not None:
556
+ lines.insert(
557
+ 0, '{} {{ background-color: {} }}'.format(prefix('hll'), hl_color)
558
+ )
559
+
560
+ return lines
561
+
562
+ def get_linenos_style_defs(self):
563
+ lines = [
564
+ f'pre {{ {self._pre_style} }}',
565
+ f'td.linenos .normal {{ {self._linenos_style} }}',
566
+ f'span.linenos {{ {self._linenos_style} }}',
567
+ f'td.linenos .special {{ {self._linenos_special_style} }}',
568
+ f'span.linenos.special {{ {self._linenos_special_style} }}',
569
+ ]
570
+
571
+ return lines
572
+
573
+ def get_css_prefix(self, arg):
574
+ if arg is None:
575
+ arg = ('cssclass' in self.options and '.'+self.cssclass or '')
576
+ if isinstance(arg, str):
577
+ args = [arg]
578
+ else:
579
+ args = list(arg)
580
+
581
+ def prefix(cls):
582
+ if cls:
583
+ cls = '.' + cls
584
+ tmp = []
585
+ for arg in args:
586
+ tmp.append((arg and arg + ' ' or '') + cls)
587
+ return ', '.join(tmp)
588
+
589
+ return prefix
590
+
591
+ @property
592
+ def _pre_style(self):
593
+ return 'line-height: 125%;'
594
+
595
+ @property
596
+ def _linenos_style(self):
597
+ color = self.style.line_number_color
598
+ background_color = self.style.line_number_background_color
599
+ return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
600
+
601
+ @property
602
+ def _linenos_special_style(self):
603
+ color = self.style.line_number_special_color
604
+ background_color = self.style.line_number_special_background_color
605
+ return f'color: {color}; background-color: {background_color}; padding-left: 5px; padding-right: 5px;'
606
+
607
+ def _decodeifneeded(self, value):
608
+ if isinstance(value, bytes):
609
+ if self.encoding:
610
+ return value.decode(self.encoding)
611
+ return value.decode()
612
+ return value
613
+
614
+ def _wrap_full(self, inner, outfile):
615
+ if self.cssfile:
616
+ if os.path.isabs(self.cssfile):
617
+ # it's an absolute filename
618
+ cssfilename = self.cssfile
619
+ else:
620
+ try:
621
+ filename = outfile.name
622
+ if not filename or filename[0] == '<':
623
+ # pseudo files, e.g. name == '<fdopen>'
624
+ raise AttributeError
625
+ cssfilename = os.path.join(os.path.dirname(filename),
626
+ self.cssfile)
627
+ except AttributeError:
628
+ print('Note: Cannot determine output file name, '
629
+ 'using current directory as base for the CSS file name',
630
+ file=sys.stderr)
631
+ cssfilename = self.cssfile
632
+ # write CSS file only if noclobber_cssfile isn't given as an option.
633
+ try:
634
+ if not os.path.exists(cssfilename) or not self.noclobber_cssfile:
635
+ with open(cssfilename, "w", encoding="utf-8") as cf:
636
+ cf.write(CSSFILE_TEMPLATE %
637
+ {'styledefs': self.get_style_defs('body')})
638
+ except OSError as err:
639
+ err.strerror = 'Error writing CSS file: ' + err.strerror
640
+ raise
641
+
642
+ yield 0, (DOC_HEADER_EXTERNALCSS %
643
+ dict(title=self.title,
644
+ cssfile=self.cssfile,
645
+ encoding=self.encoding))
646
+ else:
647
+ yield 0, (DOC_HEADER %
648
+ dict(title=self.title,
649
+ styledefs=self.get_style_defs('body'),
650
+ encoding=self.encoding))
651
+
652
+ yield from inner
653
+ yield 0, DOC_FOOTER
654
+
655
+ def _wrap_tablelinenos(self, inner):
656
+ dummyoutfile = StringIO()
657
+ lncount = 0
658
+ for t, line in inner:
659
+ if t:
660
+ lncount += 1
661
+ dummyoutfile.write(line)
662
+
663
+ fl = self.linenostart
664
+ mw = len(str(lncount + fl - 1))
665
+ sp = self.linenospecial
666
+ st = self.linenostep
667
+ anchor_name = self.lineanchors or self.linespans
668
+ aln = self.anchorlinenos
669
+ nocls = self.noclasses
670
+
671
+ lines = []
672
+
673
+ for i in range(fl, fl+lncount):
674
+ print_line = i % st == 0
675
+ special_line = sp and i % sp == 0
676
+
677
+ if print_line:
678
+ line = '%*d' % (mw, i)
679
+ if aln:
680
+ line = '<a href="#%s-%d">%s</a>' % (anchor_name, i, line)
681
+ else:
682
+ line = ' ' * mw
683
+
684
+ if nocls:
685
+ if special_line:
686
+ style = f' style="{self._linenos_special_style}"'
687
+ else:
688
+ style = f' style="{self._linenos_style}"'
689
+ else:
690
+ if special_line:
691
+ style = ' class="special"'
692
+ else:
693
+ style = ' class="normal"'
694
+
695
+ if style:
696
+ line = f'<span{style}>{line}</span>'
697
+
698
+ lines.append(line)
699
+
700
+ ls = '\n'.join(lines)
701
+
702
+ # If a filename was specified, we can't put it into the code table as it
703
+ # would misalign the line numbers. Hence we emit a separate row for it.
704
+ filename_tr = ""
705
+ if self.filename:
706
+ filename_tr = (
707
+ '<tr><th colspan="2" class="filename">'
708
+ '<span class="filename">' + self.filename + '</span>'
709
+ '</th></tr>')
710
+
711
+ # in case you wonder about the seemingly redundant <div> here: since the
712
+ # content in the other cell also is wrapped in a div, some browsers in
713
+ # some configurations seem to mess up the formatting...
714
+ yield 0, (f'<table class="{self.cssclass}table">' + filename_tr +
715
+ '<tr><td class="linenos"><div class="linenodiv"><pre>' +
716
+ ls + '</pre></div></td><td class="code">')
717
+ yield 0, '<div>'
718
+ yield 0, dummyoutfile.getvalue()
719
+ yield 0, '</div>'
720
+ yield 0, '</td></tr></table>'
721
+
722
+
723
+ def _wrap_inlinelinenos(self, inner):
724
+ # need a list of lines since we need the width of a single number :(
725
+ inner_lines = list(inner)
726
+ sp = self.linenospecial
727
+ st = self.linenostep
728
+ num = self.linenostart
729
+ mw = len(str(len(inner_lines) + num - 1))
730
+ anchor_name = self.lineanchors or self.linespans
731
+ aln = self.anchorlinenos
732
+ nocls = self.noclasses
733
+
734
+ for _, inner_line in inner_lines:
735
+ print_line = num % st == 0
736
+ special_line = sp and num % sp == 0
737
+
738
+ if print_line:
739
+ line = '%*d' % (mw, num)
740
+ else:
741
+ line = ' ' * mw
742
+
743
+ if nocls:
744
+ if special_line:
745
+ style = f' style="{self._linenos_special_style}"'
746
+ else:
747
+ style = f' style="{self._linenos_style}"'
748
+ else:
749
+ if special_line:
750
+ style = ' class="linenos special"'
751
+ else:
752
+ style = ' class="linenos"'
753
+
754
+ if style:
755
+ linenos = f'<span{style}>{line}</span>'
756
+ else:
757
+ linenos = line
758
+
759
+ if aln:
760
+ yield 1, ('<a href="#%s-%d">%s</a>' % (anchor_name, num, linenos) +
761
+ inner_line)
762
+ else:
763
+ yield 1, linenos + inner_line
764
+ num += 1
765
+
766
+ def _wrap_lineanchors(self, inner):
767
+ s = self.lineanchors
768
+ # subtract 1 since we have to increment i *before* yielding
769
+ i = self.linenostart - 1
770
+ for t, line in inner:
771
+ if t:
772
+ i += 1
773
+ href = "" if self.linenos else ' href="#%s-%d"' % (s, i)
774
+ yield 1, '<a id="%s-%d" name="%s-%d"%s></a>' % (s, i, s, i, href) + line
775
+ else:
776
+ yield 0, line
777
+
778
+ def _wrap_linespans(self, inner):
779
+ s = self.linespans
780
+ i = self.linenostart - 1
781
+ for t, line in inner:
782
+ if t:
783
+ i += 1
784
+ yield 1, '<span id="%s-%d">%s</span>' % (s, i, line)
785
+ else:
786
+ yield 0, line
787
+
788
+ def _wrap_div(self, inner):
789
+ style = []
790
+ if (self.noclasses and not self.nobackground and
791
+ self.style.background_color is not None):
792
+ style.append(f'background: {self.style.background_color}')
793
+ if self.cssstyles:
794
+ style.append(self.cssstyles)
795
+ style = '; '.join(style)
796
+
797
+ yield 0, ('<div' + (self.cssclass and f' class="{self.cssclass}"') +
798
+ (style and (f' style="{style}"')) + '>')
799
+ yield from inner
800
+ yield 0, '</div>\n'
801
+
802
+ def _wrap_pre(self, inner):
803
+ style = []
804
+ if self.prestyles:
805
+ style.append(self.prestyles)
806
+ if self.noclasses:
807
+ style.append(self._pre_style)
808
+ style = '; '.join(style)
809
+
810
+ if self.filename and self.linenos != 1:
811
+ yield 0, ('<span class="filename">' + self.filename + '</span>')
812
+
813
+ # the empty span here is to keep leading empty lines from being
814
+ # ignored by HTML parsers
815
+ yield 0, ('<pre' + (style and f' style="{style}"') + '><span></span>')
816
+ yield from inner
817
+ yield 0, '</pre>'
818
+
819
+ def _wrap_code(self, inner):
820
+ yield 0, '<code>'
821
+ yield from inner
822
+ yield 0, '</code>'
823
+
824
+ @functools.lru_cache(maxsize=100)
825
+ def _translate_parts(self, value):
826
+ """HTML-escape a value and split it by newlines."""
827
+ return value.translate(_escape_html_table).split('\n')
828
+
829
+ def _format_lines(self, tokensource):
830
+ """
831
+ Just format the tokens, without any wrapping tags.
832
+ Yield individual lines.
833
+ """
834
+ nocls = self.noclasses
835
+ lsep = self.lineseparator
836
+ tagsfile = self.tagsfile
837
+
838
+ lspan = ''
839
+ line = []
840
+ for ttype, value in tokensource:
841
+ try:
842
+ cspan = self.span_element_openers[ttype]
843
+ except KeyError:
844
+ title = ' title="{}"'.format('.'.join(ttype)) if self.debug_token_types else ''
845
+ if nocls:
846
+ css_style = self._get_css_inline_styles(ttype)
847
+ if css_style:
848
+ css_style = self.class2style[css_style][0]
849
+ cspan = f'<span style="{css_style}"{title}>'
850
+ else:
851
+ cspan = ''
852
+ else:
853
+ css_class = self._get_css_classes(ttype)
854
+ if css_class:
855
+ cspan = f'<span class="{css_class}"{title}>'
856
+ else:
857
+ cspan = ''
858
+ self.span_element_openers[ttype] = cspan
859
+
860
+ parts = self._translate_parts(value)
861
+
862
+ if tagsfile and ttype in Token.Name:
863
+ filename, linenumber = self._lookup_ctag(value)
864
+ if linenumber:
865
+ base, filename = os.path.split(filename)
866
+ if base:
867
+ base += '/'
868
+ filename, extension = os.path.splitext(filename)
869
+ url = self.tagurlformat % {'path': base, 'fname': filename,
870
+ 'fext': extension}
871
+ parts[0] = "<a href=\"%s#%s-%d\">%s" % \
872
+ (url, self.lineanchors, linenumber, parts[0])
873
+ parts[-1] = parts[-1] + "</a>"
874
+
875
+ # for all but the last line
876
+ for part in parts[:-1]:
877
+ if line:
878
+ # Also check for part being non-empty, so we avoid creating
879
+ # empty <span> tags
880
+ if lspan != cspan and part:
881
+ line.extend(((lspan and '</span>'), cspan, part,
882
+ (cspan and '</span>'), lsep))
883
+ else: # both are the same, or the current part was empty
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'].decode(), 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 = (f' style="background-color: {self.style.highlight_color}"')
929
+ yield 1, f'<span{style}>{value}</span>'
930
+ else:
931
+ yield 1, f'<span class="hll">{value}</span>'
932
+ else:
933
+ yield 1, value
934
+
935
+ def wrap(self, source):
936
+ """
937
+ Wrap the ``source``, which is a generator yielding
938
+ individual lines, in custom generators. See docstring
939
+ for `format`. Can be overridden.
940
+ """
941
+
942
+ output = source
943
+ if self.wrapcode:
944
+ output = self._wrap_code(output)
945
+
946
+ output = self._wrap_pre(output)
947
+
948
+ return output
949
+
950
+ def format_unencoded(self, tokensource, outfile):
951
+ """
952
+ The formatting process uses several nested generators; which of
953
+ them are used is determined by the user's options.
954
+
955
+ Each generator should take at least one argument, ``inner``,
956
+ and wrap the pieces of text generated by this.
957
+
958
+ Always yield 2-tuples: (code, text). If "code" is 1, the text
959
+ is part of the original tokensource being highlighted, if it's
960
+ 0, the text is some piece of wrapping. This makes it possible to
961
+ use several different wrappers that process the original source
962
+ linewise, e.g. line number generators.
963
+ """
964
+ source = self._format_lines(tokensource)
965
+
966
+ # As a special case, we wrap line numbers before line highlighting
967
+ # so the line numbers get wrapped in the highlighting tag.
968
+ if not self.nowrap and self.linenos == 2:
969
+ source = self._wrap_inlinelinenos(source)
970
+
971
+ if self.hl_lines:
972
+ source = self._highlight_lines(source)
973
+
974
+ if not self.nowrap:
975
+ if self.lineanchors:
976
+ source = self._wrap_lineanchors(source)
977
+ if self.linespans:
978
+ source = self._wrap_linespans(source)
979
+ source = self.wrap(source)
980
+ if self.linenos == 1:
981
+ source = self._wrap_tablelinenos(source)
982
+ source = self._wrap_div(source)
983
+ if self.full:
984
+ source = self._wrap_full(source, outfile)
985
+
986
+ for t, piece in source:
987
+ outfile.write(piece)
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/img.py ADDED
@@ -0,0 +1,685 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.img
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for Pixmap output.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+ import os
11
+ import sys
12
+
13
+ from pip._vendor.pygments.formatter import Formatter
14
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
15
+ get_choice_opt
16
+
17
+ import subprocess
18
+
19
+ # Import this carefully
20
+ try:
21
+ from PIL import Image, ImageDraw, ImageFont
22
+ pil_available = True
23
+ except ImportError:
24
+ pil_available = False
25
+
26
+ try:
27
+ import _winreg
28
+ except ImportError:
29
+ try:
30
+ import winreg as _winreg
31
+ except ImportError:
32
+ _winreg = None
33
+
34
+ __all__ = ['ImageFormatter', 'GifImageFormatter', 'JpgImageFormatter',
35
+ 'BmpImageFormatter']
36
+
37
+
38
+ # For some unknown reason every font calls it something different
39
+ STYLES = {
40
+ 'NORMAL': ['', 'Roman', 'Book', 'Normal', 'Regular', 'Medium'],
41
+ 'ITALIC': ['Oblique', 'Italic'],
42
+ 'BOLD': ['Bold'],
43
+ 'BOLDITALIC': ['Bold Oblique', 'Bold Italic'],
44
+ }
45
+
46
+ # A sane default for modern systems
47
+ DEFAULT_FONT_NAME_NIX = 'DejaVu Sans Mono'
48
+ DEFAULT_FONT_NAME_WIN = 'Courier New'
49
+ DEFAULT_FONT_NAME_MAC = 'Menlo'
50
+
51
+
52
+ class PilNotAvailable(ImportError):
53
+ """When Python imaging library is not available"""
54
+
55
+
56
+ class FontNotFound(Exception):
57
+ """When there are no usable fonts specified"""
58
+
59
+
60
+ class FontManager:
61
+ """
62
+ Manages a set of fonts: normal, italic, bold, etc...
63
+ """
64
+
65
+ def __init__(self, font_name, font_size=14):
66
+ self.font_name = font_name
67
+ self.font_size = font_size
68
+ self.fonts = {}
69
+ self.encoding = None
70
+ self.variable = False
71
+ if hasattr(font_name, 'read') or os.path.isfile(font_name):
72
+ font = ImageFont.truetype(font_name, self.font_size)
73
+ self.variable = True
74
+ for style in STYLES:
75
+ self.fonts[style] = font
76
+
77
+ return
78
+
79
+ if sys.platform.startswith('win'):
80
+ if not font_name:
81
+ self.font_name = DEFAULT_FONT_NAME_WIN
82
+ self._create_win()
83
+ elif sys.platform.startswith('darwin'):
84
+ if not font_name:
85
+ self.font_name = DEFAULT_FONT_NAME_MAC
86
+ self._create_mac()
87
+ else:
88
+ if not font_name:
89
+ self.font_name = DEFAULT_FONT_NAME_NIX
90
+ self._create_nix()
91
+
92
+ def _get_nix_font_path(self, name, style):
93
+ proc = subprocess.Popen(['fc-list', f"{name}:style={style}", 'file'],
94
+ stdout=subprocess.PIPE, stderr=None)
95
+ stdout, _ = proc.communicate()
96
+ if proc.returncode == 0:
97
+ lines = stdout.splitlines()
98
+ for line in lines:
99
+ if line.startswith(b'Fontconfig warning:'):
100
+ continue
101
+ path = line.decode().strip().strip(':')
102
+ if path:
103
+ return path
104
+ return None
105
+
106
+ def _create_nix(self):
107
+ for name in STYLES['NORMAL']:
108
+ path = self._get_nix_font_path(self.font_name, name)
109
+ if path is not None:
110
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
111
+ break
112
+ else:
113
+ raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
114
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
115
+ for stylename in STYLES[style]:
116
+ path = self._get_nix_font_path(self.font_name, stylename)
117
+ if path is not None:
118
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
119
+ break
120
+ else:
121
+ if style == 'BOLDITALIC':
122
+ self.fonts[style] = self.fonts['BOLD']
123
+ else:
124
+ self.fonts[style] = self.fonts['NORMAL']
125
+
126
+ def _get_mac_font_path(self, font_map, name, style):
127
+ return font_map.get((name + ' ' + style).strip().lower())
128
+
129
+ def _create_mac(self):
130
+ font_map = {}
131
+ for font_dir in (os.path.join(os.getenv("HOME"), 'Library/Fonts/'),
132
+ '/Library/Fonts/', '/System/Library/Fonts/'):
133
+ font_map.update(
134
+ (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))
135
+ for f in os.listdir(font_dir)
136
+ if f.lower().endswith(('ttf', 'ttc')))
137
+
138
+ for name in STYLES['NORMAL']:
139
+ path = self._get_mac_font_path(font_map, self.font_name, name)
140
+ if path is not None:
141
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
142
+ break
143
+ else:
144
+ raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
145
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
146
+ for stylename in STYLES[style]:
147
+ path = self._get_mac_font_path(font_map, self.font_name, stylename)
148
+ if path is not None:
149
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
150
+ break
151
+ else:
152
+ if style == 'BOLDITALIC':
153
+ self.fonts[style] = self.fonts['BOLD']
154
+ else:
155
+ self.fonts[style] = self.fonts['NORMAL']
156
+
157
+ def _lookup_win(self, key, basename, styles, fail=False):
158
+ for suffix in ('', ' (TrueType)'):
159
+ for style in styles:
160
+ try:
161
+ valname = '{}{}{}'.format(basename, style and ' '+style, suffix)
162
+ val, _ = _winreg.QueryValueEx(key, valname)
163
+ return val
164
+ except OSError:
165
+ continue
166
+ else:
167
+ if fail:
168
+ raise FontNotFound(f'Font {basename} ({styles[0]}) not found in registry')
169
+ return None
170
+
171
+ def _create_win(self):
172
+ lookuperror = None
173
+ keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
174
+ (_winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Fonts'),
175
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows NT\CurrentVersion\Fonts'),
176
+ (_winreg.HKEY_LOCAL_MACHINE, r'Software\Microsoft\Windows\CurrentVersion\Fonts') ]
177
+ for keyname in keynames:
178
+ try:
179
+ key = _winreg.OpenKey(*keyname)
180
+ try:
181
+ path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)
182
+ self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
183
+ for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
184
+ path = self._lookup_win(key, self.font_name, STYLES[style])
185
+ if path:
186
+ self.fonts[style] = ImageFont.truetype(path, self.font_size)
187
+ else:
188
+ if style == 'BOLDITALIC':
189
+ self.fonts[style] = self.fonts['BOLD']
190
+ else:
191
+ self.fonts[style] = self.fonts['NORMAL']
192
+ return
193
+ except FontNotFound as err:
194
+ lookuperror = err
195
+ finally:
196
+ _winreg.CloseKey(key)
197
+ except OSError:
198
+ pass
199
+ else:
200
+ # If we get here, we checked all registry keys and had no luck
201
+ # We can be in one of two situations now:
202
+ # * All key lookups failed. In this case lookuperror is None and we
203
+ # will raise a generic error
204
+ # * At least one lookup failed with a FontNotFound error. In this
205
+ # case, we will raise that as a more specific error
206
+ if lookuperror:
207
+ raise lookuperror
208
+ raise FontNotFound('Can\'t open Windows font registry key')
209
+
210
+ def get_char_size(self):
211
+ """
212
+ Get the character size.
213
+ """
214
+ return self.get_text_size('M')
215
+
216
+ def get_text_size(self, text):
217
+ """
218
+ Get the text size (width, height).
219
+ """
220
+ font = self.fonts['NORMAL']
221
+ if hasattr(font, 'getbbox'): # Pillow >= 9.2.0
222
+ return font.getbbox(text)[2:4]
223
+ else:
224
+ return font.getsize(text)
225
+
226
+ def get_font(self, bold, oblique):
227
+ """
228
+ Get the font based on bold and italic flags.
229
+ """
230
+ if bold and oblique:
231
+ if self.variable:
232
+ return self.get_style('BOLDITALIC')
233
+
234
+ return self.fonts['BOLDITALIC']
235
+ elif bold:
236
+ if self.variable:
237
+ return self.get_style('BOLD')
238
+
239
+ return self.fonts['BOLD']
240
+ elif oblique:
241
+ if self.variable:
242
+ return self.get_style('ITALIC')
243
+
244
+ return self.fonts['ITALIC']
245
+ else:
246
+ if self.variable:
247
+ return self.get_style('NORMAL')
248
+
249
+ return self.fonts['NORMAL']
250
+
251
+ def get_style(self, style):
252
+ """
253
+ Get the specified style of the font if it is a variable font.
254
+ If not found, return the normal font.
255
+ """
256
+ font = self.fonts[style]
257
+ for style_name in STYLES[style]:
258
+ try:
259
+ font.set_variation_by_name(style_name)
260
+ return font
261
+ except ValueError:
262
+ pass
263
+ except OSError:
264
+ return font
265
+
266
+ return font
267
+
268
+
269
+ class ImageFormatter(Formatter):
270
+ """
271
+ Create a PNG image from source code. This uses the Python Imaging Library to
272
+ generate a pixmap from the source code.
273
+
274
+ .. versionadded:: 0.10
275
+
276
+ Additional options accepted:
277
+
278
+ `image_format`
279
+ An image format to output to that is recognised by PIL, these include:
280
+
281
+ * "PNG" (default)
282
+ * "JPEG"
283
+ * "BMP"
284
+ * "GIF"
285
+
286
+ `line_pad`
287
+ The extra spacing (in pixels) between each line of text.
288
+
289
+ Default: 2
290
+
291
+ `font_name`
292
+ The font name to be used as the base font from which others, such as
293
+ bold and italic fonts will be generated. This really should be a
294
+ monospace font to look sane.
295
+ If a filename or a file-like object is specified, the user must
296
+ provide different styles of the font.
297
+
298
+ Default: "Courier New" on Windows, "Menlo" on Mac OS, and
299
+ "DejaVu Sans Mono" on \\*nix
300
+
301
+ `font_size`
302
+ The font size in points to be used.
303
+
304
+ Default: 14
305
+
306
+ `image_pad`
307
+ The padding, in pixels to be used at each edge of the resulting image.
308
+
309
+ Default: 10
310
+
311
+ `line_numbers`
312
+ Whether line numbers should be shown: True/False
313
+
314
+ Default: True
315
+
316
+ `line_number_start`
317
+ The line number of the first line.
318
+
319
+ Default: 1
320
+
321
+ `line_number_step`
322
+ The step used when printing line numbers.
323
+
324
+ Default: 1
325
+
326
+ `line_number_bg`
327
+ The background colour (in "#123456" format) of the line number bar, or
328
+ None to use the style background color.
329
+
330
+ Default: "#eed"
331
+
332
+ `line_number_fg`
333
+ The text color of the line numbers (in "#123456"-like format).
334
+
335
+ Default: "#886"
336
+
337
+ `line_number_chars`
338
+ The number of columns of line numbers allowable in the line number
339
+ margin.
340
+
341
+ Default: 2
342
+
343
+ `line_number_bold`
344
+ Whether line numbers will be bold: True/False
345
+
346
+ Default: False
347
+
348
+ `line_number_italic`
349
+ Whether line numbers will be italicized: True/False
350
+
351
+ Default: False
352
+
353
+ `line_number_separator`
354
+ Whether a line will be drawn between the line number area and the
355
+ source code area: True/False
356
+
357
+ Default: True
358
+
359
+ `line_number_pad`
360
+ The horizontal padding (in pixels) between the line number margin, and
361
+ the source code area.
362
+
363
+ Default: 6
364
+
365
+ `hl_lines`
366
+ Specify a list of lines to be highlighted.
367
+
368
+ .. versionadded:: 1.2
369
+
370
+ Default: empty list
371
+
372
+ `hl_color`
373
+ Specify the color for highlighting lines.
374
+
375
+ .. versionadded:: 1.2
376
+
377
+ Default: highlight color of the selected style
378
+ """
379
+
380
+ # Required by the pygments mapper
381
+ name = 'img'
382
+ aliases = ['img', 'IMG', 'png']
383
+ filenames = ['*.png']
384
+
385
+ unicodeoutput = False
386
+
387
+ default_image_format = 'png'
388
+
389
+ def __init__(self, **options):
390
+ """
391
+ See the class docstring for explanation of options.
392
+ """
393
+ if not pil_available:
394
+ raise PilNotAvailable(
395
+ 'Python Imaging Library is required for this formatter')
396
+ Formatter.__init__(self, **options)
397
+ self.encoding = 'latin1' # let pygments.format() do the right thing
398
+ # Read the style
399
+ self.styles = dict(self.style)
400
+ if self.style.background_color is None:
401
+ self.background_color = '#fff'
402
+ else:
403
+ self.background_color = self.style.background_color
404
+ # Image options
405
+ self.image_format = get_choice_opt(
406
+ options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
407
+ self.default_image_format, normcase=True)
408
+ self.image_pad = get_int_opt(options, 'image_pad', 10)
409
+ self.line_pad = get_int_opt(options, 'line_pad', 2)
410
+ # The fonts
411
+ fontsize = get_int_opt(options, 'font_size', 14)
412
+ self.fonts = FontManager(options.get('font_name', ''), fontsize)
413
+ self.fontw, self.fonth = self.fonts.get_char_size()
414
+ # Line number options
415
+ self.line_number_fg = options.get('line_number_fg', '#886')
416
+ self.line_number_bg = options.get('line_number_bg', '#eed')
417
+ self.line_number_chars = get_int_opt(options,
418
+ 'line_number_chars', 2)
419
+ self.line_number_bold = get_bool_opt(options,
420
+ 'line_number_bold', False)
421
+ self.line_number_italic = get_bool_opt(options,
422
+ 'line_number_italic', False)
423
+ self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
424
+ self.line_numbers = get_bool_opt(options, 'line_numbers', True)
425
+ self.line_number_separator = get_bool_opt(options,
426
+ 'line_number_separator', True)
427
+ self.line_number_step = get_int_opt(options, 'line_number_step', 1)
428
+ self.line_number_start = get_int_opt(options, 'line_number_start', 1)
429
+ if self.line_numbers:
430
+ self.line_number_width = (self.fontw * self.line_number_chars +
431
+ self.line_number_pad * 2)
432
+ else:
433
+ self.line_number_width = 0
434
+ self.hl_lines = []
435
+ hl_lines_str = get_list_opt(options, 'hl_lines', [])
436
+ for line in hl_lines_str:
437
+ try:
438
+ self.hl_lines.append(int(line))
439
+ except ValueError:
440
+ pass
441
+ self.hl_color = options.get('hl_color',
442
+ self.style.highlight_color) or '#f90'
443
+ self.drawables = []
444
+
445
+ def get_style_defs(self, arg=''):
446
+ raise NotImplementedError('The -S option is meaningless for the image '
447
+ 'formatter. Use -O style=<stylename> instead.')
448
+
449
+ def _get_line_height(self):
450
+ """
451
+ Get the height of a line.
452
+ """
453
+ return self.fonth + self.line_pad
454
+
455
+ def _get_line_y(self, lineno):
456
+ """
457
+ Get the Y coordinate of a line number.
458
+ """
459
+ return lineno * self._get_line_height() + self.image_pad
460
+
461
+ def _get_char_width(self):
462
+ """
463
+ Get the width of a character.
464
+ """
465
+ return self.fontw
466
+
467
+ def _get_char_x(self, linelength):
468
+ """
469
+ Get the X coordinate of a character position.
470
+ """
471
+ return linelength + self.image_pad + self.line_number_width
472
+
473
+ def _get_text_pos(self, linelength, lineno):
474
+ """
475
+ Get the actual position for a character and line position.
476
+ """
477
+ return self._get_char_x(linelength), self._get_line_y(lineno)
478
+
479
+ def _get_linenumber_pos(self, lineno):
480
+ """
481
+ Get the actual position for the start of a line number.
482
+ """
483
+ return (self.image_pad, self._get_line_y(lineno))
484
+
485
+ def _get_text_color(self, style):
486
+ """
487
+ Get the correct color for the token from the style.
488
+ """
489
+ if style['color'] is not None:
490
+ fill = '#' + style['color']
491
+ else:
492
+ fill = '#000'
493
+ return fill
494
+
495
+ def _get_text_bg_color(self, style):
496
+ """
497
+ Get the correct background color for the token from the style.
498
+ """
499
+ if style['bgcolor'] is not None:
500
+ bg_color = '#' + style['bgcolor']
501
+ else:
502
+ bg_color = None
503
+ return bg_color
504
+
505
+ def _get_style_font(self, style):
506
+ """
507
+ Get the correct font for the style.
508
+ """
509
+ return self.fonts.get_font(style['bold'], style['italic'])
510
+
511
+ def _get_image_size(self, maxlinelength, maxlineno):
512
+ """
513
+ Get the required image size.
514
+ """
515
+ return (self._get_char_x(maxlinelength) + self.image_pad,
516
+ self._get_line_y(maxlineno + 0) + self.image_pad)
517
+
518
+ def _draw_linenumber(self, posno, lineno):
519
+ """
520
+ Remember a line number drawable to paint later.
521
+ """
522
+ self._draw_text(
523
+ self._get_linenumber_pos(posno),
524
+ str(lineno).rjust(self.line_number_chars),
525
+ font=self.fonts.get_font(self.line_number_bold,
526
+ self.line_number_italic),
527
+ text_fg=self.line_number_fg,
528
+ text_bg=None,
529
+ )
530
+
531
+ def _draw_text(self, pos, text, font, text_fg, text_bg):
532
+ """
533
+ Remember a single drawable tuple to paint later.
534
+ """
535
+ self.drawables.append((pos, text, font, text_fg, text_bg))
536
+
537
+ def _create_drawables(self, tokensource):
538
+ """
539
+ Create drawables for the token content.
540
+ """
541
+ lineno = charno = maxcharno = 0
542
+ maxlinelength = linelength = 0
543
+ for ttype, value in tokensource:
544
+ while ttype not in self.styles:
545
+ ttype = ttype.parent
546
+ style = self.styles[ttype]
547
+ # TODO: make sure tab expansion happens earlier in the chain. It
548
+ # really ought to be done on the input, as to do it right here is
549
+ # quite complex.
550
+ value = value.expandtabs(4)
551
+ lines = value.splitlines(True)
552
+ # print lines
553
+ for i, line in enumerate(lines):
554
+ temp = line.rstrip('\n')
555
+ if temp:
556
+ self._draw_text(
557
+ self._get_text_pos(linelength, lineno),
558
+ temp,
559
+ font = self._get_style_font(style),
560
+ text_fg = self._get_text_color(style),
561
+ text_bg = self._get_text_bg_color(style),
562
+ )
563
+ temp_width, _ = self.fonts.get_text_size(temp)
564
+ linelength += temp_width
565
+ maxlinelength = max(maxlinelength, linelength)
566
+ charno += len(temp)
567
+ maxcharno = max(maxcharno, charno)
568
+ if line.endswith('\n'):
569
+ # add a line for each extra line in the value
570
+ linelength = 0
571
+ charno = 0
572
+ lineno += 1
573
+ self.maxlinelength = maxlinelength
574
+ self.maxcharno = maxcharno
575
+ self.maxlineno = lineno
576
+
577
+ def _draw_line_numbers(self):
578
+ """
579
+ Create drawables for the line numbers.
580
+ """
581
+ if not self.line_numbers:
582
+ return
583
+ for p in range(self.maxlineno):
584
+ n = p + self.line_number_start
585
+ if (n % self.line_number_step) == 0:
586
+ self._draw_linenumber(p, n)
587
+
588
+ def _paint_line_number_bg(self, im):
589
+ """
590
+ Paint the line number background on the image.
591
+ """
592
+ if not self.line_numbers:
593
+ return
594
+ if self.line_number_fg is None:
595
+ return
596
+ draw = ImageDraw.Draw(im)
597
+ recth = im.size[-1]
598
+ rectw = self.image_pad + self.line_number_width - self.line_number_pad
599
+ draw.rectangle([(0, 0), (rectw, recth)],
600
+ fill=self.line_number_bg)
601
+ if self.line_number_separator:
602
+ draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)
603
+ del draw
604
+
605
+ def format(self, tokensource, outfile):
606
+ """
607
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
608
+ tuples and write it into ``outfile``.
609
+
610
+ This implementation calculates where it should draw each token on the
611
+ pixmap, then calculates the required pixmap size and draws the items.
612
+ """
613
+ self._create_drawables(tokensource)
614
+ self._draw_line_numbers()
615
+ im = Image.new(
616
+ 'RGB',
617
+ self._get_image_size(self.maxlinelength, self.maxlineno),
618
+ self.background_color
619
+ )
620
+ self._paint_line_number_bg(im)
621
+ draw = ImageDraw.Draw(im)
622
+ # Highlight
623
+ if self.hl_lines:
624
+ x = self.image_pad + self.line_number_width - self.line_number_pad + 1
625
+ recth = self._get_line_height()
626
+ rectw = im.size[0] - x
627
+ for linenumber in self.hl_lines:
628
+ y = self._get_line_y(linenumber - 1)
629
+ draw.rectangle([(x, y), (x + rectw, y + recth)],
630
+ fill=self.hl_color)
631
+ for pos, value, font, text_fg, text_bg in self.drawables:
632
+ if text_bg:
633
+ # see deprecations https://pillow.readthedocs.io/en/stable/releasenotes/9.2.0.html#font-size-and-offset-methods
634
+ if hasattr(draw, 'textsize'):
635
+ text_size = draw.textsize(text=value, font=font)
636
+ else:
637
+ text_size = font.getbbox(value)[2:]
638
+ draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)
639
+ draw.text(pos, value, font=font, fill=text_fg)
640
+ im.save(outfile, self.image_format.upper())
641
+
642
+
643
+ # Add one formatter per format, so that the "-f gif" option gives the correct result
644
+ # when used in pygmentize.
645
+
646
+ class GifImageFormatter(ImageFormatter):
647
+ """
648
+ Create a GIF image from source code. This uses the Python Imaging Library to
649
+ generate a pixmap from the source code.
650
+
651
+ .. versionadded:: 1.0
652
+ """
653
+
654
+ name = 'img_gif'
655
+ aliases = ['gif']
656
+ filenames = ['*.gif']
657
+ default_image_format = 'gif'
658
+
659
+
660
+ class JpgImageFormatter(ImageFormatter):
661
+ """
662
+ Create a JPEG image from source code. This uses the Python Imaging Library to
663
+ generate a pixmap from the source code.
664
+
665
+ .. versionadded:: 1.0
666
+ """
667
+
668
+ name = 'img_jpg'
669
+ aliases = ['jpg', 'jpeg']
670
+ filenames = ['*.jpg']
671
+ default_image_format = 'jpeg'
672
+
673
+
674
+ class BmpImageFormatter(ImageFormatter):
675
+ """
676
+ Create a bitmap image from source code. This uses the Python Imaging Library to
677
+ generate a pixmap from the source code.
678
+
679
+ .. versionadded:: 1.0
680
+ """
681
+
682
+ name = 'img_bmp'
683
+ aliases = ['bmp', 'bitmap']
684
+ filenames = ['*.bmp']
685
+ default_image_format = 'bmp'
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/irc.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.irc
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for IRC output
6
+
7
+ :copyright: Copyright 2006-2024 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
+ if self.linenos:
132
+ self._lineno += 1
133
+ outfile.write("%04d: " % self._lineno)
134
+
135
+ def format_unencoded(self, tokensource, outfile):
136
+ self._write_lineno(outfile)
137
+
138
+ for ttype, value in tokensource:
139
+ color = self.colorscheme.get(ttype)
140
+ while color is None:
141
+ ttype = ttype[:-1]
142
+ color = self.colorscheme.get(ttype)
143
+ if color:
144
+ color = color[self.darkbg]
145
+ spl = value.split('\n')
146
+ for line in spl[:-1]:
147
+ if line:
148
+ outfile.write(ircformat(color, line))
149
+ outfile.write('\n')
150
+ self._write_lineno(outfile)
151
+ if spl[-1]:
152
+ outfile.write(ircformat(color, spl[-1]))
153
+ else:
154
+ outfile.write(value)
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/latex.py ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.latex
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for LaTeX fancyvrb output.
6
+
7
+ :copyright: Copyright 2006-2024 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', rf'\{commandprefix}Zbs{{}}'). \
27
+ replace('\x01', rf'\{commandprefix}Zob{{}}'). \
28
+ replace('\x02', rf'\{commandprefix}Zcb{{}}'). \
29
+ replace('^', rf'\{commandprefix}Zca{{}}'). \
30
+ replace('_', rf'\{commandprefix}Zus{{}}'). \
31
+ replace('&', rf'\{commandprefix}Zam{{}}'). \
32
+ replace('<', rf'\{commandprefix}Zlt{{}}'). \
33
+ replace('>', rf'\{commandprefix}Zgt{{}}'). \
34
+ replace('#', rf'\{commandprefix}Zsh{{}}'). \
35
+ replace('%', rf'\{commandprefix}Zpc{{}}'). \
36
+ replace('$', rf'\{commandprefix}Zdl{{}}'). \
37
+ replace('-', rf'\{commandprefix}Zhy{{}}'). \
38
+ replace("'", rf'\{commandprefix}Zsq{{}}'). \
39
+ replace('"', rf'\{commandprefix}Zdq{{}}'). \
40
+ replace('~', rf'\{commandprefix}Zti{{}}')
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
+ Wrapping can be disabled using the `nowrap` option.
163
+
164
+ The special command used here (``\PY``) and all the other macros it needs
165
+ are output by the `get_style_defs` method.
166
+
167
+ With the `full` option, a complete LaTeX document is output, including
168
+ the command definitions in the preamble.
169
+
170
+ The `get_style_defs()` method of a `LatexFormatter` returns a string
171
+ containing ``\def`` commands defining the macros needed inside the
172
+ ``Verbatim`` environments.
173
+
174
+ Additional options accepted:
175
+
176
+ `nowrap`
177
+ If set to ``True``, don't wrap the tokens at all, not even inside a
178
+ ``\begin{Verbatim}`` environment. This disables most other options
179
+ (default: ``False``).
180
+
181
+ `style`
182
+ The style to use, can be a string or a Style subclass (default:
183
+ ``'default'``).
184
+
185
+ `full`
186
+ Tells the formatter to output a "full" document, i.e. a complete
187
+ self-contained document (default: ``False``).
188
+
189
+ `title`
190
+ If `full` is true, the title that should be used to caption the
191
+ document (default: ``''``).
192
+
193
+ `docclass`
194
+ If the `full` option is enabled, this is the document class to use
195
+ (default: ``'article'``).
196
+
197
+ `preamble`
198
+ If the `full` option is enabled, this can be further preamble commands,
199
+ e.g. ``\usepackage`` (default: ``''``).
200
+
201
+ `linenos`
202
+ If set to ``True``, output line numbers (default: ``False``).
203
+
204
+ `linenostart`
205
+ The line number for the first line (default: ``1``).
206
+
207
+ `linenostep`
208
+ If set to a number n > 1, only every nth line number is printed.
209
+
210
+ `verboptions`
211
+ Additional options given to the Verbatim environment (see the *fancyvrb*
212
+ docs for possible values) (default: ``''``).
213
+
214
+ `commandprefix`
215
+ The LaTeX commands used to produce colored output are constructed
216
+ using this prefix and some letters (default: ``'PY'``).
217
+
218
+ .. versionadded:: 0.7
219
+ .. versionchanged:: 0.10
220
+ The default is now ``'PY'`` instead of ``'C'``.
221
+
222
+ `texcomments`
223
+ If set to ``True``, enables LaTeX comment lines. That is, LaTex markup
224
+ in comment tokens is not escaped so that LaTeX can render it (default:
225
+ ``False``).
226
+
227
+ .. versionadded:: 1.2
228
+
229
+ `mathescape`
230
+ If set to ``True``, enables LaTeX math mode escape in comments. That
231
+ is, ``'$...$'`` inside a comment will trigger math mode (default:
232
+ ``False``).
233
+
234
+ .. versionadded:: 1.2
235
+
236
+ `escapeinside`
237
+ If set to a string of length 2, enables escaping to LaTeX. Text
238
+ delimited by these 2 characters is read as LaTeX code and
239
+ typeset accordingly. It has no effect in string literals. It has
240
+ no effect in comments if `texcomments` or `mathescape` is
241
+ set. (default: ``''``).
242
+
243
+ .. versionadded:: 2.0
244
+
245
+ `envname`
246
+ Allows you to pick an alternative environment name replacing Verbatim.
247
+ The alternate environment still has to support Verbatim's option syntax.
248
+ (default: ``'Verbatim'``).
249
+
250
+ .. versionadded:: 2.0
251
+ """
252
+ name = 'LaTeX'
253
+ aliases = ['latex', 'tex']
254
+ filenames = ['*.tex']
255
+
256
+ def __init__(self, **options):
257
+ Formatter.__init__(self, **options)
258
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
259
+ self.docclass = options.get('docclass', 'article')
260
+ self.preamble = options.get('preamble', '')
261
+ self.linenos = get_bool_opt(options, 'linenos', False)
262
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
263
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
264
+ self.verboptions = options.get('verboptions', '')
265
+ self.nobackground = get_bool_opt(options, 'nobackground', False)
266
+ self.commandprefix = options.get('commandprefix', 'PY')
267
+ self.texcomments = get_bool_opt(options, 'texcomments', False)
268
+ self.mathescape = get_bool_opt(options, 'mathescape', False)
269
+ self.escapeinside = options.get('escapeinside', '')
270
+ if len(self.escapeinside) == 2:
271
+ self.left = self.escapeinside[0]
272
+ self.right = self.escapeinside[1]
273
+ else:
274
+ self.escapeinside = ''
275
+ self.envname = options.get('envname', 'Verbatim')
276
+
277
+ self._create_stylesheet()
278
+
279
+ def _create_stylesheet(self):
280
+ t2n = self.ttype2name = {Token: ''}
281
+ c2d = self.cmd2def = {}
282
+ cp = self.commandprefix
283
+
284
+ def rgbcolor(col):
285
+ if col:
286
+ return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)
287
+ for i in (0, 2, 4)])
288
+ else:
289
+ return '1,1,1'
290
+
291
+ for ttype, ndef in self.style:
292
+ name = _get_ttype_name(ttype)
293
+ cmndef = ''
294
+ if ndef['bold']:
295
+ cmndef += r'\let\$$@bf=\textbf'
296
+ if ndef['italic']:
297
+ cmndef += r'\let\$$@it=\textit'
298
+ if ndef['underline']:
299
+ cmndef += r'\let\$$@ul=\underline'
300
+ if ndef['roman']:
301
+ cmndef += r'\let\$$@ff=\textrm'
302
+ if ndef['sans']:
303
+ cmndef += r'\let\$$@ff=\textsf'
304
+ if ndef['mono']:
305
+ cmndef += r'\let\$$@ff=\textsf'
306
+ if ndef['color']:
307
+ cmndef += (r'\def\$$@tc##1{{\textcolor[rgb]{{{}}}{{##1}}}}'.format(rgbcolor(ndef['color'])))
308
+ if ndef['border']:
309
+ cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}'
310
+ r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']),
311
+ rgbcolor(ndef['bgcolor'])))
312
+ elif ndef['bgcolor']:
313
+ cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{0pt}}'
314
+ r'\colorbox[rgb]{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['bgcolor'])))
315
+ if cmndef == '':
316
+ continue
317
+ cmndef = cmndef.replace('$$', cp)
318
+ t2n[ttype] = name
319
+ c2d[name] = cmndef
320
+
321
+ def get_style_defs(self, arg=''):
322
+ """
323
+ Return the command sequences needed to define the commands
324
+ used to format text in the verbatim environment. ``arg`` is ignored.
325
+ """
326
+ cp = self.commandprefix
327
+ styles = []
328
+ for name, definition in self.cmd2def.items():
329
+ styles.append(rf'\@namedef{{{cp}@tok@{name}}}{{{definition}}}')
330
+ return STYLE_TEMPLATE % {'cp': self.commandprefix,
331
+ 'styles': '\n'.join(styles)}
332
+
333
+ def format_unencoded(self, tokensource, outfile):
334
+ # TODO: add support for background colors
335
+ t2n = self.ttype2name
336
+ cp = self.commandprefix
337
+
338
+ if self.full:
339
+ realoutfile = outfile
340
+ outfile = StringIO()
341
+
342
+ if not self.nowrap:
343
+ outfile.write('\\begin{' + self.envname + '}[commandchars=\\\\\\{\\}')
344
+ if self.linenos:
345
+ start, step = self.linenostart, self.linenostep
346
+ outfile.write(',numbers=left' +
347
+ (start and ',firstnumber=%d' % start or '') +
348
+ (step and ',stepnumber=%d' % step or ''))
349
+ if self.mathescape or self.texcomments or self.escapeinside:
350
+ outfile.write(',codes={\\catcode`\\$=3\\catcode`\\^=7'
351
+ '\\catcode`\\_=8\\relax}')
352
+ if self.verboptions:
353
+ outfile.write(',' + self.verboptions)
354
+ outfile.write(']\n')
355
+
356
+ for ttype, value in tokensource:
357
+ if ttype in Token.Comment:
358
+ if self.texcomments:
359
+ # Try to guess comment starting lexeme and escape it ...
360
+ start = value[0:1]
361
+ for i in range(1, len(value)):
362
+ if start[0] != value[i]:
363
+ break
364
+ start += value[i]
365
+
366
+ value = value[len(start):]
367
+ start = escape_tex(start, cp)
368
+
369
+ # ... but do not escape inside comment.
370
+ value = start + value
371
+ elif self.mathescape:
372
+ # Only escape parts not inside a math environment.
373
+ parts = value.split('$')
374
+ in_math = False
375
+ for i, part in enumerate(parts):
376
+ if not in_math:
377
+ parts[i] = escape_tex(part, cp)
378
+ in_math = not in_math
379
+ value = '$'.join(parts)
380
+ elif self.escapeinside:
381
+ text = value
382
+ value = ''
383
+ while text:
384
+ a, sep1, text = text.partition(self.left)
385
+ if sep1:
386
+ b, sep2, text = text.partition(self.right)
387
+ if sep2:
388
+ value += escape_tex(a, cp) + b
389
+ else:
390
+ value += escape_tex(a + sep1 + b, cp)
391
+ else:
392
+ value += escape_tex(a, cp)
393
+ else:
394
+ value = escape_tex(value, cp)
395
+ elif ttype not in Token.Escape:
396
+ value = escape_tex(value, cp)
397
+ styles = []
398
+ while ttype is not Token:
399
+ try:
400
+ styles.append(t2n[ttype])
401
+ except KeyError:
402
+ # not in current style
403
+ styles.append(_get_ttype_name(ttype))
404
+ ttype = ttype.parent
405
+ styleval = '+'.join(reversed(styles))
406
+ if styleval:
407
+ spl = value.split('\n')
408
+ for line in spl[:-1]:
409
+ if line:
410
+ outfile.write(f"\\{cp}{{{styleval}}}{{{line}}}")
411
+ outfile.write('\n')
412
+ if spl[-1]:
413
+ outfile.write(f"\\{cp}{{{styleval}}}{{{spl[-1]}}}")
414
+ else:
415
+ outfile.write(value)
416
+
417
+ if not self.nowrap:
418
+ outfile.write('\\end{' + self.envname + '}\n')
419
+
420
+ if self.full:
421
+ encoding = self.encoding or 'utf8'
422
+ # map known existings encodings from LaTeX distribution
423
+ encoding = {
424
+ 'utf_8': 'utf8',
425
+ 'latin_1': 'latin1',
426
+ 'iso_8859_1': 'latin1',
427
+ }.get(encoding.replace('-', '_'), encoding)
428
+ realoutfile.write(DOC_TEMPLATE %
429
+ dict(docclass = self.docclass,
430
+ preamble = self.preamble,
431
+ title = self.title,
432
+ encoding = encoding,
433
+ styledefs = self.get_style_defs(),
434
+ code = outfile.getvalue()))
435
+
436
+
437
+ class LatexEmbeddedLexer(Lexer):
438
+ """
439
+ This lexer takes one lexer as argument, the lexer for the language
440
+ being formatted, and the left and right delimiters for escaped text.
441
+
442
+ First everything is scanned using the language lexer to obtain
443
+ strings and comments. All other consecutive tokens are merged and
444
+ the resulting text is scanned for escaped segments, which are given
445
+ the Token.Escape type. Finally text that is not escaped is scanned
446
+ again with the language lexer.
447
+ """
448
+ def __init__(self, left, right, lang, **options):
449
+ self.left = left
450
+ self.right = right
451
+ self.lang = lang
452
+ Lexer.__init__(self, **options)
453
+
454
+ def get_tokens_unprocessed(self, text):
455
+ # find and remove all the escape tokens (replace with an empty string)
456
+ # this is very similar to DelegatingLexer.get_tokens_unprocessed.
457
+ buffered = ''
458
+ insertions = []
459
+ insertion_buf = []
460
+ for i, t, v in self._find_safe_escape_tokens(text):
461
+ if t is None:
462
+ if insertion_buf:
463
+ insertions.append((len(buffered), insertion_buf))
464
+ insertion_buf = []
465
+ buffered += v
466
+ else:
467
+ insertion_buf.append((i, t, v))
468
+ if insertion_buf:
469
+ insertions.append((len(buffered), insertion_buf))
470
+ return do_insertions(insertions,
471
+ self.lang.get_tokens_unprocessed(buffered))
472
+
473
+ def _find_safe_escape_tokens(self, text):
474
+ """ find escape tokens that are not in strings or comments """
475
+ for i, t, v in self._filter_to(
476
+ self.lang.get_tokens_unprocessed(text),
477
+ lambda t: t in Token.Comment or t in Token.String
478
+ ):
479
+ if t is None:
480
+ for i2, t2, v2 in self._find_escape_tokens(v):
481
+ yield i + i2, t2, v2
482
+ else:
483
+ yield i, None, v
484
+
485
+ def _filter_to(self, it, pred):
486
+ """ Keep only the tokens that match `pred`, merge the others together """
487
+ buf = ''
488
+ idx = 0
489
+ for i, t, v in it:
490
+ if pred(t):
491
+ if buf:
492
+ yield idx, None, buf
493
+ buf = ''
494
+ yield i, t, v
495
+ else:
496
+ if not buf:
497
+ idx = i
498
+ buf += v
499
+ if buf:
500
+ yield idx, None, buf
501
+
502
+ def _find_escape_tokens(self, text):
503
+ """ Find escape tokens within text, give token=None otherwise """
504
+ index = 0
505
+ while text:
506
+ a, sep1, text = text.partition(self.left)
507
+ if a:
508
+ yield index, None, a
509
+ index += len(a)
510
+ if sep1:
511
+ b, sep2, text = text.partition(self.right)
512
+ if sep2:
513
+ yield index + len(sep1), Token.Escape, b
514
+ index += len(sep1) + len(b) + len(sep2)
515
+ else:
516
+ yield index, Token.Error, sep1
517
+ index += len(sep1)
518
+ text = b
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/other.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.other
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Other formatters: NullFormatter, RawTokenFormatter.
6
+
7
+ :copyright: Copyright 2006-2024 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(f"Invalid color {self.error_color!r} specified")
78
+
79
+ def format(self, tokensource, outfile):
80
+ try:
81
+ outfile.write(b'')
82
+ except TypeError:
83
+ raise TypeError('The raw tokens formatter needs a binary '
84
+ 'output file')
85
+ if self.compress == 'gz':
86
+ import gzip
87
+ outfile = gzip.GzipFile('', 'wb', 9, outfile)
88
+
89
+ write = outfile.write
90
+ flush = outfile.close
91
+ elif self.compress == 'bz2':
92
+ import bz2
93
+ compressor = bz2.BZ2Compressor(9)
94
+
95
+ def write(text):
96
+ outfile.write(compressor.compress(text))
97
+
98
+ def flush():
99
+ outfile.write(compressor.flush())
100
+ outfile.flush()
101
+ else:
102
+ write = outfile.write
103
+ flush = outfile.flush
104
+
105
+ if self.error_color:
106
+ for ttype, value in tokensource:
107
+ line = b"%r\t%r\n" % (ttype, value)
108
+ if ttype is Token.Error:
109
+ write(colorize(self.error_color, line))
110
+ else:
111
+ write(line)
112
+ else:
113
+ for ttype, value in tokensource:
114
+ write(b"%r\t%r\n" % (ttype, value))
115
+ flush()
116
+
117
+
118
+ TESTCASE_BEFORE = '''\
119
+ def testNeedsName(lexer):
120
+ fragment = %r
121
+ tokens = [
122
+ '''
123
+ TESTCASE_AFTER = '''\
124
+ ]
125
+ assert list(lexer.get_tokens(fragment)) == tokens
126
+ '''
127
+
128
+
129
+ class TestcaseFormatter(Formatter):
130
+ """
131
+ Format tokens as appropriate for a new testcase.
132
+
133
+ .. versionadded:: 2.0
134
+ """
135
+ name = 'Testcase'
136
+ aliases = ['testcase']
137
+
138
+ def __init__(self, **options):
139
+ Formatter.__init__(self, **options)
140
+ if self.encoding is not None and self.encoding != 'utf-8':
141
+ raise ValueError("Only None and utf-8 are allowed encodings.")
142
+
143
+ def format(self, tokensource, outfile):
144
+ indentation = ' ' * 12
145
+ rawbuf = []
146
+ outbuf = []
147
+ for ttype, value in tokensource:
148
+ rawbuf.append(value)
149
+ outbuf.append(f'{indentation}({ttype}, {value!r}),\n')
150
+
151
+ before = TESTCASE_BEFORE % (''.join(rawbuf),)
152
+ during = ''.join(outbuf)
153
+ after = TESTCASE_AFTER
154
+ if self.encoding is None:
155
+ outfile.write(before + during + after)
156
+ else:
157
+ outfile.write(before.encode('utf-8'))
158
+ outfile.write(during.encode('utf-8'))
159
+ outfile.write(after.encode('utf-8'))
160
+ outfile.flush()
vllm/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-2024 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="#{}">'.format(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>')
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/rtf.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.rtf
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ A formatter that generates RTF files.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from collections import OrderedDict
12
+ from pip._vendor.pygments.formatter import Formatter
13
+ from pip._vendor.pygments.style import _ansimap
14
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, surrogatepair
15
+
16
+
17
+ __all__ = ['RtfFormatter']
18
+
19
+
20
+ class RtfFormatter(Formatter):
21
+ """
22
+ Format tokens as RTF markup. This formatter automatically outputs full RTF
23
+ documents with color information and other useful stuff. Perfect for Copy and
24
+ Paste into Microsoft(R) Word(R) documents.
25
+
26
+ Please note that ``encoding`` and ``outencoding`` options are ignored.
27
+ The RTF format is ASCII natively, but handles unicode characters correctly
28
+ thanks to escape sequences.
29
+
30
+ .. versionadded:: 0.6
31
+
32
+ Additional options accepted:
33
+
34
+ `style`
35
+ The style to use, can be a string or a Style subclass (default:
36
+ ``'default'``).
37
+
38
+ `fontface`
39
+ The used font family, for example ``Bitstream Vera Sans``. Defaults to
40
+ some generic font which is supposed to have fixed width.
41
+
42
+ `fontsize`
43
+ Size of the font used. Size is specified in half points. The
44
+ default is 24 half-points, giving a size 12 font.
45
+
46
+ .. versionadded:: 2.0
47
+
48
+ `linenos`
49
+ Turn on line numbering (default: ``False``).
50
+
51
+ .. versionadded:: 2.18
52
+
53
+ `lineno_fontsize`
54
+ Font size for line numbers. Size is specified in half points
55
+ (default: `fontsize`).
56
+
57
+ .. versionadded:: 2.18
58
+
59
+ `lineno_padding`
60
+ Number of spaces between the (inline) line numbers and the
61
+ source code (default: ``2``).
62
+
63
+ .. versionadded:: 2.18
64
+
65
+ `linenostart`
66
+ The line number for the first line (default: ``1``).
67
+
68
+ .. versionadded:: 2.18
69
+
70
+ `linenostep`
71
+ If set to a number n > 1, only every nth line number is printed.
72
+
73
+ .. versionadded:: 2.18
74
+
75
+ `lineno_color`
76
+ Color for line numbers specified as a hex triplet, e.g. ``'5e5e5e'``.
77
+ Defaults to the style's line number color if it is a hex triplet,
78
+ otherwise ansi bright black.
79
+
80
+ .. versionadded:: 2.18
81
+
82
+ `hl_lines`
83
+ Specify a list of lines to be highlighted, as line numbers separated by
84
+ spaces, e.g. ``'3 7 8'``. The line numbers are relative to the input
85
+ (i.e. the first line is line 1) unless `hl_linenostart` is set.
86
+
87
+ .. versionadded:: 2.18
88
+
89
+ `hl_color`
90
+ Color for highlighting the lines specified in `hl_lines`, specified as
91
+ a hex triplet (default: style's `highlight_color`).
92
+
93
+ .. versionadded:: 2.18
94
+
95
+ `hl_linenostart`
96
+ If set to ``True`` line numbers in `hl_lines` are specified
97
+ relative to `linenostart` (default ``False``).
98
+
99
+ .. versionadded:: 2.18
100
+ """
101
+ name = 'RTF'
102
+ aliases = ['rtf']
103
+ filenames = ['*.rtf']
104
+
105
+ def __init__(self, **options):
106
+ r"""
107
+ Additional options accepted:
108
+
109
+ ``fontface``
110
+ Name of the font used. Could for example be ``'Courier New'``
111
+ to further specify the default which is ``'\fmodern'``. The RTF
112
+ specification claims that ``\fmodern`` are "Fixed-pitch serif
113
+ and sans serif fonts". Hope every RTF implementation thinks
114
+ the same about modern...
115
+
116
+ """
117
+ Formatter.__init__(self, **options)
118
+ self.fontface = options.get('fontface') or ''
119
+ self.fontsize = get_int_opt(options, 'fontsize', 0)
120
+ self.linenos = get_bool_opt(options, 'linenos', False)
121
+ self.lineno_fontsize = get_int_opt(options, 'lineno_fontsize',
122
+ self.fontsize)
123
+ self.lineno_padding = get_int_opt(options, 'lineno_padding', 2)
124
+ self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
125
+ self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
126
+ self.hl_linenostart = get_bool_opt(options, 'hl_linenostart', False)
127
+
128
+ self.hl_color = options.get('hl_color', '')
129
+ if not self.hl_color:
130
+ self.hl_color = self.style.highlight_color
131
+
132
+ self.hl_lines = []
133
+ for lineno in get_list_opt(options, 'hl_lines', []):
134
+ try:
135
+ lineno = int(lineno)
136
+ if self.hl_linenostart:
137
+ lineno = lineno - self.linenostart + 1
138
+ self.hl_lines.append(lineno)
139
+ except ValueError:
140
+ pass
141
+
142
+ self.lineno_color = options.get('lineno_color', '')
143
+ if not self.lineno_color:
144
+ if self.style.line_number_color == 'inherit':
145
+ # style color is the css value 'inherit'
146
+ # default to ansi bright-black
147
+ self.lineno_color = _ansimap['ansibrightblack']
148
+ else:
149
+ # style color is assumed to be a hex triplet as other
150
+ # colors in pygments/style.py
151
+ self.lineno_color = self.style.line_number_color
152
+
153
+ self.color_mapping = self._create_color_mapping()
154
+
155
+ def _escape(self, text):
156
+ return text.replace('\\', '\\\\') \
157
+ .replace('{', '\\{') \
158
+ .replace('}', '\\}')
159
+
160
+ def _escape_text(self, text):
161
+ # empty strings, should give a small performance improvement
162
+ if not text:
163
+ return ''
164
+
165
+ # escape text
166
+ text = self._escape(text)
167
+
168
+ buf = []
169
+ for c in text:
170
+ cn = ord(c)
171
+ if cn < (2**7):
172
+ # ASCII character
173
+ buf.append(str(c))
174
+ elif (2**7) <= cn < (2**16):
175
+ # single unicode escape sequence
176
+ buf.append('{\\u%d}' % cn)
177
+ elif (2**16) <= cn:
178
+ # RTF limits unicode to 16 bits.
179
+ # Force surrogate pairs
180
+ buf.append('{\\u%d}{\\u%d}' % surrogatepair(cn))
181
+
182
+ return ''.join(buf).replace('\n', '\\par')
183
+
184
+ @staticmethod
185
+ def hex_to_rtf_color(hex_color):
186
+ if hex_color[0] == "#":
187
+ hex_color = hex_color[1:]
188
+
189
+ return '\\red%d\\green%d\\blue%d;' % (
190
+ int(hex_color[0:2], 16),
191
+ int(hex_color[2:4], 16),
192
+ int(hex_color[4:6], 16)
193
+ )
194
+
195
+ def _split_tokens_on_newlines(self, tokensource):
196
+ """
197
+ Split tokens containing newline characters into multiple token
198
+ each representing a line of the input file. Needed for numbering
199
+ lines of e.g. multiline comments.
200
+ """
201
+ for ttype, value in tokensource:
202
+ if value == '\n':
203
+ yield (ttype, value)
204
+ elif "\n" in value:
205
+ lines = value.split("\n")
206
+ for line in lines[:-1]:
207
+ yield (ttype, line+"\n")
208
+ if lines[-1]:
209
+ yield (ttype, lines[-1])
210
+ else:
211
+ yield (ttype, value)
212
+
213
+ def _create_color_mapping(self):
214
+ """
215
+ Create a mapping of style hex colors to index/offset in
216
+ the RTF color table.
217
+ """
218
+ color_mapping = OrderedDict()
219
+ offset = 1
220
+
221
+ if self.linenos:
222
+ color_mapping[self.lineno_color] = offset
223
+ offset += 1
224
+
225
+ if self.hl_lines:
226
+ color_mapping[self.hl_color] = offset
227
+ offset += 1
228
+
229
+ for _, style in self.style:
230
+ for color in style['color'], style['bgcolor'], style['border']:
231
+ if color and color not in color_mapping:
232
+ color_mapping[color] = offset
233
+ offset += 1
234
+
235
+ return color_mapping
236
+
237
+ @property
238
+ def _lineno_template(self):
239
+ if self.lineno_fontsize != self.fontsize:
240
+ return '{{\\fs{} \\cf{} %s{}}}'.format(self.lineno_fontsize,
241
+ self.color_mapping[self.lineno_color],
242
+ " " * self.lineno_padding)
243
+
244
+ return '{{\\cf{} %s{}}}'.format(self.color_mapping[self.lineno_color],
245
+ " " * self.lineno_padding)
246
+
247
+ @property
248
+ def _hl_open_str(self):
249
+ return rf'{{\highlight{self.color_mapping[self.hl_color]} '
250
+
251
+ @property
252
+ def _rtf_header(self):
253
+ lines = []
254
+ # rtf 1.8 header
255
+ lines.append('{\\rtf1\\ansi\\uc0\\deff0'
256
+ '{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset0%s;}}'
257
+ % (self.fontface and ' '
258
+ + self._escape(self.fontface) or ''))
259
+
260
+ # color table
261
+ lines.append('{\\colortbl;')
262
+ for color, _ in self.color_mapping.items():
263
+ lines.append(self.hex_to_rtf_color(color))
264
+ lines.append('}')
265
+
266
+ # font and fontsize
267
+ lines.append('\\f0\\sa0')
268
+ if self.fontsize:
269
+ lines.append('\\fs%d' % self.fontsize)
270
+
271
+ # ensure Libre Office Writer imports and renders consecutive
272
+ # space characters the same width, needed for line numbering.
273
+ # https://bugs.documentfoundation.org/show_bug.cgi?id=144050
274
+ lines.append('\\dntblnsbdb')
275
+
276
+ return lines
277
+
278
+ def format_unencoded(self, tokensource, outfile):
279
+ for line in self._rtf_header:
280
+ outfile.write(line + "\n")
281
+
282
+ tokensource = self._split_tokens_on_newlines(tokensource)
283
+
284
+ # first pass of tokens to count lines, needed for line numbering
285
+ if self.linenos:
286
+ line_count = 0
287
+ tokens = [] # for copying the token source generator
288
+ for ttype, value in tokensource:
289
+ tokens.append((ttype, value))
290
+ if value.endswith("\n"):
291
+ line_count += 1
292
+
293
+ # width of line number strings (for padding with spaces)
294
+ linenos_width = len(str(line_count+self.linenostart-1))
295
+
296
+ tokensource = tokens
297
+
298
+ # highlight stream
299
+ lineno = 1
300
+ start_new_line = True
301
+ for ttype, value in tokensource:
302
+ if start_new_line and lineno in self.hl_lines:
303
+ outfile.write(self._hl_open_str)
304
+
305
+ if start_new_line and self.linenos:
306
+ if (lineno-self.linenostart+1)%self.linenostep == 0:
307
+ current_lineno = lineno + self.linenostart - 1
308
+ lineno_str = str(current_lineno).rjust(linenos_width)
309
+ else:
310
+ lineno_str = "".rjust(linenos_width)
311
+ outfile.write(self._lineno_template % lineno_str)
312
+
313
+ while not self.style.styles_token(ttype) and ttype.parent:
314
+ ttype = ttype.parent
315
+ style = self.style.style_for_token(ttype)
316
+ buf = []
317
+ if style['bgcolor']:
318
+ buf.append('\\cb%d' % self.color_mapping[style['bgcolor']])
319
+ if style['color']:
320
+ buf.append('\\cf%d' % self.color_mapping[style['color']])
321
+ if style['bold']:
322
+ buf.append('\\b')
323
+ if style['italic']:
324
+ buf.append('\\i')
325
+ if style['underline']:
326
+ buf.append('\\ul')
327
+ if style['border']:
328
+ buf.append('\\chbrdr\\chcfpat%d' %
329
+ self.color_mapping[style['border']])
330
+ start = ''.join(buf)
331
+ if start:
332
+ outfile.write(f'{{{start} ')
333
+ outfile.write(self._escape_text(value))
334
+ if start:
335
+ outfile.write('}')
336
+ start_new_line = False
337
+
338
+ # complete line of input
339
+ if value.endswith("\n"):
340
+ # close line highlighting
341
+ if lineno in self.hl_lines:
342
+ outfile.write('}')
343
+ # newline in RTF file after closing }
344
+ outfile.write("\n")
345
+
346
+ start_new_line = True
347
+ lineno += 1
348
+
349
+ outfile.write('}\n')
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/svg.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.svg
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for SVG output.
6
+
7
+ :copyright: Copyright 2006-2024 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 Comment
13
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt
14
+
15
+ __all__ = ['SvgFormatter']
16
+
17
+
18
+ def escape_html(text):
19
+ """Escape &, <, > as well as single and double quotes for HTML."""
20
+ return text.replace('&', '&amp;'). \
21
+ replace('<', '&lt;'). \
22
+ replace('>', '&gt;'). \
23
+ replace('"', '&quot;'). \
24
+ replace("'", '&#39;')
25
+
26
+
27
+ class2style = {}
28
+
29
+ class SvgFormatter(Formatter):
30
+ """
31
+ Format tokens as an SVG graphics file. This formatter is still experimental.
32
+ Each line of code is a ``<text>`` element with explicit ``x`` and ``y``
33
+ coordinates containing ``<tspan>`` elements with the individual token styles.
34
+
35
+ By default, this formatter outputs a full SVG document including doctype
36
+ declaration and the ``<svg>`` root element.
37
+
38
+ .. versionadded:: 0.9
39
+
40
+ Additional options accepted:
41
+
42
+ `nowrap`
43
+ Don't wrap the SVG ``<text>`` elements in ``<svg><g>`` elements and
44
+ don't add a XML declaration and a doctype. If true, the `fontfamily`
45
+ and `fontsize` options are ignored. Defaults to ``False``.
46
+
47
+ `fontfamily`
48
+ The value to give the wrapping ``<g>`` element's ``font-family``
49
+ attribute, defaults to ``"monospace"``.
50
+
51
+ `fontsize`
52
+ The value to give the wrapping ``<g>`` element's ``font-size``
53
+ attribute, defaults to ``"14px"``.
54
+
55
+ `linenos`
56
+ If ``True``, add line numbers (default: ``False``).
57
+
58
+ `linenostart`
59
+ The line number for the first line (default: ``1``).
60
+
61
+ `linenostep`
62
+ If set to a number n > 1, only every nth line number is printed.
63
+
64
+ `linenowidth`
65
+ Maximum width devoted to line numbers (default: ``3*ystep``, sufficient
66
+ for up to 4-digit line numbers. Increase width for longer code blocks).
67
+
68
+ `xoffset`
69
+ Starting offset in X direction, defaults to ``0``.
70
+
71
+ `yoffset`
72
+ Starting offset in Y direction, defaults to the font size if it is given
73
+ in pixels, or ``20`` else. (This is necessary since text coordinates
74
+ refer to the text baseline, not the top edge.)
75
+
76
+ `ystep`
77
+ Offset to add to the Y coordinate for each subsequent line. This should
78
+ roughly be the text size plus 5. It defaults to that value if the text
79
+ size is given in pixels, or ``25`` else.
80
+
81
+ `spacehack`
82
+ Convert spaces in the source to ``&#160;``, which are non-breaking
83
+ spaces. SVG provides the ``xml:space`` attribute to control how
84
+ whitespace inside tags is handled, in theory, the ``preserve`` value
85
+ could be used to keep all whitespace as-is. However, many current SVG
86
+ viewers don't obey that rule, so this option is provided as a workaround
87
+ and defaults to ``True``.
88
+ """
89
+ name = 'SVG'
90
+ aliases = ['svg']
91
+ filenames = ['*.svg']
92
+
93
+ def __init__(self, **options):
94
+ Formatter.__init__(self, **options)
95
+ self.nowrap = get_bool_opt(options, 'nowrap', False)
96
+ self.fontfamily = options.get('fontfamily', 'monospace')
97
+ self.fontsize = options.get('fontsize', '14px')
98
+ self.xoffset = get_int_opt(options, 'xoffset', 0)
99
+ fs = self.fontsize.strip()
100
+ if fs.endswith('px'):
101
+ fs = fs[:-2].strip()
102
+ try:
103
+ int_fs = int(fs)
104
+ except ValueError:
105
+ int_fs = 20
106
+ self.yoffset = get_int_opt(options, 'yoffset', int_fs)
107
+ self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
108
+ self.spacehack = get_bool_opt(options, 'spacehack', True)
109
+ self.linenos = get_bool_opt(options,'linenos',False)
110
+ self.linenostart = get_int_opt(options,'linenostart',1)
111
+ self.linenostep = get_int_opt(options,'linenostep',1)
112
+ self.linenowidth = get_int_opt(options,'linenowidth', 3*self.ystep)
113
+ self._stylecache = {}
114
+
115
+ def format_unencoded(self, tokensource, outfile):
116
+ """
117
+ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``
118
+ tuples and write it into ``outfile``.
119
+
120
+ For our implementation we put all lines in their own 'line group'.
121
+ """
122
+ x = self.xoffset
123
+ y = self.yoffset
124
+ if not self.nowrap:
125
+ if self.encoding:
126
+ outfile.write(f'<?xml version="1.0" encoding="{self.encoding}"?>\n')
127
+ else:
128
+ outfile.write('<?xml version="1.0"?>\n')
129
+ outfile.write('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" '
130
+ '"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'
131
+ 'svg10.dtd">\n')
132
+ outfile.write('<svg xmlns="http://www.w3.org/2000/svg">\n')
133
+ outfile.write(f'<g font-family="{self.fontfamily}" font-size="{self.fontsize}">\n')
134
+
135
+ counter = self.linenostart
136
+ counter_step = self.linenostep
137
+ counter_style = self._get_style(Comment)
138
+ line_x = x
139
+
140
+ if self.linenos:
141
+ if counter % counter_step == 0:
142
+ outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" {counter_style} text-anchor="end">{counter}</text>')
143
+ line_x += self.linenowidth + self.ystep
144
+ counter += 1
145
+
146
+ outfile.write(f'<text x="{line_x}" y="{y}" xml:space="preserve">')
147
+ for ttype, value in tokensource:
148
+ style = self._get_style(ttype)
149
+ tspan = style and '<tspan' + style + '>' or ''
150
+ tspanend = tspan and '</tspan>' or ''
151
+ value = escape_html(value)
152
+ if self.spacehack:
153
+ value = value.expandtabs().replace(' ', '&#160;')
154
+ parts = value.split('\n')
155
+ for part in parts[:-1]:
156
+ outfile.write(tspan + part + tspanend)
157
+ y += self.ystep
158
+ outfile.write('</text>\n')
159
+ if self.linenos and counter % counter_step == 0:
160
+ outfile.write(f'<text x="{x+self.linenowidth}" y="{y}" text-anchor="end" {counter_style}>{counter}</text>')
161
+
162
+ counter += 1
163
+ outfile.write(f'<text x="{line_x}" y="{y}" ' 'xml:space="preserve">')
164
+ outfile.write(tspan + parts[-1] + tspanend)
165
+ outfile.write('</text>')
166
+
167
+ if not self.nowrap:
168
+ outfile.write('</g></svg>\n')
169
+
170
+ def _get_style(self, tokentype):
171
+ if tokentype in self._stylecache:
172
+ return self._stylecache[tokentype]
173
+ otokentype = tokentype
174
+ while not self.style.styles_token(tokentype):
175
+ tokentype = tokentype.parent
176
+ value = self.style.style_for_token(tokentype)
177
+ result = ''
178
+ if value['color']:
179
+ result = ' fill="#' + value['color'] + '"'
180
+ if value['bold']:
181
+ result += ' font-weight="bold"'
182
+ if value['italic']:
183
+ result += ' font-style="italic"'
184
+ self._stylecache[otokentype] = result
185
+ return result
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.terminal
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for terminal output with ANSI sequences.
6
+
7
+ :copyright: Copyright 2006-2024 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.console import ansiformat
15
+ from pip._vendor.pygments.util import get_choice_opt
16
+
17
+
18
+ __all__ = ['TerminalFormatter']
19
+
20
+
21
+ #: Map token types to a tuple of color values for light and dark
22
+ #: backgrounds.
23
+ TERMINAL_COLORS = {
24
+ Token: ('', ''),
25
+
26
+ Whitespace: ('gray', 'brightblack'),
27
+ Comment: ('gray', 'brightblack'),
28
+ Comment.Preproc: ('cyan', 'brightcyan'),
29
+ Keyword: ('blue', 'brightblue'),
30
+ Keyword.Type: ('cyan', 'brightcyan'),
31
+ Operator.Word: ('magenta', 'brightmagenta'),
32
+ Name.Builtin: ('cyan', 'brightcyan'),
33
+ Name.Function: ('green', 'brightgreen'),
34
+ Name.Namespace: ('_cyan_', '_brightcyan_'),
35
+ Name.Class: ('_green_', '_brightgreen_'),
36
+ Name.Exception: ('cyan', 'brightcyan'),
37
+ Name.Decorator: ('brightblack', 'gray'),
38
+ Name.Variable: ('red', 'brightred'),
39
+ Name.Constant: ('red', 'brightred'),
40
+ Name.Attribute: ('cyan', 'brightcyan'),
41
+ Name.Tag: ('brightblue', 'brightblue'),
42
+ String: ('yellow', 'yellow'),
43
+ Number: ('blue', 'brightblue'),
44
+
45
+ Generic.Deleted: ('brightred', 'brightred'),
46
+ Generic.Inserted: ('green', 'brightgreen'),
47
+ Generic.Heading: ('**', '**'),
48
+ Generic.Subheading: ('*magenta*', '*brightmagenta*'),
49
+ Generic.Prompt: ('**', '**'),
50
+ Generic.Error: ('brightred', 'brightred'),
51
+
52
+ Error: ('_brightred_', '_brightred_'),
53
+ }
54
+
55
+
56
+ class TerminalFormatter(Formatter):
57
+ r"""
58
+ Format tokens with ANSI color sequences, for output in a text console.
59
+ Color sequences are terminated at newlines, so that paging the output
60
+ works correctly.
61
+
62
+ The `get_style_defs()` method doesn't do anything special since there is
63
+ no support for common styles.
64
+
65
+ Options accepted:
66
+
67
+ `bg`
68
+ Set to ``"light"`` or ``"dark"`` depending on the terminal's background
69
+ (default: ``"light"``).
70
+
71
+ `colorscheme`
72
+ A dictionary mapping token types to (lightbg, darkbg) color names or
73
+ ``None`` (default: ``None`` = use builtin colorscheme).
74
+
75
+ `linenos`
76
+ Set to ``True`` to have line numbers on the terminal output as well
77
+ (default: ``False`` = no line numbers).
78
+ """
79
+ name = 'Terminal'
80
+ aliases = ['terminal', 'console']
81
+ filenames = []
82
+
83
+ def __init__(self, **options):
84
+ Formatter.__init__(self, **options)
85
+ self.darkbg = get_choice_opt(options, 'bg',
86
+ ['light', 'dark'], 'light') == 'dark'
87
+ self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
88
+ self.linenos = options.get('linenos', False)
89
+ self._lineno = 0
90
+
91
+ def format(self, tokensource, outfile):
92
+ return Formatter.format(self, tokensource, outfile)
93
+
94
+ def _write_lineno(self, outfile):
95
+ self._lineno += 1
96
+ outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno))
97
+
98
+ def _get_color(self, ttype):
99
+ # self.colorscheme is a dict containing usually generic types, so we
100
+ # have to walk the tree of dots. The base Token type must be a key,
101
+ # even if it's empty string, as in the default above.
102
+ colors = self.colorscheme.get(ttype)
103
+ while colors is None:
104
+ ttype = ttype.parent
105
+ colors = self.colorscheme.get(ttype)
106
+ return colors[self.darkbg]
107
+
108
+ def format_unencoded(self, tokensource, outfile):
109
+ if self.linenos:
110
+ self._write_lineno(outfile)
111
+
112
+ for ttype, value in tokensource:
113
+ color = self._get_color(ttype)
114
+
115
+ for line in value.splitlines(True):
116
+ if color:
117
+ outfile.write(ansiformat(color, line.rstrip('\n')))
118
+ else:
119
+ outfile.write(line.rstrip('\n'))
120
+ if line.endswith('\n'):
121
+ if self.linenos:
122
+ self._write_lineno(outfile)
123
+ else:
124
+ outfile.write('\n')
125
+
126
+ if self.linenos:
127
+ outfile.write("\n")
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/formatters/terminal256.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.formatters.terminal256
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Formatter for 256-color terminal output with ANSI sequences.
6
+
7
+ RGB-to-XTERM color conversion routines adapted from xterm256-conv
8
+ tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
9
+ by Wolfgang Frisch.
10
+
11
+ Formatter version 1.
12
+
13
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
14
+ :license: BSD, see LICENSE for details.
15
+ """
16
+
17
+ # TODO:
18
+ # - Options to map style's bold/underline/italic/border attributes
19
+ # to some ANSI attrbutes (something like 'italic=underline')
20
+ # - An option to output "style RGB to xterm RGB/index" conversion table
21
+ # - An option to indicate that we are running in "reverse background"
22
+ # xterm. This means that default colors are white-on-black, not
23
+ # black-on-while, so colors like "white background" need to be converted
24
+ # to "white background, black foreground", etc...
25
+
26
+ from pip._vendor.pygments.formatter import Formatter
27
+ from pip._vendor.pygments.console import codes
28
+ from pip._vendor.pygments.style import ansicolors
29
+
30
+
31
+ __all__ = ['Terminal256Formatter', 'TerminalTrueColorFormatter']
32
+
33
+
34
+ class EscapeSequence:
35
+ def __init__(self, fg=None, bg=None, bold=False, underline=False, italic=False):
36
+ self.fg = fg
37
+ self.bg = bg
38
+ self.bold = bold
39
+ self.underline = underline
40
+ self.italic = italic
41
+
42
+ def escape(self, attrs):
43
+ if len(attrs):
44
+ return "\x1b[" + ";".join(attrs) + "m"
45
+ return ""
46
+
47
+ def color_string(self):
48
+ attrs = []
49
+ if self.fg is not None:
50
+ if self.fg in ansicolors:
51
+ esc = codes[self.fg.replace('ansi','')]
52
+ if ';01m' in esc:
53
+ self.bold = True
54
+ # extract fg color code.
55
+ attrs.append(esc[2:4])
56
+ else:
57
+ attrs.extend(("38", "5", "%i" % self.fg))
58
+ if self.bg is not None:
59
+ if self.bg in ansicolors:
60
+ esc = codes[self.bg.replace('ansi','')]
61
+ # extract fg color code, add 10 for bg.
62
+ attrs.append(str(int(esc[2:4])+10))
63
+ else:
64
+ attrs.extend(("48", "5", "%i" % self.bg))
65
+ if self.bold:
66
+ attrs.append("01")
67
+ if self.underline:
68
+ attrs.append("04")
69
+ if self.italic:
70
+ attrs.append("03")
71
+ return self.escape(attrs)
72
+
73
+ def true_color_string(self):
74
+ attrs = []
75
+ if self.fg:
76
+ attrs.extend(("38", "2", str(self.fg[0]), str(self.fg[1]), str(self.fg[2])))
77
+ if self.bg:
78
+ attrs.extend(("48", "2", str(self.bg[0]), str(self.bg[1]), str(self.bg[2])))
79
+ if self.bold:
80
+ attrs.append("01")
81
+ if self.underline:
82
+ attrs.append("04")
83
+ if self.italic:
84
+ attrs.append("03")
85
+ return self.escape(attrs)
86
+
87
+ def reset_string(self):
88
+ attrs = []
89
+ if self.fg is not None:
90
+ attrs.append("39")
91
+ if self.bg is not None:
92
+ attrs.append("49")
93
+ if self.bold or self.underline or self.italic:
94
+ attrs.append("00")
95
+ return self.escape(attrs)
96
+
97
+
98
+ class Terminal256Formatter(Formatter):
99
+ """
100
+ Format tokens with ANSI color sequences, for output in a 256-color
101
+ terminal or console. Like in `TerminalFormatter` color sequences
102
+ are terminated at newlines, so that paging the output works correctly.
103
+
104
+ The formatter takes colors from a style defined by the `style` option
105
+ and converts them to nearest ANSI 256-color escape sequences. Bold and
106
+ underline attributes from the style are preserved (and displayed).
107
+
108
+ .. versionadded:: 0.9
109
+
110
+ .. versionchanged:: 2.2
111
+ If the used style defines foreground colors in the form ``#ansi*``, then
112
+ `Terminal256Formatter` will map these to non extended foreground color.
113
+ See :ref:`AnsiTerminalStyle` for more information.
114
+
115
+ .. versionchanged:: 2.4
116
+ The ANSI color names have been updated with names that are easier to
117
+ understand and align with colornames of other projects and terminals.
118
+ See :ref:`this table <new-ansi-color-names>` for more information.
119
+
120
+
121
+ Options accepted:
122
+
123
+ `style`
124
+ The style to use, can be a string or a Style subclass (default:
125
+ ``'default'``).
126
+
127
+ `linenos`
128
+ Set to ``True`` to have line numbers on the terminal output as well
129
+ (default: ``False`` = no line numbers).
130
+ """
131
+ name = 'Terminal256'
132
+ aliases = ['terminal256', 'console256', '256']
133
+ filenames = []
134
+
135
+ def __init__(self, **options):
136
+ Formatter.__init__(self, **options)
137
+
138
+ self.xterm_colors = []
139
+ self.best_match = {}
140
+ self.style_string = {}
141
+
142
+ self.usebold = 'nobold' not in options
143
+ self.useunderline = 'nounderline' not in options
144
+ self.useitalic = 'noitalic' not in options
145
+
146
+ self._build_color_table() # build an RGB-to-256 color conversion table
147
+ self._setup_styles() # convert selected style's colors to term. colors
148
+
149
+ self.linenos = options.get('linenos', False)
150
+ self._lineno = 0
151
+
152
+ def _build_color_table(self):
153
+ # colors 0..15: 16 basic colors
154
+
155
+ self.xterm_colors.append((0x00, 0x00, 0x00)) # 0
156
+ self.xterm_colors.append((0xcd, 0x00, 0x00)) # 1
157
+ self.xterm_colors.append((0x00, 0xcd, 0x00)) # 2
158
+ self.xterm_colors.append((0xcd, 0xcd, 0x00)) # 3
159
+ self.xterm_colors.append((0x00, 0x00, 0xee)) # 4
160
+ self.xterm_colors.append((0xcd, 0x00, 0xcd)) # 5
161
+ self.xterm_colors.append((0x00, 0xcd, 0xcd)) # 6
162
+ self.xterm_colors.append((0xe5, 0xe5, 0xe5)) # 7
163
+ self.xterm_colors.append((0x7f, 0x7f, 0x7f)) # 8
164
+ self.xterm_colors.append((0xff, 0x00, 0x00)) # 9
165
+ self.xterm_colors.append((0x00, 0xff, 0x00)) # 10
166
+ self.xterm_colors.append((0xff, 0xff, 0x00)) # 11
167
+ self.xterm_colors.append((0x5c, 0x5c, 0xff)) # 12
168
+ self.xterm_colors.append((0xff, 0x00, 0xff)) # 13
169
+ self.xterm_colors.append((0x00, 0xff, 0xff)) # 14
170
+ self.xterm_colors.append((0xff, 0xff, 0xff)) # 15
171
+
172
+ # colors 16..232: the 6x6x6 color cube
173
+
174
+ valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)
175
+
176
+ for i in range(217):
177
+ r = valuerange[(i // 36) % 6]
178
+ g = valuerange[(i // 6) % 6]
179
+ b = valuerange[i % 6]
180
+ self.xterm_colors.append((r, g, b))
181
+
182
+ # colors 233..253: grayscale
183
+
184
+ for i in range(1, 22):
185
+ v = 8 + i * 10
186
+ self.xterm_colors.append((v, v, v))
187
+
188
+ def _closest_color(self, r, g, b):
189
+ distance = 257*257*3 # "infinity" (>distance from #000000 to #ffffff)
190
+ match = 0
191
+
192
+ for i in range(0, 254):
193
+ values = self.xterm_colors[i]
194
+
195
+ rd = r - values[0]
196
+ gd = g - values[1]
197
+ bd = b - values[2]
198
+ d = rd*rd + gd*gd + bd*bd
199
+
200
+ if d < distance:
201
+ match = i
202
+ distance = d
203
+ return match
204
+
205
+ def _color_index(self, color):
206
+ index = self.best_match.get(color, None)
207
+ if color in ansicolors:
208
+ # strip the `ansi/#ansi` part and look up code
209
+ index = color
210
+ self.best_match[color] = index
211
+ if index is None:
212
+ try:
213
+ rgb = int(str(color), 16)
214
+ except ValueError:
215
+ rgb = 0
216
+
217
+ r = (rgb >> 16) & 0xff
218
+ g = (rgb >> 8) & 0xff
219
+ b = rgb & 0xff
220
+ index = self._closest_color(r, g, b)
221
+ self.best_match[color] = index
222
+ return index
223
+
224
+ def _setup_styles(self):
225
+ for ttype, ndef in self.style:
226
+ escape = EscapeSequence()
227
+ # get foreground from ansicolor if set
228
+ if ndef['ansicolor']:
229
+ escape.fg = self._color_index(ndef['ansicolor'])
230
+ elif ndef['color']:
231
+ escape.fg = self._color_index(ndef['color'])
232
+ if ndef['bgansicolor']:
233
+ escape.bg = self._color_index(ndef['bgansicolor'])
234
+ elif ndef['bgcolor']:
235
+ escape.bg = self._color_index(ndef['bgcolor'])
236
+ if self.usebold and ndef['bold']:
237
+ escape.bold = True
238
+ if self.useunderline and ndef['underline']:
239
+ escape.underline = True
240
+ if self.useitalic and ndef['italic']:
241
+ escape.italic = True
242
+ self.style_string[str(ttype)] = (escape.color_string(),
243
+ escape.reset_string())
244
+
245
+ def _write_lineno(self, outfile):
246
+ self._lineno += 1
247
+ outfile.write("%s%04d: " % (self._lineno != 1 and '\n' or '', self._lineno))
248
+
249
+ def format(self, tokensource, outfile):
250
+ return Formatter.format(self, tokensource, outfile)
251
+
252
+ def format_unencoded(self, tokensource, outfile):
253
+ if self.linenos:
254
+ self._write_lineno(outfile)
255
+
256
+ for ttype, value in tokensource:
257
+ not_found = True
258
+ while ttype and not_found:
259
+ try:
260
+ # outfile.write( "<" + str(ttype) + ">" )
261
+ on, off = self.style_string[str(ttype)]
262
+
263
+ # Like TerminalFormatter, add "reset colors" escape sequence
264
+ # on newline.
265
+ spl = value.split('\n')
266
+ for line in spl[:-1]:
267
+ if line:
268
+ outfile.write(on + line + off)
269
+ if self.linenos:
270
+ self._write_lineno(outfile)
271
+ else:
272
+ outfile.write('\n')
273
+
274
+ if spl[-1]:
275
+ outfile.write(on + spl[-1] + off)
276
+
277
+ not_found = False
278
+ # outfile.write( '#' + str(ttype) + '#' )
279
+
280
+ except KeyError:
281
+ # ottype = ttype
282
+ ttype = ttype.parent
283
+ # outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )
284
+
285
+ if not_found:
286
+ outfile.write(value)
287
+
288
+ if self.linenos:
289
+ outfile.write("\n")
290
+
291
+
292
+
293
+ class TerminalTrueColorFormatter(Terminal256Formatter):
294
+ r"""
295
+ Format tokens with ANSI color sequences, for output in a true-color
296
+ terminal or console. Like in `TerminalFormatter` color sequences
297
+ are terminated at newlines, so that paging the output works correctly.
298
+
299
+ .. versionadded:: 2.1
300
+
301
+ Options accepted:
302
+
303
+ `style`
304
+ The style to use, can be a string or a Style subclass (default:
305
+ ``'default'``).
306
+ """
307
+ name = 'TerminalTrueColor'
308
+ aliases = ['terminal16m', 'console16m', '16m']
309
+ filenames = []
310
+
311
+ def _build_color_table(self):
312
+ pass
313
+
314
+ def _color_tuple(self, color):
315
+ try:
316
+ rgb = int(str(color), 16)
317
+ except ValueError:
318
+ return None
319
+ r = (rgb >> 16) & 0xff
320
+ g = (rgb >> 8) & 0xff
321
+ b = rgb & 0xff
322
+ return (r, g, b)
323
+
324
+ def _setup_styles(self):
325
+ for ttype, ndef in self.style:
326
+ escape = EscapeSequence()
327
+ if ndef['color']:
328
+ escape.fg = self._color_tuple(ndef['color'])
329
+ if ndef['bgcolor']:
330
+ escape.bg = self._color_tuple(ndef['bgcolor'])
331
+ if self.usebold and ndef['bold']:
332
+ escape.bold = True
333
+ if self.useunderline and ndef['underline']:
334
+ escape.underline = True
335
+ if self.useitalic and ndef['italic']:
336
+ escape.italic = True
337
+ self.style_string[str(ttype)] = (escape.true_color_string(),
338
+ escape.reset_string())
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexer.py ADDED
@@ -0,0 +1,963 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexer
3
+ ~~~~~~~~~~~~~~
4
+
5
+ Base lexer classes.
6
+
7
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+ import sys
13
+ import time
14
+
15
+ from pip._vendor.pygments.filter import apply_filters, Filter
16
+ from pip._vendor.pygments.filters import get_filter_by_name
17
+ from pip._vendor.pygments.token import Error, Text, Other, Whitespace, _TokenType
18
+ from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
19
+ make_analysator, Future, guess_decode
20
+ from pip._vendor.pygments.regexopt import regex_opt
21
+
22
+ __all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer',
23
+ 'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this',
24
+ 'default', 'words', 'line_re']
25
+
26
+ line_re = re.compile('.*?\n')
27
+
28
+ _encoding_map = [(b'\xef\xbb\xbf', 'utf-8'),
29
+ (b'\xff\xfe\0\0', 'utf-32'),
30
+ (b'\0\0\xfe\xff', 'utf-32be'),
31
+ (b'\xff\xfe', 'utf-16'),
32
+ (b'\xfe\xff', 'utf-16be')]
33
+
34
+ _default_analyse = staticmethod(lambda x: 0.0)
35
+
36
+
37
+ class LexerMeta(type):
38
+ """
39
+ This metaclass automagically converts ``analyse_text`` methods into
40
+ static methods which always return float values.
41
+ """
42
+
43
+ def __new__(mcs, name, bases, d):
44
+ if 'analyse_text' in d:
45
+ d['analyse_text'] = make_analysator(d['analyse_text'])
46
+ return type.__new__(mcs, name, bases, d)
47
+
48
+
49
+ class Lexer(metaclass=LexerMeta):
50
+ """
51
+ Lexer for a specific language.
52
+
53
+ See also :doc:`lexerdevelopment`, a high-level guide to writing
54
+ lexers.
55
+
56
+ Lexer classes have attributes used for choosing the most appropriate
57
+ lexer based on various criteria.
58
+
59
+ .. autoattribute:: name
60
+ :no-value:
61
+ .. autoattribute:: aliases
62
+ :no-value:
63
+ .. autoattribute:: filenames
64
+ :no-value:
65
+ .. autoattribute:: alias_filenames
66
+ .. autoattribute:: mimetypes
67
+ :no-value:
68
+ .. autoattribute:: priority
69
+
70
+ Lexers included in Pygments should have two additional attributes:
71
+
72
+ .. autoattribute:: url
73
+ :no-value:
74
+ .. autoattribute:: version_added
75
+ :no-value:
76
+
77
+ Lexers included in Pygments may have additional attributes:
78
+
79
+ .. autoattribute:: _example
80
+ :no-value:
81
+
82
+ You can pass options to the constructor. The basic options recognized
83
+ by all lexers and processed by the base `Lexer` class are:
84
+
85
+ ``stripnl``
86
+ Strip leading and trailing newlines from the input (default: True).
87
+ ``stripall``
88
+ Strip all leading and trailing whitespace from the input
89
+ (default: False).
90
+ ``ensurenl``
91
+ Make sure that the input ends with a newline (default: True). This
92
+ is required for some lexers that consume input linewise.
93
+
94
+ .. versionadded:: 1.3
95
+
96
+ ``tabsize``
97
+ If given and greater than 0, expand tabs in the input (default: 0).
98
+ ``encoding``
99
+ If given, must be an encoding name. This encoding will be used to
100
+ convert the input string to Unicode, if it is not already a Unicode
101
+ string (default: ``'guess'``, which uses a simple UTF-8 / Locale /
102
+ Latin1 detection. Can also be ``'chardet'`` to use the chardet
103
+ library, if it is installed.
104
+ ``inencoding``
105
+ Overrides the ``encoding`` if given.
106
+ """
107
+
108
+ #: Full name of the lexer, in human-readable form
109
+ name = None
110
+
111
+ #: A list of short, unique identifiers that can be used to look
112
+ #: up the lexer from a list, e.g., using `get_lexer_by_name()`.
113
+ aliases = []
114
+
115
+ #: A list of `fnmatch` patterns that match filenames which contain
116
+ #: content for this lexer. The patterns in this list should be unique among
117
+ #: all lexers.
118
+ filenames = []
119
+
120
+ #: A list of `fnmatch` patterns that match filenames which may or may not
121
+ #: contain content for this lexer. This list is used by the
122
+ #: :func:`.guess_lexer_for_filename()` function, to determine which lexers
123
+ #: are then included in guessing the correct one. That means that
124
+ #: e.g. every lexer for HTML and a template language should include
125
+ #: ``\*.html`` in this list.
126
+ alias_filenames = []
127
+
128
+ #: A list of MIME types for content that can be lexed with this lexer.
129
+ mimetypes = []
130
+
131
+ #: Priority, should multiple lexers match and no content is provided
132
+ priority = 0
133
+
134
+ #: URL of the language specification/definition. Used in the Pygments
135
+ #: documentation. Set to an empty string to disable.
136
+ url = None
137
+
138
+ #: Version of Pygments in which the lexer was added.
139
+ version_added = None
140
+
141
+ #: Example file name. Relative to the ``tests/examplefiles`` directory.
142
+ #: This is used by the documentation generator to show an example.
143
+ _example = None
144
+
145
+ def __init__(self, **options):
146
+ """
147
+ This constructor takes arbitrary options as keyword arguments.
148
+ Every subclass must first process its own options and then call
149
+ the `Lexer` constructor, since it processes the basic
150
+ options like `stripnl`.
151
+
152
+ An example looks like this:
153
+
154
+ .. sourcecode:: python
155
+
156
+ def __init__(self, **options):
157
+ self.compress = options.get('compress', '')
158
+ Lexer.__init__(self, **options)
159
+
160
+ As these options must all be specifiable as strings (due to the
161
+ command line usage), there are various utility functions
162
+ available to help with that, see `Utilities`_.
163
+ """
164
+ self.options = options
165
+ self.stripnl = get_bool_opt(options, 'stripnl', True)
166
+ self.stripall = get_bool_opt(options, 'stripall', False)
167
+ self.ensurenl = get_bool_opt(options, 'ensurenl', True)
168
+ self.tabsize = get_int_opt(options, 'tabsize', 0)
169
+ self.encoding = options.get('encoding', 'guess')
170
+ self.encoding = options.get('inencoding') or self.encoding
171
+ self.filters = []
172
+ for filter_ in get_list_opt(options, 'filters', ()):
173
+ self.add_filter(filter_)
174
+
175
+ def __repr__(self):
176
+ if self.options:
177
+ return f'<pygments.lexers.{self.__class__.__name__} with {self.options!r}>'
178
+ else:
179
+ return f'<pygments.lexers.{self.__class__.__name__}>'
180
+
181
+ def add_filter(self, filter_, **options):
182
+ """
183
+ Add a new stream filter to this lexer.
184
+ """
185
+ if not isinstance(filter_, Filter):
186
+ filter_ = get_filter_by_name(filter_, **options)
187
+ self.filters.append(filter_)
188
+
189
+ def analyse_text(text):
190
+ """
191
+ A static method which is called for lexer guessing.
192
+
193
+ It should analyse the text and return a float in the range
194
+ from ``0.0`` to ``1.0``. If it returns ``0.0``, the lexer
195
+ will not be selected as the most probable one, if it returns
196
+ ``1.0``, it will be selected immediately. This is used by
197
+ `guess_lexer`.
198
+
199
+ The `LexerMeta` metaclass automatically wraps this function so
200
+ that it works like a static method (no ``self`` or ``cls``
201
+ parameter) and the return value is automatically converted to
202
+ `float`. If the return value is an object that is boolean `False`
203
+ it's the same as if the return values was ``0.0``.
204
+ """
205
+
206
+ def _preprocess_lexer_input(self, text):
207
+ """Apply preprocessing such as decoding the input, removing BOM and normalizing newlines."""
208
+
209
+ if not isinstance(text, str):
210
+ if self.encoding == 'guess':
211
+ text, _ = guess_decode(text)
212
+ elif self.encoding == 'chardet':
213
+ try:
214
+ # pip vendoring note: this code is not reachable by pip,
215
+ # removed import of chardet to make it clear.
216
+ raise ImportError('chardet is not vendored by pip')
217
+ except ImportError as e:
218
+ raise ImportError('To enable chardet encoding guessing, '
219
+ 'please install the chardet library '
220
+ 'from http://chardet.feedparser.org/') from e
221
+ # check for BOM first
222
+ decoded = None
223
+ for bom, encoding in _encoding_map:
224
+ if text.startswith(bom):
225
+ decoded = text[len(bom):].decode(encoding, 'replace')
226
+ break
227
+ # no BOM found, so use chardet
228
+ if decoded is None:
229
+ enc = chardet.detect(text[:1024]) # Guess using first 1KB
230
+ decoded = text.decode(enc.get('encoding') or 'utf-8',
231
+ 'replace')
232
+ text = decoded
233
+ else:
234
+ text = text.decode(self.encoding)
235
+ if text.startswith('\ufeff'):
236
+ text = text[len('\ufeff'):]
237
+ else:
238
+ if text.startswith('\ufeff'):
239
+ text = text[len('\ufeff'):]
240
+
241
+ # text now *is* a unicode string
242
+ text = text.replace('\r\n', '\n')
243
+ text = text.replace('\r', '\n')
244
+ if self.stripall:
245
+ text = text.strip()
246
+ elif self.stripnl:
247
+ text = text.strip('\n')
248
+ if self.tabsize > 0:
249
+ text = text.expandtabs(self.tabsize)
250
+ if self.ensurenl and not text.endswith('\n'):
251
+ text += '\n'
252
+
253
+ return text
254
+
255
+ def get_tokens(self, text, unfiltered=False):
256
+ """
257
+ This method is the basic interface of a lexer. It is called by
258
+ the `highlight()` function. It must process the text and return an
259
+ iterable of ``(tokentype, value)`` pairs from `text`.
260
+
261
+ Normally, you don't need to override this method. The default
262
+ implementation processes the options recognized by all lexers
263
+ (`stripnl`, `stripall` and so on), and then yields all tokens
264
+ from `get_tokens_unprocessed()`, with the ``index`` dropped.
265
+
266
+ If `unfiltered` is set to `True`, the filtering mechanism is
267
+ bypassed even if filters are defined.
268
+ """
269
+ text = self._preprocess_lexer_input(text)
270
+
271
+ def streamer():
272
+ for _, t, v in self.get_tokens_unprocessed(text):
273
+ yield t, v
274
+ stream = streamer()
275
+ if not unfiltered:
276
+ stream = apply_filters(stream, self.filters, self)
277
+ return stream
278
+
279
+ def get_tokens_unprocessed(self, text):
280
+ """
281
+ This method should process the text and return an iterable of
282
+ ``(index, tokentype, value)`` tuples where ``index`` is the starting
283
+ position of the token within the input text.
284
+
285
+ It must be overridden by subclasses. It is recommended to
286
+ implement it as a generator to maximize effectiveness.
287
+ """
288
+ raise NotImplementedError
289
+
290
+
291
+ class DelegatingLexer(Lexer):
292
+ """
293
+ This lexer takes two lexer as arguments. A root lexer and
294
+ a language lexer. First everything is scanned using the language
295
+ lexer, afterwards all ``Other`` tokens are lexed using the root
296
+ lexer.
297
+
298
+ The lexers from the ``template`` lexer package use this base lexer.
299
+ """
300
+
301
+ def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options):
302
+ self.root_lexer = _root_lexer(**options)
303
+ self.language_lexer = _language_lexer(**options)
304
+ self.needle = _needle
305
+ Lexer.__init__(self, **options)
306
+
307
+ def get_tokens_unprocessed(self, text):
308
+ buffered = ''
309
+ insertions = []
310
+ lng_buffer = []
311
+ for i, t, v in self.language_lexer.get_tokens_unprocessed(text):
312
+ if t is self.needle:
313
+ if lng_buffer:
314
+ insertions.append((len(buffered), lng_buffer))
315
+ lng_buffer = []
316
+ buffered += v
317
+ else:
318
+ lng_buffer.append((i, t, v))
319
+ if lng_buffer:
320
+ insertions.append((len(buffered), lng_buffer))
321
+ return do_insertions(insertions,
322
+ self.root_lexer.get_tokens_unprocessed(buffered))
323
+
324
+
325
+ # ------------------------------------------------------------------------------
326
+ # RegexLexer and ExtendedRegexLexer
327
+ #
328
+
329
+
330
+ class include(str): # pylint: disable=invalid-name
331
+ """
332
+ Indicates that a state should include rules from another state.
333
+ """
334
+ pass
335
+
336
+
337
+ class _inherit:
338
+ """
339
+ Indicates the a state should inherit from its superclass.
340
+ """
341
+ def __repr__(self):
342
+ return 'inherit'
343
+
344
+ inherit = _inherit() # pylint: disable=invalid-name
345
+
346
+
347
+ class combined(tuple): # pylint: disable=invalid-name
348
+ """
349
+ Indicates a state combined from multiple states.
350
+ """
351
+
352
+ def __new__(cls, *args):
353
+ return tuple.__new__(cls, args)
354
+
355
+ def __init__(self, *args):
356
+ # tuple.__init__ doesn't do anything
357
+ pass
358
+
359
+
360
+ class _PseudoMatch:
361
+ """
362
+ A pseudo match object constructed from a string.
363
+ """
364
+
365
+ def __init__(self, start, text):
366
+ self._text = text
367
+ self._start = start
368
+
369
+ def start(self, arg=None):
370
+ return self._start
371
+
372
+ def end(self, arg=None):
373
+ return self._start + len(self._text)
374
+
375
+ def group(self, arg=None):
376
+ if arg:
377
+ raise IndexError('No such group')
378
+ return self._text
379
+
380
+ def groups(self):
381
+ return (self._text,)
382
+
383
+ def groupdict(self):
384
+ return {}
385
+
386
+
387
+ def bygroups(*args):
388
+ """
389
+ Callback that yields multiple actions for each group in the match.
390
+ """
391
+ def callback(lexer, match, ctx=None):
392
+ for i, action in enumerate(args):
393
+ if action is None:
394
+ continue
395
+ elif type(action) is _TokenType:
396
+ data = match.group(i + 1)
397
+ if data:
398
+ yield match.start(i + 1), action, data
399
+ else:
400
+ data = match.group(i + 1)
401
+ if data is not None:
402
+ if ctx:
403
+ ctx.pos = match.start(i + 1)
404
+ for item in action(lexer,
405
+ _PseudoMatch(match.start(i + 1), data), ctx):
406
+ if item:
407
+ yield item
408
+ if ctx:
409
+ ctx.pos = match.end()
410
+ return callback
411
+
412
+
413
+ class _This:
414
+ """
415
+ Special singleton used for indicating the caller class.
416
+ Used by ``using``.
417
+ """
418
+
419
+ this = _This()
420
+
421
+
422
+ def using(_other, **kwargs):
423
+ """
424
+ Callback that processes the match with a different lexer.
425
+
426
+ The keyword arguments are forwarded to the lexer, except `state` which
427
+ is handled separately.
428
+
429
+ `state` specifies the state that the new lexer will start in, and can
430
+ be an enumerable such as ('root', 'inline', 'string') or a simple
431
+ string which is assumed to be on top of the root state.
432
+
433
+ Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.
434
+ """
435
+ gt_kwargs = {}
436
+ if 'state' in kwargs:
437
+ s = kwargs.pop('state')
438
+ if isinstance(s, (list, tuple)):
439
+ gt_kwargs['stack'] = s
440
+ else:
441
+ gt_kwargs['stack'] = ('root', s)
442
+
443
+ if _other is this:
444
+ def callback(lexer, match, ctx=None):
445
+ # if keyword arguments are given the callback
446
+ # function has to create a new lexer instance
447
+ if kwargs:
448
+ # XXX: cache that somehow
449
+ kwargs.update(lexer.options)
450
+ lx = lexer.__class__(**kwargs)
451
+ else:
452
+ lx = lexer
453
+ s = match.start()
454
+ for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
455
+ yield i + s, t, v
456
+ if ctx:
457
+ ctx.pos = match.end()
458
+ else:
459
+ def callback(lexer, match, ctx=None):
460
+ # XXX: cache that somehow
461
+ kwargs.update(lexer.options)
462
+ lx = _other(**kwargs)
463
+
464
+ s = match.start()
465
+ for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
466
+ yield i + s, t, v
467
+ if ctx:
468
+ ctx.pos = match.end()
469
+ return callback
470
+
471
+
472
+ class default:
473
+ """
474
+ Indicates a state or state action (e.g. #pop) to apply.
475
+ For example default('#pop') is equivalent to ('', Token, '#pop')
476
+ Note that state tuples may be used as well.
477
+
478
+ .. versionadded:: 2.0
479
+ """
480
+ def __init__(self, state):
481
+ self.state = state
482
+
483
+
484
+ class words(Future):
485
+ """
486
+ Indicates a list of literal words that is transformed into an optimized
487
+ regex that matches any of the words.
488
+
489
+ .. versionadded:: 2.0
490
+ """
491
+ def __init__(self, words, prefix='', suffix=''):
492
+ self.words = words
493
+ self.prefix = prefix
494
+ self.suffix = suffix
495
+
496
+ def get(self):
497
+ return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)
498
+
499
+
500
+ class RegexLexerMeta(LexerMeta):
501
+ """
502
+ Metaclass for RegexLexer, creates the self._tokens attribute from
503
+ self.tokens on the first instantiation.
504
+ """
505
+
506
+ def _process_regex(cls, regex, rflags, state):
507
+ """Preprocess the regular expression component of a token definition."""
508
+ if isinstance(regex, Future):
509
+ regex = regex.get()
510
+ return re.compile(regex, rflags).match
511
+
512
+ def _process_token(cls, token):
513
+ """Preprocess the token component of a token definition."""
514
+ assert type(token) is _TokenType or callable(token), \
515
+ f'token type must be simple type or callable, not {token!r}'
516
+ return token
517
+
518
+ def _process_new_state(cls, new_state, unprocessed, processed):
519
+ """Preprocess the state transition action of a token definition."""
520
+ if isinstance(new_state, str):
521
+ # an existing state
522
+ if new_state == '#pop':
523
+ return -1
524
+ elif new_state in unprocessed:
525
+ return (new_state,)
526
+ elif new_state == '#push':
527
+ return new_state
528
+ elif new_state[:5] == '#pop:':
529
+ return -int(new_state[5:])
530
+ else:
531
+ assert False, f'unknown new state {new_state!r}'
532
+ elif isinstance(new_state, combined):
533
+ # combine a new state from existing ones
534
+ tmp_state = '_tmp_%d' % cls._tmpname
535
+ cls._tmpname += 1
536
+ itokens = []
537
+ for istate in new_state:
538
+ assert istate != new_state, f'circular state ref {istate!r}'
539
+ itokens.extend(cls._process_state(unprocessed,
540
+ processed, istate))
541
+ processed[tmp_state] = itokens
542
+ return (tmp_state,)
543
+ elif isinstance(new_state, tuple):
544
+ # push more than one state
545
+ for istate in new_state:
546
+ assert (istate in unprocessed or
547
+ istate in ('#pop', '#push')), \
548
+ 'unknown new state ' + istate
549
+ return new_state
550
+ else:
551
+ assert False, f'unknown new state def {new_state!r}'
552
+
553
+ def _process_state(cls, unprocessed, processed, state):
554
+ """Preprocess a single state definition."""
555
+ assert isinstance(state, str), f"wrong state name {state!r}"
556
+ assert state[0] != '#', f"invalid state name {state!r}"
557
+ if state in processed:
558
+ return processed[state]
559
+ tokens = processed[state] = []
560
+ rflags = cls.flags
561
+ for tdef in unprocessed[state]:
562
+ if isinstance(tdef, include):
563
+ # it's a state reference
564
+ assert tdef != state, f"circular state reference {state!r}"
565
+ tokens.extend(cls._process_state(unprocessed, processed,
566
+ str(tdef)))
567
+ continue
568
+ if isinstance(tdef, _inherit):
569
+ # should be processed already, but may not in the case of:
570
+ # 1. the state has no counterpart in any parent
571
+ # 2. the state includes more than one 'inherit'
572
+ continue
573
+ if isinstance(tdef, default):
574
+ new_state = cls._process_new_state(tdef.state, unprocessed, processed)
575
+ tokens.append((re.compile('').match, None, new_state))
576
+ continue
577
+
578
+ assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
579
+
580
+ try:
581
+ rex = cls._process_regex(tdef[0], rflags, state)
582
+ except Exception as err:
583
+ raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err
584
+
585
+ token = cls._process_token(tdef[1])
586
+
587
+ if len(tdef) == 2:
588
+ new_state = None
589
+ else:
590
+ new_state = cls._process_new_state(tdef[2],
591
+ unprocessed, processed)
592
+
593
+ tokens.append((rex, token, new_state))
594
+ return tokens
595
+
596
+ def process_tokendef(cls, name, tokendefs=None):
597
+ """Preprocess a dictionary of token definitions."""
598
+ processed = cls._all_tokens[name] = {}
599
+ tokendefs = tokendefs or cls.tokens[name]
600
+ for state in list(tokendefs):
601
+ cls._process_state(tokendefs, processed, state)
602
+ return processed
603
+
604
+ def get_tokendefs(cls):
605
+ """
606
+ Merge tokens from superclasses in MRO order, returning a single tokendef
607
+ dictionary.
608
+
609
+ Any state that is not defined by a subclass will be inherited
610
+ automatically. States that *are* defined by subclasses will, by
611
+ default, override that state in the superclass. If a subclass wishes to
612
+ inherit definitions from a superclass, it can use the special value
613
+ "inherit", which will cause the superclass' state definition to be
614
+ included at that point in the state.
615
+ """
616
+ tokens = {}
617
+ inheritable = {}
618
+ for c in cls.__mro__:
619
+ toks = c.__dict__.get('tokens', {})
620
+
621
+ for state, items in toks.items():
622
+ curitems = tokens.get(state)
623
+ if curitems is None:
624
+ # N.b. because this is assigned by reference, sufficiently
625
+ # deep hierarchies are processed incrementally (e.g. for
626
+ # A(B), B(C), C(RegexLexer), B will be premodified so X(B)
627
+ # will not see any inherits in B).
628
+ tokens[state] = items
629
+ try:
630
+ inherit_ndx = items.index(inherit)
631
+ except ValueError:
632
+ continue
633
+ inheritable[state] = inherit_ndx
634
+ continue
635
+
636
+ inherit_ndx = inheritable.pop(state, None)
637
+ if inherit_ndx is None:
638
+ continue
639
+
640
+ # Replace the "inherit" value with the items
641
+ curitems[inherit_ndx:inherit_ndx+1] = items
642
+ try:
643
+ # N.b. this is the index in items (that is, the superclass
644
+ # copy), so offset required when storing below.
645
+ new_inh_ndx = items.index(inherit)
646
+ except ValueError:
647
+ pass
648
+ else:
649
+ inheritable[state] = inherit_ndx + new_inh_ndx
650
+
651
+ return tokens
652
+
653
+ def __call__(cls, *args, **kwds):
654
+ """Instantiate cls after preprocessing its token definitions."""
655
+ if '_tokens' not in cls.__dict__:
656
+ cls._all_tokens = {}
657
+ cls._tmpname = 0
658
+ if hasattr(cls, 'token_variants') and cls.token_variants:
659
+ # don't process yet
660
+ pass
661
+ else:
662
+ cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
663
+
664
+ return type.__call__(cls, *args, **kwds)
665
+
666
+
667
+ class RegexLexer(Lexer, metaclass=RegexLexerMeta):
668
+ """
669
+ Base for simple stateful regular expression-based lexers.
670
+ Simplifies the lexing process so that you need only
671
+ provide a list of states and regular expressions.
672
+ """
673
+
674
+ #: Flags for compiling the regular expressions.
675
+ #: Defaults to MULTILINE.
676
+ flags = re.MULTILINE
677
+
678
+ #: At all time there is a stack of states. Initially, the stack contains
679
+ #: a single state 'root'. The top of the stack is called "the current state".
680
+ #:
681
+ #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}``
682
+ #:
683
+ #: ``new_state`` can be omitted to signify no state transition.
684
+ #: If ``new_state`` is a string, it is pushed on the stack. This ensure
685
+ #: the new current state is ``new_state``.
686
+ #: If ``new_state`` is a tuple of strings, all of those strings are pushed
687
+ #: on the stack and the current state will be the last element of the list.
688
+ #: ``new_state`` can also be ``combined('state1', 'state2', ...)``
689
+ #: to signify a new, anonymous state combined from the rules of two
690
+ #: or more existing ones.
691
+ #: Furthermore, it can be '#pop' to signify going back one step in
692
+ #: the state stack, or '#push' to push the current state on the stack
693
+ #: again. Note that if you push while in a combined state, the combined
694
+ #: state itself is pushed, and not only the state in which the rule is
695
+ #: defined.
696
+ #:
697
+ #: The tuple can also be replaced with ``include('state')``, in which
698
+ #: case the rules from the state named by the string are included in the
699
+ #: current one.
700
+ tokens = {}
701
+
702
+ def get_tokens_unprocessed(self, text, stack=('root',)):
703
+ """
704
+ Split ``text`` into (tokentype, text) pairs.
705
+
706
+ ``stack`` is the initial stack (default: ``['root']``)
707
+ """
708
+ pos = 0
709
+ tokendefs = self._tokens
710
+ statestack = list(stack)
711
+ statetokens = tokendefs[statestack[-1]]
712
+ while 1:
713
+ for rexmatch, action, new_state in statetokens:
714
+ m = rexmatch(text, pos)
715
+ if m:
716
+ if action is not None:
717
+ if type(action) is _TokenType:
718
+ yield pos, action, m.group()
719
+ else:
720
+ yield from action(self, m)
721
+ pos = m.end()
722
+ if new_state is not None:
723
+ # state transition
724
+ if isinstance(new_state, tuple):
725
+ for state in new_state:
726
+ if state == '#pop':
727
+ if len(statestack) > 1:
728
+ statestack.pop()
729
+ elif state == '#push':
730
+ statestack.append(statestack[-1])
731
+ else:
732
+ statestack.append(state)
733
+ elif isinstance(new_state, int):
734
+ # pop, but keep at least one state on the stack
735
+ # (random code leading to unexpected pops should
736
+ # not allow exceptions)
737
+ if abs(new_state) >= len(statestack):
738
+ del statestack[1:]
739
+ else:
740
+ del statestack[new_state:]
741
+ elif new_state == '#push':
742
+ statestack.append(statestack[-1])
743
+ else:
744
+ assert False, f"wrong state def: {new_state!r}"
745
+ statetokens = tokendefs[statestack[-1]]
746
+ break
747
+ else:
748
+ # We are here only if all state tokens have been considered
749
+ # and there was not a match on any of them.
750
+ try:
751
+ if text[pos] == '\n':
752
+ # at EOL, reset state to "root"
753
+ statestack = ['root']
754
+ statetokens = tokendefs['root']
755
+ yield pos, Whitespace, '\n'
756
+ pos += 1
757
+ continue
758
+ yield pos, Error, text[pos]
759
+ pos += 1
760
+ except IndexError:
761
+ break
762
+
763
+
764
+ class LexerContext:
765
+ """
766
+ A helper object that holds lexer position data.
767
+ """
768
+
769
+ def __init__(self, text, pos, stack=None, end=None):
770
+ self.text = text
771
+ self.pos = pos
772
+ self.end = end or len(text) # end=0 not supported ;-)
773
+ self.stack = stack or ['root']
774
+
775
+ def __repr__(self):
776
+ return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'
777
+
778
+
779
+ class ExtendedRegexLexer(RegexLexer):
780
+ """
781
+ A RegexLexer that uses a context object to store its state.
782
+ """
783
+
784
+ def get_tokens_unprocessed(self, text=None, context=None):
785
+ """
786
+ Split ``text`` into (tokentype, text) pairs.
787
+ If ``context`` is given, use this lexer context instead.
788
+ """
789
+ tokendefs = self._tokens
790
+ if not context:
791
+ ctx = LexerContext(text, 0)
792
+ statetokens = tokendefs['root']
793
+ else:
794
+ ctx = context
795
+ statetokens = tokendefs[ctx.stack[-1]]
796
+ text = ctx.text
797
+ while 1:
798
+ for rexmatch, action, new_state in statetokens:
799
+ m = rexmatch(text, ctx.pos, ctx.end)
800
+ if m:
801
+ if action is not None:
802
+ if type(action) is _TokenType:
803
+ yield ctx.pos, action, m.group()
804
+ ctx.pos = m.end()
805
+ else:
806
+ yield from action(self, m, ctx)
807
+ if not new_state:
808
+ # altered the state stack?
809
+ statetokens = tokendefs[ctx.stack[-1]]
810
+ # CAUTION: callback must set ctx.pos!
811
+ if new_state is not None:
812
+ # state transition
813
+ if isinstance(new_state, tuple):
814
+ for state in new_state:
815
+ if state == '#pop':
816
+ if len(ctx.stack) > 1:
817
+ ctx.stack.pop()
818
+ elif state == '#push':
819
+ ctx.stack.append(ctx.stack[-1])
820
+ else:
821
+ ctx.stack.append(state)
822
+ elif isinstance(new_state, int):
823
+ # see RegexLexer for why this check is made
824
+ if abs(new_state) >= len(ctx.stack):
825
+ del ctx.stack[1:]
826
+ else:
827
+ del ctx.stack[new_state:]
828
+ elif new_state == '#push':
829
+ ctx.stack.append(ctx.stack[-1])
830
+ else:
831
+ assert False, f"wrong state def: {new_state!r}"
832
+ statetokens = tokendefs[ctx.stack[-1]]
833
+ break
834
+ else:
835
+ try:
836
+ if ctx.pos >= ctx.end:
837
+ break
838
+ if text[ctx.pos] == '\n':
839
+ # at EOL, reset state to "root"
840
+ ctx.stack = ['root']
841
+ statetokens = tokendefs['root']
842
+ yield ctx.pos, Text, '\n'
843
+ ctx.pos += 1
844
+ continue
845
+ yield ctx.pos, Error, text[ctx.pos]
846
+ ctx.pos += 1
847
+ except IndexError:
848
+ break
849
+
850
+
851
+ def do_insertions(insertions, tokens):
852
+ """
853
+ Helper for lexers which must combine the results of several
854
+ sublexers.
855
+
856
+ ``insertions`` is a list of ``(index, itokens)`` pairs.
857
+ Each ``itokens`` iterable should be inserted at position
858
+ ``index`` into the token stream given by the ``tokens``
859
+ argument.
860
+
861
+ The result is a combined token stream.
862
+
863
+ TODO: clean up the code here.
864
+ """
865
+ insertions = iter(insertions)
866
+ try:
867
+ index, itokens = next(insertions)
868
+ except StopIteration:
869
+ # no insertions
870
+ yield from tokens
871
+ return
872
+
873
+ realpos = None
874
+ insleft = True
875
+
876
+ # iterate over the token stream where we want to insert
877
+ # the tokens from the insertion list.
878
+ for i, t, v in tokens:
879
+ # first iteration. store the position of first item
880
+ if realpos is None:
881
+ realpos = i
882
+ oldi = 0
883
+ while insleft and i + len(v) >= index:
884
+ tmpval = v[oldi:index - i]
885
+ if tmpval:
886
+ yield realpos, t, tmpval
887
+ realpos += len(tmpval)
888
+ for it_index, it_token, it_value in itokens:
889
+ yield realpos, it_token, it_value
890
+ realpos += len(it_value)
891
+ oldi = index - i
892
+ try:
893
+ index, itokens = next(insertions)
894
+ except StopIteration:
895
+ insleft = False
896
+ break # not strictly necessary
897
+ if oldi < len(v):
898
+ yield realpos, t, v[oldi:]
899
+ realpos += len(v) - oldi
900
+
901
+ # leftover tokens
902
+ while insleft:
903
+ # no normal tokens, set realpos to zero
904
+ realpos = realpos or 0
905
+ for p, t, v in itokens:
906
+ yield realpos, t, v
907
+ realpos += len(v)
908
+ try:
909
+ index, itokens = next(insertions)
910
+ except StopIteration:
911
+ insleft = False
912
+ break # not strictly necessary
913
+
914
+
915
+ class ProfilingRegexLexerMeta(RegexLexerMeta):
916
+ """Metaclass for ProfilingRegexLexer, collects regex timing info."""
917
+
918
+ def _process_regex(cls, regex, rflags, state):
919
+ if isinstance(regex, words):
920
+ rex = regex_opt(regex.words, prefix=regex.prefix,
921
+ suffix=regex.suffix)
922
+ else:
923
+ rex = regex
924
+ compiled = re.compile(rex, rflags)
925
+
926
+ def match_func(text, pos, endpos=sys.maxsize):
927
+ info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])
928
+ t0 = time.time()
929
+ res = compiled.match(text, pos, endpos)
930
+ t1 = time.time()
931
+ info[0] += 1
932
+ info[1] += t1 - t0
933
+ return res
934
+ return match_func
935
+
936
+
937
+ class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta):
938
+ """Drop-in replacement for RegexLexer that does profiling of its regexes."""
939
+
940
+ _prof_data = []
941
+ _prof_sort_index = 4 # defaults to time per call
942
+
943
+ def get_tokens_unprocessed(self, text, stack=('root',)):
944
+ # this needs to be a stack, since using(this) will produce nested calls
945
+ self.__class__._prof_data.append({})
946
+ yield from RegexLexer.get_tokens_unprocessed(self, text, stack)
947
+ rawdata = self.__class__._prof_data.pop()
948
+ data = sorted(((s, repr(r).strip('u\'').replace('\\\\', '\\')[:65],
949
+ n, 1000 * t, 1000 * t / n)
950
+ for ((s, r), (n, t)) in rawdata.items()),
951
+ key=lambda x: x[self._prof_sort_index],
952
+ reverse=True)
953
+ sum_total = sum(x[3] for x in data)
954
+
955
+ print()
956
+ print('Profiling result for %s lexing %d chars in %.3f ms' %
957
+ (self.__class__.__name__, len(text), sum_total))
958
+ print('=' * 110)
959
+ print('%-20s %-64s ncalls tottime percall' % ('state', 'regex'))
960
+ print('-' * 110)
961
+ for d in data:
962
+ print('%-20s %-65s %5d %8.4f %8.4f' % d)
963
+ print('=' * 110)
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__init__.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ Pygments lexers.
6
+
7
+ :copyright: Copyright 2006-2024 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.lexers._mapping import LEXERS
18
+ from pip._vendor.pygments.modeline import get_filetype_from_buffer
19
+ from pip._vendor.pygments.plugin import find_plugin_lexers
20
+ from pip._vendor.pygments.util import ClassNotFound, guess_decode
21
+
22
+ COMPAT = {
23
+ 'Python3Lexer': 'PythonLexer',
24
+ 'Python3TracebackLexer': 'PythonTracebackLexer',
25
+ 'LeanLexer': 'Lean3Lexer',
26
+ }
27
+
28
+ __all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',
29
+ 'guess_lexer', 'load_lexer_from_file'] + list(LEXERS) + list(COMPAT)
30
+
31
+ _lexer_cache = {}
32
+ _pattern_cache = {}
33
+
34
+
35
+ def _fn_matches(fn, glob):
36
+ """Return whether the supplied file name fn matches pattern filename."""
37
+ if glob not in _pattern_cache:
38
+ pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob))
39
+ return pattern.match(fn)
40
+ return _pattern_cache[glob].match(fn)
41
+
42
+
43
+ def _load_lexers(module_name):
44
+ """Load a lexer (and all others in the module too)."""
45
+ mod = __import__(module_name, None, None, ['__all__'])
46
+ for lexer_name in mod.__all__:
47
+ cls = getattr(mod, lexer_name)
48
+ _lexer_cache[cls.name] = cls
49
+
50
+
51
+ def get_all_lexers(plugins=True):
52
+ """Return a generator of tuples in the form ``(name, aliases,
53
+ filenames, mimetypes)`` of all know lexers.
54
+
55
+ If *plugins* is true (the default), plugin lexers supplied by entrypoints
56
+ are also returned. Otherwise, only builtin ones are considered.
57
+ """
58
+ for item in LEXERS.values():
59
+ yield item[1:]
60
+ if plugins:
61
+ for lexer in find_plugin_lexers():
62
+ yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes
63
+
64
+
65
+ def find_lexer_class(name):
66
+ """
67
+ Return the `Lexer` subclass that with the *name* attribute as given by
68
+ the *name* argument.
69
+ """
70
+ if name in _lexer_cache:
71
+ return _lexer_cache[name]
72
+ # lookup builtin lexers
73
+ for module_name, lname, aliases, _, _ in LEXERS.values():
74
+ if name == lname:
75
+ _load_lexers(module_name)
76
+ return _lexer_cache[name]
77
+ # continue with lexers from setuptools entrypoints
78
+ for cls in find_plugin_lexers():
79
+ if cls.name == name:
80
+ return cls
81
+
82
+
83
+ def find_lexer_class_by_name(_alias):
84
+ """
85
+ Return the `Lexer` subclass that has `alias` in its aliases list, without
86
+ instantiating it.
87
+
88
+ Like `get_lexer_by_name`, but does not instantiate the class.
89
+
90
+ Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is
91
+ found.
92
+
93
+ .. versionadded:: 2.2
94
+ """
95
+ if not _alias:
96
+ raise ClassNotFound(f'no lexer for alias {_alias!r} found')
97
+ # lookup builtin lexers
98
+ for module_name, name, aliases, _, _ in LEXERS.values():
99
+ if _alias.lower() in aliases:
100
+ if name not in _lexer_cache:
101
+ _load_lexers(module_name)
102
+ return _lexer_cache[name]
103
+ # continue with lexers from setuptools entrypoints
104
+ for cls in find_plugin_lexers():
105
+ if _alias.lower() in cls.aliases:
106
+ return cls
107
+ raise ClassNotFound(f'no lexer for alias {_alias!r} found')
108
+
109
+
110
+ def get_lexer_by_name(_alias, **options):
111
+ """
112
+ Return an instance of a `Lexer` subclass that has `alias` in its
113
+ aliases list. The lexer is given the `options` at its
114
+ instantiation.
115
+
116
+ Will raise :exc:`pygments.util.ClassNotFound` if no lexer with that alias is
117
+ found.
118
+ """
119
+ if not _alias:
120
+ raise ClassNotFound(f'no lexer for alias {_alias!r} found')
121
+
122
+ # lookup builtin lexers
123
+ for module_name, name, aliases, _, _ in LEXERS.values():
124
+ if _alias.lower() in aliases:
125
+ if name not in _lexer_cache:
126
+ _load_lexers(module_name)
127
+ return _lexer_cache[name](**options)
128
+ # continue with lexers from setuptools entrypoints
129
+ for cls in find_plugin_lexers():
130
+ if _alias.lower() in cls.aliases:
131
+ return cls(**options)
132
+ raise ClassNotFound(f'no lexer for alias {_alias!r} found')
133
+
134
+
135
+ def load_lexer_from_file(filename, lexername="CustomLexer", **options):
136
+ """Load a lexer from a file.
137
+
138
+ This method expects a file located relative to the current working
139
+ directory, which contains a Lexer class. By default, it expects the
140
+ Lexer to be name CustomLexer; you can specify your own class name
141
+ as the second argument to this function.
142
+
143
+ Users should be very careful with the input, because this method
144
+ is equivalent to running eval on the input file.
145
+
146
+ Raises ClassNotFound if there are any problems importing the Lexer.
147
+
148
+ .. versionadded:: 2.2
149
+ """
150
+ try:
151
+ # This empty dict will contain the namespace for the exec'd file
152
+ custom_namespace = {}
153
+ with open(filename, 'rb') as f:
154
+ exec(f.read(), custom_namespace)
155
+ # Retrieve the class `lexername` from that namespace
156
+ if lexername not in custom_namespace:
157
+ raise ClassNotFound(f'no valid {lexername} class found in {filename}')
158
+ lexer_class = custom_namespace[lexername]
159
+ # And finally instantiate it with the options
160
+ return lexer_class(**options)
161
+ except OSError as err:
162
+ raise ClassNotFound(f'cannot read {filename}: {err}')
163
+ except ClassNotFound:
164
+ raise
165
+ except Exception as err:
166
+ raise ClassNotFound(f'error when loading custom lexer: {err}')
167
+
168
+
169
+ def find_lexer_class_for_filename(_fn, code=None):
170
+ """Get a lexer for a filename.
171
+
172
+ If multiple lexers match the filename pattern, use ``analyse_text()`` to
173
+ figure out which one is more appropriate.
174
+
175
+ Returns None if not found.
176
+ """
177
+ matches = []
178
+ fn = basename(_fn)
179
+ for modname, name, _, filenames, _ in LEXERS.values():
180
+ for filename in filenames:
181
+ if _fn_matches(fn, filename):
182
+ if name not in _lexer_cache:
183
+ _load_lexers(modname)
184
+ matches.append((_lexer_cache[name], filename))
185
+ for cls in find_plugin_lexers():
186
+ for filename in cls.filenames:
187
+ if _fn_matches(fn, filename):
188
+ matches.append((cls, filename))
189
+
190
+ if isinstance(code, bytes):
191
+ # decode it, since all analyse_text functions expect unicode
192
+ code = guess_decode(code)
193
+
194
+ def get_rating(info):
195
+ cls, filename = info
196
+ # explicit patterns get a bonus
197
+ bonus = '*' not in filename and 0.5 or 0
198
+ # The class _always_ defines analyse_text because it's included in
199
+ # the Lexer class. The default implementation returns None which
200
+ # gets turned into 0.0. Run scripts/detect_missing_analyse_text.py
201
+ # to find lexers which need it overridden.
202
+ if code:
203
+ return cls.analyse_text(code) + bonus, cls.__name__
204
+ return cls.priority + bonus, cls.__name__
205
+
206
+ if matches:
207
+ matches.sort(key=get_rating)
208
+ # print "Possible lexers, after sort:", matches
209
+ return matches[-1][0]
210
+
211
+
212
+ def get_lexer_for_filename(_fn, code=None, **options):
213
+ """Get a lexer for a filename.
214
+
215
+ Return a `Lexer` subclass instance that has a filename pattern
216
+ matching `fn`. The lexer is given the `options` at its
217
+ instantiation.
218
+
219
+ Raise :exc:`pygments.util.ClassNotFound` if no lexer for that filename
220
+ is found.
221
+
222
+ If multiple lexers match the filename pattern, use their ``analyse_text()``
223
+ methods to figure out which one is more appropriate.
224
+ """
225
+ res = find_lexer_class_for_filename(_fn, code)
226
+ if not res:
227
+ raise ClassNotFound(f'no lexer for filename {_fn!r} found')
228
+ return res(**options)
229
+
230
+
231
+ def get_lexer_for_mimetype(_mime, **options):
232
+ """
233
+ Return a `Lexer` subclass instance that has `mime` in its mimetype
234
+ list. The lexer is given the `options` at its instantiation.
235
+
236
+ Will raise :exc:`pygments.util.ClassNotFound` if not lexer for that mimetype
237
+ is found.
238
+ """
239
+ for modname, name, _, _, mimetypes in LEXERS.values():
240
+ if _mime in mimetypes:
241
+ if name not in _lexer_cache:
242
+ _load_lexers(modname)
243
+ return _lexer_cache[name](**options)
244
+ for cls in find_plugin_lexers():
245
+ if _mime in cls.mimetypes:
246
+ return cls(**options)
247
+ raise ClassNotFound(f'no lexer for mimetype {_mime!r} found')
248
+
249
+
250
+ def _iter_lexerclasses(plugins=True):
251
+ """Return an iterator over all lexer classes."""
252
+ for key in sorted(LEXERS):
253
+ module_name, name = LEXERS[key][:2]
254
+ if name not in _lexer_cache:
255
+ _load_lexers(module_name)
256
+ yield _lexer_cache[name]
257
+ if plugins:
258
+ yield from find_plugin_lexers()
259
+
260
+
261
+ def guess_lexer_for_filename(_fn, _text, **options):
262
+ """
263
+ As :func:`guess_lexer()`, but only lexers which have a pattern in `filenames`
264
+ or `alias_filenames` that matches `filename` are taken into consideration.
265
+
266
+ :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can
267
+ handle the content.
268
+ """
269
+ fn = basename(_fn)
270
+ primary = {}
271
+ matching_lexers = set()
272
+ for lexer in _iter_lexerclasses():
273
+ for filename in lexer.filenames:
274
+ if _fn_matches(fn, filename):
275
+ matching_lexers.add(lexer)
276
+ primary[lexer] = True
277
+ for filename in lexer.alias_filenames:
278
+ if _fn_matches(fn, filename):
279
+ matching_lexers.add(lexer)
280
+ primary[lexer] = False
281
+ if not matching_lexers:
282
+ raise ClassNotFound(f'no lexer for filename {fn!r} found')
283
+ if len(matching_lexers) == 1:
284
+ return matching_lexers.pop()(**options)
285
+ result = []
286
+ for lexer in matching_lexers:
287
+ rv = lexer.analyse_text(_text)
288
+ if rv == 1.0:
289
+ return lexer(**options)
290
+ result.append((rv, lexer))
291
+
292
+ def type_sort(t):
293
+ # sort by:
294
+ # - analyse score
295
+ # - is primary filename pattern?
296
+ # - priority
297
+ # - last resort: class name
298
+ return (t[0], primary[t[1]], t[1].priority, t[1].__name__)
299
+ result.sort(key=type_sort)
300
+
301
+ return result[-1][1](**options)
302
+
303
+
304
+ def guess_lexer(_text, **options):
305
+ """
306
+ Return a `Lexer` subclass instance that's guessed from the text in
307
+ `text`. For that, the :meth:`.analyse_text()` method of every known lexer
308
+ class is called with the text as argument, and the lexer which returned the
309
+ highest value will be instantiated and returned.
310
+
311
+ :exc:`pygments.util.ClassNotFound` is raised if no lexer thinks it can
312
+ handle the content.
313
+ """
314
+
315
+ if not isinstance(_text, str):
316
+ inencoding = options.get('inencoding', options.get('encoding'))
317
+ if inencoding:
318
+ _text = _text.decode(inencoding or 'utf8')
319
+ else:
320
+ _text, _ = guess_decode(_text)
321
+
322
+ # try to get a vim modeline first
323
+ ft = get_filetype_from_buffer(_text)
324
+
325
+ if ft is not None:
326
+ try:
327
+ return get_lexer_by_name(ft, **options)
328
+ except ClassNotFound:
329
+ pass
330
+
331
+ best_lexer = [0.0, None]
332
+ for lexer in _iter_lexerclasses():
333
+ rv = lexer.analyse_text(_text)
334
+ if rv == 1.0:
335
+ return lexer(**options)
336
+ if rv > best_lexer[0]:
337
+ best_lexer[:] = (rv, lexer)
338
+ if not best_lexer[0] or best_lexer[1] is None:
339
+ raise ClassNotFound('no lexer matching the text found')
340
+ return best_lexer[1](**options)
341
+
342
+
343
+ class _automodule(types.ModuleType):
344
+ """Automatically import lexers."""
345
+
346
+ def __getattr__(self, name):
347
+ info = LEXERS.get(name)
348
+ if info:
349
+ _load_lexers(info[0])
350
+ cls = _lexer_cache[info[1]]
351
+ setattr(self, name, cls)
352
+ return cls
353
+ if name in COMPAT:
354
+ return getattr(self, COMPAT[name])
355
+ raise AttributeError(name)
356
+
357
+
358
+ oldmod = sys.modules[__name__]
359
+ newmod = _automodule(__name__)
360
+ newmod.__dict__.update(oldmod.__dict__)
361
+ sys.modules[__name__] = newmod
362
+ del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/_mapping.cpython-310.pyc ADDED
Binary file (64.9 kB). View file
 
vllm/lib/python3.10/site-packages/pip/_vendor/pygments/lexers/__pycache__/python.cpython-310.pyc ADDED
Binary file (30.2 kB). View file