python.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. """
  2. pygments.lexers.python
  3. ~~~~~~~~~~~~~~~~~~~~~~
  4. Lexers for Python and related languages.
  5. :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
  6. :license: BSD, see LICENSE for details.
  7. """
  8. import re
  9. import keyword
  10. from pip._vendor.pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \
  11. default, words, combined, do_insertions, this
  12. from pip._vendor.pygments.util import get_bool_opt, shebang_matches
  13. from pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \
  14. Number, Punctuation, Generic, Other, Error
  15. from pip._vendor.pygments import unistring as uni
  16. __all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer',
  17. 'Python2Lexer', 'Python2TracebackLexer',
  18. 'CythonLexer', 'DgLexer', 'NumPyLexer']
  19. line_re = re.compile('.*?\n')
  20. class PythonLexer(RegexLexer):
  21. """
  22. For Python source code (version 3.x).
  23. .. versionadded:: 0.10
  24. .. versionchanged:: 2.5
  25. This is now the default ``PythonLexer``. It is still available as the
  26. alias ``Python3Lexer``.
  27. """
  28. name = 'Python'
  29. url = 'http://www.python.org'
  30. aliases = ['python', 'py', 'sage', 'python3', 'py3']
  31. filenames = [
  32. '*.py',
  33. '*.pyw',
  34. # Jython
  35. '*.jy',
  36. # Sage
  37. '*.sage',
  38. # SCons
  39. '*.sc',
  40. 'SConstruct',
  41. 'SConscript',
  42. # Skylark/Starlark (used by Bazel, Buck, and Pants)
  43. '*.bzl',
  44. 'BUCK',
  45. 'BUILD',
  46. 'BUILD.bazel',
  47. 'WORKSPACE',
  48. # Twisted Application infrastructure
  49. '*.tac',
  50. ]
  51. mimetypes = ['text/x-python', 'application/x-python',
  52. 'text/x-python3', 'application/x-python3']
  53. uni_name = "[%s][%s]*" % (uni.xid_start, uni.xid_continue)
  54. def innerstring_rules(ttype):
  55. return [
  56. # the old style '%s' % (...) string formatting (still valid in Py3)
  57. (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
  58. '[hlL]?[E-GXc-giorsaux%]', String.Interpol),
  59. # the new style '{}'.format(...) string formatting
  60. (r'\{'
  61. r'((\w+)((\.\w+)|(\[[^\]]+\]))*)?' # field name
  62. r'(\![sra])?' # conversion
  63. r'(\:(.?[<>=\^])?[-+ ]?#?0?(\d+)?,?(\.\d+)?[E-GXb-gnosx%]?)?'
  64. r'\}', String.Interpol),
  65. # backslashes, quotes and formatting signs must be parsed one at a time
  66. (r'[^\\\'"%{\n]+', ttype),
  67. (r'[\'"\\]', ttype),
  68. # unhandled string formatting sign
  69. (r'%|(\{{1,2})', ttype)
  70. # newlines are an error (use "nl" state)
  71. ]
  72. def fstring_rules(ttype):
  73. return [
  74. # Assuming that a '}' is the closing brace after format specifier.
  75. # Sadly, this means that we won't detect syntax error. But it's
  76. # more important to parse correct syntax correctly, than to
  77. # highlight invalid syntax.
  78. (r'\}', String.Interpol),
  79. (r'\{', String.Interpol, 'expr-inside-fstring'),
  80. # backslashes, quotes and formatting signs must be parsed one at a time
  81. (r'[^\\\'"{}\n]+', ttype),
  82. (r'[\'"\\]', ttype),
  83. # newlines are an error (use "nl" state)
  84. ]
  85. tokens = {
  86. 'root': [
  87. (r'\n', Text),
  88. (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
  89. bygroups(Text, String.Affix, String.Doc)),
  90. (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
  91. bygroups(Text, String.Affix, String.Doc)),
  92. (r'\A#!.+$', Comment.Hashbang),
  93. (r'#.*$', Comment.Single),
  94. (r'\\\n', Text),
  95. (r'\\', Text),
  96. include('keywords'),
  97. include('soft-keywords'),
  98. (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'),
  99. (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'),
  100. (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
  101. 'fromimport'),
  102. (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
  103. 'import'),
  104. include('expr'),
  105. ],
  106. 'expr': [
  107. # raw f-strings
  108. ('(?i)(rf|fr)(""")',
  109. bygroups(String.Affix, String.Double),
  110. combined('rfstringescape', 'tdqf')),
  111. ("(?i)(rf|fr)(''')",
  112. bygroups(String.Affix, String.Single),
  113. combined('rfstringescape', 'tsqf')),
  114. ('(?i)(rf|fr)(")',
  115. bygroups(String.Affix, String.Double),
  116. combined('rfstringescape', 'dqf')),
  117. ("(?i)(rf|fr)(')",
  118. bygroups(String.Affix, String.Single),
  119. combined('rfstringescape', 'sqf')),
  120. # non-raw f-strings
  121. ('([fF])(""")', bygroups(String.Affix, String.Double),
  122. combined('fstringescape', 'tdqf')),
  123. ("([fF])(''')", bygroups(String.Affix, String.Single),
  124. combined('fstringescape', 'tsqf')),
  125. ('([fF])(")', bygroups(String.Affix, String.Double),
  126. combined('fstringescape', 'dqf')),
  127. ("([fF])(')", bygroups(String.Affix, String.Single),
  128. combined('fstringescape', 'sqf')),
  129. # raw bytes and strings
  130. ('(?i)(rb|br|r)(""")',
  131. bygroups(String.Affix, String.Double), 'tdqs'),
  132. ("(?i)(rb|br|r)(''')",
  133. bygroups(String.Affix, String.Single), 'tsqs'),
  134. ('(?i)(rb|br|r)(")',
  135. bygroups(String.Affix, String.Double), 'dqs'),
  136. ("(?i)(rb|br|r)(')",
  137. bygroups(String.Affix, String.Single), 'sqs'),
  138. # non-raw strings
  139. ('([uU]?)(""")', bygroups(String.Affix, String.Double),
  140. combined('stringescape', 'tdqs')),
  141. ("([uU]?)(''')", bygroups(String.Affix, String.Single),
  142. combined('stringescape', 'tsqs')),
  143. ('([uU]?)(")', bygroups(String.Affix, String.Double),
  144. combined('stringescape', 'dqs')),
  145. ("([uU]?)(')", bygroups(String.Affix, String.Single),
  146. combined('stringescape', 'sqs')),
  147. # non-raw bytes
  148. ('([bB])(""")', bygroups(String.Affix, String.Double),
  149. combined('bytesescape', 'tdqs')),
  150. ("([bB])(''')", bygroups(String.Affix, String.Single),
  151. combined('bytesescape', 'tsqs')),
  152. ('([bB])(")', bygroups(String.Affix, String.Double),
  153. combined('bytesescape', 'dqs')),
  154. ("([bB])(')", bygroups(String.Affix, String.Single),
  155. combined('bytesescape', 'sqs')),
  156. (r'[^\S\n]+', Text),
  157. include('numbers'),
  158. (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator),
  159. (r'[]{}:(),;[]', Punctuation),
  160. (r'(in|is|and|or|not)\b', Operator.Word),
  161. include('expr-keywords'),
  162. include('builtins'),
  163. include('magicfuncs'),
  164. include('magicvars'),
  165. include('name'),
  166. ],
  167. 'expr-inside-fstring': [
  168. (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
  169. # without format specifier
  170. (r'(=\s*)?' # debug (https://bugs.python.org/issue36817)
  171. r'(\![sraf])?' # conversion
  172. r'\}', String.Interpol, '#pop'),
  173. # with format specifier
  174. # we'll catch the remaining '}' in the outer scope
  175. (r'(=\s*)?' # debug (https://bugs.python.org/issue36817)
  176. r'(\![sraf])?' # conversion
  177. r':', String.Interpol, '#pop'),
  178. (r'\s+', Text), # allow new lines
  179. include('expr'),
  180. ],
  181. 'expr-inside-fstring-inner': [
  182. (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),
  183. (r'[])}]', Punctuation, '#pop'),
  184. (r'\s+', Text), # allow new lines
  185. include('expr'),
  186. ],
  187. 'expr-keywords': [
  188. # Based on https://docs.python.org/3/reference/expressions.html
  189. (words((
  190. 'async for', 'await', 'else', 'for', 'if', 'lambda',
  191. 'yield', 'yield from'), suffix=r'\b'),
  192. Keyword),
  193. (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant),
  194. ],
  195. 'keywords': [
  196. (words((
  197. 'assert', 'async', 'await', 'break', 'continue', 'del', 'elif',
  198. 'else', 'except', 'finally', 'for', 'global', 'if', 'lambda',
  199. 'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield',
  200. 'yield from', 'as', 'with'), suffix=r'\b'),
  201. Keyword),
  202. (words(('True', 'False', 'None'), suffix=r'\b'), Keyword.Constant),
  203. ],
  204. 'soft-keywords': [
  205. # `match`, `case` and `_` soft keywords
  206. (r'(^[ \t]*)' # at beginning of line + possible indentation
  207. r'(match|case)\b' # a possible keyword
  208. r'(?![ \t]*(?:' # not followed by...
  209. r'[:,;=^&|@~)\]}]|(?:' + # characters and keywords that mean this isn't
  210. r'|'.join(keyword.kwlist) + r')\b))', # pattern matching
  211. bygroups(Text, Keyword), 'soft-keywords-inner'),
  212. ],
  213. 'soft-keywords-inner': [
  214. # optional `_` keyword
  215. (r'(\s+)([^\n_]*)(_\b)', bygroups(Text, using(this), Keyword)),
  216. default('#pop')
  217. ],
  218. 'builtins': [
  219. (words((
  220. '__import__', 'abs', 'all', 'any', 'bin', 'bool', 'bytearray',
  221. 'breakpoint', 'bytes', 'chr', 'classmethod', 'compile', 'complex',
  222. 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'filter',
  223. 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
  224. 'hash', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
  225. 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview',
  226. 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
  227. 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',
  228. 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
  229. 'type', 'vars', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'),
  230. Name.Builtin),
  231. (r'(?<!\.)(self|Ellipsis|NotImplemented|cls)\b', Name.Builtin.Pseudo),
  232. (words((
  233. 'ArithmeticError', 'AssertionError', 'AttributeError',
  234. 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning',
  235. 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError',
  236. 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
  237. 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',
  238. 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',
  239. 'NotImplementedError', 'OSError', 'OverflowError',
  240. 'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning',
  241. 'RuntimeError', 'RuntimeWarning', 'StopIteration',
  242. 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
  243. 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
  244. 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
  245. 'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError',
  246. 'Warning', 'WindowsError', 'ZeroDivisionError',
  247. # new builtin exceptions from PEP 3151
  248. 'BlockingIOError', 'ChildProcessError', 'ConnectionError',
  249. 'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError',
  250. 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError',
  251. 'InterruptedError', 'IsADirectoryError', 'NotADirectoryError',
  252. 'PermissionError', 'ProcessLookupError', 'TimeoutError',
  253. # others new in Python 3
  254. 'StopAsyncIteration', 'ModuleNotFoundError', 'RecursionError',
  255. 'EncodingWarning'),
  256. prefix=r'(?<!\.)', suffix=r'\b'),
  257. Name.Exception),
  258. ],
  259. 'magicfuncs': [
  260. (words((
  261. '__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__',
  262. '__and__', '__anext__', '__await__', '__bool__', '__bytes__',
  263. '__call__', '__complex__', '__contains__', '__del__', '__delattr__',
  264. '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__',
  265. '__eq__', '__exit__', '__float__', '__floordiv__', '__format__',
  266. '__ge__', '__get__', '__getattr__', '__getattribute__',
  267. '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__',
  268. '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__',
  269. '__imul__', '__index__', '__init__', '__instancecheck__',
  270. '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__',
  271. '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__',
  272. '__len__', '__length_hint__', '__lshift__', '__lt__', '__matmul__',
  273. '__missing__', '__mod__', '__mul__', '__ne__', '__neg__',
  274. '__new__', '__next__', '__or__', '__pos__', '__pow__',
  275. '__prepare__', '__radd__', '__rand__', '__rdivmod__', '__repr__',
  276. '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__',
  277. '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__',
  278. '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',
  279. '__rxor__', '__set__', '__setattr__', '__setitem__', '__str__',
  280. '__sub__', '__subclasscheck__', '__truediv__',
  281. '__xor__'), suffix=r'\b'),
  282. Name.Function.Magic),
  283. ],
  284. 'magicvars': [
  285. (words((
  286. '__annotations__', '__bases__', '__class__', '__closure__',
  287. '__code__', '__defaults__', '__dict__', '__doc__', '__file__',
  288. '__func__', '__globals__', '__kwdefaults__', '__module__',
  289. '__mro__', '__name__', '__objclass__', '__qualname__',
  290. '__self__', '__slots__', '__weakref__'), suffix=r'\b'),
  291. Name.Variable.Magic),
  292. ],
  293. 'numbers': [
  294. (r'(\d(?:_?\d)*\.(?:\d(?:_?\d)*)?|(?:\d(?:_?\d)*)?\.\d(?:_?\d)*)'
  295. r'([eE][+-]?\d(?:_?\d)*)?', Number.Float),
  296. (r'\d(?:_?\d)*[eE][+-]?\d(?:_?\d)*j?', Number.Float),
  297. (r'0[oO](?:_?[0-7])+', Number.Oct),
  298. (r'0[bB](?:_?[01])+', Number.Bin),
  299. (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex),
  300. (r'\d(?:_?\d)*', Number.Integer),
  301. ],
  302. 'name': [
  303. (r'@' + uni_name, Name.Decorator),
  304. (r'@', Operator), # new matrix multiplication operator
  305. (uni_name, Name),
  306. ],
  307. 'funcname': [
  308. include('magicfuncs'),
  309. (uni_name, Name.Function, '#pop'),
  310. default('#pop'),
  311. ],
  312. 'classname': [
  313. (uni_name, Name.Class, '#pop'),
  314. ],
  315. 'import': [
  316. (r'(\s+)(as)(\s+)', bygroups(Text, Keyword, Text)),
  317. (r'\.', Name.Namespace),
  318. (uni_name, Name.Namespace),
  319. (r'(\s*)(,)(\s*)', bygroups(Text, Operator, Text)),
  320. default('#pop') # all else: go back
  321. ],
  322. 'fromimport': [
  323. (r'(\s+)(import)\b', bygroups(Text, Keyword.Namespace), '#pop'),
  324. (r'\.', Name.Namespace),
  325. # if None occurs here, it's "raise x from None", since None can
  326. # never be a module name
  327. (r'None\b', Name.Builtin.Pseudo, '#pop'),
  328. (uni_name, Name.Namespace),
  329. default('#pop'),
  330. ],
  331. 'rfstringescape': [
  332. (r'\{\{', String.Escape),
  333. (r'\}\}', String.Escape),
  334. ],
  335. 'fstringescape': [
  336. include('rfstringescape'),
  337. include('stringescape'),
  338. ],
  339. 'bytesescape': [
  340. (r'\\([\\abfnrtv"\']|\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
  341. ],
  342. 'stringescape': [
  343. (r'\\(N\{.*?\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})', String.Escape),
  344. include('bytesescape')
  345. ],
  346. 'fstrings-single': fstring_rules(String.Single),
  347. 'fstrings-double': fstring_rules(String.Double),
  348. 'strings-single': innerstring_rules(String.Single),
  349. 'strings-double': innerstring_rules(String.Double),
  350. 'dqf': [
  351. (r'"', String.Double, '#pop'),
  352. (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
  353. include('fstrings-double')
  354. ],
  355. 'sqf': [
  356. (r"'", String.Single, '#pop'),
  357. (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
  358. include('fstrings-single')
  359. ],
  360. 'dqs': [
  361. (r'"', String.Double, '#pop'),
  362. (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
  363. include('strings-double')
  364. ],
  365. 'sqs': [
  366. (r"'", String.Single, '#pop'),
  367. (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
  368. include('strings-single')
  369. ],
  370. 'tdqf': [
  371. (r'"""', String.Double, '#pop'),
  372. include('fstrings-double'),
  373. (r'\n', String.Double)
  374. ],
  375. 'tsqf': [
  376. (r"'''", String.Single, '#pop'),
  377. include('fstrings-single'),
  378. (r'\n', String.Single)
  379. ],
  380. 'tdqs': [
  381. (r'"""', String.Double, '#pop'),
  382. include('strings-double'),
  383. (r'\n', String.Double)
  384. ],
  385. 'tsqs': [
  386. (r"'''", String.Single, '#pop'),
  387. include('strings-single'),
  388. (r'\n', String.Single)
  389. ],
  390. }
  391. def analyse_text(text):
  392. return shebang_matches(text, r'pythonw?(3(\.\d)?)?') or \
  393. 'import ' in text[:1000]
  394. Python3Lexer = PythonLexer
  395. class Python2Lexer(RegexLexer):
  396. """
  397. For Python 2.x source code.
  398. .. versionchanged:: 2.5
  399. This class has been renamed from ``PythonLexer``. ``PythonLexer`` now
  400. refers to the Python 3 variant. File name patterns like ``*.py`` have
  401. been moved to Python 3 as well.
  402. """
  403. name = 'Python 2.x'
  404. url = 'http://www.python.org'
  405. aliases = ['python2', 'py2']
  406. filenames = [] # now taken over by PythonLexer (3.x)
  407. mimetypes = ['text/x-python2', 'application/x-python2']
  408. def innerstring_rules(ttype):
  409. return [
  410. # the old style '%s' % (...) string formatting
  411. (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
  412. '[hlL]?[E-GXc-giorsux%]', String.Interpol),
  413. # backslashes, quotes and formatting signs must be parsed one at a time
  414. (r'[^\\\'"%\n]+', ttype),
  415. (r'[\'"\\]', ttype),
  416. # unhandled string formatting sign
  417. (r'%', ttype),
  418. # newlines are an error (use "nl" state)
  419. ]
  420. tokens = {
  421. 'root': [
  422. (r'\n', Text),
  423. (r'^(\s*)([rRuUbB]{,2})("""(?:.|\n)*?""")',
  424. bygroups(Text, String.Affix, String.Doc)),
  425. (r"^(\s*)([rRuUbB]{,2})('''(?:.|\n)*?''')",
  426. bygroups(Text, String.Affix, String.Doc)),
  427. (r'[^\S\n]+', Text),
  428. (r'\A#!.+$', Comment.Hashbang),
  429. (r'#.*$', Comment.Single),
  430. (r'[]{}:(),;[]', Punctuation),
  431. (r'\\\n', Text),
  432. (r'\\', Text),
  433. (r'(in|is|and|or|not)\b', Operator.Word),
  434. (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator),
  435. include('keywords'),
  436. (r'(def)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'funcname'),
  437. (r'(class)((?:\s|\\\s)+)', bygroups(Keyword, Text), 'classname'),
  438. (r'(from)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
  439. 'fromimport'),
  440. (r'(import)((?:\s|\\\s)+)', bygroups(Keyword.Namespace, Text),
  441. 'import'),
  442. include('builtins'),
  443. include('magicfuncs'),
  444. include('magicvars'),
  445. include('backtick'),
  446. ('([rR]|[uUbB][rR]|[rR][uUbB])(""")',
  447. bygroups(String.Affix, String.Double), 'tdqs'),
  448. ("([rR]|[uUbB][rR]|[rR][uUbB])(''')",
  449. bygroups(String.Affix, String.Single), 'tsqs'),
  450. ('([rR]|[uUbB][rR]|[rR][uUbB])(")',
  451. bygroups(String.Affix, String.Double), 'dqs'),
  452. ("([rR]|[uUbB][rR]|[rR][uUbB])(')",
  453. bygroups(String.Affix, String.Single), 'sqs'),
  454. ('([uUbB]?)(""")', bygroups(String.Affix, String.Double),
  455. combined('stringescape', 'tdqs')),
  456. ("([uUbB]?)(''')", bygroups(String.Affix, String.Single),
  457. combined('stringescape', 'tsqs')),
  458. ('([uUbB]?)(")', bygroups(String.Affix, String.Double),
  459. combined('stringescape', 'dqs')),
  460. ("([uUbB]?)(')", bygroups(String.Affix, String.Single),
  461. combined('stringescape', 'sqs')),
  462. include('name'),
  463. include('numbers'),
  464. ],
  465. 'keywords': [
  466. (words((
  467. 'assert', 'break', 'continue', 'del', 'elif', 'else', 'except',
  468. 'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass',
  469. 'print', 'raise', 'return', 'try', 'while', 'yield',
  470. 'yield from', 'as', 'with'), suffix=r'\b'),
  471. Keyword),
  472. ],
  473. 'builtins': [
  474. (words((
  475. '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin',
  476. 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod',
  477. 'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',
  478. 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
  479. 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id',
  480. 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',
  481. 'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object',
  482. 'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce',
  483. 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
  484. 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',
  485. 'unichr', 'unicode', 'vars', 'xrange', 'zip'),
  486. prefix=r'(?<!\.)', suffix=r'\b'),
  487. Name.Builtin),
  488. (r'(?<!\.)(self|None|Ellipsis|NotImplemented|False|True|cls'
  489. r')\b', Name.Builtin.Pseudo),
  490. (words((
  491. 'ArithmeticError', 'AssertionError', 'AttributeError',
  492. 'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',
  493. 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',
  494. 'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
  495. 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
  496. 'MemoryError', 'NameError',
  497. 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
  498. 'PendingDeprecationWarning', 'ReferenceError',
  499. 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
  500. 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
  501. 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
  502. 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
  503. 'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning',
  504. 'WindowsError', 'ZeroDivisionError'), prefix=r'(?<!\.)', suffix=r'\b'),
  505. Name.Exception),
  506. ],
  507. 'magicfuncs': [
  508. (words((
  509. '__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',
  510. '__complex__', '__contains__', '__del__', '__delattr__', '__delete__',
  511. '__delitem__', '__delslice__', '__div__', '__divmod__', '__enter__',
  512. '__eq__', '__exit__', '__float__', '__floordiv__', '__ge__', '__get__',
  513. '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',
  514. '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__',
  515. '__ilshift__', '__imod__', '__imul__', '__index__', '__init__',
  516. '__instancecheck__', '__int__', '__invert__', '__iop__', '__ior__',
  517. '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__',
  518. '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__',
  519. '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',
  520. '__nonzero__', '__oct__', '__op__', '__or__', '__pos__', '__pow__',
  521. '__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__repr__',
  522. '__reversed__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
  523. '__rop__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
  524. '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__',
  525. '__setslice__', '__str__', '__sub__', '__subclasscheck__', '__truediv__',
  526. '__unicode__', '__xor__'), suffix=r'\b'),
  527. Name.Function.Magic),
  528. ],
  529. 'magicvars': [
  530. (words((
  531. '__bases__', '__class__', '__closure__', '__code__', '__defaults__',
  532. '__dict__', '__doc__', '__file__', '__func__', '__globals__',
  533. '__metaclass__', '__module__', '__mro__', '__name__', '__self__',
  534. '__slots__', '__weakref__'),
  535. suffix=r'\b'),
  536. Name.Variable.Magic),
  537. ],
  538. 'numbers': [
  539. (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?j?', Number.Float),
  540. (r'\d+[eE][+-]?[0-9]+j?', Number.Float),
  541. (r'0[0-7]+j?', Number.Oct),
  542. (r'0[bB][01]+', Number.Bin),
  543. (r'0[xX][a-fA-F0-9]+', Number.Hex),
  544. (r'\d+L', Number.Integer.Long),
  545. (r'\d+j?', Number.Integer)
  546. ],
  547. 'backtick': [
  548. ('`.*?`', String.Backtick),
  549. ],
  550. 'name': [
  551. (r'@[\w.]+', Name.Decorator),
  552. (r'[a-zA-Z_]\w*', Name),
  553. ],
  554. 'funcname': [
  555. include('magicfuncs'),
  556. (r'[a-zA-Z_]\w*', Name.Function, '#pop'),
  557. default('#pop'),
  558. ],
  559. 'classname': [
  560. (r'[a-zA-Z_]\w*', Name.Class, '#pop')
  561. ],
  562. 'import': [
  563. (r'(?:[ \t]|\\\n)+', Text),
  564. (r'as\b', Keyword.Namespace),
  565. (r',', Operator),
  566. (r'[a-zA-Z_][\w.]*', Name.Namespace),
  567. default('#pop') # all else: go back
  568. ],
  569. 'fromimport': [
  570. (r'(?:[ \t]|\\\n)+', Text),
  571. (r'import\b', Keyword.Namespace, '#pop'),
  572. # if None occurs here, it's "raise x from None", since None can
  573. # never be a module name
  574. (r'None\b', Name.Builtin.Pseudo, '#pop'),
  575. # sadly, in "raise x from y" y will be highlighted as namespace too
  576. (r'[a-zA-Z_.][\w.]*', Name.Namespace),
  577. # anything else here also means "raise x from y" and is therefore
  578. # not an error
  579. default('#pop'),
  580. ],
  581. 'stringescape': [
  582. (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|'
  583. r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
  584. ],
  585. 'strings-single': innerstring_rules(String.Single),
  586. 'strings-double': innerstring_rules(String.Double),
  587. 'dqs': [
  588. (r'"', String.Double, '#pop'),
  589. (r'\\\\|\\"|\\\n', String.Escape), # included here for raw strings
  590. include('strings-double')
  591. ],
  592. 'sqs': [
  593. (r"'", String.Single, '#pop'),
  594. (r"\\\\|\\'|\\\n", String.Escape), # included here for raw strings
  595. include('strings-single')
  596. ],
  597. 'tdqs': [
  598. (r'"""', String.Double, '#pop'),
  599. include('strings-double'),
  600. (r'\n', String.Double)
  601. ],
  602. 'tsqs': [
  603. (r"'''", String.Single, '#pop'),
  604. include('strings-single'),
  605. (r'\n', String.Single)
  606. ],
  607. }
  608. def analyse_text(text):
  609. return shebang_matches(text, r'pythonw?2(\.\d)?')
  610. class PythonConsoleLexer(Lexer):
  611. """
  612. For Python console output or doctests, such as:
  613. .. sourcecode:: pycon
  614. >>> a = 'foo'
  615. >>> print a
  616. foo
  617. >>> 1 / 0
  618. Traceback (most recent call last):
  619. File "<stdin>", line 1, in <module>
  620. ZeroDivisionError: integer division or modulo by zero
  621. Additional options:
  622. `python3`
  623. Use Python 3 lexer for code. Default is ``True``.
  624. .. versionadded:: 1.0
  625. .. versionchanged:: 2.5
  626. Now defaults to ``True``.
  627. """
  628. name = 'Python console session'
  629. aliases = ['pycon']
  630. mimetypes = ['text/x-python-doctest']
  631. def __init__(self, **options):
  632. self.python3 = get_bool_opt(options, 'python3', True)
  633. Lexer.__init__(self, **options)
  634. def get_tokens_unprocessed(self, text):
  635. if self.python3:
  636. pylexer = PythonLexer(**self.options)
  637. tblexer = PythonTracebackLexer(**self.options)
  638. else:
  639. pylexer = Python2Lexer(**self.options)
  640. tblexer = Python2TracebackLexer(**self.options)
  641. curcode = ''
  642. insertions = []
  643. curtb = ''
  644. tbindex = 0
  645. tb = 0
  646. for match in line_re.finditer(text):
  647. line = match.group()
  648. if line.startswith('>>> ') or line.startswith('... '):
  649. tb = 0
  650. insertions.append((len(curcode),
  651. [(0, Generic.Prompt, line[:4])]))
  652. curcode += line[4:]
  653. elif line.rstrip() == '...' and not tb:
  654. # only a new >>> prompt can end an exception block
  655. # otherwise an ellipsis in place of the traceback frames
  656. # will be mishandled
  657. insertions.append((len(curcode),
  658. [(0, Generic.Prompt, '...')]))
  659. curcode += line[3:]
  660. else:
  661. if curcode:
  662. yield from do_insertions(
  663. insertions, pylexer.get_tokens_unprocessed(curcode))
  664. curcode = ''
  665. insertions = []
  666. if (line.startswith('Traceback (most recent call last):') or
  667. re.match(' File "[^"]+", line \\d+\\n$', line)):
  668. tb = 1
  669. curtb = line
  670. tbindex = match.start()
  671. elif line == 'KeyboardInterrupt\n':
  672. yield match.start(), Name.Class, line
  673. elif tb:
  674. curtb += line
  675. if not (line.startswith(' ') or line.strip() == '...'):
  676. tb = 0
  677. for i, t, v in tblexer.get_tokens_unprocessed(curtb):
  678. yield tbindex+i, t, v
  679. curtb = ''
  680. else:
  681. yield match.start(), Generic.Output, line
  682. if curcode:
  683. yield from do_insertions(insertions,
  684. pylexer.get_tokens_unprocessed(curcode))
  685. if curtb:
  686. for i, t, v in tblexer.get_tokens_unprocessed(curtb):
  687. yield tbindex+i, t, v
  688. class PythonTracebackLexer(RegexLexer):
  689. """
  690. For Python 3.x tracebacks, with support for chained exceptions.
  691. .. versionadded:: 1.0
  692. .. versionchanged:: 2.5
  693. This is now the default ``PythonTracebackLexer``. It is still available
  694. as the alias ``Python3TracebackLexer``.
  695. """
  696. name = 'Python Traceback'
  697. aliases = ['pytb', 'py3tb']
  698. filenames = ['*.pytb', '*.py3tb']
  699. mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback']
  700. tokens = {
  701. 'root': [
  702. (r'\n', Text),
  703. (r'^Traceback \(most recent call last\):\n', Generic.Traceback, 'intb'),
  704. (r'^During handling of the above exception, another '
  705. r'exception occurred:\n\n', Generic.Traceback),
  706. (r'^The above exception was the direct cause of the '
  707. r'following exception:\n\n', Generic.Traceback),
  708. (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'),
  709. (r'^.*\n', Other),
  710. ],
  711. 'intb': [
  712. (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
  713. bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),
  714. (r'^( File )("[^"]+")(, line )(\d+)(\n)',
  715. bygroups(Text, Name.Builtin, Text, Number, Text)),
  716. (r'^( )(.+)(\n)',
  717. bygroups(Text, using(PythonLexer), Text), 'markers'),
  718. (r'^([ \t]*)(\.\.\.)(\n)',
  719. bygroups(Text, Comment, Text)), # for doctests...
  720. (r'^([^:]+)(: )(.+)(\n)',
  721. bygroups(Generic.Error, Text, Name, Text), '#pop'),
  722. (r'^([a-zA-Z_][\w.]*)(:?\n)',
  723. bygroups(Generic.Error, Text), '#pop')
  724. ],
  725. 'markers': [
  726. # Either `PEP 657 <https://www.python.org/dev/peps/pep-0657/>`
  727. # error locations in Python 3.11+, or single-caret markers
  728. # for syntax errors before that.
  729. (r'^( {4,})([~^]+)(\n)',
  730. bygroups(Text, Punctuation.Marker, Text),
  731. '#pop'),
  732. default('#pop'),
  733. ],
  734. }
  735. Python3TracebackLexer = PythonTracebackLexer
  736. class Python2TracebackLexer(RegexLexer):
  737. """
  738. For Python tracebacks.
  739. .. versionadded:: 0.7
  740. .. versionchanged:: 2.5
  741. This class has been renamed from ``PythonTracebackLexer``.
  742. ``PythonTracebackLexer`` now refers to the Python 3 variant.
  743. """
  744. name = 'Python 2.x Traceback'
  745. aliases = ['py2tb']
  746. filenames = ['*.py2tb']
  747. mimetypes = ['text/x-python2-traceback']
  748. tokens = {
  749. 'root': [
  750. # Cover both (most recent call last) and (innermost last)
  751. # The optional ^C allows us to catch keyboard interrupt signals.
  752. (r'^(\^C)?(Traceback.*\n)',
  753. bygroups(Text, Generic.Traceback), 'intb'),
  754. # SyntaxError starts with this.
  755. (r'^(?= File "[^"]+", line \d+)', Generic.Traceback, 'intb'),
  756. (r'^.*\n', Other),
  757. ],
  758. 'intb': [
  759. (r'^( File )("[^"]+")(, line )(\d+)(, in )(.+)(\n)',
  760. bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),
  761. (r'^( File )("[^"]+")(, line )(\d+)(\n)',
  762. bygroups(Text, Name.Builtin, Text, Number, Text)),
  763. (r'^( )(.+)(\n)',
  764. bygroups(Text, using(Python2Lexer), Text), 'marker'),
  765. (r'^([ \t]*)(\.\.\.)(\n)',
  766. bygroups(Text, Comment, Text)), # for doctests...
  767. (r'^([^:]+)(: )(.+)(\n)',
  768. bygroups(Generic.Error, Text, Name, Text), '#pop'),
  769. (r'^([a-zA-Z_]\w*)(:?\n)',
  770. bygroups(Generic.Error, Text), '#pop')
  771. ],
  772. 'marker': [
  773. # For syntax errors.
  774. (r'( {4,})(\^)', bygroups(Text, Punctuation.Marker), '#pop'),
  775. default('#pop'),
  776. ],
  777. }
  778. class CythonLexer(RegexLexer):
  779. """
  780. For Pyrex and Cython source code.
  781. .. versionadded:: 1.1
  782. """
  783. name = 'Cython'
  784. url = 'http://cython.org'
  785. aliases = ['cython', 'pyx', 'pyrex']
  786. filenames = ['*.pyx', '*.pxd', '*.pxi']
  787. mimetypes = ['text/x-cython', 'application/x-cython']
  788. tokens = {
  789. 'root': [
  790. (r'\n', Text),
  791. (r'^(\s*)("""(?:.|\n)*?""")', bygroups(Text, String.Doc)),
  792. (r"^(\s*)('''(?:.|\n)*?''')", bygroups(Text, String.Doc)),
  793. (r'[^\S\n]+', Text),
  794. (r'#.*$', Comment),
  795. (r'[]{}:(),;[]', Punctuation),
  796. (r'\\\n', Text),
  797. (r'\\', Text),
  798. (r'(in|is|and|or|not)\b', Operator.Word),
  799. (r'(<)([a-zA-Z0-9.?]+)(>)',
  800. bygroups(Punctuation, Keyword.Type, Punctuation)),
  801. (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator),
  802. (r'(from)(\d+)(<=)(\s+)(<)(\d+)(:)',
  803. bygroups(Keyword, Number.Integer, Operator, Name, Operator,
  804. Name, Punctuation)),
  805. include('keywords'),
  806. (r'(def|property)(\s+)', bygroups(Keyword, Text), 'funcname'),
  807. (r'(cp?def)(\s+)', bygroups(Keyword, Text), 'cdef'),
  808. # (should actually start a block with only cdefs)
  809. (r'(cdef)(:)', bygroups(Keyword, Punctuation)),
  810. (r'(class|struct)(\s+)', bygroups(Keyword, Text), 'classname'),
  811. (r'(from)(\s+)', bygroups(Keyword, Text), 'fromimport'),
  812. (r'(c?import)(\s+)', bygroups(Keyword, Text), 'import'),
  813. include('builtins'),
  814. include('backtick'),
  815. ('(?:[rR]|[uU][rR]|[rR][uU])"""', String, 'tdqs'),
  816. ("(?:[rR]|[uU][rR]|[rR][uU])'''", String, 'tsqs'),
  817. ('(?:[rR]|[uU][rR]|[rR][uU])"', String, 'dqs'),
  818. ("(?:[rR]|[uU][rR]|[rR][uU])'", String, 'sqs'),
  819. ('[uU]?"""', String, combined('stringescape', 'tdqs')),
  820. ("[uU]?'''", String, combined('stringescape', 'tsqs')),
  821. ('[uU]?"', String, combined('stringescape', 'dqs')),
  822. ("[uU]?'", String, combined('stringescape', 'sqs')),
  823. include('name'),
  824. include('numbers'),
  825. ],
  826. 'keywords': [
  827. (words((
  828. 'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', 'elif',
  829. 'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil',
  830. 'global', 'if', 'include', 'lambda', 'nogil', 'pass', 'print',
  831. 'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), suffix=r'\b'),
  832. Keyword),
  833. (r'(DEF|IF|ELIF|ELSE)\b', Comment.Preproc),
  834. ],
  835. 'builtins': [
  836. (words((
  837. '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint',
  838. 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',
  839. 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr',
  840. 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit',
  841. 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals',
  842. 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance',
  843. 'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max',
  844. 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'Py_ssize_t',
  845. 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed',
  846. 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod',
  847. 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'unsigned',
  848. 'vars', 'xrange', 'zip'), prefix=r'(?<!\.)', suffix=r'\b'),
  849. Name.Builtin),
  850. (r'(?<!\.)(self|None|Ellipsis|NotImplemented|False|True|NULL'
  851. r')\b', Name.Builtin.Pseudo),
  852. (words((
  853. 'ArithmeticError', 'AssertionError', 'AttributeError',
  854. 'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',
  855. 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',
  856. 'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
  857. 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
  858. 'MemoryError', 'NameError', 'NotImplemented', 'NotImplementedError',
  859. 'OSError', 'OverflowError', 'OverflowWarning',
  860. 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
  861. 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
  862. 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
  863. 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
  864. 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
  865. 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
  866. 'ZeroDivisionError'), prefix=r'(?<!\.)', suffix=r'\b'),
  867. Name.Exception),
  868. ],
  869. 'numbers': [
  870. (r'(\d+\.?\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float),
  871. (r'0\d+', Number.Oct),
  872. (r'0[xX][a-fA-F0-9]+', Number.Hex),
  873. (r'\d+L', Number.Integer.Long),
  874. (r'\d+', Number.Integer)
  875. ],
  876. 'backtick': [
  877. ('`.*?`', String.Backtick),
  878. ],
  879. 'name': [
  880. (r'@\w+', Name.Decorator),
  881. (r'[a-zA-Z_]\w*', Name),
  882. ],
  883. 'funcname': [
  884. (r'[a-zA-Z_]\w*', Name.Function, '#pop')
  885. ],
  886. 'cdef': [
  887. (r'(public|readonly|extern|api|inline)\b', Keyword.Reserved),
  888. (r'(struct|enum|union|class)\b', Keyword),
  889. (r'([a-zA-Z_]\w*)(\s*)(?=[(:#=]|$)',
  890. bygroups(Name.Function, Text), '#pop'),
  891. (r'([a-zA-Z_]\w*)(\s*)(,)',
  892. bygroups(Name.Function, Text, Punctuation)),
  893. (r'from\b', Keyword, '#pop'),
  894. (r'as\b', Keyword),
  895. (r':', Punctuation, '#pop'),
  896. (r'(?=["\'])', Text, '#pop'),
  897. (r'[a-zA-Z_]\w*', Keyword.Type),
  898. (r'.', Text),
  899. ],
  900. 'classname': [
  901. (r'[a-zA-Z_]\w*', Name.Class, '#pop')
  902. ],
  903. 'import': [
  904. (r'(\s+)(as)(\s+)', bygroups(Text, Keyword, Text)),
  905. (r'[a-zA-Z_][\w.]*', Name.Namespace),
  906. (r'(\s*)(,)(\s*)', bygroups(Text, Operator, Text)),
  907. default('#pop') # all else: go back
  908. ],
  909. 'fromimport': [
  910. (r'(\s+)(c?import)\b', bygroups(Text, Keyword), '#pop'),
  911. (r'[a-zA-Z_.][\w.]*', Name.Namespace),
  912. # ``cdef foo from "header"``, or ``for foo from 0 < i < 10``
  913. default('#pop'),
  914. ],
  915. 'stringescape': [
  916. (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|'
  917. r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
  918. ],
  919. 'strings': [
  920. (r'%(\([a-zA-Z0-9]+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
  921. '[hlL]?[E-GXc-giorsux%]', String.Interpol),
  922. (r'[^\\\'"%\n]+', String),
  923. # quotes, percents and backslashes must be parsed one at a time
  924. (r'[\'"\\]', String),
  925. # unhandled string formatting sign
  926. (r'%', String)
  927. # newlines are an error (use "nl" state)
  928. ],
  929. 'nl': [
  930. (r'\n', String)
  931. ],
  932. 'dqs': [
  933. (r'"', String, '#pop'),
  934. (r'\\\\|\\"|\\\n', String.Escape), # included here again for raw strings
  935. include('strings')
  936. ],
  937. 'sqs': [
  938. (r"'", String, '#pop'),
  939. (r"\\\\|\\'|\\\n", String.Escape), # included here again for raw strings
  940. include('strings')
  941. ],
  942. 'tdqs': [
  943. (r'"""', String, '#pop'),
  944. include('strings'),
  945. include('nl')
  946. ],
  947. 'tsqs': [
  948. (r"'''", String, '#pop'),
  949. include('strings'),
  950. include('nl')
  951. ],
  952. }
  953. class DgLexer(RegexLexer):
  954. """
  955. Lexer for dg,
  956. a functional and object-oriented programming language
  957. running on the CPython 3 VM.
  958. .. versionadded:: 1.6
  959. """
  960. name = 'dg'
  961. aliases = ['dg']
  962. filenames = ['*.dg']
  963. mimetypes = ['text/x-dg']
  964. tokens = {
  965. 'root': [
  966. (r'\s+', Text),
  967. (r'#.*?$', Comment.Single),
  968. (r'(?i)0b[01]+', Number.Bin),
  969. (r'(?i)0o[0-7]+', Number.Oct),
  970. (r'(?i)0x[0-9a-f]+', Number.Hex),
  971. (r'(?i)[+-]?[0-9]+\.[0-9]+(e[+-]?[0-9]+)?j?', Number.Float),
  972. (r'(?i)[+-]?[0-9]+e[+-]?\d+j?', Number.Float),
  973. (r'(?i)[+-]?[0-9]+j?', Number.Integer),
  974. (r"(?i)(br|r?b?)'''", String, combined('stringescape', 'tsqs', 'string')),
  975. (r'(?i)(br|r?b?)"""', String, combined('stringescape', 'tdqs', 'string')),
  976. (r"(?i)(br|r?b?)'", String, combined('stringescape', 'sqs', 'string')),
  977. (r'(?i)(br|r?b?)"', String, combined('stringescape', 'dqs', 'string')),
  978. (r"`\w+'*`", Operator),
  979. (r'\b(and|in|is|or|where)\b', Operator.Word),
  980. (r'[!$%&*+\-./:<-@\\^|~;,]+', Operator),
  981. (words((
  982. 'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'dict\'',
  983. 'float', 'frozenset', 'int', 'list', 'list\'', 'memoryview', 'object',
  984. 'property', 'range', 'set', 'set\'', 'slice', 'staticmethod', 'str',
  985. 'super', 'tuple', 'tuple\'', 'type'),
  986. prefix=r'(?<!\.)', suffix=r'(?![\'\w])'),
  987. Name.Builtin),
  988. (words((
  989. '__import__', 'abs', 'all', 'any', 'bin', 'bind', 'chr', 'cmp', 'compile',
  990. 'complex', 'delattr', 'dir', 'divmod', 'drop', 'dropwhile', 'enumerate',
  991. 'eval', 'exhaust', 'filter', 'flip', 'foldl1?', 'format', 'fst',
  992. 'getattr', 'globals', 'hasattr', 'hash', 'head', 'hex', 'id', 'init',
  993. 'input', 'isinstance', 'issubclass', 'iter', 'iterate', 'last', 'len',
  994. 'locals', 'map', 'max', 'min', 'next', 'oct', 'open', 'ord', 'pow',
  995. 'print', 'repr', 'reversed', 'round', 'setattr', 'scanl1?', 'snd',
  996. 'sorted', 'sum', 'tail', 'take', 'takewhile', 'vars', 'zip'),
  997. prefix=r'(?<!\.)', suffix=r'(?![\'\w])'),
  998. Name.Builtin),
  999. (r"(?<!\.)(self|Ellipsis|NotImplemented|None|True|False)(?!['\w])",
  1000. Name.Builtin.Pseudo),
  1001. (r"(?<!\.)[A-Z]\w*(Error|Exception|Warning)'*(?!['\w])",
  1002. Name.Exception),
  1003. (r"(?<!\.)(Exception|GeneratorExit|KeyboardInterrupt|StopIteration|"
  1004. r"SystemExit)(?!['\w])", Name.Exception),
  1005. (r"(?<![\w.])(except|finally|for|if|import|not|otherwise|raise|"
  1006. r"subclass|while|with|yield)(?!['\w])", Keyword.Reserved),
  1007. (r"[A-Z_]+'*(?!['\w])", Name),
  1008. (r"[A-Z]\w+'*(?!['\w])", Keyword.Type),
  1009. (r"\w+'*", Name),
  1010. (r'[()]', Punctuation),
  1011. (r'.', Error),
  1012. ],
  1013. 'stringescape': [
  1014. (r'\\([\\abfnrtv"\']|\n|N\{.*?\}|u[a-fA-F0-9]{4}|'
  1015. r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)
  1016. ],
  1017. 'string': [
  1018. (r'%(\(\w+\))?[-#0 +]*([0-9]+|[*])?(\.([0-9]+|[*]))?'
  1019. '[hlL]?[E-GXc-giorsux%]', String.Interpol),
  1020. (r'[^\\\'"%\n]+', String),
  1021. # quotes, percents and backslashes must be parsed one at a time
  1022. (r'[\'"\\]', String),
  1023. # unhandled string formatting sign
  1024. (r'%', String),
  1025. (r'\n', String)
  1026. ],
  1027. 'dqs': [
  1028. (r'"', String, '#pop')
  1029. ],
  1030. 'sqs': [
  1031. (r"'", String, '#pop')
  1032. ],
  1033. 'tdqs': [
  1034. (r'"""', String, '#pop')
  1035. ],
  1036. 'tsqs': [
  1037. (r"'''", String, '#pop')
  1038. ],
  1039. }
  1040. class NumPyLexer(PythonLexer):
  1041. """
  1042. A Python lexer recognizing Numerical Python builtins.
  1043. .. versionadded:: 0.10
  1044. """
  1045. name = 'NumPy'
  1046. url = 'https://numpy.org/'
  1047. aliases = ['numpy']
  1048. # override the mimetypes to not inherit them from python
  1049. mimetypes = []
  1050. filenames = []
  1051. EXTRA_KEYWORDS = {
  1052. 'abs', 'absolute', 'accumulate', 'add', 'alen', 'all', 'allclose',
  1053. 'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append',
  1054. 'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh',
  1055. 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin',
  1056. 'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal',
  1057. 'array_equiv', 'array_repr', 'array_split', 'array_str', 'arrayrange',
  1058. 'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray',
  1059. 'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'astype',
  1060. 'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett',
  1061. 'base_repr', 'beta', 'binary_repr', 'bincount', 'binomial',
  1062. 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman',
  1063. 'bmat', 'broadcast', 'byte_bounds', 'bytes', 'byteswap', 'c_',
  1064. 'can_cast', 'ceil', 'choose', 'clip', 'column_stack', 'common_type',
  1065. 'compare_chararrays', 'compress', 'concatenate', 'conj', 'conjugate',
  1066. 'convolve', 'copy', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov',
  1067. 'cross', 'cumprod', 'cumproduct', 'cumsum', 'delete', 'deprecate',
  1068. 'diag', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide',
  1069. 'dot', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'empty',
  1070. 'empty_like', 'equal', 'exp', 'expand_dims', 'expm1', 'extract', 'eye',
  1071. 'fabs', 'fastCopyAndTranspose', 'fft', 'fftfreq', 'fftshift', 'fill',
  1072. 'finfo', 'fix', 'flat', 'flatnonzero', 'flatten', 'fliplr', 'flipud',
  1073. 'floor', 'floor_divide', 'fmod', 'frexp', 'fromarrays', 'frombuffer',
  1074. 'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromstring',
  1075. 'generic', 'get_array_wrap', 'get_include', 'get_numarray_include',
  1076. 'get_numpy_include', 'get_printoptions', 'getbuffer', 'getbufsize',
  1077. 'geterr', 'geterrcall', 'geterrobj', 'getfield', 'gradient', 'greater',
  1078. 'greater_equal', 'gumbel', 'hamming', 'hanning', 'histogram',
  1079. 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0',
  1080. 'identity', 'ifft', 'imag', 'index_exp', 'indices', 'inf', 'info',
  1081. 'inner', 'insert', 'int_asbuffer', 'interp', 'intersect1d',
  1082. 'intersect1d_nu', 'inv', 'invert', 'iscomplex', 'iscomplexobj',
  1083. 'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf',
  1084. 'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_',
  1085. 'issubdtype', 'issubsctype', 'item', 'itemset', 'iterable', 'ix_',
  1086. 'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort',
  1087. 'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2',
  1088. 'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace',
  1089. 'lstsq', 'mat', 'matrix', 'max', 'maximum', 'maximum_sctype',
  1090. 'may_share_memory', 'mean', 'median', 'meshgrid', 'mgrid', 'min',
  1091. 'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan',
  1092. 'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum',
  1093. 'ndenumerate', 'ndim', 'ndindex', 'negative', 'newaxis', 'newbuffer',
  1094. 'newbyteorder', 'nonzero', 'not_equal', 'obj2sctype', 'ogrid', 'ones',
  1095. 'ones_like', 'outer', 'permutation', 'piecewise', 'pinv', 'pkgload',
  1096. 'place', 'poisson', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv',
  1097. 'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'prod',
  1098. 'product', 'ptp', 'put', 'putmask', 'r_', 'randint', 'random_integers',
  1099. 'random_sample', 'ranf', 'rank', 'ravel', 'real', 'real_if_close',
  1100. 'recarray', 'reciprocal', 'reduce', 'remainder', 'repeat', 'require',
  1101. 'reshape', 'resize', 'restoredot', 'right_shift', 'rint', 'roll',
  1102. 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_',
  1103. 'sample', 'savetxt', 'sctype2char', 'searchsorted', 'seed', 'select',
  1104. 'set_numeric_ops', 'set_printoptions', 'set_string_function',
  1105. 'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj',
  1106. 'setfield', 'setflags', 'setmember1d', 'setxor1d', 'shape',
  1107. 'show_config', 'shuffle', 'sign', 'signbit', 'sin', 'sinc', 'sinh',
  1108. 'size', 'slice', 'solve', 'sometrue', 'sort', 'sort_complex', 'source',
  1109. 'split', 'sqrt', 'square', 'squeeze', 'standard_normal', 'std',
  1110. 'subtract', 'sum', 'svd', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot',
  1111. 'test', 'tile', 'tofile', 'tolist', 'tostring', 'trace', 'transpose',
  1112. 'trapz', 'tri', 'tril', 'trim_zeros', 'triu', 'true_divide', 'typeDict',
  1113. 'typename', 'uniform', 'union1d', 'unique', 'unique1d', 'unravel_index',
  1114. 'unwrap', 'vander', 'var', 'vdot', 'vectorize', 'view', 'vonmises',
  1115. 'vsplit', 'vstack', 'weibull', 'where', 'who', 'zeros', 'zeros_like'
  1116. }
  1117. def get_tokens_unprocessed(self, text):
  1118. for index, token, value in \
  1119. PythonLexer.get_tokens_unprocessed(self, text):
  1120. if token is Name and value in self.EXTRA_KEYWORDS:
  1121. yield index, Keyword.Pseudo, value
  1122. else:
  1123. yield index, token, value
  1124. def analyse_text(text):
  1125. ltext = text[:1000]
  1126. return (shebang_matches(text, r'pythonw?(3(\.\d)?)?') or
  1127. 'import ' in ltext) \
  1128. and ('import numpy' in ltext or 'from numpy import' in ltext)