python.py 52 KB

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