Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2c895b3

Browse files
committed
Add support for syntax-highlighting ipython console sessions.
svn path=/trunk/matplotlib/; revision=5227
1 parent b83d96b commit 2c895b3

3 files changed

Lines changed: 104 additions & 10 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
from pygments.lexer import Lexer, do_insertions
2+
from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
3+
PythonTracebackLexer
4+
from pygments.token import Comment, Generic
5+
from sphinx import highlighting
6+
import re
7+
8+
line_re = re.compile('.*?\n')
9+
10+
class IPythonConsoleLexer(Lexer):
11+
"""
12+
For IPython console output or doctests, such as:
13+
14+
Tracebacks are not currently supported.
15+
16+
.. sourcecode:: pycon
17+
18+
In [1]: a = 'foo'
19+
20+
In [2]: a
21+
Out[2]: 'foo'
22+
23+
In [3]: print a
24+
foo
25+
26+
In [4]: 1 / 0
27+
"""
28+
name = 'IPython console session'
29+
aliases = ['ipython']
30+
mimetypes = ['text/x-ipython-console']
31+
input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
32+
output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
33+
continue_prompt = re.compile(" \.\.\.+:")
34+
tb_start = re.compile("\-+")
35+
36+
def get_tokens_unprocessed(self, text):
37+
pylexer = PythonLexer(**self.options)
38+
tblexer = PythonTracebackLexer(**self.options)
39+
40+
curcode = ''
41+
insertions = []
42+
for match in line_re.finditer(text):
43+
line = match.group()
44+
input_prompt = self.input_prompt.match(line)
45+
continue_prompt = self.continue_prompt.match(line.rstrip())
46+
output_prompt = self.output_prompt.match(line)
47+
if line.startswith("#"):
48+
insertions.append((len(curcode),
49+
[(0, Comment, line)]))
50+
elif input_prompt is not None:
51+
insertions.append((len(curcode),
52+
[(0, Generic.Prompt, input_prompt.group())]))
53+
curcode += line[input_prompt.end():]
54+
elif continue_prompt is not None:
55+
insertions.append((len(curcode),
56+
[(0, Generic.Prompt, continue_prompt.group())]))
57+
curcode += line[continue_prompt.end():]
58+
elif output_prompt is not None:
59+
insertions.append((len(curcode),
60+
[(0, Generic.Output, output_prompt.group())]))
61+
curcode += line[output_prompt.end():]
62+
else:
63+
if curcode:
64+
for item in do_insertions(insertions,
65+
pylexer.get_tokens_unprocessed(curcode)):
66+
yield item
67+
curcode = ''
68+
insertions = []
69+
yield match.start(), Generic.Output, line
70+
if curcode:
71+
for item in do_insertions(insertions,
72+
pylexer.get_tokens_unprocessed(curcode)):
73+
yield item
74+
75+
highlighting.lexers['ipython'] = IPythonConsoleLexer()

doc/users_guide/artist_api_tut.txt

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ fig.add_subplot call above (remember Subplot is just a subclass of
6161
Axes) and when you call ax.plot, it creates a Line2D instance and adds
6262
it the the Axes.lines list. In the interactive ipython session below,
6363
you can see that Axes.lines list is length one and contains the same
64-
line that was returned by the "line, ax.plot(x, y, 'o')" call::
64+
line that was returned by the "line, ax.plot(x, y, 'o')" call:
65+
66+
.. sourcecode:: ipython
6567

6668
In [101]: ax.lines[0]
6769
Out[101]: <matplotlib.lines.Line2D instance at 0x19a95710>
@@ -159,8 +161,9 @@ If you are working interactively at the python shell, a handy way to
159161
inspect the artist properties is to use the matplotlib.artist.getp
160162
method, which lists the properties and their values (simply "getp") in
161163
pylab. This works for classes derived from Artist as well, eg Figure
162-
and Rectangle. Here are the Figure rectangle properties mentioned above::
164+
and Rectangle. Here are the Figure rectangle properties mentioned above:
163165

166+
.. sourcecode:: ipython
164167

