ipython_pygments_lexers.py 19 KB

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