lexers.py 18 KB

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