python.py 46 KB

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