lexers.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. """
  165. A subclass of `DelegatingLexer` which delegates to the appropriate to either IPyLexer,
  166. IPythonPartialTracebackLexer.
  167. """
  168. # note we need a __init__ doc, as otherwise it inherits the doc from the super class
  169. # which will fail the documentation build as it references section of the pygments docs that
  170. # do not exists when building IPython's docs.
  171. self.python3 = get_bool_opt(options, 'python3', False)
  172. if self.python3:
  173. self.aliases = ['ipython3tb']
  174. else:
  175. self.aliases = ['ipython2tb', 'ipythontb']
  176. if self.python3:
  177. IPyLexer = IPython3Lexer
  178. else:
  179. IPyLexer = IPythonLexer
  180. DelegatingLexer.__init__(self, IPyLexer,
  181. IPythonPartialTracebackLexer, **options)
  182. class IPythonConsoleLexer(Lexer):
  183. """
  184. An IPython console lexer for IPython code-blocks and doctests, such as:
  185. .. code-block:: rst
  186. .. code-block:: ipythonconsole
  187. In [1]: a = 'foo'
  188. In [2]: a
  189. Out[2]: 'foo'
  190. In [3]: print(a)
  191. foo
  192. Support is also provided for IPython exceptions:
  193. .. code-block:: rst
  194. .. code-block:: ipythonconsole
  195. In [1]: raise Exception
  196. Traceback (most recent call last):
  197. ...
  198. Exception
  199. """
  200. name = 'IPython console session'
  201. aliases = ['ipythonconsole']
  202. mimetypes = ['text/x-ipython-console']
  203. # The regexps used to determine what is input and what is output.
  204. # The default prompts for IPython are:
  205. #
  206. # in = 'In [#]: '
  207. # continuation = ' .D.: '
  208. # template = 'Out[#]: '
  209. #
  210. # Where '#' is the 'prompt number' or 'execution count' and 'D'
  211. # D is a number of dots matching the width of the execution count
  212. #
  213. in1_regex = r'In \[[0-9]+\]: '
  214. in2_regex = r' \.\.+\.: '
  215. out_regex = r'Out\[[0-9]+\]: '
  216. #: The regex to determine when a traceback starts.
  217. ipytb_start = re.compile(r'^(\^C)?(-+\n)|^( File)(.*)(, line )(\d+\n)')
  218. def __init__(self, **options):
  219. """Initialize the IPython console lexer.
  220. Parameters
  221. ----------
  222. python3 : bool
  223. If `True`, then the console inputs are parsed using a Python 3
  224. lexer. Otherwise, they are parsed using a Python 2 lexer.
  225. in1_regex : RegexObject
  226. The compiled regular expression used to detect the start
  227. of inputs. Although the IPython configuration setting may have a
  228. trailing whitespace, do not include it in the regex. If `None`,
  229. then the default input prompt is assumed.
  230. in2_regex : RegexObject
  231. The compiled regular expression used to detect the continuation
  232. of inputs. Although the IPython configuration setting may have a
  233. trailing whitespace, do not include it in the regex. If `None`,
  234. then the default input prompt is assumed.
  235. out_regex : RegexObject
  236. The compiled regular expression used to detect outputs. If `None`,
  237. then the default output prompt is assumed.
  238. """
  239. self.python3 = get_bool_opt(options, 'python3', False)
  240. if self.python3:
  241. self.aliases = ['ipython3console']
  242. else:
  243. self.aliases = ['ipython2console', 'ipythonconsole']
  244. in1_regex = options.get('in1_regex', self.in1_regex)
  245. in2_regex = options.get('in2_regex', self.in2_regex)
  246. out_regex = options.get('out_regex', self.out_regex)
  247. # So that we can work with input and output prompts which have been
  248. # rstrip'd (possibly by editors) we also need rstrip'd variants. If
  249. # we do not do this, then such prompts will be tagged as 'output'.
  250. # The reason can't just use the rstrip'd variants instead is because
  251. # we want any whitespace associated with the prompt to be inserted
  252. # with the token. This allows formatted code to be modified so as hide
  253. # the appearance of prompts, with the whitespace included. One example
  254. # use of this is in copybutton.js from the standard lib Python docs.
  255. in1_regex_rstrip = in1_regex.rstrip() + '\n'
  256. in2_regex_rstrip = in2_regex.rstrip() + '\n'
  257. out_regex_rstrip = out_regex.rstrip() + '\n'
  258. # Compile and save them all.
  259. attrs = ['in1_regex', 'in2_regex', 'out_regex',
  260. 'in1_regex_rstrip', 'in2_regex_rstrip', 'out_regex_rstrip']
  261. for attr in attrs:
  262. self.__setattr__(attr, re.compile(locals()[attr]))
  263. Lexer.__init__(self, **options)
  264. if self.python3:
  265. pylexer = IPython3Lexer
  266. tblexer = IPythonTracebackLexer
  267. else:
  268. pylexer = IPythonLexer
  269. tblexer = IPythonTracebackLexer
  270. self.pylexer = pylexer(**options)
  271. self.tblexer = tblexer(**options)
  272. self.reset()
  273. def reset(self):
  274. self.mode = 'output'
  275. self.index = 0
  276. self.buffer = u''
  277. self.insertions = []
  278. def buffered_tokens(self):
  279. """
  280. Generator of unprocessed tokens after doing insertions and before
  281. changing to a new state.
  282. """
  283. if self.mode == 'output':
  284. tokens = [(0, Generic.Output, self.buffer)]
  285. elif self.mode == 'input':
  286. tokens = self.pylexer.get_tokens_unprocessed(self.buffer)
  287. else: # traceback
  288. tokens = self.tblexer.get_tokens_unprocessed(self.buffer)
  289. for i, t, v in do_insertions(self.insertions, tokens):
  290. # All token indexes are relative to the buffer.
  291. yield self.index + i, t, v
  292. # Clear it all
  293. self.index += len(self.buffer)
  294. self.buffer = u''
  295. self.insertions = []
  296. def get_mci(self, line):
  297. """
  298. Parses the line and returns a 3-tuple: (mode, code, insertion).
  299. `mode` is the next mode (or state) of the lexer, and is always equal
  300. to 'input', 'output', or 'tb'.
  301. `code` is a portion of the line that should be added to the buffer
  302. corresponding to the next mode and eventually lexed by another lexer.
  303. For example, `code` could be Python code if `mode` were 'input'.
  304. `insertion` is a 3-tuple (index, token, text) representing an
  305. unprocessed "token" that will be inserted into the stream of tokens
  306. that are created from the buffer once we change modes. This is usually
  307. the input or output prompt.
  308. In general, the next mode depends on current mode and on the contents
  309. of `line`.
  310. """
  311. # To reduce the number of regex match checks, we have multiple
  312. # 'if' blocks instead of 'if-elif' blocks.
  313. # Check for possible end of input
  314. in2_match = self.in2_regex.match(line)
  315. in2_match_rstrip = self.in2_regex_rstrip.match(line)
  316. if (in2_match and in2_match.group().rstrip() == line.rstrip()) or \
  317. in2_match_rstrip:
  318. end_input = True
  319. else:
  320. end_input = False
  321. if end_input and self.mode != 'tb':
  322. # Only look for an end of input when not in tb mode.
  323. # An ellipsis could appear within the traceback.
  324. mode = 'output'
  325. code = u''
  326. insertion = (0, Generic.Prompt, line)
  327. return mode, code, insertion
  328. # Check for output prompt
  329. out_match = self.out_regex.match(line)
  330. out_match_rstrip = self.out_regex_rstrip.match(line)
  331. if out_match or out_match_rstrip:
  332. mode = 'output'
  333. if out_match:
  334. idx = out_match.end()
  335. else:
  336. idx = out_match_rstrip.end()
  337. code = line[idx:]
  338. # Use the 'heading' token for output. We cannot use Generic.Error
  339. # since it would conflict with exceptions.
  340. insertion = (0, Generic.Heading, line[:idx])
  341. return mode, code, insertion
  342. # Check for input or continuation prompt (non stripped version)
  343. in1_match = self.in1_regex.match(line)
  344. if in1_match or (in2_match and self.mode != 'tb'):
  345. # New input or when not in tb, continued input.
  346. # We do not check for continued input when in tb since it is
  347. # allowable to replace a long stack with an ellipsis.
  348. mode = 'input'
  349. if in1_match:
  350. idx = in1_match.end()
  351. else: # in2_match
  352. idx = in2_match.end()
  353. code = line[idx:]
  354. insertion = (0, Generic.Prompt, line[:idx])
  355. return mode, code, insertion
  356. # Check for input or continuation prompt (stripped version)
  357. in1_match_rstrip = self.in1_regex_rstrip.match(line)
  358. if in1_match_rstrip or (in2_match_rstrip and self.mode != 'tb'):
  359. # New input or when not in tb, continued input.
  360. # We do not check for continued input when in tb since it is
  361. # allowable to replace a long stack with an ellipsis.
  362. mode = 'input'
  363. if in1_match_rstrip:
  364. idx = in1_match_rstrip.end()
  365. else: # in2_match
  366. idx = in2_match_rstrip.end()
  367. code = line[idx:]
  368. insertion = (0, Generic.Prompt, line[:idx])
  369. return mode, code, insertion
  370. # Check for traceback
  371. if self.ipytb_start.match(line):
  372. mode = 'tb'
  373. code = line
  374. insertion = None
  375. return mode, code, insertion
  376. # All other stuff...
  377. if self.mode in ('input', 'output'):
  378. # We assume all other text is output. Multiline input that
  379. # does not use the continuation marker cannot be detected.
  380. # For example, the 3 in the following is clearly output:
  381. #
  382. # In [1]: print(3)
  383. # 3
  384. #
  385. # But the following second line is part of the input:
  386. #
  387. # In [2]: while True:
  388. # print(True)
  389. #
  390. # In both cases, the 2nd line will be 'output'.
  391. #
  392. mode = 'output'
  393. else:
  394. mode = 'tb'
  395. code = line
  396. insertion = None
  397. return mode, code, insertion
  398. def get_tokens_unprocessed(self, text):
  399. self.reset()
  400. for match in line_re.finditer(text):
  401. line = match.group()
  402. mode, code, insertion = self.get_mci(line)
  403. if mode != self.mode:
  404. # Yield buffered tokens before transitioning to new mode.
  405. for token in self.buffered_tokens():
  406. yield token
  407. self.mode = mode
  408. if insertion:
  409. self.insertions.append((len(self.buffer), [insertion]))
  410. self.buffer += code
  411. for token in self.buffered_tokens():
  412. yield token
  413. class IPyLexer(Lexer):
  414. r"""
  415. Primary lexer for all IPython-like code.
  416. This is a simple helper lexer. If the first line of the text begins with
  417. "In \[[0-9]+\]:", then the entire text is parsed with an IPython console
  418. lexer. If not, then the entire text is parsed with an IPython lexer.
  419. The goal is to reduce the number of lexers that are registered
  420. with Pygments.
  421. """
  422. name = 'IPy session'
  423. aliases = ['ipy']
  424. def __init__(self, **options):
  425. """
  426. Create a new IPyLexer instance which dispatch to either an
  427. IPythonCOnsoleLexer (if In prompts are present) or and IPythonLexer (if
  428. In prompts are not present).
  429. """
  430. # init docstring is necessary for docs not to fail to build do to parent
  431. # docs referenceing a section in pygments docs.
  432. self.python3 = get_bool_opt(options, 'python3', False)
  433. if self.python3:
  434. self.aliases = ['ipy3']
  435. else:
  436. self.aliases = ['ipy2', 'ipy']
  437. Lexer.__init__(self, **options)
  438. self.IPythonLexer = IPythonLexer(**options)
  439. self.IPythonConsoleLexer = IPythonConsoleLexer(**options)
  440. def get_tokens_unprocessed(self, text):
  441. # Search for the input prompt anywhere...this allows code blocks to
  442. # begin with comments as well.
  443. if re.match(r'.*(In \[[0-9]+\]:)', text.strip(), re.DOTALL):
  444. lex = self.IPythonConsoleLexer
  445. else:
  446. lex = self.IPythonLexer
  447. for token in lex.get_tokens_unprocessed(text):
  448. yield token