python.py 50 KB

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