##// END OF EJS Templates
Add %guiref to give a quick reference to the GUI console.
Fernando Perez -
Show More
@@ -1,297 +1,480 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2010 The IPython Development Team
5 # Copyright (C) 2008-2010 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 ipython [options] [files]
16 ipython [options] [files]
17
17
18 IPython: an enhanced interactive Python shell.
18 IPython: an enhanced interactive Python shell.
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the
21 introspection, easier configuration, command completion, access to the
22 system shell and more. IPython can also be embedded in running programs.
22 system shell and more. IPython can also be embedded in running programs.
23
23
24 If invoked with no options, it executes all the files listed in sequence
24 If invoked with no options, it executes all the files listed in sequence
25 and exits, use -i to enter interactive mode after running the files. Files
25 and exits, use -i to enter interactive mode after running the files. Files
26 ending in .py will be treated as normal Python, but files ending in .ipy
26 ending in .py will be treated as normal Python, but files ending in .ipy
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28
28
29 Please note that some of the configuration options are not available at the
29 Please note that some of the configuration options are not available at the
30 command line, simply because they are not practical here. Look into your
30 command line, simply because they are not practical here. Look into your
31 ipython_config.py configuration file for details on those.
31 ipython_config.py configuration file for details on those.
32
32
33 This file typically installed in the $HOME/.ipython directory. For Windows
33 This file typically installed in the $HOME/.ipython directory. For Windows
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 instances.
35 instances.
36
36
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 you can change its default location by setting any path you want in this
38 you can change its default location by setting any path you want in this
39 environment variable.
39 environment variable.
40
40
41 For more information, see the manual available in HTML and PDF in your
41 For more information, see the manual available in HTML and PDF in your
42 installation, or online at http://ipython.scipy.org.
42 installation, or online at http://ipython.scipy.org.
43 """
43 """
44
44
45 interactive_usage = """
45 interactive_usage = """
46 IPython -- An enhanced Interactive Python
46 IPython -- An enhanced Interactive Python
47 =========================================
47 =========================================
48
48
49 IPython offers a combination of convenient shell features, special commands
49 IPython offers a combination of convenient shell features, special commands
50 and a history mechanism for both input (command history) and output (results
50 and a history mechanism for both input (command history) and output (results
51 caching, similar to Mathematica). It is intended to be a fully compatible
51 caching, similar to Mathematica). It is intended to be a fully compatible
52 replacement for the standard Python interpreter, while offering vastly
52 replacement for the standard Python interpreter, while offering vastly
53 improved functionality and flexibility.
53 improved functionality and flexibility.
54
54
55 At your system command line, type 'ipython -help' to see the command line
55 At your system command line, type 'ipython -help' to see the command line
56 options available. This document only describes interactive features.
56 options available. This document only describes interactive features.
57
57
58 Warning: IPython relies on the existence of a global variable called __IP which
58 Warning: IPython relies on the existence of a global variable called __IP which
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
60 will quickly occur.
60 will quickly occur.
61
61
62 MAIN FEATURES
62 MAIN FEATURES
63
63
64 * Access to the standard Python help. As of Python 2.1, a help system is
64 * Access to the standard Python help. As of Python 2.1, a help system is
65 available with access to object docstrings and the Python manuals. Simply
65 available with access to object docstrings and the Python manuals. Simply
66 type 'help' (no quotes) to access it.
66 type 'help' (no quotes) to access it.
67
67
68 * Magic commands: type %magic for information on the magic subsystem.
68 * Magic commands: type %magic for information on the magic subsystem.
69
69
70 * System command aliases, via the %alias command or the ipythonrc config file.
70 * System command aliases, via the %alias command or the ipythonrc config file.
71
71
72 * Dynamic object information:
72 * Dynamic object information:
73
73
74 Typing ?word or word? prints detailed information about an object. If
74 Typing ?word or word? prints detailed information about an object. If
75 certain strings in the object are too long (docstrings, code, etc.) they get
75 certain strings in the object are too long (docstrings, code, etc.) they get
76 snipped in the center for brevity.
76 snipped in the center for brevity.
77
77
78 Typing ??word or word?? gives access to the full information without
78 Typing ??word or word?? gives access to the full information without
79 snipping long strings. Long strings are sent to the screen through the less
79 snipping long strings. Long strings are sent to the screen through the less
80 pager if longer than the screen, printed otherwise.
80 pager if longer than the screen, printed otherwise.
81
81
82 The ?/?? system gives access to the full source code for any object (if
82 The ?/?? system gives access to the full source code for any object (if
83 available), shows function prototypes and other useful information.
83 available), shows function prototypes and other useful information.
84
84
85 If you just want to see an object's docstring, type '%pdoc object' (without
85 If you just want to see an object's docstring, type '%pdoc object' (without
86 quotes, and without % if you have automagic on).
86 quotes, and without % if you have automagic on).
87
87
88 Both %pdoc and ?/?? give you access to documentation even on things which are
88 Both %pdoc and ?/?? give you access to documentation even on things which are
89 not explicitely defined. Try for example typing {}.get? or after import os,
89 not explicitely defined. Try for example typing {}.get? or after import os,
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
91 similarly.
91 similarly.
92
92
93 * Completion in the local namespace, by typing TAB at the prompt.
93 * Completion in the local namespace, by typing TAB at the prompt.
94
94
95 At any time, hitting tab will complete any available python commands or
95 At any time, hitting tab will complete any available python commands or
96 variable names, and show you a list of the possible completions if there's
96 variable names, and show you a list of the possible completions if there's
97 no unambiguous one. It will also complete filenames in the current directory.
97 no unambiguous one. It will also complete filenames in the current directory.
98
98
99 This feature requires the readline and rlcomplete modules, so it won't work
99 This feature requires the readline and rlcomplete modules, so it won't work
100 if your Python lacks readline support (such as under Windows).
100 if your Python lacks readline support (such as under Windows).
101
101
102 * Search previous command history in two ways (also requires readline):
102 * Search previous command history in two ways (also requires readline):
103
103
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
105 search through only the history items that match what you've typed so
105 search through only the history items that match what you've typed so
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
107 normal arrow keys.
107 normal arrow keys.
108
108
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
110 your history for lines that match what you've typed so far, completing as
110 your history for lines that match what you've typed so far, completing as
111 much as it can.
111 much as it can.
112
112
113 * Persistent command history across sessions (readline required).
113 * Persistent command history across sessions (readline required).
114
114
115 * Logging of input with the ability to save and restore a working session.
115 * Logging of input with the ability to save and restore a working session.
116
116
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
118
118
119 * The reload command does a 'deep' reload of a module: changes made to the
119 * The reload command does a 'deep' reload of a module: changes made to the
120 module since you imported will actually be available without having to exit.
120 module since you imported will actually be available without having to exit.
121
121
122 * Verbose and colored exception traceback printouts. See the magic xmode and
122 * Verbose and colored exception traceback printouts. See the magic xmode and
123 xcolor functions for details (just type %magic).
123 xcolor functions for details (just type %magic).
124
124
125 * Input caching system:
125 * Input caching system:
126
126
127 IPython offers numbered prompts (In/Out) with input and output caching. All
127 IPython offers numbered prompts (In/Out) with input and output caching. All
128 input is saved and can be retrieved as variables (besides the usual arrow
128 input is saved and can be retrieved as variables (besides the usual arrow
129 key recall).
129 key recall).
130
130
131 The following GLOBAL variables always exist (so don't overwrite them!):
131 The following GLOBAL variables always exist (so don't overwrite them!):
132 _i: stores previous input.
132 _i: stores previous input.
133 _ii: next previous.
133 _ii: next previous.
134 _iii: next-next previous.
134 _iii: next-next previous.
135 _ih : a list of all input _ih[n] is the input from line n.
135 _ih : a list of all input _ih[n] is the input from line n.
136
136
137 Additionally, global variables named _i<n> are dynamically created (<n>
137 Additionally, global variables named _i<n> are dynamically created (<n>
138 being the prompt counter), such that _i<n> == _ih[<n>]
138 being the prompt counter), such that _i<n> == _ih[<n>]
139
139
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
141
141
142 You can create macros which contain multiple input lines from this history,
142 You can create macros which contain multiple input lines from this history,
143 for later re-execution, with the %macro function.
143 for later re-execution, with the %macro function.
144
144
145 The history function %hist allows you to see any part of your input history
145 The history function %hist allows you to see any part of your input history
146 by printing a range of the _i variables. Note that inputs which contain
146 by printing a range of the _i variables. Note that inputs which contain
147 magic functions (%) appear in the history with a prepended comment. This is
147 magic functions (%) appear in the history with a prepended comment. This is
148 because they aren't really valid Python code, so you can't exec them.
148 because they aren't really valid Python code, so you can't exec them.
149
149
150 * Output caching system:
150 * Output caching system:
151
151
152 For output that is returned from actions, a system similar to the input
152 For output that is returned from actions, a system similar to the input
153 cache exists but using _ instead of _i. Only actions that produce a result
153 cache exists but using _ instead of _i. Only actions that produce a result
154 (NOT assignments, for example) are cached. If you are familiar with
154 (NOT assignments, for example) are cached. If you are familiar with
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
156 variables.
156 variables.
157
157
158 The following GLOBAL variables always exist (so don't overwrite them!):
158 The following GLOBAL variables always exist (so don't overwrite them!):
159 _ (one underscore): previous output.
159 _ (one underscore): previous output.
160 __ (two underscores): next previous.
160 __ (two underscores): next previous.
161 ___ (three underscores): next-next previous.
161 ___ (three underscores): next-next previous.
162
162
163 Global variables named _<n> are dynamically created (<n> being the prompt
163 Global variables named _<n> are dynamically created (<n> being the prompt
164 counter), such that the result of output <n> is always available as _<n>.
164 counter), such that the result of output <n> is always available as _<n>.
165
165
166 Finally, a global dictionary named _oh exists with entries for all lines
166 Finally, a global dictionary named _oh exists with entries for all lines
167 which generated output.
167 which generated output.
168
168
169 * Directory history:
169 * Directory history:
170
170
171 Your history of visited directories is kept in the global list _dh, and the
171 Your history of visited directories is kept in the global list _dh, and the
172 magic %cd command can be used to go to any entry in that list.
172 magic %cd command can be used to go to any entry in that list.
173
173
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
175
175
176 1. Auto-parentheses
176 1. Auto-parentheses
177 Callable objects (i.e. functions, methods, etc) can be invoked like
177 Callable objects (i.e. functions, methods, etc) can be invoked like
178 this (notice the commas between the arguments):
178 this (notice the commas between the arguments):
179 >>> callable_ob arg1, arg2, arg3
179 >>> callable_ob arg1, arg2, arg3
180 and the input will be translated to this:
180 and the input will be translated to this:
181 --> callable_ob(arg1, arg2, arg3)
181 --> callable_ob(arg1, arg2, arg3)
182 You can force auto-parentheses by using '/' as the first character
182 You can force auto-parentheses by using '/' as the first character
183 of a line. For example:
183 of a line. For example:
184 >>> /globals # becomes 'globals()'
184 >>> /globals # becomes 'globals()'
185 Note that the '/' MUST be the first character on the line! This
185 Note that the '/' MUST be the first character on the line! This
186 won't work:
186 won't work:
187 >>> print /globals # syntax error
187 >>> print /globals # syntax error
188
188
189 In most cases the automatic algorithm should work, so you should
189 In most cases the automatic algorithm should work, so you should
190 rarely need to explicitly invoke /. One notable exception is if you
190 rarely need to explicitly invoke /. One notable exception is if you
191 are trying to call a function with a list of tuples as arguments (the
191 are trying to call a function with a list of tuples as arguments (the
192 parenthesis will confuse IPython):
192 parenthesis will confuse IPython):
193 In [1]: zip (1,2,3),(4,5,6) # won't work
193 In [1]: zip (1,2,3),(4,5,6) # won't work
194 but this will work:
194 but this will work:
195 In [2]: /zip (1,2,3),(4,5,6)
195 In [2]: /zip (1,2,3),(4,5,6)
196 ------> zip ((1,2,3),(4,5,6))
196 ------> zip ((1,2,3),(4,5,6))
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
198
198
199 IPython tells you that it has altered your command line by
199 IPython tells you that it has altered your command line by
200 displaying the new command line preceded by -->. e.g.:
200 displaying the new command line preceded by -->. e.g.:
201 In [18]: callable list
201 In [18]: callable list
202 -------> callable (list)
202 -------> callable (list)
203
203
204 2. Auto-Quoting
204 2. Auto-Quoting
205 You can force auto-quoting of a function's arguments by using ',' as
205 You can force auto-quoting of a function's arguments by using ',' as
206 the first character of a line. For example:
206 the first character of a line. For example:
207 >>> ,my_function /home/me # becomes my_function("/home/me")
207 >>> ,my_function /home/me # becomes my_function("/home/me")
208
208
209 If you use ';' instead, the whole argument is quoted as a single
209 If you use ';' instead, the whole argument is quoted as a single
210 string (while ',' splits on whitespace):
210 string (while ',' splits on whitespace):
211 >>> ,my_function a b c # becomes my_function("a","b","c")
211 >>> ,my_function a b c # becomes my_function("a","b","c")
212 >>> ;my_function a b c # becomes my_function("a b c")
212 >>> ;my_function a b c # becomes my_function("a b c")
213
213
214 Note that the ',' MUST be the first character on the line! This
214 Note that the ',' MUST be the first character on the line! This
215 won't work:
215 won't work:
216 >>> x = ,my_function /home/me # syntax error
216 >>> x = ,my_function /home/me # syntax error
217 """
217 """
218
218
219 interactive_usage_min = """\
219 interactive_usage_min = """\
220 An enhanced console for Python.
220 An enhanced console for Python.
221 Some of its features are:
221 Some of its features are:
222 - Readline support if the readline library is present.
222 - Readline support if the readline library is present.
223 - Tab completion in the local namespace.
223 - Tab completion in the local namespace.
224 - Logging of input, see command-line options.
224 - Logging of input, see command-line options.
225 - System shell escape via ! , eg !ls.
225 - System shell escape via ! , eg !ls.
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
227 - Keeps track of locally defined variables via %who, %whos.
227 - Keeps track of locally defined variables via %who, %whos.
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
229 """
229 """
230
230
231 quick_reference = r"""
231 quick_reference = r"""
232 IPython -- An enhanced Interactive Python - Quick Reference Card
232 IPython -- An enhanced Interactive Python - Quick Reference Card
233 ================================================================
233 ================================================================
234
234
235 obj?, obj?? : Get help, or more help for object (also works as
235 obj?, obj?? : Get help, or more help for object (also works as
236 ?obj, ??obj).
236 ?obj, ??obj).
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
238 %magic : Information about IPython's 'magic' % functions.
238 %magic : Information about IPython's 'magic' % functions.
239
239
240 Magic functions are prefixed by %, and typically take their arguments without
240 Magic functions are prefixed by %, and typically take their arguments without
241 parentheses, quotes or even commas for convenience.
241 parentheses, quotes or even commas for convenience.
242
242
243 Example magic function calls:
243 Example magic function calls:
244
244
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
246 alias d ls -F : Works if 'alias' not a python name
246 alias d ls -F : Works if 'alias' not a python name
247 alist = %alias : Get list of aliases to 'alist'
247 alist = %alias : Get list of aliases to 'alist'
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
249 %cd?? : See help AND source for magic %cd
249 %cd?? : See help AND source for magic %cd
250
250
251 System commands:
251 System commands:
252
252
253 !cp a.txt b/ : System command escape, calls os.system()
253 !cp a.txt b/ : System command escape, calls os.system()
254 cp a.txt b/ : after %rehashx, most system commands work without !
254 cp a.txt b/ : after %rehashx, most system commands work without !
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
256 files = !ls /usr : Capture sytem command output
256 files = !ls /usr : Capture sytem command output
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
258
258
259 History:
259 History:
260
260
261 _i, _ii, _iii : Previous, next previous, next next previous input
261 _i, _ii, _iii : Previous, next previous, next next previous input
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
263 exec _i81 : Execute input history line #81 again
263 exec _i81 : Execute input history line #81 again
264 %rep 81 : Edit input history line #81
264 %rep 81 : Edit input history line #81
265 _, __, ___ : previous, next previous, next next previous output
265 _, __, ___ : previous, next previous, next next previous output
266 _dh : Directory history
266 _dh : Directory history
267 _oh : Output history
267 _oh : Output history
268 %hist : Command history. '%hist -g foo' search history for 'foo'
268 %hist : Command history. '%hist -g foo' search history for 'foo'
269
269
270 Autocall:
270 Autocall:
271
271
272 f 1,2 : f(1,2)
272 f 1,2 : f(1,2)
273 /f 1,2 : f(1,2) (forced autoparen)
273 /f 1,2 : f(1,2) (forced autoparen)
274 ,f 1 2 : f("1","2")
274 ,f 1 2 : f("1","2")
275 ;f 1 2 : f("1 2")
275 ;f 1 2 : f("1 2")
276
276
277 Remember: TAB completion works in many contexts, not just file names
277 Remember: TAB completion works in many contexts, not just file names
278 or python names.
278 or python names.
279
279
280 The following magic functions are currently available:
280 The following magic functions are currently available:
281
281
282 """
282 """
283
283
284 gui_reference = """\
285 ===============================
286 The IPython graphical console
287 ===============================
288
289 This console is designed to emulate in many aspects the look, feel and workflow
290 typical of a terminal environment, but it adds support for a number of
291 enhancements that are simply not possible in a real terminal, such as inline
292 syntax highlighting, true multiline editing, inline graphics and much more.
293
294 This quick reference document contains the basic information you'll need to
295 know to make the most efficient use of it. For the various command line
296 options available at startup, type ``--help`` at the command line.
297
298
299 Multiline editing
300 =================
301
302 The graphical console is capable of true multiline editing, but it also tries
303 to behave intuitively like a terminal when possible. If you are used to
304 IPyhton's old terminal behavior, you should find the transition painless, and
305 once you learn a few basic keybindings it will be a much more efficient
306 environment.
307
308 For single expressions or indented blocks, the console behaves almost like the
309 terminal IPython: single expressions are immediately evaluated *if the cursor
310 is at the end of the line*, and indented blocks are evaluated once a single
311 blank line is entered::
312
313 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
314 Hello IPython!
315
316 In [2]: for i in range(10):
317 ...: print i,
318 ...:
319 0 1 2 3 4 5 6 7 8 9
320
321 If you have a single expression and you go back to edit something in the
322 beginning, hitting ``Enter`` will split the line (like a text editor) instead
323 of executing it. To execute, you can either go to the end of the line to hit
324 ``Enter``, or hit ``Shift-Enter`` anywhere, which is the 'force execution'
325 keybinding.
326
327 If you want to enter more than one expression in a single input block
328 (something not possible in the terminal), you can use ``Control-Enter`` at the
329 end of your first line instead of ``Enter``. At that point the console goes
330 into 'cell mode' and even if your inputs are not indented, it will continue
331 accepting arbitrarily many lines until either you enter an extra blank line or
332 you hit ``Shift-Enter`` (the key binding that forces execution). When a
333 multiline cell is entered, IPython analyzes it and executes its code producing
334 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
335 cell is executed as if it was a script. A few examples should clarify this::
336
337
338 In [3]: x=1 # Hit C-Enter here
339 ...: y=2 # from now on, regular Enter is sufficient
340 ...: z=3
341 ...: x**2 # This does *not* produce an Out[] value
342 ...: x+y+z # Only the last expression does
343 ...:
344 Out[3]: 6
345
346 The behavior where an extra blank line forces execution is only active if you
347 are actually typing at the keyboard each line, and is meant to make it mimic
348 the IPython terminal behavior. If you paste a long chunk of input (for example
349 a long script copied form an editor or web browser), it can contain arbitrarily
350 many intermediate blank lines and they won't cause any problems. You can then
351 make it execute by appending a blank line *at the end* or hitting
352 ``Shift-Enter`` anywhere within the cell.
353
354 With the up arrow key, you can retrieve previous blocks of input that contain
355 multiple lines. You can move inside of it like you would in any text editor.
356 When you want it executed, the simplest thing to do is to hit the force
357 execution key, ``Shift-Enter`` (though you can also navigate to the end and
358 append a blank line by using ``Enter`` twice).
359
360 If you've edited a multiline cell and accidentally navigate out of it with the
361 up or down arrow keys, IPython will clear the cell and replace it with the
362 contents of the one above or below that you navigated to. If this was an
363 accident and you want to retrieve the cell you were editing, use the Undo
364 keybinding, ``Control-z``.
365
366
367 Key bindings
368 ============
369
370 The IPython console supports most of the basic Emacs line-oriented
371 keybindings, in addition to some of its own.
372
373 The keybinding prefixes mean:
374
375 C : Control
376 S : Shift
377 M : Meta (typically the Alt key)
378
379 The keybindings themselves are:
380
381 Enter : insert new line (may cause execution, see above).
382 C-Enter : force new line, *never* causes execution.
383 S-Enter : *force* execution regardless of where cursor is, no newline added.
384 C-c : copy highlighted text to clipboard (prompts are automatically stripped).
385 C-v : paste text from clipboard.
386 C-z : undo (retrieves lost text if you move out of a cell with the arrows).
387 C-o : move to 'other' area, between pager and terminal.
388 C-l : clear terminal.
389 C-a : go to beginning of line.
390 C-e : go to end of line.
391 C-k : kill from cursor to the end of the line.
392 C-y : yank (paste)
393 C-p : previous line (like up arrow)
394 C-n : next line (like down arrow)
395 C-f : forward (like right arrow)
396 C-b : back (like left arrow)
397 C-d : delete next character.
398 M-d : delete next word.
399 M-Backspace : delete previous word.
400 C-. : forced restart of the kernel (a confirmation dialog appears).
401
402
403 The IPython pager
404 =================
405
406 IPython will show long blocks of text from many sources using a builtin pager.
407 You can control where this pager appears with the ``--paging`` command-line
408 flag:
409
410 - default: it is overlaid on top of the main terminal. You must quit the pager
411 to get back to the terminal (similar to how a kkk pager such as ``less``
412 works).
413
414 - vertical: the console is made double-tall, and the pager appears on the
415 bottom area when needed. You can view its contents while using the terminal.
416
417 - horizontal: the console is made double-wide, and the pager appears on the
418 right area when needed. You can view its contents while using the terminal.
419
420 If you use the vertical or horizontal paging modes, you can navigate between
421 terminal and pager as follows:
422
423 - Tab key: goes from pager to terminal (but not the other way around).
424 - Control-o: goes from one to another always.
425 - Mouse: click on either.
426
427 In all cases, the ``q`` or ``Escape`` keys quit the pager.
428
429
430 Running subprocesses
431 ====================
432
433 The graphical IPython console uses the ``pexpect`` module to run subprocesses
434 when you type ``!command``. This has a number of advantages (true asynchronous
435 output from subprocesses as well as very robust termination of rogue
436 subprocesses with Control-C), as well as some limitations. The main limitation
437 is that you can *not* interact back with the subprocess, so anything that
438 invokes a pager or expects you to type input into it will block and hang (you
439 can kill it with Control-C).
440
441 We have provided as magics ``%less`` (aliased to ``%more``), ``%clear`` to
442 clear the terminal, and ``%man`` on Linux/OSX to cover the most common commands
443 you'd want to call in your subshell, but you need to be aware of this
444 limitation.
445
446
447 Inline matplotlib graphics
448 ==========================
449
450 The IPython console is capable of displaying matplotlib figures inline, in SVG
451 format. If started with the ``--pylab inline`` flag, then all figures are
452 rendered inline automatically. If started with ``--pylab`` or ``--pylab
453 <your backend>``, then a GUI backend will be used, but the ``paste()`` function
454 is added to the global and ``plt`` namespaces. You can paste any figure that
455 is currently open in a window with this function; type ``paste?`` for
456 additional details."""
457
284 quick_guide = """\
458 quick_guide = """\
285 ? -> Introduction and overview of IPython's features.
459 ? -> Introduction and overview of IPython's features.
286 %quickref -> Quick reference.
460 %quickref -> Quick reference.
287 help -> Python's own help system.
461 help -> Python's own help system.
288 object? -> Details about 'object'. ?object also works, ?? prints more."""
462 object? -> Details about 'object', use 'object??' for extra details.
463 """
464
465 gui_note = """\
466 %guiref -> A brief reference about the graphical user interface.
467 """
289
468
290 default_banner_parts = [
469 default_banner_parts = [
291 'Python %s' % (sys.version.split('\n')[0],),
470 'Python %s\n' % (sys.version.split('\n')[0],),
292 'Type "copyright", "credits" or "license" for more information.\n',
471 'Type "copyright", "credits" or "license" for more information.\n\n',
293 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
472 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
294 quick_guide
473 quick_guide
295 ]
474 ]
296
475
297 default_banner = '\n'.join(default_banner_parts)
476 default_gui_banner_parts = default_banner_parts + [gui_note]
477
478 default_banner = ''.join(default_banner_parts)
479
480 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,455 +1,455 b''
1 """ A FrontendWidget that emulates the interface of the console IPython and
1 """ A FrontendWidget that emulates the interface of the console IPython and
2 supports the additional functionality provided by the IPython kernel.
2 supports the additional functionality provided by the IPython kernel.
3
3
4 TODO: Add support for retrieving the system default editor. Requires code
4 TODO: Add support for retrieving the system default editor. Requires code
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
5 paths for Windows (use the registry), Mac OS (use LaunchServices), and
6 Linux (use the xdg system).
6 Linux (use the xdg system).
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Imports
10 # Imports
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 # Standard library imports
13 # Standard library imports
14 from collections import namedtuple
14 from collections import namedtuple
15 import re
15 import re
16 from subprocess import Popen
16 from subprocess import Popen
17
17
18 # System library imports
18 # System library imports
19 from PyQt4 import QtCore, QtGui
19 from PyQt4 import QtCore, QtGui
20
20
21 # Local imports
21 # Local imports
22 from IPython.core.inputsplitter import IPythonInputSplitter, \
22 from IPython.core.inputsplitter import IPythonInputSplitter, \
23 transform_ipy_prompt
23 transform_ipy_prompt
24 from IPython.core.usage import default_banner
24 from IPython.core.usage import default_gui_banner
25 from IPython.utils.traitlets import Bool, Str
25 from IPython.utils.traitlets import Bool, Str
26 from frontend_widget import FrontendWidget
26 from frontend_widget import FrontendWidget
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Constants
29 # Constants
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 # The default light style sheet: black text on a white background.
32 # The default light style sheet: black text on a white background.
33 default_light_style_sheet = '''
33 default_light_style_sheet = '''
34 .error { color: red; }
34 .error { color: red; }
35 .in-prompt { color: navy; }
35 .in-prompt { color: navy; }
36 .in-prompt-number { font-weight: bold; }
36 .in-prompt-number { font-weight: bold; }
37 .out-prompt { color: darkred; }
37 .out-prompt { color: darkred; }
38 .out-prompt-number { font-weight: bold; }
38 .out-prompt-number { font-weight: bold; }
39 '''
39 '''
40 default_light_syntax_style = 'default'
40 default_light_syntax_style = 'default'
41
41
42 # The default dark style sheet: white text on a black background.
42 # The default dark style sheet: white text on a black background.
43 default_dark_style_sheet = '''
43 default_dark_style_sheet = '''
44 QPlainTextEdit, QTextEdit { background-color: black; color: white }
44 QPlainTextEdit, QTextEdit { background-color: black; color: white }
45 QFrame { border: 1px solid grey; }
45 QFrame { border: 1px solid grey; }
46 .error { color: red; }
46 .error { color: red; }
47 .in-prompt { color: lime; }
47 .in-prompt { color: lime; }
48 .in-prompt-number { color: lime; font-weight: bold; }
48 .in-prompt-number { color: lime; font-weight: bold; }
49 .out-prompt { color: red; }
49 .out-prompt { color: red; }
50 .out-prompt-number { color: red; font-weight: bold; }
50 .out-prompt-number { color: red; font-weight: bold; }
51 '''
51 '''
52 default_dark_syntax_style = 'monokai'
52 default_dark_syntax_style = 'monokai'
53
53
54 # Default strings to build and display input and output prompts (and separators
54 # Default strings to build and display input and output prompts (and separators
55 # in between)
55 # in between)
56 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
56 default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: '
57 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
57 default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: '
58 default_input_sep = '\n'
58 default_input_sep = '\n'
59 default_output_sep = ''
59 default_output_sep = ''
60 default_output_sep2 = ''
60 default_output_sep2 = ''
61
61
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63 # IPythonWidget class
63 # IPythonWidget class
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65
65
66 class IPythonWidget(FrontendWidget):
66 class IPythonWidget(FrontendWidget):
67 """ A FrontendWidget for an IPython kernel.
67 """ A FrontendWidget for an IPython kernel.
68 """
68 """
69
69
70 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
70 # If set, the 'custom_edit_requested(str, int)' signal will be emitted when
71 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
71 # an editor is needed for a file. This overrides 'editor' and 'editor_line'
72 # settings.
72 # settings.
73 custom_edit = Bool(False)
73 custom_edit = Bool(False)
74 custom_edit_requested = QtCore.pyqtSignal(object, object)
74 custom_edit_requested = QtCore.pyqtSignal(object, object)
75
75
76 # A command for invoking a system text editor. If the string contains a
76 # A command for invoking a system text editor. If the string contains a
77 # {filename} format specifier, it will be used. Otherwise, the filename will
77 # {filename} format specifier, it will be used. Otherwise, the filename will
78 # be appended to the end the command.
78 # be appended to the end the command.
79 editor = Str('default', config=True)
79 editor = Str('default', config=True)
80
80
81 # The editor command to use when a specific line number is requested. The
81 # The editor command to use when a specific line number is requested. The
82 # string should contain two format specifiers: {line} and {filename}. If
82 # string should contain two format specifiers: {line} and {filename}. If
83 # this parameter is not specified, the line number option to the %edit magic
83 # this parameter is not specified, the line number option to the %edit magic
84 # will be ignored.
84 # will be ignored.
85 editor_line = Str(config=True)
85 editor_line = Str(config=True)
86
86
87 # A CSS stylesheet. The stylesheet can contain classes for:
87 # A CSS stylesheet. The stylesheet can contain classes for:
88 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
88 # 1. Qt: QPlainTextEdit, QFrame, QWidget, etc
89 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
89 # 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter)
90 # 3. IPython: .error, .in-prompt, .out-prompt, etc
90 # 3. IPython: .error, .in-prompt, .out-prompt, etc
91 style_sheet = Str(config=True)
91 style_sheet = Str(config=True)
92
92
93 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
93 # If not empty, use this Pygments style for syntax highlighting. Otherwise,
94 # the style sheet is queried for Pygments style information.
94 # the style sheet is queried for Pygments style information.
95 syntax_style = Str(config=True)
95 syntax_style = Str(config=True)
96
96
97 # Prompts.
97 # Prompts.
98 in_prompt = Str(default_in_prompt, config=True)
98 in_prompt = Str(default_in_prompt, config=True)
99 out_prompt = Str(default_out_prompt, config=True)
99 out_prompt = Str(default_out_prompt, config=True)
100 input_sep = Str(default_input_sep, config=True)
100 input_sep = Str(default_input_sep, config=True)
101 output_sep = Str(default_output_sep, config=True)
101 output_sep = Str(default_output_sep, config=True)
102 output_sep2 = Str(default_output_sep2, config=True)
102 output_sep2 = Str(default_output_sep2, config=True)
103
103
104 # FrontendWidget protected class variables.
104 # FrontendWidget protected class variables.
105 _input_splitter_class = IPythonInputSplitter
105 _input_splitter_class = IPythonInputSplitter
106
106
107 # IPythonWidget protected class variables.
107 # IPythonWidget protected class variables.
108 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
108 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
109 _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic'
109 _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic'
110 _payload_source_exit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit'
110 _payload_source_exit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit'
111 _payload_source_page = 'IPython.zmq.page.page'
111 _payload_source_page = 'IPython.zmq.page.page'
112
112
113 #---------------------------------------------------------------------------
113 #---------------------------------------------------------------------------
114 # 'object' interface
114 # 'object' interface
115 #---------------------------------------------------------------------------
115 #---------------------------------------------------------------------------
116
116
117 def __init__(self, *args, **kw):
117 def __init__(self, *args, **kw):
118 super(IPythonWidget, self).__init__(*args, **kw)
118 super(IPythonWidget, self).__init__(*args, **kw)
119
119
120 # IPythonWidget protected variables.
120 # IPythonWidget protected variables.
121 self._payload_handlers = {
121 self._payload_handlers = {
122 self._payload_source_edit : self._handle_payload_edit,
122 self._payload_source_edit : self._handle_payload_edit,
123 self._payload_source_exit : self._handle_payload_exit,
123 self._payload_source_exit : self._handle_payload_exit,
124 self._payload_source_page : self._handle_payload_page }
124 self._payload_source_page : self._handle_payload_page }
125 self._previous_prompt_obj = None
125 self._previous_prompt_obj = None
126
126
127 # Initialize widget styling.
127 # Initialize widget styling.
128 if self.style_sheet:
128 if self.style_sheet:
129 self._style_sheet_changed()
129 self._style_sheet_changed()
130 self._syntax_style_changed()
130 self._syntax_style_changed()
131 else:
131 else:
132 self.set_default_style()
132 self.set_default_style()
133
133
134 #---------------------------------------------------------------------------
134 #---------------------------------------------------------------------------
135 # 'BaseFrontendMixin' abstract interface
135 # 'BaseFrontendMixin' abstract interface
136 #---------------------------------------------------------------------------
136 #---------------------------------------------------------------------------
137
137
138 def _handle_complete_reply(self, rep):
138 def _handle_complete_reply(self, rep):
139 """ Reimplemented to support IPython's improved completion machinery.
139 """ Reimplemented to support IPython's improved completion machinery.
140 """
140 """
141 cursor = self._get_cursor()
141 cursor = self._get_cursor()
142 info = self._request_info.get('complete')
142 info = self._request_info.get('complete')
143 if info and info.id == rep['parent_header']['msg_id'] and \
143 if info and info.id == rep['parent_header']['msg_id'] and \
144 info.pos == cursor.position():
144 info.pos == cursor.position():
145 matches = rep['content']['matches']
145 matches = rep['content']['matches']
146 text = rep['content']['matched_text']
146 text = rep['content']['matched_text']
147 offset = len(text)
147 offset = len(text)
148
148
149 # Clean up matches with period and path separators if the matched
149 # Clean up matches with period and path separators if the matched
150 # text has not been transformed. This is done by truncating all
150 # text has not been transformed. This is done by truncating all
151 # but the last component and then suitably decreasing the offset
151 # but the last component and then suitably decreasing the offset
152 # between the current cursor position and the start of completion.
152 # between the current cursor position and the start of completion.
153 if len(matches) > 1 and matches[0][:offset] == text:
153 if len(matches) > 1 and matches[0][:offset] == text:
154 parts = re.split(r'[./\\]', text)
154 parts = re.split(r'[./\\]', text)
155 sep_count = len(parts) - 1
155 sep_count = len(parts) - 1
156 if sep_count:
156 if sep_count:
157 chop_length = sum(map(len, parts[:sep_count])) + sep_count
157 chop_length = sum(map(len, parts[:sep_count])) + sep_count
158 matches = [ match[chop_length:] for match in matches ]
158 matches = [ match[chop_length:] for match in matches ]
159 offset -= chop_length
159 offset -= chop_length
160
160
161 # Move the cursor to the start of the match and complete.
161 # Move the cursor to the start of the match and complete.
162 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
162 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
163 self._complete_with_items(cursor, matches)
163 self._complete_with_items(cursor, matches)
164
164
165 def _handle_execute_reply(self, msg):
165 def _handle_execute_reply(self, msg):
166 """ Reimplemented to support prompt requests.
166 """ Reimplemented to support prompt requests.
167 """
167 """
168 info = self._request_info.get('execute')
168 info = self._request_info.get('execute')
169 if info and info.id == msg['parent_header']['msg_id']:
169 if info and info.id == msg['parent_header']['msg_id']:
170 if info.kind == 'prompt':
170 if info.kind == 'prompt':
171 number = msg['content']['execution_count'] + 1
171 number = msg['content']['execution_count'] + 1
172 self._show_interpreter_prompt(number)
172 self._show_interpreter_prompt(number)
173 else:
173 else:
174 super(IPythonWidget, self)._handle_execute_reply(msg)
174 super(IPythonWidget, self)._handle_execute_reply(msg)
175
175
176 def _handle_history_reply(self, msg):
176 def _handle_history_reply(self, msg):
177 """ Implemented to handle history replies, which are only supported by
177 """ Implemented to handle history replies, which are only supported by
178 the IPython kernel.
178 the IPython kernel.
179 """
179 """
180 history_dict = msg['content']['history']
180 history_dict = msg['content']['history']
181 items = [ history_dict[key] for key in sorted(history_dict.keys()) ]
181 items = [ history_dict[key] for key in sorted(history_dict.keys()) ]
182 self._set_history(items)
182 self._set_history(items)
183
183
184 def _handle_pyout(self, msg):
184 def _handle_pyout(self, msg):
185 """ Reimplemented for IPython-style "display hook".
185 """ Reimplemented for IPython-style "display hook".
186 """
186 """
187 if not self._hidden and self._is_from_this_session(msg):
187 if not self._hidden and self._is_from_this_session(msg):
188 content = msg['content']
188 content = msg['content']
189 prompt_number = content['execution_count']
189 prompt_number = content['execution_count']
190 self._append_plain_text(self.output_sep)
190 self._append_plain_text(self.output_sep)
191 self._append_html(self._make_out_prompt(prompt_number))
191 self._append_html(self._make_out_prompt(prompt_number))
192 self._append_plain_text(content['data']+self.output_sep2)
192 self._append_plain_text(content['data']+self.output_sep2)
193
193
194 def _started_channels(self):
194 def _started_channels(self):
195 """ Reimplemented to make a history request.
195 """ Reimplemented to make a history request.
196 """
196 """
197 super(IPythonWidget, self)._started_channels()
197 super(IPythonWidget, self)._started_channels()
198 # FIXME: Disabled until history requests are properly implemented.
198 # FIXME: Disabled until history requests are properly implemented.
199 #self.kernel_manager.xreq_channel.history(raw=True, output=False)
199 #self.kernel_manager.xreq_channel.history(raw=True, output=False)
200
200
201 #---------------------------------------------------------------------------
201 #---------------------------------------------------------------------------
202 # 'ConsoleWidget' public interface
202 # 'ConsoleWidget' public interface
203 #---------------------------------------------------------------------------
203 #---------------------------------------------------------------------------
204
204
205 def copy(self):
205 def copy(self):
206 """ Copy the currently selected text to the clipboard, removing prompts
206 """ Copy the currently selected text to the clipboard, removing prompts
207 if possible.
207 if possible.
208 """
208 """
209 text = str(self._control.textCursor().selection().toPlainText())
209 text = str(self._control.textCursor().selection().toPlainText())
210 if text:
210 if text:
211 # Remove prompts.
211 # Remove prompts.
212 lines = map(transform_ipy_prompt, text.splitlines())
212 lines = map(transform_ipy_prompt, text.splitlines())
213 text = '\n'.join(lines)
213 text = '\n'.join(lines)
214 # Expand tabs so that we respect PEP-8.
214 # Expand tabs so that we respect PEP-8.
215 QtGui.QApplication.clipboard().setText(text.expandtabs(4))
215 QtGui.QApplication.clipboard().setText(text.expandtabs(4))
216
216
217 #---------------------------------------------------------------------------
217 #---------------------------------------------------------------------------
218 # 'FrontendWidget' public interface
218 # 'FrontendWidget' public interface
219 #---------------------------------------------------------------------------
219 #---------------------------------------------------------------------------
220
220
221 def execute_file(self, path, hidden=False):
221 def execute_file(self, path, hidden=False):
222 """ Reimplemented to use the 'run' magic.
222 """ Reimplemented to use the 'run' magic.
223 """
223 """
224 self.execute('%%run %s' % path, hidden=hidden)
224 self.execute('%%run %s' % path, hidden=hidden)
225
225
226 #---------------------------------------------------------------------------
226 #---------------------------------------------------------------------------
227 # 'FrontendWidget' protected interface
227 # 'FrontendWidget' protected interface
228 #---------------------------------------------------------------------------
228 #---------------------------------------------------------------------------
229
229
230 def _complete(self):
230 def _complete(self):
231 """ Reimplemented to support IPython's improved completion machinery.
231 """ Reimplemented to support IPython's improved completion machinery.
232 """
232 """
233 # We let the kernel split the input line, so we *always* send an empty
233 # We let the kernel split the input line, so we *always* send an empty
234 # text field. Readline-based frontends do get a real text field which
234 # text field. Readline-based frontends do get a real text field which
235 # they can use.
235 # they can use.
236 text = ''
236 text = ''
237
237
238 # Send the completion request to the kernel
238 # Send the completion request to the kernel
239 msg_id = self.kernel_manager.xreq_channel.complete(
239 msg_id = self.kernel_manager.xreq_channel.complete(
240 text, # text
240 text, # text
241 self._get_input_buffer_cursor_line(), # line
241 self._get_input_buffer_cursor_line(), # line
242 self._get_input_buffer_cursor_column(), # cursor_pos
242 self._get_input_buffer_cursor_column(), # cursor_pos
243 self.input_buffer) # block
243 self.input_buffer) # block
244 pos = self._get_cursor().position()
244 pos = self._get_cursor().position()
245 info = self._CompletionRequest(msg_id, pos)
245 info = self._CompletionRequest(msg_id, pos)
246 self._request_info['complete'] = info
246 self._request_info['complete'] = info
247
247
248 def _get_banner(self):
248 def _get_banner(self):
249 """ Reimplemented to return IPython's default banner.
249 """ Reimplemented to return IPython's default banner.
250 """
250 """
251 return default_banner + '\n'
251 return default_gui_banner
252
252
253 def _process_execute_error(self, msg):
253 def _process_execute_error(self, msg):
254 """ Reimplemented for IPython-style traceback formatting.
254 """ Reimplemented for IPython-style traceback formatting.
255 """
255 """
256 content = msg['content']
256 content = msg['content']
257 traceback = '\n'.join(content['traceback']) + '\n'
257 traceback = '\n'.join(content['traceback']) + '\n'
258 if False:
258 if False:
259 # FIXME: For now, tracebacks come as plain text, so we can't use
259 # FIXME: For now, tracebacks come as plain text, so we can't use
260 # the html renderer yet. Once we refactor ultratb to produce
260 # the html renderer yet. Once we refactor ultratb to produce
261 # properly styled tracebacks, this branch should be the default
261 # properly styled tracebacks, this branch should be the default
262 traceback = traceback.replace(' ', '&nbsp;')
262 traceback = traceback.replace(' ', '&nbsp;')
263 traceback = traceback.replace('\n', '<br/>')
263 traceback = traceback.replace('\n', '<br/>')
264
264
265 ename = content['ename']
265 ename = content['ename']
266 ename_styled = '<span class="error">%s</span>' % ename
266 ename_styled = '<span class="error">%s</span>' % ename
267 traceback = traceback.replace(ename, ename_styled)
267 traceback = traceback.replace(ename, ename_styled)
268
268
269 self._append_html(traceback)
269 self._append_html(traceback)
270 else:
270 else:
271 # This is the fallback for now, using plain text with ansi escapes
271 # This is the fallback for now, using plain text with ansi escapes
272 self._append_plain_text(traceback)
272 self._append_plain_text(traceback)
273
273
274 def _process_execute_payload(self, item):
274 def _process_execute_payload(self, item):
275 """ Reimplemented to dispatch payloads to handler methods.
275 """ Reimplemented to dispatch payloads to handler methods.
276 """
276 """
277 handler = self._payload_handlers.get(item['source'])
277 handler = self._payload_handlers.get(item['source'])
278 if handler is None:
278 if handler is None:
279 # We have no handler for this type of payload, simply ignore it
279 # We have no handler for this type of payload, simply ignore it
280 return False
280 return False
281 else:
281 else:
282 handler(item)
282 handler(item)
283 return True
283 return True
284
284
285 def _show_interpreter_prompt(self, number=None):
285 def _show_interpreter_prompt(self, number=None):
286 """ Reimplemented for IPython-style prompts.
286 """ Reimplemented for IPython-style prompts.
287 """
287 """
288 # If a number was not specified, make a prompt number request.
288 # If a number was not specified, make a prompt number request.
289 if number is None:
289 if number is None:
290 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
290 msg_id = self.kernel_manager.xreq_channel.execute('', silent=True)
291 info = self._ExecutionRequest(msg_id, 'prompt')
291 info = self._ExecutionRequest(msg_id, 'prompt')
292 self._request_info['execute'] = info
292 self._request_info['execute'] = info
293 return
293 return
294
294
295 # Show a new prompt and save information about it so that it can be
295 # Show a new prompt and save information about it so that it can be
296 # updated later if the prompt number turns out to be wrong.
296 # updated later if the prompt number turns out to be wrong.
297 self._prompt_sep = self.input_sep
297 self._prompt_sep = self.input_sep
298 self._show_prompt(self._make_in_prompt(number), html=True)
298 self._show_prompt(self._make_in_prompt(number), html=True)
299 block = self._control.document().lastBlock()
299 block = self._control.document().lastBlock()
300 length = len(self._prompt)
300 length = len(self._prompt)
301 self._previous_prompt_obj = self._PromptBlock(block, length, number)
301 self._previous_prompt_obj = self._PromptBlock(block, length, number)
302
302
303 # Update continuation prompt to reflect (possibly) new prompt length.
303 # Update continuation prompt to reflect (possibly) new prompt length.
304 self._set_continuation_prompt(
304 self._set_continuation_prompt(
305 self._make_continuation_prompt(self._prompt), html=True)
305 self._make_continuation_prompt(self._prompt), html=True)
306
306
307 def _show_interpreter_prompt_for_reply(self, msg):
307 def _show_interpreter_prompt_for_reply(self, msg):
308 """ Reimplemented for IPython-style prompts.
308 """ Reimplemented for IPython-style prompts.
309 """
309 """
310 # Update the old prompt number if necessary.
310 # Update the old prompt number if necessary.
311 content = msg['content']
311 content = msg['content']
312 previous_prompt_number = content['execution_count']
312 previous_prompt_number = content['execution_count']
313 if self._previous_prompt_obj and \
313 if self._previous_prompt_obj and \
314 self._previous_prompt_obj.number != previous_prompt_number:
314 self._previous_prompt_obj.number != previous_prompt_number:
315 block = self._previous_prompt_obj.block
315 block = self._previous_prompt_obj.block
316
316
317 # Make sure the prompt block has not been erased.
317 # Make sure the prompt block has not been erased.
318 if block.isValid() and not block.text().isEmpty():
318 if block.isValid() and not block.text().isEmpty():
319
319
320 # Remove the old prompt and insert a new prompt.
320 # Remove the old prompt and insert a new prompt.
321 cursor = QtGui.QTextCursor(block)
321 cursor = QtGui.QTextCursor(block)
322 cursor.movePosition(QtGui.QTextCursor.Right,
322 cursor.movePosition(QtGui.QTextCursor.Right,
323 QtGui.QTextCursor.KeepAnchor,
323 QtGui.QTextCursor.KeepAnchor,
324 self._previous_prompt_obj.length)
324 self._previous_prompt_obj.length)
325 prompt = self._make_in_prompt(previous_prompt_number)
325 prompt = self._make_in_prompt(previous_prompt_number)
326 self._prompt = self._insert_html_fetching_plain_text(
326 self._prompt = self._insert_html_fetching_plain_text(
327 cursor, prompt)
327 cursor, prompt)
328
328
329 # When the HTML is inserted, Qt blows away the syntax
329 # When the HTML is inserted, Qt blows away the syntax
330 # highlighting for the line, so we need to rehighlight it.
330 # highlighting for the line, so we need to rehighlight it.
331 self._highlighter.rehighlightBlock(cursor.block())
331 self._highlighter.rehighlightBlock(cursor.block())
332
332
333 self._previous_prompt_obj = None
333 self._previous_prompt_obj = None
334
334
335 # Show a new prompt with the kernel's estimated prompt number.
335 # Show a new prompt with the kernel's estimated prompt number.
336 self._show_interpreter_prompt(previous_prompt_number+1)
336 self._show_interpreter_prompt(previous_prompt_number+1)
337
337
338 #---------------------------------------------------------------------------
338 #---------------------------------------------------------------------------
339 # 'IPythonWidget' interface
339 # 'IPythonWidget' interface
340 #---------------------------------------------------------------------------
340 #---------------------------------------------------------------------------
341
341
342 def set_default_style(self, lightbg=True):
342 def set_default_style(self, lightbg=True):
343 """ Sets the widget style to the class defaults.
343 """ Sets the widget style to the class defaults.
344
344
345 Parameters:
345 Parameters:
346 -----------
346 -----------
347 lightbg : bool, optional (default True)
347 lightbg : bool, optional (default True)
348 Whether to use the default IPython light background or dark
348 Whether to use the default IPython light background or dark
349 background style.
349 background style.
350 """
350 """
351 if lightbg:
351 if lightbg:
352 self.style_sheet = default_light_style_sheet
352 self.style_sheet = default_light_style_sheet
353 self.syntax_style = default_light_syntax_style
353 self.syntax_style = default_light_syntax_style
354 else:
354 else:
355 self.style_sheet = default_dark_style_sheet
355 self.style_sheet = default_dark_style_sheet
356 self.syntax_style = default_dark_syntax_style
356 self.syntax_style = default_dark_syntax_style
357
357
358 #---------------------------------------------------------------------------
358 #---------------------------------------------------------------------------
359 # 'IPythonWidget' protected interface
359 # 'IPythonWidget' protected interface
360 #---------------------------------------------------------------------------
360 #---------------------------------------------------------------------------
361
361
362 def _edit(self, filename, line=None):
362 def _edit(self, filename, line=None):
363 """ Opens a Python script for editing.
363 """ Opens a Python script for editing.
364
364
365 Parameters:
365 Parameters:
366 -----------
366 -----------
367 filename : str
367 filename : str
368 A path to a local system file.
368 A path to a local system file.
369
369
370 line : int, optional
370 line : int, optional
371 A line of interest in the file.
371 A line of interest in the file.
372 """
372 """
373 if self.custom_edit:
373 if self.custom_edit:
374 self.custom_edit_requested.emit(filename, line)
374 self.custom_edit_requested.emit(filename, line)
375 elif self.editor == 'default':
375 elif self.editor == 'default':
376 self._append_plain_text('No default editor available.\n')
376 self._append_plain_text('No default editor available.\n')
377 else:
377 else:
378 try:
378 try:
379 filename = '"%s"' % filename
379 filename = '"%s"' % filename
380 if line and self.editor_line:
380 if line and self.editor_line:
381 command = self.editor_line.format(filename=filename,
381 command = self.editor_line.format(filename=filename,
382 line=line)
382 line=line)
383 else:
383 else:
384 try:
384 try:
385 command = self.editor.format()
385 command = self.editor.format()
386 except KeyError:
386 except KeyError:
387 command = self.editor.format(filename=filename)
387 command = self.editor.format(filename=filename)
388 else:
388 else:
389 command += ' ' + filename
389 command += ' ' + filename
390 except KeyError:
390 except KeyError:
391 self._append_plain_text('Invalid editor command.\n')
391 self._append_plain_text('Invalid editor command.\n')
392 else:
392 else:
393 try:
393 try:
394 Popen(command, shell=True)
394 Popen(command, shell=True)
395 except OSError:
395 except OSError:
396 msg = 'Opening editor with command "%s" failed.\n'
396 msg = 'Opening editor with command "%s" failed.\n'
397 self._append_plain_text(msg % command)
397 self._append_plain_text(msg % command)
398
398
399 def _make_in_prompt(self, number):
399 def _make_in_prompt(self, number):
400 """ Given a prompt number, returns an HTML In prompt.
400 """ Given a prompt number, returns an HTML In prompt.
401 """
401 """
402 body = self.in_prompt % number
402 body = self.in_prompt % number
403 return '<span class="in-prompt">%s</span>' % body
403 return '<span class="in-prompt">%s</span>' % body
404
404
405 def _make_continuation_prompt(self, prompt):
405 def _make_continuation_prompt(self, prompt):
406 """ Given a plain text version of an In prompt, returns an HTML
406 """ Given a plain text version of an In prompt, returns an HTML
407 continuation prompt.
407 continuation prompt.
408 """
408 """
409 end_chars = '...: '
409 end_chars = '...: '
410 space_count = len(prompt.lstrip('\n')) - len(end_chars)
410 space_count = len(prompt.lstrip('\n')) - len(end_chars)
411 body = '&nbsp;' * space_count + end_chars
411 body = '&nbsp;' * space_count + end_chars
412 return '<span class="in-prompt">%s</span>' % body
412 return '<span class="in-prompt">%s</span>' % body
413
413
414 def _make_out_prompt(self, number):
414 def _make_out_prompt(self, number):
415 """ Given a prompt number, returns an HTML Out prompt.
415 """ Given a prompt number, returns an HTML Out prompt.
416 """
416 """
417 body = self.out_prompt % number
417 body = self.out_prompt % number
418 return '<span class="out-prompt">%s</span>' % body
418 return '<span class="out-prompt">%s</span>' % body
419
419
420 #------ Payload handlers --------------------------------------------------
420 #------ Payload handlers --------------------------------------------------
421
421
422 # Payload handlers with a generic interface: each takes the opaque payload
422 # Payload handlers with a generic interface: each takes the opaque payload
423 # dict, unpacks it and calls the underlying functions with the necessary
423 # dict, unpacks it and calls the underlying functions with the necessary
424 # arguments.
424 # arguments.
425
425
426 def _handle_payload_edit(self, item):
426 def _handle_payload_edit(self, item):
427 self._edit(item['filename'], item['line_number'])
427 self._edit(item['filename'], item['line_number'])
428
428
429 def _handle_payload_exit(self, item):
429 def _handle_payload_exit(self, item):
430 self.exit_requested.emit()
430 self.exit_requested.emit()
431
431
432 def _handle_payload_page(self, item):
432 def _handle_payload_page(self, item):
433 self._page(item['data'])
433 self._page(item['data'])
434
434
435 #------ Trait change handlers ---------------------------------------------
435 #------ Trait change handlers ---------------------------------------------
436
436
437 def _style_sheet_changed(self):
437 def _style_sheet_changed(self):
438 """ Set the style sheets of the underlying widgets.
438 """ Set the style sheets of the underlying widgets.
439 """
439 """
440 self.setStyleSheet(self.style_sheet)
440 self.setStyleSheet(self.style_sheet)
441 self._control.document().setDefaultStyleSheet(self.style_sheet)
441 self._control.document().setDefaultStyleSheet(self.style_sheet)
442 if self._page_control:
442 if self._page_control:
443 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
443 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
444
444
445 bg_color = self._control.palette().background().color()
445 bg_color = self._control.palette().background().color()
446 self._ansi_processor.set_background_color(bg_color)
446 self._ansi_processor.set_background_color(bg_color)
447
447
448 def _syntax_style_changed(self):
448 def _syntax_style_changed(self):
449 """ Set the style for the syntax highlighter.
449 """ Set the style for the syntax highlighter.
450 """
450 """
451 if self.syntax_style:
451 if self.syntax_style:
452 self._highlighter.set_style(self.syntax_style)
452 self._highlighter.set_style(self.syntax_style)
453 else:
453 else:
454 self._highlighter.set_style_sheet(self.style_sheet)
454 self._highlighter.set_style_sheet(self.style_sheet)
455
455
@@ -1,652 +1,652 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Subclass of InteractiveShell for terminal based frontends."""
2 """Subclass of InteractiveShell for terminal based frontends."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import __builtin__
17 import __builtin__
18 import bdb
18 import bdb
19 from contextlib import nested
19 from contextlib import nested
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23
23
24 from IPython.core.error import TryNext
24 from IPython.core.error import TryNext
25 from IPython.core.usage import interactive_usage, default_banner
25 from IPython.core.usage import interactive_usage, default_banner
26 from IPython.core.inputlist import InputList
26 from IPython.core.inputlist import InputList
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
27 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
28 from IPython.lib.inputhook import enable_gui
28 from IPython.lib.inputhook import enable_gui
29 from IPython.lib.pylabtools import pylab_activate
29 from IPython.lib.pylabtools import pylab_activate
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 from IPython.utils.process import abbrev_cwd
31 from IPython.utils.process import abbrev_cwd
32 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
33 from IPython.utils.text import num_ini_spaces
33 from IPython.utils.text import num_ini_spaces
34 from IPython.utils.traitlets import Int, Str, CBool
34 from IPython.utils.traitlets import Int, Str, CBool
35
35
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Utilities
38 # Utilities
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41
41
42 def get_default_editor():
42 def get_default_editor():
43 try:
43 try:
44 ed = os.environ['EDITOR']
44 ed = os.environ['EDITOR']
45 except KeyError:
45 except KeyError:
46 if os.name == 'posix':
46 if os.name == 'posix':
47 ed = 'vi' # the only one guaranteed to be there!
47 ed = 'vi' # the only one guaranteed to be there!
48 else:
48 else:
49 ed = 'notepad' # same in Windows!
49 ed = 'notepad' # same in Windows!
50 return ed
50 return ed
51
51
52
52
53 # store the builtin raw_input globally, and use this always, in case user code
53 # store the builtin raw_input globally, and use this always, in case user code
54 # overwrites it (like wx.py.PyShell does)
54 # overwrites it (like wx.py.PyShell does)
55 raw_input_original = raw_input
55 raw_input_original = raw_input
56
56
57
57
58 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
59 # Main class
59 # Main class
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61
61
62
62
63 class TerminalInteractiveShell(InteractiveShell):
63 class TerminalInteractiveShell(InteractiveShell):
64
64
65 autoedit_syntax = CBool(False, config=True)
65 autoedit_syntax = CBool(False, config=True)
66 banner = Str('')
66 banner = Str('')
67 banner1 = Str(default_banner, config=True)
67 banner1 = Str(default_banner, config=True)
68 banner2 = Str('', config=True)
68 banner2 = Str('', config=True)
69 confirm_exit = CBool(True, config=True)
69 confirm_exit = CBool(True, config=True)
70 # This display_banner only controls whether or not self.show_banner()
70 # This display_banner only controls whether or not self.show_banner()
71 # is called when mainloop/interact are called. The default is False
71 # is called when mainloop/interact are called. The default is False
72 # because for the terminal based application, the banner behavior
72 # because for the terminal based application, the banner behavior
73 # is controlled by Global.display_banner, which IPythonApp looks at
73 # is controlled by Global.display_banner, which IPythonApp looks at
74 # to determine if *it* should call show_banner() by hand or not.
74 # to determine if *it* should call show_banner() by hand or not.
75 display_banner = CBool(False) # This isn't configurable!
75 display_banner = CBool(False) # This isn't configurable!
76 embedded = CBool(False)
76 embedded = CBool(False)
77 embedded_active = CBool(False)
77 embedded_active = CBool(False)
78 editor = Str(get_default_editor(), config=True)
78 editor = Str(get_default_editor(), config=True)
79 pager = Str('less', config=True)
79 pager = Str('less', config=True)
80
80
81 screen_length = Int(0, config=True)
81 screen_length = Int(0, config=True)
82 term_title = CBool(False, config=True)
82 term_title = CBool(False, config=True)
83
83
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
84 def __init__(self, config=None, ipython_dir=None, user_ns=None,
85 user_global_ns=None, custom_exceptions=((),None),
85 user_global_ns=None, custom_exceptions=((),None),
86 usage=None, banner1=None, banner2=None,
86 usage=None, banner1=None, banner2=None,
87 display_banner=None):
87 display_banner=None):
88
88
89 super(TerminalInteractiveShell, self).__init__(
89 super(TerminalInteractiveShell, self).__init__(
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
90 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
91 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
92 )
92 )
93 self.init_term_title()
93 self.init_term_title()
94 self.init_usage(usage)
94 self.init_usage(usage)
95 self.init_banner(banner1, banner2, display_banner)
95 self.init_banner(banner1, banner2, display_banner)
96
96
97 #-------------------------------------------------------------------------
97 #-------------------------------------------------------------------------
98 # Things related to the terminal
98 # Things related to the terminal
99 #-------------------------------------------------------------------------
99 #-------------------------------------------------------------------------
100
100
101 @property
101 @property
102 def usable_screen_length(self):
102 def usable_screen_length(self):
103 if self.screen_length == 0:
103 if self.screen_length == 0:
104 return 0
104 return 0
105 else:
105 else:
106 num_lines_bot = self.separate_in.count('\n')+1
106 num_lines_bot = self.separate_in.count('\n')+1
107 return self.screen_length - num_lines_bot
107 return self.screen_length - num_lines_bot
108
108
109 def init_term_title(self):
109 def init_term_title(self):
110 # Enable or disable the terminal title.
110 # Enable or disable the terminal title.
111 if self.term_title:
111 if self.term_title:
112 toggle_set_term_title(True)
112 toggle_set_term_title(True)
113 set_term_title('IPython: ' + abbrev_cwd())
113 set_term_title('IPython: ' + abbrev_cwd())
114 else:
114 else:
115 toggle_set_term_title(False)
115 toggle_set_term_title(False)
116
116
117 #-------------------------------------------------------------------------
117 #-------------------------------------------------------------------------
118 # Things related to aliases
118 # Things related to aliases
119 #-------------------------------------------------------------------------
119 #-------------------------------------------------------------------------
120
120
121 def init_alias(self):
121 def init_alias(self):
122 # The parent class defines aliases that can be safely used with any
122 # The parent class defines aliases that can be safely used with any
123 # frontend.
123 # frontend.
124 super(TerminalInteractiveShell, self).init_alias()
124 super(TerminalInteractiveShell, self).init_alias()
125
125
126 # Now define aliases that only make sense on the terminal, because they
126 # Now define aliases that only make sense on the terminal, because they
127 # need direct access to the console in a way that we can't emulate in
127 # need direct access to the console in a way that we can't emulate in
128 # GUI or web frontend
128 # GUI or web frontend
129 if os.name == 'posix':
129 if os.name == 'posix':
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
130 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
131 ('man', 'man')]
131 ('man', 'man')]
132 elif os.name == 'nt':
132 elif os.name == 'nt':
133 aliases = [('cls', 'cls')]
133 aliases = [('cls', 'cls')]
134
134
135
135
136 for name, cmd in aliases:
136 for name, cmd in aliases:
137 self.alias_manager.define_alias(name, cmd)
137 self.alias_manager.define_alias(name, cmd)
138
138
139 #-------------------------------------------------------------------------
139 #-------------------------------------------------------------------------
140 # Things related to the banner and usage
140 # Things related to the banner and usage
141 #-------------------------------------------------------------------------
141 #-------------------------------------------------------------------------
142
142
143 def _banner1_changed(self):
143 def _banner1_changed(self):
144 self.compute_banner()
144 self.compute_banner()
145
145
146 def _banner2_changed(self):
146 def _banner2_changed(self):
147 self.compute_banner()
147 self.compute_banner()
148
148
149 def _term_title_changed(self, name, new_value):
149 def _term_title_changed(self, name, new_value):
150 self.init_term_title()
150 self.init_term_title()
151
151
152 def init_banner(self, banner1, banner2, display_banner):
152 def init_banner(self, banner1, banner2, display_banner):
153 if banner1 is not None:
153 if banner1 is not None:
154 self.banner1 = banner1
154 self.banner1 = banner1
155 if banner2 is not None:
155 if banner2 is not None:
156 self.banner2 = banner2
156 self.banner2 = banner2
157 if display_banner is not None:
157 if display_banner is not None:
158 self.display_banner = display_banner
158 self.display_banner = display_banner
159 self.compute_banner()
159 self.compute_banner()
160
160
161 def show_banner(self, banner=None):
161 def show_banner(self, banner=None):
162 if banner is None:
162 if banner is None:
163 banner = self.banner
163 banner = self.banner
164 self.write(banner)
164 self.write(banner)
165
165
166 def compute_banner(self):
166 def compute_banner(self):
167 self.banner = self.banner1 + '\n'
167 self.banner = self.banner1
168 if self.profile:
168 if self.profile:
169 self.banner += '\nIPython profile: %s\n' % self.profile
169 self.banner += '\nIPython profile: %s\n' % self.profile
170 if self.banner2:
170 if self.banner2:
171 self.banner += '\n' + self.banner2 + '\n'
171 self.banner += '\n' + self.banner2
172
172
173 def init_usage(self, usage=None):
173 def init_usage(self, usage=None):
174 if usage is None:
174 if usage is None:
175 self.usage = interactive_usage
175 self.usage = interactive_usage
176 else:
176 else:
177 self.usage = usage
177 self.usage = usage
178
178
179 #-------------------------------------------------------------------------
179 #-------------------------------------------------------------------------
180 # Mainloop and code execution logic
180 # Mainloop and code execution logic
181 #-------------------------------------------------------------------------
181 #-------------------------------------------------------------------------
182
182
183 def mainloop(self, display_banner=None):
183 def mainloop(self, display_banner=None):
184 """Start the mainloop.
184 """Start the mainloop.
185
185
186 If an optional banner argument is given, it will override the
186 If an optional banner argument is given, it will override the
187 internally created default banner.
187 internally created default banner.
188 """
188 """
189
189
190 with nested(self.builtin_trap, self.display_trap):
190 with nested(self.builtin_trap, self.display_trap):
191
191
192 # if you run stuff with -c <cmd>, raw hist is not updated
192 # if you run stuff with -c <cmd>, raw hist is not updated
193 # ensure that it's in sync
193 # ensure that it's in sync
194 if len(self.input_hist) != len (self.input_hist_raw):
194 if len(self.input_hist) != len (self.input_hist_raw):
195 self.input_hist_raw = InputList(self.input_hist)
195 self.input_hist_raw = InputList(self.input_hist)
196
196
197 while 1:
197 while 1:
198 try:
198 try:
199 self.interact(display_banner=display_banner)
199 self.interact(display_banner=display_banner)
200 #self.interact_with_readline()
200 #self.interact_with_readline()
201 # XXX for testing of a readline-decoupled repl loop, call
201 # XXX for testing of a readline-decoupled repl loop, call
202 # interact_with_readline above
202 # interact_with_readline above
203 break
203 break
204 except KeyboardInterrupt:
204 except KeyboardInterrupt:
205 # this should not be necessary, but KeyboardInterrupt
205 # this should not be necessary, but KeyboardInterrupt
206 # handling seems rather unpredictable...
206 # handling seems rather unpredictable...
207 self.write("\nKeyboardInterrupt in interact()\n")
207 self.write("\nKeyboardInterrupt in interact()\n")
208
208
209 def interact(self, display_banner=None):
209 def interact(self, display_banner=None):
210 """Closely emulate the interactive Python console."""
210 """Closely emulate the interactive Python console."""
211
211
212 # batch run -> do not interact
212 # batch run -> do not interact
213 if self.exit_now:
213 if self.exit_now:
214 return
214 return
215
215
216 if display_banner is None:
216 if display_banner is None:
217 display_banner = self.display_banner
217 display_banner = self.display_banner
218 if display_banner:
218 if display_banner:
219 self.show_banner()
219 self.show_banner()
220
220
221 more = 0
221 more = 0
222
222
223 # Mark activity in the builtins
223 # Mark activity in the builtins
224 __builtin__.__dict__['__IPYTHON__active'] += 1
224 __builtin__.__dict__['__IPYTHON__active'] += 1
225
225
226 if self.has_readline:
226 if self.has_readline:
227 self.readline_startup_hook(self.pre_readline)
227 self.readline_startup_hook(self.pre_readline)
228 # exit_now is set by a call to %Exit or %Quit, through the
228 # exit_now is set by a call to %Exit or %Quit, through the
229 # ask_exit callback.
229 # ask_exit callback.
230
230
231 while not self.exit_now:
231 while not self.exit_now:
232 self.hooks.pre_prompt_hook()
232 self.hooks.pre_prompt_hook()
233 if more:
233 if more:
234 try:
234 try:
235 prompt = self.hooks.generate_prompt(True)
235 prompt = self.hooks.generate_prompt(True)
236 except:
236 except:
237 self.showtraceback()
237 self.showtraceback()
238 if self.autoindent:
238 if self.autoindent:
239 self.rl_do_indent = True
239 self.rl_do_indent = True
240
240
241 else:
241 else:
242 try:
242 try:
243 prompt = self.hooks.generate_prompt(False)
243 prompt = self.hooks.generate_prompt(False)
244 except:
244 except:
245 self.showtraceback()
245 self.showtraceback()
246 try:
246 try:
247 line = self.raw_input(prompt, more)
247 line = self.raw_input(prompt, more)
248 if self.exit_now:
248 if self.exit_now:
249 # quick exit on sys.std[in|out] close
249 # quick exit on sys.std[in|out] close
250 break
250 break
251 if self.autoindent:
251 if self.autoindent:
252 self.rl_do_indent = False
252 self.rl_do_indent = False
253
253
254 except KeyboardInterrupt:
254 except KeyboardInterrupt:
255 #double-guard against keyboardinterrupts during kbdint handling
255 #double-guard against keyboardinterrupts during kbdint handling
256 try:
256 try:
257 self.write('\nKeyboardInterrupt\n')
257 self.write('\nKeyboardInterrupt\n')
258 self.resetbuffer()
258 self.resetbuffer()
259 # keep cache in sync with the prompt counter:
259 # keep cache in sync with the prompt counter:
260 self.displayhook.prompt_count -= 1
260 self.displayhook.prompt_count -= 1
261
261
262 if self.autoindent:
262 if self.autoindent:
263 self.indent_current_nsp = 0
263 self.indent_current_nsp = 0
264 more = 0
264 more = 0
265 except KeyboardInterrupt:
265 except KeyboardInterrupt:
266 pass
266 pass
267 except EOFError:
267 except EOFError:
268 if self.autoindent:
268 if self.autoindent:
269 self.rl_do_indent = False
269 self.rl_do_indent = False
270 if self.has_readline:
270 if self.has_readline:
271 self.readline_startup_hook(None)
271 self.readline_startup_hook(None)
272 self.write('\n')
272 self.write('\n')
273 self.exit()
273 self.exit()
274 except bdb.BdbQuit:
274 except bdb.BdbQuit:
275 warn('The Python debugger has exited with a BdbQuit exception.\n'
275 warn('The Python debugger has exited with a BdbQuit exception.\n'
276 'Because of how pdb handles the stack, it is impossible\n'
276 'Because of how pdb handles the stack, it is impossible\n'
277 'for IPython to properly format this particular exception.\n'
277 'for IPython to properly format this particular exception.\n'
278 'IPython will resume normal operation.')
278 'IPython will resume normal operation.')
279 except:
279 except:
280 # exceptions here are VERY RARE, but they can be triggered
280 # exceptions here are VERY RARE, but they can be triggered
281 # asynchronously by signal handlers, for example.
281 # asynchronously by signal handlers, for example.
282 self.showtraceback()
282 self.showtraceback()
283 else:
283 else:
284 more = self.push_line(line)
284 more = self.push_line(line)
285 if (self.SyntaxTB.last_syntax_error and
285 if (self.SyntaxTB.last_syntax_error and
286 self.autoedit_syntax):
286 self.autoedit_syntax):
287 self.edit_syntax_error()
287 self.edit_syntax_error()
288
288
289 # We are off again...
289 # We are off again...
290 __builtin__.__dict__['__IPYTHON__active'] -= 1
290 __builtin__.__dict__['__IPYTHON__active'] -= 1
291
291
292 # Turn off the exit flag, so the mainloop can be restarted if desired
292 # Turn off the exit flag, so the mainloop can be restarted if desired
293 self.exit_now = False
293 self.exit_now = False
294
294
295 def raw_input(self,prompt='',continue_prompt=False):
295 def raw_input(self,prompt='',continue_prompt=False):
296 """Write a prompt and read a line.
296 """Write a prompt and read a line.
297
297
298 The returned line does not include the trailing newline.
298 The returned line does not include the trailing newline.
299 When the user enters the EOF key sequence, EOFError is raised.
299 When the user enters the EOF key sequence, EOFError is raised.
300
300
301 Optional inputs:
301 Optional inputs:
302
302
303 - prompt(''): a string to be printed to prompt the user.
303 - prompt(''): a string to be printed to prompt the user.
304
304
305 - continue_prompt(False): whether this line is the first one or a
305 - continue_prompt(False): whether this line is the first one or a
306 continuation in a sequence of inputs.
306 continuation in a sequence of inputs.
307 """
307 """
308 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
308 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
309
309
310 # Code run by the user may have modified the readline completer state.
310 # Code run by the user may have modified the readline completer state.
311 # We must ensure that our completer is back in place.
311 # We must ensure that our completer is back in place.
312
312
313 if self.has_readline:
313 if self.has_readline:
314 self.set_readline_completer()
314 self.set_readline_completer()
315
315
316 try:
316 try:
317 line = raw_input_original(prompt).decode(self.stdin_encoding)
317 line = raw_input_original(prompt).decode(self.stdin_encoding)
318 except ValueError:
318 except ValueError:
319 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
319 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
320 " or sys.stdout.close()!\nExiting IPython!")
320 " or sys.stdout.close()!\nExiting IPython!")
321 self.ask_exit()
321 self.ask_exit()
322 return ""
322 return ""
323
323
324 # Try to be reasonably smart about not re-indenting pasted input more
324 # Try to be reasonably smart about not re-indenting pasted input more
325 # than necessary. We do this by trimming out the auto-indent initial
325 # than necessary. We do this by trimming out the auto-indent initial
326 # spaces, if the user's actual input started itself with whitespace.
326 # spaces, if the user's actual input started itself with whitespace.
327 #debugx('self.buffer[-1]')
327 #debugx('self.buffer[-1]')
328
328
329 if self.autoindent:
329 if self.autoindent:
330 if num_ini_spaces(line) > self.indent_current_nsp:
330 if num_ini_spaces(line) > self.indent_current_nsp:
331 line = line[self.indent_current_nsp:]
331 line = line[self.indent_current_nsp:]
332 self.indent_current_nsp = 0
332 self.indent_current_nsp = 0
333
333
334 # store the unfiltered input before the user has any chance to modify
334 # store the unfiltered input before the user has any chance to modify
335 # it.
335 # it.
336 if line.strip():
336 if line.strip():
337 if continue_prompt:
337 if continue_prompt:
338 self.input_hist_raw[-1] += '%s\n' % line
338 self.input_hist_raw[-1] += '%s\n' % line
339 if self.has_readline and self.readline_use:
339 if self.has_readline and self.readline_use:
340 try:
340 try:
341 histlen = self.readline.get_current_history_length()
341 histlen = self.readline.get_current_history_length()
342 if histlen > 1:
342 if histlen > 1:
343 newhist = self.input_hist_raw[-1].rstrip()
343 newhist = self.input_hist_raw[-1].rstrip()
344 self.readline.remove_history_item(histlen-1)
344 self.readline.remove_history_item(histlen-1)
345 self.readline.replace_history_item(histlen-2,
345 self.readline.replace_history_item(histlen-2,
346 newhist.encode(self.stdin_encoding))
346 newhist.encode(self.stdin_encoding))
347 except AttributeError:
347 except AttributeError:
348 pass # re{move,place}_history_item are new in 2.4.
348 pass # re{move,place}_history_item are new in 2.4.
349 else:
349 else:
350 self.input_hist_raw.append('%s\n' % line)
350 self.input_hist_raw.append('%s\n' % line)
351 # only entries starting at first column go to shadow history
351 # only entries starting at first column go to shadow history
352 if line.lstrip() == line:
352 if line.lstrip() == line:
353 self.shadowhist.add(line.strip())
353 self.shadowhist.add(line.strip())
354 elif not continue_prompt:
354 elif not continue_prompt:
355 self.input_hist_raw.append('\n')
355 self.input_hist_raw.append('\n')
356 try:
356 try:
357 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
357 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
358 except:
358 except:
359 # blanket except, in case a user-defined prefilter crashes, so it
359 # blanket except, in case a user-defined prefilter crashes, so it
360 # can't take all of ipython with it.
360 # can't take all of ipython with it.
361 self.showtraceback()
361 self.showtraceback()
362 return ''
362 return ''
363 else:
363 else:
364 return lineout
364 return lineout
365
365
366 # TODO: The following three methods are an early attempt to refactor
366 # TODO: The following three methods are an early attempt to refactor
367 # the main code execution logic. We don't use them, but they may be
367 # the main code execution logic. We don't use them, but they may be
368 # helpful when we refactor the code execution logic further.
368 # helpful when we refactor the code execution logic further.
369 # def interact_prompt(self):
369 # def interact_prompt(self):
370 # """ Print the prompt (in read-eval-print loop)
370 # """ Print the prompt (in read-eval-print loop)
371 #
371 #
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
372 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
373 # used in standard IPython flow.
373 # used in standard IPython flow.
374 # """
374 # """
375 # if self.more:
375 # if self.more:
376 # try:
376 # try:
377 # prompt = self.hooks.generate_prompt(True)
377 # prompt = self.hooks.generate_prompt(True)
378 # except:
378 # except:
379 # self.showtraceback()
379 # self.showtraceback()
380 # if self.autoindent:
380 # if self.autoindent:
381 # self.rl_do_indent = True
381 # self.rl_do_indent = True
382 #
382 #
383 # else:
383 # else:
384 # try:
384 # try:
385 # prompt = self.hooks.generate_prompt(False)
385 # prompt = self.hooks.generate_prompt(False)
386 # except:
386 # except:
387 # self.showtraceback()
387 # self.showtraceback()
388 # self.write(prompt)
388 # self.write(prompt)
389 #
389 #
390 # def interact_handle_input(self,line):
390 # def interact_handle_input(self,line):
391 # """ Handle the input line (in read-eval-print loop)
391 # """ Handle the input line (in read-eval-print loop)
392 #
392 #
393 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
393 # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
394 # used in standard IPython flow.
394 # used in standard IPython flow.
395 # """
395 # """
396 # if line.lstrip() == line:
396 # if line.lstrip() == line:
397 # self.shadowhist.add(line.strip())
397 # self.shadowhist.add(line.strip())
398 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
398 # lineout = self.prefilter_manager.prefilter_lines(line,self.more)
399 #
399 #
400 # if line.strip():
400 # if line.strip():
401 # if self.more:
401 # if self.more:
402 # self.input_hist_raw[-1] += '%s\n' % line
402 # self.input_hist_raw[-1] += '%s\n' % line
403 # else:
403 # else:
404 # self.input_hist_raw.append('%s\n' % line)
404 # self.input_hist_raw.append('%s\n' % line)
405 #
405 #
406 #
406 #
407 # self.more = self.push_line(lineout)
407 # self.more = self.push_line(lineout)
408 # if (self.SyntaxTB.last_syntax_error and
408 # if (self.SyntaxTB.last_syntax_error and
409 # self.autoedit_syntax):
409 # self.autoedit_syntax):
410 # self.edit_syntax_error()
410 # self.edit_syntax_error()
411 #
411 #
412 # def interact_with_readline(self):
412 # def interact_with_readline(self):
413 # """ Demo of using interact_handle_input, interact_prompt
413 # """ Demo of using interact_handle_input, interact_prompt
414 #
414 #
415 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
415 # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
416 # it should work like this.
416 # it should work like this.
417 # """
417 # """
418 # self.readline_startup_hook(self.pre_readline)
418 # self.readline_startup_hook(self.pre_readline)
419 # while not self.exit_now:
419 # while not self.exit_now:
420 # self.interact_prompt()
420 # self.interact_prompt()
421 # if self.more:
421 # if self.more:
422 # self.rl_do_indent = True
422 # self.rl_do_indent = True
423 # else:
423 # else:
424 # self.rl_do_indent = False
424 # self.rl_do_indent = False
425 # line = raw_input_original().decode(self.stdin_encoding)
425 # line = raw_input_original().decode(self.stdin_encoding)
426 # self.interact_handle_input(line)
426 # self.interact_handle_input(line)
427
427
428 #-------------------------------------------------------------------------
428 #-------------------------------------------------------------------------
429 # Methods to support auto-editing of SyntaxErrors.
429 # Methods to support auto-editing of SyntaxErrors.
430 #-------------------------------------------------------------------------
430 #-------------------------------------------------------------------------
431
431
432 def edit_syntax_error(self):
432 def edit_syntax_error(self):
433 """The bottom half of the syntax error handler called in the main loop.
433 """The bottom half of the syntax error handler called in the main loop.
434
434
435 Loop until syntax error is fixed or user cancels.
435 Loop until syntax error is fixed or user cancels.
436 """
436 """
437
437
438 while self.SyntaxTB.last_syntax_error:
438 while self.SyntaxTB.last_syntax_error:
439 # copy and clear last_syntax_error
439 # copy and clear last_syntax_error
440 err = self.SyntaxTB.clear_err_state()
440 err = self.SyntaxTB.clear_err_state()
441 if not self._should_recompile(err):
441 if not self._should_recompile(err):
442 return
442 return
443 try:
443 try:
444 # may set last_syntax_error again if a SyntaxError is raised
444 # may set last_syntax_error again if a SyntaxError is raised
445 self.safe_execfile(err.filename,self.user_ns)
445 self.safe_execfile(err.filename,self.user_ns)
446 except:
446 except:
447 self.showtraceback()
447 self.showtraceback()
448 else:
448 else:
449 try:
449 try:
450 f = file(err.filename)
450 f = file(err.filename)
451 try:
451 try:
452 # This should be inside a display_trap block and I
452 # This should be inside a display_trap block and I
453 # think it is.
453 # think it is.
454 sys.displayhook(f.read())
454 sys.displayhook(f.read())
455 finally:
455 finally:
456 f.close()
456 f.close()
457 except:
457 except:
458 self.showtraceback()
458 self.showtraceback()
459
459
460 def _should_recompile(self,e):
460 def _should_recompile(self,e):
461 """Utility routine for edit_syntax_error"""
461 """Utility routine for edit_syntax_error"""
462
462
463 if e.filename in ('<ipython console>','<input>','<string>',
463 if e.filename in ('<ipython console>','<input>','<string>',
464 '<console>','<BackgroundJob compilation>',
464 '<console>','<BackgroundJob compilation>',
465 None):
465 None):
466
466
467 return False
467 return False
468 try:
468 try:
469 if (self.autoedit_syntax and
469 if (self.autoedit_syntax and
470 not self.ask_yes_no('Return to editor to correct syntax error? '
470 not self.ask_yes_no('Return to editor to correct syntax error? '
471 '[Y/n] ','y')):
471 '[Y/n] ','y')):
472 return False
472 return False
473 except EOFError:
473 except EOFError:
474 return False
474 return False
475
475
476 def int0(x):
476 def int0(x):
477 try:
477 try:
478 return int(x)
478 return int(x)
479 except TypeError:
479 except TypeError:
480 return 0
480 return 0
481 # always pass integer line and offset values to editor hook
481 # always pass integer line and offset values to editor hook
482 try:
482 try:
483 self.hooks.fix_error_editor(e.filename,
483 self.hooks.fix_error_editor(e.filename,
484 int0(e.lineno),int0(e.offset),e.msg)
484 int0(e.lineno),int0(e.offset),e.msg)
485 except TryNext:
485 except TryNext:
486 warn('Could not open editor')
486 warn('Could not open editor')
487 return False
487 return False
488 return True
488 return True
489
489
490 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
491 # Things related to GUI support and pylab
491 # Things related to GUI support and pylab
492 #-------------------------------------------------------------------------
492 #-------------------------------------------------------------------------
493
493
494 def enable_pylab(self, gui=None):
494 def enable_pylab(self, gui=None):
495 """Activate pylab support at runtime.
495 """Activate pylab support at runtime.
496
496
497 This turns on support for matplotlib, preloads into the interactive
497 This turns on support for matplotlib, preloads into the interactive
498 namespace all of numpy and pylab, and configures IPython to correcdtly
498 namespace all of numpy and pylab, and configures IPython to correcdtly
499 interact with the GUI event loop. The GUI backend to be used can be
499 interact with the GUI event loop. The GUI backend to be used can be
500 optionally selected with the optional :param:`gui` argument.
500 optionally selected with the optional :param:`gui` argument.
501
501
502 Parameters
502 Parameters
503 ----------
503 ----------
504 gui : optional, string
504 gui : optional, string
505
505
506 If given, dictates the choice of matplotlib GUI backend to use
506 If given, dictates the choice of matplotlib GUI backend to use
507 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
507 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
508 'gtk'), otherwise we use the default chosen by matplotlib (as
508 'gtk'), otherwise we use the default chosen by matplotlib (as
509 dictated by the matplotlib build-time options plus the user's
509 dictated by the matplotlib build-time options plus the user's
510 matplotlibrc configuration file).
510 matplotlibrc configuration file).
511 """
511 """
512 # We want to prevent the loading of pylab to pollute the user's
512 # We want to prevent the loading of pylab to pollute the user's
513 # namespace as shown by the %who* magics, so we execute the activation
513 # namespace as shown by the %who* magics, so we execute the activation
514 # code in an empty namespace, and we update *both* user_ns and
514 # code in an empty namespace, and we update *both* user_ns and
515 # user_ns_hidden with this information.
515 # user_ns_hidden with this information.
516 ns = {}
516 ns = {}
517 gui = pylab_activate(ns, gui)
517 gui = pylab_activate(ns, gui)
518 self.user_ns.update(ns)
518 self.user_ns.update(ns)
519 self.user_ns_hidden.update(ns)
519 self.user_ns_hidden.update(ns)
520 # Now we must activate the gui pylab wants to use, and fix %run to take
520 # Now we must activate the gui pylab wants to use, and fix %run to take
521 # plot updates into account
521 # plot updates into account
522 enable_gui(gui)
522 enable_gui(gui)
523 self.magic_run = self._pylab_magic_run
523 self.magic_run = self._pylab_magic_run
524
524
525 #-------------------------------------------------------------------------
525 #-------------------------------------------------------------------------
526 # Things related to exiting
526 # Things related to exiting
527 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
528
528
529 def ask_exit(self):
529 def ask_exit(self):
530 """ Ask the shell to exit. Can be overiden and used as a callback. """
530 """ Ask the shell to exit. Can be overiden and used as a callback. """
531 self.exit_now = True
531 self.exit_now = True
532
532
533 def exit(self):
533 def exit(self):
534 """Handle interactive exit.
534 """Handle interactive exit.
535
535
536 This method calls the ask_exit callback."""
536 This method calls the ask_exit callback."""
537 if self.confirm_exit:
537 if self.confirm_exit:
538 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
538 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
539 self.ask_exit()
539 self.ask_exit()
540 else:
540 else:
541 self.ask_exit()
541 self.ask_exit()
542
542
543 #------------------------------------------------------------------------
543 #------------------------------------------------------------------------
544 # Magic overrides
544 # Magic overrides
545 #------------------------------------------------------------------------
545 #------------------------------------------------------------------------
546 # Once the base class stops inheriting from magic, this code needs to be
546 # Once the base class stops inheriting from magic, this code needs to be
547 # moved into a separate machinery as well. For now, at least isolate here
547 # moved into a separate machinery as well. For now, at least isolate here
548 # the magics which this class needs to implement differently from the base
548 # the magics which this class needs to implement differently from the base
549 # class, or that are unique to it.
549 # class, or that are unique to it.
550
550
551 def magic_autoindent(self, parameter_s = ''):
551 def magic_autoindent(self, parameter_s = ''):
552 """Toggle autoindent on/off (if available)."""
552 """Toggle autoindent on/off (if available)."""
553
553
554 self.shell.set_autoindent()
554 self.shell.set_autoindent()
555 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
555 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
556
556
557 def magic_cpaste(self, parameter_s=''):
557 def magic_cpaste(self, parameter_s=''):
558 """Paste & execute a pre-formatted code block from clipboard.
558 """Paste & execute a pre-formatted code block from clipboard.
559
559
560 You must terminate the block with '--' (two minus-signs) alone on the
560 You must terminate the block with '--' (two minus-signs) alone on the
561 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
561 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
562 is the new sentinel for this operation)
562 is the new sentinel for this operation)
563
563
564 The block is dedented prior to execution to enable execution of method
564 The block is dedented prior to execution to enable execution of method
565 definitions. '>' and '+' characters at the beginning of a line are
565 definitions. '>' and '+' characters at the beginning of a line are
566 ignored, to allow pasting directly from e-mails, diff files and
566 ignored, to allow pasting directly from e-mails, diff files and
567 doctests (the '...' continuation prompt is also stripped). The
567 doctests (the '...' continuation prompt is also stripped). The
568 executed block is also assigned to variable named 'pasted_block' for
568 executed block is also assigned to variable named 'pasted_block' for
569 later editing with '%edit pasted_block'.
569 later editing with '%edit pasted_block'.
570
570
571 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
571 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
572 This assigns the pasted block to variable 'foo' as string, without
572 This assigns the pasted block to variable 'foo' as string, without
573 dedenting or executing it (preceding >>> and + is still stripped)
573 dedenting or executing it (preceding >>> and + is still stripped)
574
574
575 '%cpaste -r' re-executes the block previously entered by cpaste.
575 '%cpaste -r' re-executes the block previously entered by cpaste.
576
576
577 Do not be alarmed by garbled output on Windows (it's a readline bug).
577 Do not be alarmed by garbled output on Windows (it's a readline bug).
578 Just press enter and type -- (and press enter again) and the block
578 Just press enter and type -- (and press enter again) and the block
579 will be what was just pasted.
579 will be what was just pasted.
580
580
581 IPython statements (magics, shell escapes) are not supported (yet).
581 IPython statements (magics, shell escapes) are not supported (yet).
582
582
583 See also
583 See also
584 --------
584 --------
585 paste: automatically pull code from clipboard.
585 paste: automatically pull code from clipboard.
586 """
586 """
587
587
588 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
588 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
589 par = args.strip()
589 par = args.strip()
590 if opts.has_key('r'):
590 if opts.has_key('r'):
591 self._rerun_pasted()
591 self._rerun_pasted()
592 return
592 return
593
593
594 sentinel = opts.get('s','--')
594 sentinel = opts.get('s','--')
595
595
596 block = self._strip_pasted_lines_for_code(
596 block = self._strip_pasted_lines_for_code(
597 self._get_pasted_lines(sentinel))
597 self._get_pasted_lines(sentinel))
598
598
599 self._execute_block(block, par)
599 self._execute_block(block, par)
600
600
601 def magic_paste(self, parameter_s=''):
601 def magic_paste(self, parameter_s=''):
602 """Paste & execute a pre-formatted code block from clipboard.
602 """Paste & execute a pre-formatted code block from clipboard.
603
603
604 The text is pulled directly from the clipboard without user
604 The text is pulled directly from the clipboard without user
605 intervention and printed back on the screen before execution (unless
605 intervention and printed back on the screen before execution (unless
606 the -q flag is given to force quiet mode).
606 the -q flag is given to force quiet mode).
607
607
608 The block is dedented prior to execution to enable execution of method
608 The block is dedented prior to execution to enable execution of method
609 definitions. '>' and '+' characters at the beginning of a line are
609 definitions. '>' and '+' characters at the beginning of a line are
610 ignored, to allow pasting directly from e-mails, diff files and
610 ignored, to allow pasting directly from e-mails, diff files and
611 doctests (the '...' continuation prompt is also stripped). The
611 doctests (the '...' continuation prompt is also stripped). The
612 executed block is also assigned to variable named 'pasted_block' for
612 executed block is also assigned to variable named 'pasted_block' for
613 later editing with '%edit pasted_block'.
613 later editing with '%edit pasted_block'.
614
614
615 You can also pass a variable name as an argument, e.g. '%paste foo'.
615 You can also pass a variable name as an argument, e.g. '%paste foo'.
616 This assigns the pasted block to variable 'foo' as string, without
616 This assigns the pasted block to variable 'foo' as string, without
617 dedenting or executing it (preceding >>> and + is still stripped)
617 dedenting or executing it (preceding >>> and + is still stripped)
618
618
619 Options
619 Options
620 -------
620 -------
621
621
622 -r: re-executes the block previously entered by cpaste.
622 -r: re-executes the block previously entered by cpaste.
623
623
624 -q: quiet mode: do not echo the pasted text back to the terminal.
624 -q: quiet mode: do not echo the pasted text back to the terminal.
625
625
626 IPython statements (magics, shell escapes) are not supported (yet).
626 IPython statements (magics, shell escapes) are not supported (yet).
627
627
628 See also
628 See also
629 --------
629 --------
630 cpaste: manually paste code into terminal until you mark its end.
630 cpaste: manually paste code into terminal until you mark its end.
631 """
631 """
632 opts,args = self.parse_options(parameter_s,'rq',mode='string')
632 opts,args = self.parse_options(parameter_s,'rq',mode='string')
633 par = args.strip()
633 par = args.strip()
634 if opts.has_key('r'):
634 if opts.has_key('r'):
635 self._rerun_pasted()
635 self._rerun_pasted()
636 return
636 return
637
637
638 text = self.shell.hooks.clipboard_get()
638 text = self.shell.hooks.clipboard_get()
639 block = self._strip_pasted_lines_for_code(text.splitlines())
639 block = self._strip_pasted_lines_for_code(text.splitlines())
640
640
641 # By default, echo back to terminal unless quiet mode is requested
641 # By default, echo back to terminal unless quiet mode is requested
642 if not opts.has_key('q'):
642 if not opts.has_key('q'):
643 write = self.shell.write
643 write = self.shell.write
644 write(self.shell.pycolorize(block))
644 write(self.shell.pycolorize(block))
645 if not block.endswith('\n'):
645 if not block.endswith('\n'):
646 write('\n')
646 write('\n')
647 write("## -- End pasted text --\n")
647 write("## -- End pasted text --\n")
648
648
649 self._execute_block(block, par)
649 self._execute_block(block, par)
650
650
651
651
652 InteractiveShellABC.register(TerminalInteractiveShell)
652 InteractiveShellABC.register(TerminalInteractiveShell)
@@ -1,535 +1,545 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22
22
23 # Our own
23 # Our own
24 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
25 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
26 )
26 )
27 from IPython.core import page
27 from IPython.core import page
28 from IPython.core.displayhook import DisplayHook
28 from IPython.core.displayhook import DisplayHook
29 from IPython.core.macro import Macro
29 from IPython.core.macro import Macro
30 from IPython.core.payloadpage import install_payload_page
30 from IPython.core.payloadpage import install_payload_page
31 from IPython.utils import io
31 from IPython.utils import io
32 from IPython.utils.path import get_py_filename
32 from IPython.utils.path import get_py_filename
33 from IPython.utils.text import StringTypes
33 from IPython.utils.text import StringTypes
34 from IPython.utils.traitlets import Instance, Type, Dict
34 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.warn import warn
35 from IPython.utils.warn import warn
36 from IPython.zmq.session import extract_header
36 from IPython.zmq.session import extract_header
37 from session import Session
37 from session import Session
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Globals and side-effects
40 # Globals and side-effects
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43 # Install the payload version of page.
43 # Install the payload version of page.
44 install_payload_page()
44 install_payload_page()
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Functions and classes
47 # Functions and classes
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50 class ZMQDisplayHook(DisplayHook):
50 class ZMQDisplayHook(DisplayHook):
51
51
52 session = Instance(Session)
52 session = Instance(Session)
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 parent_header = Dict({})
54 parent_header = Dict({})
55
55
56 def set_parent(self, parent):
56 def set_parent(self, parent):
57 """Set the parent for outbound messages."""
57 """Set the parent for outbound messages."""
58 self.parent_header = extract_header(parent)
58 self.parent_header = extract_header(parent)
59
59
60 def start_displayhook(self):
60 def start_displayhook(self):
61 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
61 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
62
62
63 def write_output_prompt(self):
63 def write_output_prompt(self):
64 """Write the output prompt."""
64 """Write the output prompt."""
65 if self.do_full_cache:
65 if self.do_full_cache:
66 self.msg['content']['execution_count'] = self.prompt_count
66 self.msg['content']['execution_count'] = self.prompt_count
67
67
68 def write_result_repr(self, result_repr):
68 def write_result_repr(self, result_repr):
69 self.msg['content']['data'] = result_repr
69 self.msg['content']['data'] = result_repr
70
70
71 def finish_displayhook(self):
71 def finish_displayhook(self):
72 """Finish up all displayhook activities."""
72 """Finish up all displayhook activities."""
73 self.pub_socket.send_json(self.msg)
73 self.pub_socket.send_json(self.msg)
74 self.msg = None
74 self.msg = None
75
75
76
76
77 class ZMQInteractiveShell(InteractiveShell):
77 class ZMQInteractiveShell(InteractiveShell):
78 """A subclass of InteractiveShell for ZMQ."""
78 """A subclass of InteractiveShell for ZMQ."""
79
79
80 displayhook_class = Type(ZMQDisplayHook)
80 displayhook_class = Type(ZMQDisplayHook)
81
81
82 def init_environment(self):
82 def init_environment(self):
83 """Configure the user's environment.
83 """Configure the user's environment.
84
84
85 """
85 """
86 env = os.environ
86 env = os.environ
87 # These two ensure 'ls' produces nice coloring on BSD-derived systems
87 # These two ensure 'ls' produces nice coloring on BSD-derived systems
88 env['TERM'] = 'xterm-color'
88 env['TERM'] = 'xterm-color'
89 env['CLICOLOR'] = '1'
89 env['CLICOLOR'] = '1'
90 # Since normal pagers don't work at all (over pexpect we don't have
90 # Since normal pagers don't work at all (over pexpect we don't have
91 # single-key control of the subprocess), try to disable paging in
91 # single-key control of the subprocess), try to disable paging in
92 # subprocesses as much as possible.
92 # subprocesses as much as possible.
93 env['PAGER'] = 'cat'
93 env['PAGER'] = 'cat'
94 env['GIT_PAGER'] = 'cat'
94 env['GIT_PAGER'] = 'cat'
95
95
96 def auto_rewrite_input(self, cmd):
96 def auto_rewrite_input(self, cmd):
97 """Called to show the auto-rewritten input for autocall and friends.
97 """Called to show the auto-rewritten input for autocall and friends.
98
98
99 FIXME: this payload is currently not correctly processed by the
99 FIXME: this payload is currently not correctly processed by the
100 frontend.
100 frontend.
101 """
101 """
102 new = self.displayhook.prompt1.auto_rewrite() + cmd
102 new = self.displayhook.prompt1.auto_rewrite() + cmd
103 payload = dict(
103 payload = dict(
104 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
104 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
105 transformed_input=new,
105 transformed_input=new,
106 )
106 )
107 self.payload_manager.write_payload(payload)
107 self.payload_manager.write_payload(payload)
108
108
109 def ask_exit(self):
109 def ask_exit(self):
110 """Engage the exit actions."""
110 """Engage the exit actions."""
111 payload = dict(
111 payload = dict(
112 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
112 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
113 exit=True,
113 exit=True,
114 )
114 )
115 self.payload_manager.write_payload(payload)
115 self.payload_manager.write_payload(payload)
116
116
117 def _showtraceback(self, etype, evalue, stb):
117 def _showtraceback(self, etype, evalue, stb):
118
118
119 exc_content = {
119 exc_content = {
120 u'traceback' : stb,
120 u'traceback' : stb,
121 u'ename' : unicode(etype.__name__),
121 u'ename' : unicode(etype.__name__),
122 u'evalue' : unicode(evalue)
122 u'evalue' : unicode(evalue)
123 }
123 }
124
124
125 dh = self.displayhook
125 dh = self.displayhook
126 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
126 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
127 # Send exception info over pub socket for other clients than the caller
127 # Send exception info over pub socket for other clients than the caller
128 # to pick up
128 # to pick up
129 dh.pub_socket.send_json(exc_msg)
129 dh.pub_socket.send_json(exc_msg)
130
130
131 # FIXME - Hack: store exception info in shell object. Right now, the
131 # FIXME - Hack: store exception info in shell object. Right now, the
132 # caller is reading this info after the fact, we need to fix this logic
132 # caller is reading this info after the fact, we need to fix this logic
133 # to remove this hack. Even uglier, we need to store the error status
133 # to remove this hack. Even uglier, we need to store the error status
134 # here, because in the main loop, the logic that sets it is being
134 # here, because in the main loop, the logic that sets it is being
135 # skipped because runlines swallows the exceptions.
135 # skipped because runlines swallows the exceptions.
136 exc_content[u'status'] = u'error'
136 exc_content[u'status'] = u'error'
137 self._reply_content = exc_content
137 self._reply_content = exc_content
138 # /FIXME
138 # /FIXME
139
139
140 return exc_content
140 return exc_content
141
141
142 #------------------------------------------------------------------------
142 #------------------------------------------------------------------------
143 # Magic overrides
143 # Magic overrides
144 #------------------------------------------------------------------------
144 #------------------------------------------------------------------------
145 # Once the base class stops inheriting from magic, this code needs to be
145 # Once the base class stops inheriting from magic, this code needs to be
146 # moved into a separate machinery as well. For now, at least isolate here
146 # moved into a separate machinery as well. For now, at least isolate here
147 # the magics which this class needs to implement differently from the base
147 # the magics which this class needs to implement differently from the base
148 # class, or that are unique to it.
148 # class, or that are unique to it.
149
149
150 def magic_doctest_mode(self,parameter_s=''):
150 def magic_doctest_mode(self,parameter_s=''):
151 """Toggle doctest mode on and off.
151 """Toggle doctest mode on and off.
152
152
153 This mode is intended to make IPython behave as much as possible like a
153 This mode is intended to make IPython behave as much as possible like a
154 plain Python shell, from the perspective of how its prompts, exceptions
154 plain Python shell, from the perspective of how its prompts, exceptions
155 and output look. This makes it easy to copy and paste parts of a
155 and output look. This makes it easy to copy and paste parts of a
156 session into doctests. It does so by:
156 session into doctests. It does so by:
157
157
158 - Changing the prompts to the classic ``>>>`` ones.
158 - Changing the prompts to the classic ``>>>`` ones.
159 - Changing the exception reporting mode to 'Plain'.
159 - Changing the exception reporting mode to 'Plain'.
160 - Disabling pretty-printing of output.
160 - Disabling pretty-printing of output.
161
161
162 Note that IPython also supports the pasting of code snippets that have
162 Note that IPython also supports the pasting of code snippets that have
163 leading '>>>' and '...' prompts in them. This means that you can paste
163 leading '>>>' and '...' prompts in them. This means that you can paste
164 doctests from files or docstrings (even if they have leading
164 doctests from files or docstrings (even if they have leading
165 whitespace), and the code will execute correctly. You can then use
165 whitespace), and the code will execute correctly. You can then use
166 '%history -t' to see the translated history; this will give you the
166 '%history -t' to see the translated history; this will give you the
167 input after removal of all the leading prompts and whitespace, which
167 input after removal of all the leading prompts and whitespace, which
168 can be pasted back into an editor.
168 can be pasted back into an editor.
169
169
170 With these features, you can switch into this mode easily whenever you
170 With these features, you can switch into this mode easily whenever you
171 need to do testing and changes to doctests, without having to leave
171 need to do testing and changes to doctests, without having to leave
172 your existing IPython session.
172 your existing IPython session.
173 """
173 """
174
174
175 from IPython.utils.ipstruct import Struct
175 from IPython.utils.ipstruct import Struct
176
176
177 # Shorthands
177 # Shorthands
178 shell = self.shell
178 shell = self.shell
179 # dstore is a data store kept in the instance metadata bag to track any
179 # dstore is a data store kept in the instance metadata bag to track any
180 # changes we make, so we can undo them later.
180 # changes we make, so we can undo them later.
181 dstore = shell.meta.setdefault('doctest_mode', Struct())
181 dstore = shell.meta.setdefault('doctest_mode', Struct())
182 save_dstore = dstore.setdefault
182 save_dstore = dstore.setdefault
183
183
184 # save a few values we'll need to recover later
184 # save a few values we'll need to recover later
185 mode = save_dstore('mode', False)
185 mode = save_dstore('mode', False)
186 save_dstore('rc_pprint', shell.pprint)
186 save_dstore('rc_pprint', shell.pprint)
187 save_dstore('xmode', shell.InteractiveTB.mode)
187 save_dstore('xmode', shell.InteractiveTB.mode)
188
188
189 if mode == False:
189 if mode == False:
190 # turn on
190 # turn on
191 shell.pprint = False
191 shell.pprint = False
192 shell.magic_xmode('Plain')
192 shell.magic_xmode('Plain')
193 else:
193 else:
194 # turn off
194 # turn off
195 shell.pprint = dstore.rc_pprint
195 shell.pprint = dstore.rc_pprint
196 shell.magic_xmode(dstore.xmode)
196 shell.magic_xmode(dstore.xmode)
197
197
198 # Store new mode and inform on console
198 # Store new mode and inform on console
199 dstore.mode = bool(1-int(mode))
199 dstore.mode = bool(1-int(mode))
200 mode_label = ['OFF','ON'][dstore.mode]
200 mode_label = ['OFF','ON'][dstore.mode]
201 print('Doctest mode is:', mode_label)
201 print('Doctest mode is:', mode_label)
202
202
203 # Send the payload back so that clients can modify their prompt display
203 # Send the payload back so that clients can modify their prompt display
204 payload = dict(
204 payload = dict(
205 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
205 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
206 mode=dstore.mode)
206 mode=dstore.mode)
207 self.payload_manager.write_payload(payload)
207 self.payload_manager.write_payload(payload)
208
208
209 def magic_edit(self,parameter_s='',last_call=['','']):
209 def magic_edit(self,parameter_s='',last_call=['','']):
210 """Bring up an editor and execute the resulting code.
210 """Bring up an editor and execute the resulting code.
211
211
212 Usage:
212 Usage:
213 %edit [options] [args]
213 %edit [options] [args]
214
214
215 %edit runs IPython's editor hook. The default version of this hook is
215 %edit runs IPython's editor hook. The default version of this hook is
216 set to call the __IPYTHON__.rc.editor command. This is read from your
216 set to call the __IPYTHON__.rc.editor command. This is read from your
217 environment variable $EDITOR. If this isn't found, it will default to
217 environment variable $EDITOR. If this isn't found, it will default to
218 vi under Linux/Unix and to notepad under Windows. See the end of this
218 vi under Linux/Unix and to notepad under Windows. See the end of this
219 docstring for how to change the editor hook.
219 docstring for how to change the editor hook.
220
220
221 You can also set the value of this editor via the command line option
221 You can also set the value of this editor via the command line option
222 '-editor' or in your ipythonrc file. This is useful if you wish to use
222 '-editor' or in your ipythonrc file. This is useful if you wish to use
223 specifically for IPython an editor different from your typical default
223 specifically for IPython an editor different from your typical default
224 (and for Windows users who typically don't set environment variables).
224 (and for Windows users who typically don't set environment variables).
225
225
226 This command allows you to conveniently edit multi-line code right in
226 This command allows you to conveniently edit multi-line code right in
227 your IPython session.
227 your IPython session.
228
228
229 If called without arguments, %edit opens up an empty editor with a
229 If called without arguments, %edit opens up an empty editor with a
230 temporary file and will execute the contents of this file when you
230 temporary file and will execute the contents of this file when you
231 close it (don't forget to save it!).
231 close it (don't forget to save it!).
232
232
233
233
234 Options:
234 Options:
235
235
236 -n <number>: open the editor at a specified line number. By default,
236 -n <number>: open the editor at a specified line number. By default,
237 the IPython editor hook uses the unix syntax 'editor +N filename', but
237 the IPython editor hook uses the unix syntax 'editor +N filename', but
238 you can configure this by providing your own modified hook if your
238 you can configure this by providing your own modified hook if your
239 favorite editor supports line-number specifications with a different
239 favorite editor supports line-number specifications with a different
240 syntax.
240 syntax.
241
241
242 -p: this will call the editor with the same data as the previous time
242 -p: this will call the editor with the same data as the previous time
243 it was used, regardless of how long ago (in your current session) it
243 it was used, regardless of how long ago (in your current session) it
244 was.
244 was.
245
245
246 -r: use 'raw' input. This option only applies to input taken from the
246 -r: use 'raw' input. This option only applies to input taken from the
247 user's history. By default, the 'processed' history is used, so that
247 user's history. By default, the 'processed' history is used, so that
248 magics are loaded in their transformed version to valid Python. If
248 magics are loaded in their transformed version to valid Python. If
249 this option is given, the raw input as typed as the command line is
249 this option is given, the raw input as typed as the command line is
250 used instead. When you exit the editor, it will be executed by
250 used instead. When you exit the editor, it will be executed by
251 IPython's own processor.
251 IPython's own processor.
252
252
253 -x: do not execute the edited code immediately upon exit. This is
253 -x: do not execute the edited code immediately upon exit. This is
254 mainly useful if you are editing programs which need to be called with
254 mainly useful if you are editing programs which need to be called with
255 command line arguments, which you can then do using %run.
255 command line arguments, which you can then do using %run.
256
256
257
257
258 Arguments:
258 Arguments:
259
259
260 If arguments are given, the following possibilites exist:
260 If arguments are given, the following possibilites exist:
261
261
262 - The arguments are numbers or pairs of colon-separated numbers (like
262 - The arguments are numbers or pairs of colon-separated numbers (like
263 1 4:8 9). These are interpreted as lines of previous input to be
263 1 4:8 9). These are interpreted as lines of previous input to be
264 loaded into the editor. The syntax is the same of the %macro command.
264 loaded into the editor. The syntax is the same of the %macro command.
265
265
266 - If the argument doesn't start with a number, it is evaluated as a
266 - If the argument doesn't start with a number, it is evaluated as a
267 variable and its contents loaded into the editor. You can thus edit
267 variable and its contents loaded into the editor. You can thus edit
268 any string which contains python code (including the result of
268 any string which contains python code (including the result of
269 previous edits).
269 previous edits).
270
270
271 - If the argument is the name of an object (other than a string),
271 - If the argument is the name of an object (other than a string),
272 IPython will try to locate the file where it was defined and open the
272 IPython will try to locate the file where it was defined and open the
273 editor at the point where it is defined. You can use `%edit function`
273 editor at the point where it is defined. You can use `%edit function`
274 to load an editor exactly at the point where 'function' is defined,
274 to load an editor exactly at the point where 'function' is defined,
275 edit it and have the file be executed automatically.
275 edit it and have the file be executed automatically.
276
276
277 If the object is a macro (see %macro for details), this opens up your
277 If the object is a macro (see %macro for details), this opens up your
278 specified editor with a temporary file containing the macro's data.
278 specified editor with a temporary file containing the macro's data.
279 Upon exit, the macro is reloaded with the contents of the file.
279 Upon exit, the macro is reloaded with the contents of the file.
280
280
281 Note: opening at an exact line is only supported under Unix, and some
281 Note: opening at an exact line is only supported under Unix, and some
282 editors (like kedit and gedit up to Gnome 2.8) do not understand the
282 editors (like kedit and gedit up to Gnome 2.8) do not understand the
283 '+NUMBER' parameter necessary for this feature. Good editors like
283 '+NUMBER' parameter necessary for this feature. Good editors like
284 (X)Emacs, vi, jed, pico and joe all do.
284 (X)Emacs, vi, jed, pico and joe all do.
285
285
286 - If the argument is not found as a variable, IPython will look for a
286 - If the argument is not found as a variable, IPython will look for a
287 file with that name (adding .py if necessary) and load it into the
287 file with that name (adding .py if necessary) and load it into the
288 editor. It will execute its contents with execfile() when you exit,
288 editor. It will execute its contents with execfile() when you exit,
289 loading any code in the file into your interactive namespace.
289 loading any code in the file into your interactive namespace.
290
290
291 After executing your code, %edit will return as output the code you
291 After executing your code, %edit will return as output the code you
292 typed in the editor (except when it was an existing file). This way
292 typed in the editor (except when it was an existing file). This way
293 you can reload the code in further invocations of %edit as a variable,
293 you can reload the code in further invocations of %edit as a variable,
294 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
294 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
295 the output.
295 the output.
296
296
297 Note that %edit is also available through the alias %ed.
297 Note that %edit is also available through the alias %ed.
298
298
299 This is an example of creating a simple function inside the editor and
299 This is an example of creating a simple function inside the editor and
300 then modifying it. First, start up the editor:
300 then modifying it. First, start up the editor:
301
301
302 In [1]: ed
302 In [1]: ed
303 Editing... done. Executing edited code...
303 Editing... done. Executing edited code...
304 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
304 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
305
305
306 We can then call the function foo():
306 We can then call the function foo():
307
307
308 In [2]: foo()
308 In [2]: foo()
309 foo() was defined in an editing session
309 foo() was defined in an editing session
310
310
311 Now we edit foo. IPython automatically loads the editor with the
311 Now we edit foo. IPython automatically loads the editor with the
312 (temporary) file where foo() was previously defined:
312 (temporary) file where foo() was previously defined:
313
313
314 In [3]: ed foo
314 In [3]: ed foo
315 Editing... done. Executing edited code...
315 Editing... done. Executing edited code...
316
316
317 And if we call foo() again we get the modified version:
317 And if we call foo() again we get the modified version:
318
318
319 In [4]: foo()
319 In [4]: foo()
320 foo() has now been changed!
320 foo() has now been changed!
321
321
322 Here is an example of how to edit a code snippet successive
322 Here is an example of how to edit a code snippet successive
323 times. First we call the editor:
323 times. First we call the editor:
324
324
325 In [5]: ed
325 In [5]: ed
326 Editing... done. Executing edited code...
326 Editing... done. Executing edited code...
327 hello
327 hello
328 Out[5]: "print 'hello'n"
328 Out[5]: "print 'hello'n"
329
329
330 Now we call it again with the previous output (stored in _):
330 Now we call it again with the previous output (stored in _):
331
331
332 In [6]: ed _
332 In [6]: ed _
333 Editing... done. Executing edited code...
333 Editing... done. Executing edited code...
334 hello world
334 hello world
335 Out[6]: "print 'hello world'n"
335 Out[6]: "print 'hello world'n"
336
336
337 Now we call it with the output #8 (stored in _8, also as Out[8]):
337 Now we call it with the output #8 (stored in _8, also as Out[8]):
338
338
339 In [7]: ed _8
339 In [7]: ed _8
340 Editing... done. Executing edited code...
340 Editing... done. Executing edited code...
341 hello again
341 hello again
342 Out[7]: "print 'hello again'n"
342 Out[7]: "print 'hello again'n"
343
343
344
344
345 Changing the default editor hook:
345 Changing the default editor hook:
346
346
347 If you wish to write your own editor hook, you can put it in a
347 If you wish to write your own editor hook, you can put it in a
348 configuration file which you load at startup time. The default hook
348 configuration file which you load at startup time. The default hook
349 is defined in the IPython.core.hooks module, and you can use that as a
349 is defined in the IPython.core.hooks module, and you can use that as a
350 starting example for further modifications. That file also has
350 starting example for further modifications. That file also has
351 general instructions on how to set a new hook for use once you've
351 general instructions on how to set a new hook for use once you've
352 defined it."""
352 defined it."""
353
353
354 # FIXME: This function has become a convoluted mess. It needs a
354 # FIXME: This function has become a convoluted mess. It needs a
355 # ground-up rewrite with clean, simple logic.
355 # ground-up rewrite with clean, simple logic.
356
356
357 def make_filename(arg):
357 def make_filename(arg):
358 "Make a filename from the given args"
358 "Make a filename from the given args"
359 try:
359 try:
360 filename = get_py_filename(arg)
360 filename = get_py_filename(arg)
361 except IOError:
361 except IOError:
362 if args.endswith('.py'):
362 if args.endswith('.py'):
363 filename = arg
363 filename = arg
364 else:
364 else:
365 filename = None
365 filename = None
366 return filename
366 return filename
367
367
368 # custom exceptions
368 # custom exceptions
369 class DataIsObject(Exception): pass
369 class DataIsObject(Exception): pass
370
370
371 opts,args = self.parse_options(parameter_s,'prn:')
371 opts,args = self.parse_options(parameter_s,'prn:')
372 # Set a few locals from the options for convenience:
372 # Set a few locals from the options for convenience:
373 opts_p = opts.has_key('p')
373 opts_p = opts.has_key('p')
374 opts_r = opts.has_key('r')
374 opts_r = opts.has_key('r')
375
375
376 # Default line number value
376 # Default line number value
377 lineno = opts.get('n',None)
377 lineno = opts.get('n',None)
378 if lineno is not None:
378 if lineno is not None:
379 try:
379 try:
380 lineno = int(lineno)
380 lineno = int(lineno)
381 except:
381 except:
382 warn("The -n argument must be an integer.")
382 warn("The -n argument must be an integer.")
383 return
383 return
384
384
385 if opts_p:
385 if opts_p:
386 args = '_%s' % last_call[0]
386 args = '_%s' % last_call[0]
387 if not self.shell.user_ns.has_key(args):
387 if not self.shell.user_ns.has_key(args):
388 args = last_call[1]
388 args = last_call[1]
389
389
390 # use last_call to remember the state of the previous call, but don't
390 # use last_call to remember the state of the previous call, but don't
391 # let it be clobbered by successive '-p' calls.
391 # let it be clobbered by successive '-p' calls.
392 try:
392 try:
393 last_call[0] = self.shell.displayhook.prompt_count
393 last_call[0] = self.shell.displayhook.prompt_count
394 if not opts_p:
394 if not opts_p:
395 last_call[1] = parameter_s
395 last_call[1] = parameter_s
396 except:
396 except:
397 pass
397 pass
398
398
399 # by default this is done with temp files, except when the given
399 # by default this is done with temp files, except when the given
400 # arg is a filename
400 # arg is a filename
401 use_temp = 1
401 use_temp = 1
402
402
403 if re.match(r'\d',args):
403 if re.match(r'\d',args):
404 # Mode where user specifies ranges of lines, like in %macro.
404 # Mode where user specifies ranges of lines, like in %macro.
405 # This means that you can't edit files whose names begin with
405 # This means that you can't edit files whose names begin with
406 # numbers this way. Tough.
406 # numbers this way. Tough.
407 ranges = args.split()
407 ranges = args.split()
408 data = ''.join(self.extract_input_slices(ranges,opts_r))
408 data = ''.join(self.extract_input_slices(ranges,opts_r))
409 elif args.endswith('.py'):
409 elif args.endswith('.py'):
410 filename = make_filename(args)
410 filename = make_filename(args)
411 data = ''
411 data = ''
412 use_temp = 0
412 use_temp = 0
413 elif args:
413 elif args:
414 try:
414 try:
415 # Load the parameter given as a variable. If not a string,
415 # Load the parameter given as a variable. If not a string,
416 # process it as an object instead (below)
416 # process it as an object instead (below)
417
417
418 #print '*** args',args,'type',type(args) # dbg
418 #print '*** args',args,'type',type(args) # dbg
419 data = eval(args,self.shell.user_ns)
419 data = eval(args,self.shell.user_ns)
420 if not type(data) in StringTypes:
420 if not type(data) in StringTypes:
421 raise DataIsObject
421 raise DataIsObject
422
422
423 except (NameError,SyntaxError):
423 except (NameError,SyntaxError):
424 # given argument is not a variable, try as a filename
424 # given argument is not a variable, try as a filename
425 filename = make_filename(args)
425 filename = make_filename(args)
426 if filename is None:
426 if filename is None:
427 warn("Argument given (%s) can't be found as a variable "
427 warn("Argument given (%s) can't be found as a variable "
428 "or as a filename." % args)
428 "or as a filename." % args)
429 return
429 return
430
430
431 data = ''
431 data = ''
432 use_temp = 0
432 use_temp = 0
433 except DataIsObject:
433 except DataIsObject:
434
434
435 # macros have a special edit function
435 # macros have a special edit function
436 if isinstance(data,Macro):
436 if isinstance(data,Macro):
437 self._edit_macro(args,data)
437 self._edit_macro(args,data)
438 return
438 return
439
439
440 # For objects, try to edit the file where they are defined
440 # For objects, try to edit the file where they are defined
441 try:
441 try:
442 filename = inspect.getabsfile(data)
442 filename = inspect.getabsfile(data)
443 if 'fakemodule' in filename.lower() and inspect.isclass(data):
443 if 'fakemodule' in filename.lower() and inspect.isclass(data):
444 # class created by %edit? Try to find source
444 # class created by %edit? Try to find source
445 # by looking for method definitions instead, the
445 # by looking for method definitions instead, the
446 # __module__ in those classes is FakeModule.
446 # __module__ in those classes is FakeModule.
447 attrs = [getattr(data, aname) for aname in dir(data)]
447 attrs = [getattr(data, aname) for aname in dir(data)]
448 for attr in attrs:
448 for attr in attrs:
449 if not inspect.ismethod(attr):
449 if not inspect.ismethod(attr):
450 continue
450 continue
451 filename = inspect.getabsfile(attr)
451 filename = inspect.getabsfile(attr)
452 if filename and 'fakemodule' not in filename.lower():
452 if filename and 'fakemodule' not in filename.lower():
453 # change the attribute to be the edit target instead
453 # change the attribute to be the edit target instead
454 data = attr
454 data = attr
455 break
455 break
456
456
457 datafile = 1
457 datafile = 1
458 except TypeError:
458 except TypeError:
459 filename = make_filename(args)
459 filename = make_filename(args)
460 datafile = 1
460 datafile = 1
461 warn('Could not find file where `%s` is defined.\n'
461 warn('Could not find file where `%s` is defined.\n'
462 'Opening a file named `%s`' % (args,filename))
462 'Opening a file named `%s`' % (args,filename))
463 # Now, make sure we can actually read the source (if it was in
463 # Now, make sure we can actually read the source (if it was in
464 # a temp file it's gone by now).
464 # a temp file it's gone by now).
465 if datafile:
465 if datafile:
466 try:
466 try:
467 if lineno is None:
467 if lineno is None:
468 lineno = inspect.getsourcelines(data)[1]
468 lineno = inspect.getsourcelines(data)[1]
469 except IOError:
469 except IOError:
470 filename = make_filename(args)
470 filename = make_filename(args)
471 if filename is None:
471 if filename is None:
472 warn('The file `%s` where `%s` was defined cannot '
472 warn('The file `%s` where `%s` was defined cannot '
473 'be read.' % (filename,data))
473 'be read.' % (filename,data))
474 return
474 return
475 use_temp = 0
475 use_temp = 0
476 else:
476 else:
477 data = ''
477 data = ''
478
478
479 if use_temp:
479 if use_temp:
480 filename = self.shell.mktempfile(data)
480 filename = self.shell.mktempfile(data)
481 print('IPython will make a temporary file named:', filename)
481 print('IPython will make a temporary file named:', filename)
482
482
483 # Make sure we send to the client an absolute path, in case the working
483 # Make sure we send to the client an absolute path, in case the working
484 # directory of client and kernel don't match
484 # directory of client and kernel don't match
485 filename = os.path.abspath(filename)
485 filename = os.path.abspath(filename)
486
486
487 payload = {
487 payload = {
488 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
488 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
489 'filename' : filename,
489 'filename' : filename,
490 'line_number' : lineno
490 'line_number' : lineno
491 }
491 }
492 self.payload_manager.write_payload(payload)
492 self.payload_manager.write_payload(payload)
493
493
494 def magic_gui(self, *args, **kwargs):
494 def magic_gui(self, *args, **kwargs):
495 raise NotImplementedError(
495 raise NotImplementedError(
496 'GUI support must be enabled in command line options.')
496 'GUI support must be enabled in command line options.')
497
497
498 def magic_pylab(self, *args, **kwargs):
498 def magic_pylab(self, *args, **kwargs):
499 raise NotImplementedError(
499 raise NotImplementedError(
500 'pylab support must be enabled in command line options.')
500 'pylab support must be enabled in command line options.')
501
501
502 # A few magics that are adapted to the specifics of using pexpect and a
502 # A few magics that are adapted to the specifics of using pexpect and a
503 # remote terminal
503 # remote terminal
504
504
505 def magic_clear(self, arg_s):
505 def magic_clear(self, arg_s):
506 """Clear the terminal."""
506 """Clear the terminal."""
507 if os.name == 'posix':
507 if os.name == 'posix':
508 self.shell.system("clear")
508 self.shell.system("clear")
509 else:
509 else:
510 self.shell.system("cls")
510 self.shell.system("cls")
511
511
512 if os.name == 'nt':
512 if os.name == 'nt':
513 # This is the usual name in windows
513 # This is the usual name in windows
514 magic_cls = magic_clear
514 magic_cls = magic_clear
515
515
516 # Terminal pagers won't work over pexpect, but we do have our own pager
516 # Terminal pagers won't work over pexpect, but we do have our own pager
517
517
518 def magic_less(self, arg_s):
518 def magic_less(self, arg_s):
519 """Show a file through the pager.
519 """Show a file through the pager.
520
520
521 Files ending in .py are syntax-highlighted."""
521 Files ending in .py are syntax-highlighted."""
522 cont = open(arg_s).read()
522 cont = open(arg_s).read()
523 if arg_s.endswith('.py'):
523 if arg_s.endswith('.py'):
524 cont = self.shell.pycolorize(cont)
524 cont = self.shell.pycolorize(cont)
525 page.page(cont)
525 page.page(cont)
526
526
527 magic_more = magic_less
527 magic_more = magic_less
528
528
529 # Man calls a pager, so we also need to redefine it
529 # Man calls a pager, so we also need to redefine it
530 if os.name == 'posix':
530 if os.name == 'posix':
531 def magic_man(self, arg_s):
531 def magic_man(self, arg_s):
532 """Find the man page for the given command and display in pager."""
532 """Find the man page for the given command and display in pager."""
533 page.page(self.shell.getoutput('man %s' % arg_s, split=False))
533 page.page(self.shell.getoutput('man %s' % arg_s, split=False))
534
534
535 # FIXME: this is specific to the GUI, so we should let the gui app load
536 # magics at startup that are only for the gui. Once the gui app has proper
537 # profile and configuration management, we can have it initialize a kernel
538 # with a special config file that provides these.
539 def magic_guiref(self, arg_s):
540 """Show a basic reference about the GUI console."""
541 from IPython.core.usage import gui_reference
542 page.page(gui_reference)
543
544
535 InteractiveShellABC.register(ZMQInteractiveShell)
545 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now