PageRenderTime 46ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/lib/lexers.py

http://github.com/ipython/ipython
Python | 532 lines | 476 code | 7 blank | 49 comment | 1 complexity | 2ddf2ca8b18fec8f68cbbb7bf236d346 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, Apache-2.0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Defines a variety of Pygments lexers for highlighting IPython code.
  4. This includes:
  5. IPythonLexer, IPython3Lexer
  6. Lexers for pure IPython (python + magic/shell commands)
  7. IPythonPartialTracebackLexer, IPythonTracebackLexer
  8. Supports 2.x and 3.x via keyword `python3`. The partial traceback
  9. lexer reads everything but the Python code appearing in a traceback.
  10. The full lexer combines the partial lexer with an IPython lexer.
  11. IPythonConsoleLexer
  12. A lexer for IPython console sessions, with support for tracebacks.
  13. IPyLexer
  14. A friendly lexer which examines the first line of text and from it,
  15. decides whether to use an IPython lexer or an IPython console lexer.
  16. This is probably the only lexer that needs to be explicitly added
  17. to Pygments.
  18. """
  19. #-----------------------------------------------------------------------------
  20. # Copyright (c) 2013, the IPython Development Team.
  21. #
  22. # Distributed under the terms of the Modified BSD License.
  23. #
  24. # The full license is in the file COPYING.txt, distributed with this software.
  25. #-----------------------------------------------------------------------------
  26. # Standard library
  27. import re
  28. # Third party
  29. from pygments.lexers import (
  30. BashLexer, HtmlLexer, JavascriptLexer, RubyLexer, PerlLexer, PythonLexer,
  31. Python3Lexer, TexLexer)
  32. from pygments.lexer import (
  33. Lexer, DelegatingLexer, RegexLexer, do_insertions, bygroups, using,
  34. )
  35. from pygments.token import (
  36. Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
  37. )
  38. from pygments.util import get_bool_opt
  39. # Local
  40. line_re = re.compile('.*?\n')
  41. __all__ = ['build_ipy_lexer', 'IPython3Lexer', 'IPythonLexer',
  42. 'IPythonPartialTracebackLexer', 'IPythonTracebackLexer',
  43. 'IPythonConsoleLexer', 'IPyLexer']
  44. def build_ipy_lexer(python3):
  45. """Builds IPython lexers depending on the value of `python3`.
  46. The lexer inherits from an appropriate Python lexer and then adds
  47. information about IPython specific keywords (i.e. magic commands,
  48. shell commands, etc.)
  49. Parameters
  50. ----------
  51. python3 : bool
  52. If `True`, then build an IPython lexer from a Python 3 lexer.
  53. """
  54. # It would be nice to have a single IPython lexer class which takes
  55. # a boolean `python3`. But since there are two Python lexer classes,
  56. # we will also have two IPython lexer classes.
  57. if python3:
  58. PyLexer = Python3Lexer
  59. name = 'IPython3'
  60. aliases = ['ipython3']
  61. doc = """IPython3 Lexer"""
  62. else:
  63. PyLexer = PythonLexer
  64. name = 'IPython'
  65. aliases = ['ipython2', 'ipython']
  66. doc = """IPython Lexer"""
  67. ipython_tokens = [
  68. (r'(?s)(\s*)(%%capture)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  69. (r'(?s)(\s*)(%%debug)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  70. (r'(?is)(\s*)(%%html)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(HtmlLexer))),
  71. (r'(?s)(\s*)(%%javascript)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(JavascriptLexer))),
  72. (r'(?s)(\s*)(%%js)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(JavascriptLexer))),
  73. (r'(?s)(\s*)(%%latex)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(TexLexer))),
  74. (r'(?s)(\s*)(%%perl)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PerlLexer))),
  75. (r'(?s)(\s*)(%%prun)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  76. (r'(?s)(\s*)(%%pypy)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  77. (r'(?s)(\s*)(%%python)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  78. (r'(?s)(\s*)(%%python2)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PythonLexer))),
  79. (r'(?s)(\s*)(%%python3)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(Python3Lexer))),
  80. (r'(?s)(\s*)(%%ruby)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(RubyLexer))),
  81. (r'(?s)(\s*)(%%time)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  82. (r'(?s)(\s*)(%%timeit)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  83. (r'(?s)(\s*)(%%writefile)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  84. (r'(?s)(\s*)(%%file)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(PyLexer))),
  85. (r"(?s)(\s*)(%%)(\w+)(.*)", bygroups(Text, Operator, Keyword, Text)),
  86. (r'(?s)(^\s*)(%%!)([^\n]*\n)(.*)', bygroups(Text, Operator, Text, using(BashLexer))),
  87. (r"(%%?)(\w+)(\?\??)$", bygroups(Operator, Keyword, Operator)),
  88. (r"\b(\?\??)(\s*)$", bygroups(Operator, Text)),
  89. (r'(%)(sx|sc|system)(.*)(\n)', bygroups(Operator, Keyword,
  90. using(BashLexer), Text)),
  91. (r'(%)(\w+)(.*\n)', bygroups(Operator, Keyword, Text)),
  92. (r'^(!!)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
  93. (r'(!)(?!=)(.+)(\n)', bygroups(Operator, using(BashLexer), Text)),
  94. (r'^(\s*)(\?\??)(\s*%{0,2}[\w\.\*]*)', bygroups(Text, Operator, Text)),
  95. (r'(\s*%{0,2}[\w\.\*]*)(\?\??)(\s*)$', bygroups(Text, Operator, Text)),
  96. ]
  97. tokens = PyLexer.tokens.copy()
  98. tokens['root'] = ipython_tokens + tokens['root']
  99. attrs = {'name': name, 'aliases': aliases, 'filenames': [],
  100. '__doc__': doc, 'tokens': tokens}
  101. return type(name, (PyLexer,), attrs)
  102. IPython3Lexer = build_ipy_lexer(python3=True)
  103. IPythonLexer = build_ipy_lexer(python3=False)
  104. class IPythonPartialTracebackLexer(RegexLexer):
  105. """
  106. Partial lexer for IPython tracebacks.
  107. Handles all the non-python output.
  108. """
  109. name = 'IPython Partial Traceback'
  110. tokens = {
  111. 'root': [
  112. # Tracebacks for syntax errors have a different style.
  113. # For both types of tracebacks, we mark the first line with
  114. # Generic.Traceback. For syntax errors, we mark the filename
  115. # as we mark the filenames for non-syntax tracebacks.
  116. #
  117. # These two regexps define how IPythonConsoleLexer finds a
  118. # traceback.
  119. #
  120. ## Non-syntax traceback
  121. (r'^(\^C)?(-+\n)', bygroups(Error, Generic.Traceback)),
  122. ## Syntax traceback
  123. (r'^( File)(.*)(, line )(\d+\n)',
  124. bygroups(Generic.Traceback, Name.Namespace,
  125. Generic.Traceback, Literal.Number.Integer)),
  126. # (Exception Identifier)(Whitespace)(Traceback Message)
  127. (r'(?u)(^[^\d\W]\w*)(\s*)(Traceback.*?\n)',
  128. bygroups(Name.Exception, Generic.Whitespace, Text)),
  129. # (Module/Filename)(Text)(Callee)(Function Signature)
  130. # Better options for callee and function signature?
  131. (r'(.*)( in )(.*)(\(.*\)\n)',
  132. bygroups(Name.Namespace, Text, Name.Entity, Name.Tag)),
  133. # Regular line: (Whitespace)(Line Number)(Python Code)
  134. (r'(\s*?)(\d+)(.*?\n)',
  135. bygroups(Generic.Whitespace, Literal.Number.Integer, Other)),
  136. # Emphasized line: (Arrow)(Line Number)(Python Code)
  137. # Using Exception token so arrow color matches the Exception.
  138. (r'(-*>?\s?)(\d+)(.*?\n)',
  139. bygroups(Name.Exception, Literal.Number.Integer, Other)),
  140. # (Exception Identifier)(Message)
  141. (r'(?u)(^[^\d\W]\w*)(:.*?\n)',
  142. bygroups(Name.Exception, Text)),
  143. # Tag everything else as Other, will be handled later.
  144. (r'.*\n', Other),
  145. ],
  146. }
  147. class IPythonTracebackLexer(DelegatingLexer):
  148. """
  149. IPython traceback lexer.
  150. For doctests, the tracebacks can be snipped as much as desired with the
  151. exception to the lines that designate a traceback. For non-syntax error
  152. tracebacks, this is the line of hyphens. For syntax error tracebacks,
  153. this is the line which lists the File and line number.
  154. """
  155. # The lexer inherits from DelegatingLexer. The "root" lexer is an
  156. # appropriate IPython lexer, which depends on the value of the boolean
  157. # `python3`. First, we parse with the partial IPython traceback lexer.
  158. # Then, any code marked with the "Other" token is delegated to the root
  159. # lexer.
  160. #
  161. name = 'IPython Traceback'
  162. aliases = ['ipythontb']
  163. def __init__(self, **options):
  164. self.python3 = get_bool_opt(options, 'python3', False)
  165. if self.python3:
  166. self.aliases = ['ipython3tb']
  167. else:
  168. self.aliases = ['ipython2tb', 'ipythontb']
  169. if self.python3:
  170. IPyLexer = IPython3Lexer
  171. else:
  172. IPyLexer = IPythonLexer
  173. DelegatingLexer.__init__(self, IPyLexer,
  174. IPythonPartialTracebackLexer, **options)
  175. class IPythonConsoleLexer(Lexer):
  176. """
  177. An IPython console lexer for IPython code-blocks and doctests, such as:
  178. .. code-block:: rst
  179. .. code-block:: ipythonconsole
  180. In [1]: a = 'foo'
  181. In [2]: a
  182. Out[2]: 'foo'
  183. In [3]: print a
  184. foo
  185. In [4]: 1 / 0
  186. Support is also provided for IPython exceptions:
  187. .. code-block:: rst
  188. .. code-block:: ipythonconsole
  189. In [1]: raise Exception
  190. ---------------------------------------------------------------------------
  191. Exception Traceback (most recent call last)
  192. <ipython-input-1-fca2ab0ca76b> in <module>
  193. ----> 1 raise Exception
  194. Exception:
  195. """
  196. name = 'IPython console session'
  197. aliases = ['ipythonconsole']
  198. mimetypes = ['text/x-ipython-console']
  199. # The regexps used to determine what is input and what is output.
  200. # The default prompts for IPython are:
  201. #
  202. # in = 'In [#]: '
  203. # continuation = ' .D.: '
  204. # template = 'Out[#]: '
  205. #
  206. # Where '#' is the 'prompt number' or 'execution count' and 'D'
  207. # D is a number of dots matching the width of the execution count
  208. #
  209. in1_regex = r'In \[[0-9]+\]: '
  210. in2_regex = r' \.\.+\.: '
  211. out_regex = r'Out\[[0-9]+\]: '
  212. #: The regex to determine when a traceback starts.
  213. ipytb_start = re.compile(r'^(\^C)?(-+\n)|^( File)(.*)(, line )(\d+\n)')
  214. def __init__(self, **options):
  215. """Initialize the IPython console lexer.
  216. Parameters
  217. ----------
  218. python3 : bool
  219. If `True`, then the console inputs are parsed using a Python 3
  220. lexer. Otherwise, they are parsed using a Python 2 lexer.
  221. in1_regex : RegexObject
  222. The compiled regular expression used to detect the start
  223. of inputs. Although the IPython configuration setting may have a
  224. trailing whitespace, do not include it in the regex. If `None`,
  225. then the default input prompt is assumed.
  226. in2_regex : RegexObject
  227. The compiled regular expression used to detect the continuation
  228. of inputs. Although the IPython configuration setting may have a
  229. trailing whitespace, do not include it in the regex. If `None`,
  230. then the default input prompt is assumed.
  231. out_regex : RegexObject
  232. The compiled regular expression used to detect outputs. If `None`,
  233. then the default output prompt is assumed.
  234. """
  235. self.python3 = get_bool_opt(options, 'python3', False)
  236. if self.python3:
  237. self.aliases = ['ipython3console']
  238. else:
  239. self.aliases = ['ipython2console', 'ipythonconsole']
  240. in1_regex = options.get('in1_regex', self.in1_regex)
  241. in2_regex = options.get('in2_regex', self.in2_regex)
  242. out_regex = options.get('out_regex', self.out_regex)
  243. # So that we can work with input and output prompts which have been
  244. # rstrip'd (possibly by editors) we also need rstrip'd variants. If
  245. # we do not do this, then such prompts will be tagged as 'output'.
  246. # The reason can't just use the rstrip'd variants instead is because
  247. # we want any whitespace associated with the prompt to be inserted
  248. # with the token. This allows formatted code to be modified so as hide
  249. # the appearance of prompts, with the whitespace included. One example
  250. # use of this is in copybutton.js from the standard lib Python docs.
  251. in1_regex_rstrip = in1_regex.rstrip() + '\n'
  252. in2_regex_rstrip = in2_regex.rstrip() + '\n'
  253. out_regex_rstrip = out_regex.rstrip() + '\n'
  254. # Compile and save them all.
  255. attrs = ['in1_regex', 'in2_regex', 'out_regex',
  256. 'in1_regex_rstrip', 'in2_regex_rstrip', 'out_regex_rstrip']
  257. for attr in attrs:
  258. self.__setattr__(attr, re.compile(locals()[attr]))
  259. Lexer.__init__(self, **options)
  260. if self.python3:
  261. pylexer = IPython3Lexer
  262. tblexer = IPythonTracebackLexer
  263. else:
  264. pylexer = IPythonLexer
  265. tblexer = IPythonTracebackLexer
  266. self.pylexer = pylexer(**options)
  267. self.tblexer = tblexer(**options)
  268. self.reset()
  269. def reset(self):
  270. self.mode = 'output'
  271. self.index = 0
  272. self.buffer = u''
  273. self.insertions = []
  274. def buffered_tokens(self):
  275. """
  276. Generator of unprocessed tokens after doing insertions and before
  277. changing to a new state.
  278. """
  279. if self.mode == 'output':
  280. tokens = [(0, Generic.Output, self.buffer)]
  281. elif self.mode == 'input':
  282. tokens = self.pylexer.get_tokens_unprocessed(self.buffer)
  283. else: # traceback
  284. tokens = self.tblexer.get_tokens_unprocessed(self.buffer)
  285. for i, t, v in do_insertions(self.insertions, tokens):
  286. # All token indexes are relative to the buffer.
  287. yield self.index + i, t, v
  288. # Clear it all
  289. self.index += len(self.buffer)
  290. self.buffer = u''
  291. self.insertions = []
  292. def get_mci(self, line):
  293. """
  294. Parses the line and returns a 3-tuple: (mode, code, insertion).
  295. `mode` is the next mode (or state) of the lexer, and is always equal
  296. to 'input', 'output', or 'tb'.
  297. `code` is a portion of the line that should be added to the buffer
  298. corresponding to the next mode and eventually lexed by another lexer.
  299. For example, `code` could be Python code if `mode` were 'input'.
  300. `insertion` is a 3-tuple (index, token, text) representing an
  301. unprocessed "token" that will be inserted into the stream of tokens
  302. that are created from the buffer once we change modes. This is usually
  303. the input or output prompt.
  304. In general, the next mode depends on current mode and on the contents
  305. of `line`.
  306. """
  307. # To reduce the number of regex match checks, we have multiple
  308. # 'if' blocks instead of 'if-elif' blocks.
  309. # Check for possible end of input
  310. in2_match = self.in2_regex.match(line)
  311. in2_match_rstrip = self.in2_regex_rstrip.match(line)
  312. if (in2_match and in2_match.group().rstrip() == line.rstrip()) or \
  313. in2_match_rstrip:
  314. end_input = True
  315. else:
  316. end_input = False
  317. if end_input and self.mode != 'tb':
  318. # Only look for an end of input when not in tb mode.
  319. # An ellipsis could appear within the traceback.
  320. mode = 'output'
  321. code = u''
  322. insertion = (0, Generic.Prompt, line)
  323. return mode, code, insertion
  324. # Check for output prompt
  325. out_match = self.out_regex.match(line)
  326. out_match_rstrip = self.out_regex_rstrip.match(line)
  327. if out_match or out_match_rstrip:
  328. mode = 'output'
  329. if out_match:
  330. idx = out_match.end()
  331. else:
  332. idx = out_match_rstrip.end()
  333. code = line[idx:]
  334. # Use the 'heading' token for output. We cannot use Generic.Error
  335. # since it would conflict with exceptions.
  336. insertion = (0, Generic.Heading, line[:idx])
  337. return mode, code, insertion
  338. # Check for input or continuation prompt (non stripped version)
  339. in1_match = self.in1_regex.match(line)
  340. if in1_match or (in2_match and self.mode != 'tb'):
  341. # New input or when not in tb, continued input.
  342. # We do not check for continued input when in tb since it is
  343. # allowable to replace a long stack with an ellipsis.
  344. mode = 'input'
  345. if in1_match:
  346. idx = in1_match.end()
  347. else: # in2_match
  348. idx = in2_match.end()
  349. code = line[idx:]
  350. insertion = (0, Generic.Prompt, line[:idx])
  351. return mode, code, insertion
  352. # Check for input or continuation prompt (stripped version)
  353. in1_match_rstrip = self.in1_regex_rstrip.match(line)
  354. if in1_match_rstrip or (in2_match_rstrip and self.mode != 'tb'):
  355. # New input or when not in tb, continued input.
  356. # We do not check for continued input when in tb since it is
  357. # allowable to replace a long stack with an ellipsis.
  358. mode = 'input'
  359. if in1_match_rstrip:
  360. idx = in1_match_rstrip.end()
  361. else: # in2_match
  362. idx = in2_match_rstrip.end()
  363. code = line[idx:]
  364. insertion = (0, Generic.Prompt, line[:idx])
  365. return mode, code, insertion
  366. # Check for traceback
  367. if self.ipytb_start.match(line):
  368. mode = 'tb'
  369. code = line
  370. insertion = None
  371. return mode, code, insertion
  372. # All other stuff...
  373. if self.mode in ('input', 'output'):
  374. # We assume all other text is output. Multiline input that
  375. # does not use the continuation marker cannot be detected.
  376. # For example, the 3 in the following is clearly output:
  377. #
  378. # In [1]: print 3
  379. # 3
  380. #
  381. # But the following second line is part of the input:
  382. #
  383. # In [2]: while True:
  384. # print True
  385. #
  386. # In both cases, the 2nd line will be 'output'.
  387. #
  388. mode = 'output'
  389. else:
  390. mode = 'tb'
  391. code = line
  392. insertion = None
  393. return mode, code, insertion
  394. def get_tokens_unprocessed(self, text):
  395. self.reset()
  396. for match in line_re.finditer(text):
  397. line = match.group()
  398. mode, code, insertion = self.get_mci(line)
  399. if mode != self.mode:
  400. # Yield buffered tokens before transitioning to new mode.
  401. for token in self.buffered_tokens():
  402. yield token
  403. self.mode = mode
  404. if insertion:
  405. self.insertions.append((len(self.buffer), [insertion]))
  406. self.buffer += code
  407. for token in self.buffered_tokens():
  408. yield token
  409. class IPyLexer(Lexer):
  410. r"""
  411. Primary lexer for all IPython-like code.
  412. This is a simple helper lexer. If the first line of the text begins with
  413. "In \[[0-9]+\]:", then the entire text is parsed with an IPython console
  414. lexer. If not, then the entire text is parsed with an IPython lexer.
  415. The goal is to reduce the number of lexers that are registered
  416. with Pygments.
  417. """
  418. name = 'IPy session'
  419. aliases = ['ipy']
  420. def __init__(self, **options):
  421. self.python3 = get_bool_opt(options, 'python3', False)
  422. if self.python3:
  423. self.aliases = ['ipy3']
  424. else:
  425. self.aliases = ['ipy2', 'ipy']
  426. Lexer.__init__(self, **options)
  427. self.IPythonLexer = IPythonLexer(**options)
  428. self.IPythonConsoleLexer = IPythonConsoleLexer(**options)
  429. def get_tokens_unprocessed(self, text):
  430. # Search for the input prompt anywhere...this allows code blocks to
  431. # begin with comments as well.
  432. if re.match(r'.*(In \[[0-9]+\]:)', text.strip(), re.DOTALL):
  433. lex = self.IPythonConsoleLexer
  434. else:
  435. lex = self.IPythonLexer
  436. for token in lex.get_tokens_unprocessed(text):
  437. yield token