165168
In [149]: matplotlib.artist.getp(fig.figurePatch)
166169
alpha = 1.0
@@ -218,7 +221,9 @@ contains everything in the figure. The background of the figure is a
218221
Rectangle which is stored in fig.figurePatch (where fig is your Figure
219222
instance). As you add subplots (fig.add_subplot) and axes
220223
(ax.add_axes)to the figure these will be appended to the fig.axes
221-
list. These are also returned by the methods that create them::
224+
list. These are also returned by the methods that create them:
225+
226+
.. sourcecode:: ipython
222227

223228
In [156]: fig = plt.figure()
224229

@@ -232,7 +237,6 @@ list. These are also returned by the methods that create them::
232237
In [160]: print fig.axes
233238
[<matplotlib.axes.Subplot instance at 0xd54b26c>, <matplotlib.axes.Axes instance at 0xd3f0b2c>]
234239

235-
236240
Because the figure maintains the concept of the "current axes" (see
237241
Figure.gca and Figure.sca) to support the pylab/pyplot state machine,
238242
you should not insert or remove axes directly from the axes list, but
@@ -253,7 +257,9 @@ want) but you can control this by setting the transform property of
253257
the Artist you are adding to the figure. More useful is "figure
254258
coordinates" where 0,0 is the bottom, left of the figure and 1,1 is
255259
the top, right of the figure which you can obtain by setting the
256-
Artist transform to fig.transFigure::
260+
Artist transform to fig.transFigure:
261+
262+
.. sourcecode:: ipython
257263

258264
In [191]: fig = plt.figure()
259265

@@ -303,7 +309,9 @@ When you call a plotting method, eg the canonical "ax.plot" and pass
303309
in arrays or list of values, the method will a matplotlib.lines.Line2D
304310
instance, update the line with all the Line2D properties passed as
305311
keyword arguments, add the line to the Axes.lines container, and
306-
returns it to you::
312+
returns it to you:
313+
314+
.. sourcecode:: ipython
307315

308316
In [213]: x, y = np.random.rand(2, 100)
309317

@@ -312,14 +320,17 @@ returns it to you::
312320
ax.plot returns a list of lines because you can pass in multiple x, y
313321
pairs to plot, and we are unpacking the first element of the length
314322
one list into the line variable. The line has been added to the
315-
ax.lines list::
323+
ax.lines list:
316324

325+
.. sourcecode:: ipython
317326

318327
In [229]: print ax.lines
319328
[<matplotlib.lines.Line2D instance at 0xd378b0c>]
320329

321330
Similarly, methods that create patches, like ax.bar creates a list of
322-
rectangles, will add the patches to the ax.patches list::
331+
rectangles, will add the patches to the ax.patches list:
332+
333+
.. sourcecode:: ipython
323334

324335
In [233]: n, bins, rectangles = ax.hist(np.random.randn(1000), 50, facecolor='yellow')
325336

@@ -338,7 +349,9 @@ auto-scaling, so that the view limits can be adjusted to contain the
338349
plotted data. You can, nonetheless, create objects yourself and add
339350
them directly to the Axes using helper methods like ax.add_line and
340351
ax.add_patch. Here is an annotated interactive session illustrating
341-
what is going on::
352+
what is going on:
353+
354+
.. sourcecode:: ipython
342355

343356
In [261]: fig = plt.figure()
344357

@@ -460,7 +473,9 @@ and zooming), you should access the lists of major and minor ticks
460473
through their accessor methods axis.get_major_ticks() and
461474
axis.get_minor_ticks(). Although the ticks contain all the primitives
462475
and will be covered below, the Axis methods contain accessor methods
463-
to return the tick lines, tick labels, tick locations etc....::
476+
to return the tick lines, tick labels, tick locations etc....:
477+
478+
.. sourcecode:: ipython
464479

465480
In [285]: axis = ax.xaxis
466481

doc/users_guide/conf.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
# absolute, like shown here.
1919
sys.path.append(os.path.abspath('../sphinxext'))
2020

21+
# Import support for ipython console session syntax highlighting (lives
22+
# in the sphinxext directory defined above)
23+
import ipython_console_highlighting
24+
2125
# General configuration
2226
# ---------------------
2327

0 commit comments

Comments
 (0)