python.py 53 KB

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