##// END OF EJS Templates
in %edit, don't save "last_call" unless last call succeeded...
MinRK -
Show More
@@ -1,558 +1,559 b''
1 """Implementation of code management magic functions.
1 """Implementation of code management magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import inspect
16 import inspect
17 import io
17 import io
18 import json
18 import json
19 import os
19 import os
20 import re
20 import re
21 import sys
21 import sys
22 from urllib2 import urlopen
22 from urllib2 import urlopen
23
23
24 # Our own packages
24 # Our own packages
25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
25 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
26 from IPython.core.macro import Macro
26 from IPython.core.macro import Macro
27 from IPython.core.magic import Magics, magics_class, line_magic
27 from IPython.core.magic import Magics, magics_class, line_magic
28 from IPython.core.oinspect import find_file, find_source_lines
28 from IPython.core.oinspect import find_file, find_source_lines
29 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.testing.skipdoctest import skip_doctest
30 from IPython.utils import openpy
30 from IPython.utils import openpy
31 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 from IPython.utils.contexts import preserve_keys
32 from IPython.utils.contexts import preserve_keys
33 from IPython.utils.io import file_read
33 from IPython.utils.io import file_read
34 from IPython.utils.path import get_py_filename, unquote_filename
34 from IPython.utils.path import get_py_filename, unquote_filename
35 from IPython.utils.warn import warn
35 from IPython.utils.warn import warn
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Magic implementation classes
38 # Magic implementation classes
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 # Used for exception handling in magic_edit
41 # Used for exception handling in magic_edit
42 class MacroToEdit(ValueError): pass
42 class MacroToEdit(ValueError): pass
43
43
44 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
44 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
45
45
46 class InteractivelyDefined(Exception):
46 class InteractivelyDefined(Exception):
47 """Exception for interactively defined variable in magic_edit"""
47 """Exception for interactively defined variable in magic_edit"""
48 def __init__(self, index):
48 def __init__(self, index):
49 self.index = index
49 self.index = index
50
50
51
51
52 @magics_class
52 @magics_class
53 class CodeMagics(Magics):
53 class CodeMagics(Magics):
54 """Magics related to code management (loading, saving, editing, ...)."""
54 """Magics related to code management (loading, saving, editing, ...)."""
55
55
56 @line_magic
56 @line_magic
57 def save(self, parameter_s=''):
57 def save(self, parameter_s=''):
58 """Save a set of lines or a macro to a given filename.
58 """Save a set of lines or a macro to a given filename.
59
59
60 Usage:\\
60 Usage:\\
61 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
61 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
62
62
63 Options:
63 Options:
64
64
65 -r: use 'raw' input. By default, the 'processed' history is used,
65 -r: use 'raw' input. By default, the 'processed' history is used,
66 so that magics are loaded in their transformed version to valid
66 so that magics are loaded in their transformed version to valid
67 Python. If this option is given, the raw input as typed as the
67 Python. If this option is given, the raw input as typed as the
68 command line is used instead.
68 command line is used instead.
69
69
70 -f: force overwrite. If file exists, %save will prompt for overwrite
70 -f: force overwrite. If file exists, %save will prompt for overwrite
71 unless -f is given.
71 unless -f is given.
72
72
73 -a: append to the file instead of overwriting it.
73 -a: append to the file instead of overwriting it.
74
74
75 This function uses the same syntax as %history for input ranges,
75 This function uses the same syntax as %history for input ranges,
76 then saves the lines to the filename you specify.
76 then saves the lines to the filename you specify.
77
77
78 It adds a '.py' extension to the file if you don't do so yourself, and
78 It adds a '.py' extension to the file if you don't do so yourself, and
79 it asks for confirmation before overwriting existing files.
79 it asks for confirmation before overwriting existing files.
80
80
81 If `-r` option is used, the default extension is `.ipy`.
81 If `-r` option is used, the default extension is `.ipy`.
82 """
82 """
83
83
84 opts,args = self.parse_options(parameter_s,'fra',mode='list')
84 opts,args = self.parse_options(parameter_s,'fra',mode='list')
85 if not args:
85 if not args:
86 raise UsageError('Missing filename.')
86 raise UsageError('Missing filename.')
87 raw = 'r' in opts
87 raw = 'r' in opts
88 force = 'f' in opts
88 force = 'f' in opts
89 append = 'a' in opts
89 append = 'a' in opts
90 mode = 'a' if append else 'w'
90 mode = 'a' if append else 'w'
91 ext = u'.ipy' if raw else u'.py'
91 ext = u'.ipy' if raw else u'.py'
92 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
92 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
93 if not fname.endswith((u'.py',u'.ipy')):
93 if not fname.endswith((u'.py',u'.ipy')):
94 fname += ext
94 fname += ext
95 file_exists = os.path.isfile(fname)
95 file_exists = os.path.isfile(fname)
96 if file_exists and not force and not append:
96 if file_exists and not force and not append:
97 try:
97 try:
98 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
98 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
99 except StdinNotImplementedError:
99 except StdinNotImplementedError:
100 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
100 print "File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s)
101 return
101 return
102 if not overwrite :
102 if not overwrite :
103 print 'Operation cancelled.'
103 print 'Operation cancelled.'
104 return
104 return
105 try:
105 try:
106 cmds = self.shell.find_user_code(codefrom,raw)
106 cmds = self.shell.find_user_code(codefrom,raw)
107 except (TypeError, ValueError) as e:
107 except (TypeError, ValueError) as e:
108 print e.args[0]
108 print e.args[0]
109 return
109 return
110 out = py3compat.cast_unicode(cmds)
110 out = py3compat.cast_unicode(cmds)
111 with io.open(fname, mode, encoding="utf-8") as f:
111 with io.open(fname, mode, encoding="utf-8") as f:
112 if not file_exists or not append:
112 if not file_exists or not append:
113 f.write(u"# coding: utf-8\n")
113 f.write(u"# coding: utf-8\n")
114 f.write(out)
114 f.write(out)
115 # make sure we end on a newline
115 # make sure we end on a newline
116 if not out.endswith(u'\n'):
116 if not out.endswith(u'\n'):
117 f.write(u'\n')
117 f.write(u'\n')
118 print 'The following commands were written to file `%s`:' % fname
118 print 'The following commands were written to file `%s`:' % fname
119 print cmds
119 print cmds
120
120
121 @line_magic
121 @line_magic
122 def pastebin(self, parameter_s=''):
122 def pastebin(self, parameter_s=''):
123 """Upload code to Github's Gist paste bin, returning the URL.
123 """Upload code to Github's Gist paste bin, returning the URL.
124
124
125 Usage:\\
125 Usage:\\
126 %pastebin [-d "Custom description"] 1-7
126 %pastebin [-d "Custom description"] 1-7
127
127
128 The argument can be an input history range, a filename, or the name of a
128 The argument can be an input history range, a filename, or the name of a
129 string or macro.
129 string or macro.
130
130
131 Options:
131 Options:
132
132
133 -d: Pass a custom description for the gist. The default will say
133 -d: Pass a custom description for the gist. The default will say
134 "Pasted from IPython".
134 "Pasted from IPython".
135 """
135 """
136 opts, args = self.parse_options(parameter_s, 'd:')
136 opts, args = self.parse_options(parameter_s, 'd:')
137
137
138 try:
138 try:
139 code = self.shell.find_user_code(args)
139 code = self.shell.find_user_code(args)
140 except (ValueError, TypeError) as e:
140 except (ValueError, TypeError) as e:
141 print e.args[0]
141 print e.args[0]
142 return
142 return
143
143
144 post_data = json.dumps({
144 post_data = json.dumps({
145 "description": opts.get('d', "Pasted from IPython"),
145 "description": opts.get('d', "Pasted from IPython"),
146 "public": True,
146 "public": True,
147 "files": {
147 "files": {
148 "file1.py": {
148 "file1.py": {
149 "content": code
149 "content": code
150 }
150 }
151 }
151 }
152 }).encode('utf-8')
152 }).encode('utf-8')
153
153
154 response = urlopen("https://api.github.com/gists", post_data)
154 response = urlopen("https://api.github.com/gists", post_data)
155 response_data = json.loads(response.read().decode('utf-8'))
155 response_data = json.loads(response.read().decode('utf-8'))
156 return response_data['html_url']
156 return response_data['html_url']
157
157
158 @line_magic
158 @line_magic
159 def loadpy(self, arg_s):
159 def loadpy(self, arg_s):
160 """Alias of `%load`
160 """Alias of `%load`
161
161
162 `%loadpy` has gained some flexibility and droped the requirement of a `.py`
162 `%loadpy` has gained some flexibility and droped the requirement of a `.py`
163 extension. So it has been renamed simply into %load. You can look at
163 extension. So it has been renamed simply into %load. You can look at
164 `%load`'s docstring for more info.
164 `%load`'s docstring for more info.
165 """
165 """
166 self.load(arg_s)
166 self.load(arg_s)
167
167
168 @line_magic
168 @line_magic
169 def load(self, arg_s):
169 def load(self, arg_s):
170 """Load code into the current frontend.
170 """Load code into the current frontend.
171
171
172 Usage:\\
172 Usage:\\
173 %load [options] source
173 %load [options] source
174
174
175 where source can be a filename, URL, input history range or macro
175 where source can be a filename, URL, input history range or macro
176
176
177 Options:
177 Options:
178 --------
178 --------
179 -y : Don't ask confirmation for loading source above 200 000 characters.
179 -y : Don't ask confirmation for loading source above 200 000 characters.
180
180
181 This magic command can either take a local filename, a URL, an history
181 This magic command can either take a local filename, a URL, an history
182 range (see %history) or a macro as argument, it will prompt for
182 range (see %history) or a macro as argument, it will prompt for
183 confirmation before loading source with more than 200 000 characters, unless
183 confirmation before loading source with more than 200 000 characters, unless
184 -y flag is passed or if the frontend does not support raw_input::
184 -y flag is passed or if the frontend does not support raw_input::
185
185
186 %load myscript.py
186 %load myscript.py
187 %load 7-27
187 %load 7-27
188 %load myMacro
188 %load myMacro
189 %load http://www.example.com/myscript.py
189 %load http://www.example.com/myscript.py
190 """
190 """
191 opts,args = self.parse_options(arg_s,'y')
191 opts,args = self.parse_options(arg_s,'y')
192 if not args:
192 if not args:
193 raise UsageError('Missing filename, URL, input history range, '
193 raise UsageError('Missing filename, URL, input history range, '
194 'or macro.')
194 'or macro.')
195
195
196 contents = self.shell.find_user_code(args)
196 contents = self.shell.find_user_code(args)
197 l = len(contents)
197 l = len(contents)
198
198
199 # 200 000 is ~ 2500 full 80 caracter lines
199 # 200 000 is ~ 2500 full 80 caracter lines
200 # so in average, more than 5000 lines
200 # so in average, more than 5000 lines
201 if l > 200000 and 'y' not in opts:
201 if l > 200000 and 'y' not in opts:
202 try:
202 try:
203 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
203 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
204 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
204 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
205 except StdinNotImplementedError:
205 except StdinNotImplementedError:
206 #asume yes if raw input not implemented
206 #asume yes if raw input not implemented
207 ans = True
207 ans = True
208
208
209 if ans is False :
209 if ans is False :
210 print 'Operation cancelled.'
210 print 'Operation cancelled.'
211 return
211 return
212
212
213 self.shell.set_next_input(contents)
213 self.shell.set_next_input(contents)
214
214
215 @staticmethod
215 @staticmethod
216 def _find_edit_target(shell, args, opts, last_call):
216 def _find_edit_target(shell, args, opts, last_call):
217 """Utility method used by magic_edit to find what to edit."""
217 """Utility method used by magic_edit to find what to edit."""
218
218
219 def make_filename(arg):
219 def make_filename(arg):
220 "Make a filename from the given args"
220 "Make a filename from the given args"
221 arg = unquote_filename(arg)
221 arg = unquote_filename(arg)
222 try:
222 try:
223 filename = get_py_filename(arg)
223 filename = get_py_filename(arg)
224 except IOError:
224 except IOError:
225 # If it ends with .py but doesn't already exist, assume we want
225 # If it ends with .py but doesn't already exist, assume we want
226 # a new file.
226 # a new file.
227 if arg.endswith('.py'):
227 if arg.endswith('.py'):
228 filename = arg
228 filename = arg
229 else:
229 else:
230 filename = None
230 filename = None
231 return filename
231 return filename
232
232
233 # Set a few locals from the options for convenience:
233 # Set a few locals from the options for convenience:
234 opts_prev = 'p' in opts
234 opts_prev = 'p' in opts
235 opts_raw = 'r' in opts
235 opts_raw = 'r' in opts
236
236
237 # custom exceptions
237 # custom exceptions
238 class DataIsObject(Exception): pass
238 class DataIsObject(Exception): pass
239
239
240 # Default line number value
240 # Default line number value
241 lineno = opts.get('n',None)
241 lineno = opts.get('n',None)
242
242
243 if opts_prev:
243 if opts_prev:
244 args = '_%s' % last_call[0]
244 args = '_%s' % last_call[0]
245 if args not in shell.user_ns:
245 if args not in shell.user_ns:
246 args = last_call[1]
246 args = last_call[1]
247
247
248 # use last_call to remember the state of the previous call, but don't
249 # let it be clobbered by successive '-p' calls.
250 try:
251 last_call[0] = shell.displayhook.prompt_count
252 if not opts_prev:
253 last_call[1] = args
254 except:
255 pass
256
257 # by default this is done with temp files, except when the given
248 # by default this is done with temp files, except when the given
258 # arg is a filename
249 # arg is a filename
259 use_temp = True
250 use_temp = True
260
251
261 data = ''
252 data = ''
262
253
263 # First, see if the arguments should be a filename.
254 # First, see if the arguments should be a filename.
264 filename = make_filename(args)
255 filename = make_filename(args)
265 if filename:
256 if filename:
266 use_temp = False
257 use_temp = False
267 elif args:
258 elif args:
268 # Mode where user specifies ranges of lines, like in %macro.
259 # Mode where user specifies ranges of lines, like in %macro.
269 data = shell.extract_input_lines(args, opts_raw)
260 data = shell.extract_input_lines(args, opts_raw)
270 if not data:
261 if not data:
271 try:
262 try:
272 # Load the parameter given as a variable. If not a string,
263 # Load the parameter given as a variable. If not a string,
273 # process it as an object instead (below)
264 # process it as an object instead (below)
274
265
275 #print '*** args',args,'type',type(args) # dbg
266 #print '*** args',args,'type',type(args) # dbg
276 data = eval(args, shell.user_ns)
267 data = eval(args, shell.user_ns)
277 if not isinstance(data, basestring):
268 if not isinstance(data, basestring):
278 raise DataIsObject
269 raise DataIsObject
279
270
280 except (NameError,SyntaxError):
271 except (NameError,SyntaxError):
281 # given argument is not a variable, try as a filename
272 # given argument is not a variable, try as a filename
282 filename = make_filename(args)
273 filename = make_filename(args)
283 if filename is None:
274 if filename is None:
284 warn("Argument given (%s) can't be found as a variable "
275 warn("Argument given (%s) can't be found as a variable "
285 "or as a filename." % args)
276 "or as a filename." % args)
286 return (None, None, None)
277 return (None, None, None)
287 use_temp = False
278 use_temp = False
288
279
289 except DataIsObject:
280 except DataIsObject:
290 # macros have a special edit function
281 # macros have a special edit function
291 if isinstance(data, Macro):
282 if isinstance(data, Macro):
292 raise MacroToEdit(data)
283 raise MacroToEdit(data)
293
284
294 # For objects, try to edit the file where they are defined
285 # For objects, try to edit the file where they are defined
295 filename = find_file(data)
286 filename = find_file(data)
296 if filename:
287 if filename:
297 if 'fakemodule' in filename.lower() and \
288 if 'fakemodule' in filename.lower() and \
298 inspect.isclass(data):
289 inspect.isclass(data):
299 # class created by %edit? Try to find source
290 # class created by %edit? Try to find source
300 # by looking for method definitions instead, the
291 # by looking for method definitions instead, the
301 # __module__ in those classes is FakeModule.
292 # __module__ in those classes is FakeModule.
302 attrs = [getattr(data, aname) for aname in dir(data)]
293 attrs = [getattr(data, aname) for aname in dir(data)]
303 for attr in attrs:
294 for attr in attrs:
304 if not inspect.ismethod(attr):
295 if not inspect.ismethod(attr):
305 continue
296 continue
306 filename = find_file(attr)
297 filename = find_file(attr)
307 if filename and \
298 if filename and \
308 'fakemodule' not in filename.lower():
299 'fakemodule' not in filename.lower():
309 # change the attribute to be the edit
300 # change the attribute to be the edit
310 # target instead
301 # target instead
311 data = attr
302 data = attr
312 break
303 break
313
304
314 m = ipython_input_pat.match(os.path.basename(filename))
305 m = ipython_input_pat.match(os.path.basename(filename))
315 if m:
306 if m:
316 raise InteractivelyDefined(int(m.groups()[0]))
307 raise InteractivelyDefined(int(m.groups()[0]))
317
308
318 datafile = 1
309 datafile = 1
319 if filename is None:
310 if filename is None:
320 filename = make_filename(args)
311 filename = make_filename(args)
321 datafile = 1
312 datafile = 1
322 if filename is not None:
313 if filename is not None:
323 # only warn about this if we get a real name
314 # only warn about this if we get a real name
324 warn('Could not find file where `%s` is defined.\n'
315 warn('Could not find file where `%s` is defined.\n'
325 'Opening a file named `%s`' % (args, filename))
316 'Opening a file named `%s`' % (args, filename))
326 # Now, make sure we can actually read the source (if it was
317 # Now, make sure we can actually read the source (if it was
327 # in a temp file it's gone by now).
318 # in a temp file it's gone by now).
328 if datafile:
319 if datafile:
329 if lineno is None:
320 if lineno is None:
330 lineno = find_source_lines(data)
321 lineno = find_source_lines(data)
331 if lineno is None:
322 if lineno is None:
332 filename = make_filename(args)
323 filename = make_filename(args)
333 if filename is None:
324 if filename is None:
334 warn('The file where `%s` was defined '
325 warn('The file where `%s` was defined '
335 'cannot be read or found.' % data)
326 'cannot be read or found.' % data)
336 return (None, None, None)
327 return (None, None, None)
337 use_temp = False
328 use_temp = False
338
329
339 if use_temp:
330 if use_temp:
340 filename = shell.mktempfile(data)
331 filename = shell.mktempfile(data)
341 print 'IPython will make a temporary file named:',filename
332 print 'IPython will make a temporary file named:',filename
342
333
334 # use last_call to remember the state of the previous call, but don't
335 # let it be clobbered by successive '-p' calls.
336 try:
337 last_call[0] = shell.displayhook.prompt_count
338 if not opts_prev:
339 last_call[1] = args
340 except:
341 pass
342
343
343 return filename, lineno, use_temp
344 return filename, lineno, use_temp
344
345
345 def _edit_macro(self,mname,macro):
346 def _edit_macro(self,mname,macro):
346 """open an editor with the macro data in a file"""
347 """open an editor with the macro data in a file"""
347 filename = self.shell.mktempfile(macro.value)
348 filename = self.shell.mktempfile(macro.value)
348 self.shell.hooks.editor(filename)
349 self.shell.hooks.editor(filename)
349
350
350 # and make a new macro object, to replace the old one
351 # and make a new macro object, to replace the old one
351 mfile = open(filename)
352 mfile = open(filename)
352 mvalue = mfile.read()
353 mvalue = mfile.read()
353 mfile.close()
354 mfile.close()
354 self.shell.user_ns[mname] = Macro(mvalue)
355 self.shell.user_ns[mname] = Macro(mvalue)
355
356
356 @skip_doctest
357 @skip_doctest
357 @line_magic
358 @line_magic
358 def edit(self, parameter_s='',last_call=['','']):
359 def edit(self, parameter_s='',last_call=['','']):
359 """Bring up an editor and execute the resulting code.
360 """Bring up an editor and execute the resulting code.
360
361
361 Usage:
362 Usage:
362 %edit [options] [args]
363 %edit [options] [args]
363
364
364 %edit runs IPython's editor hook. The default version of this hook is
365 %edit runs IPython's editor hook. The default version of this hook is
365 set to call the editor specified by your $EDITOR environment variable.
366 set to call the editor specified by your $EDITOR environment variable.
366 If this isn't found, it will default to vi under Linux/Unix and to
367 If this isn't found, it will default to vi under Linux/Unix and to
367 notepad under Windows. See the end of this docstring for how to change
368 notepad under Windows. See the end of this docstring for how to change
368 the editor hook.
369 the editor hook.
369
370
370 You can also set the value of this editor via the
371 You can also set the value of this editor via the
371 ``TerminalInteractiveShell.editor`` option in your configuration file.
372 ``TerminalInteractiveShell.editor`` option in your configuration file.
372 This is useful if you wish to use a different editor from your typical
373 This is useful if you wish to use a different editor from your typical
373 default with IPython (and for Windows users who typically don't set
374 default with IPython (and for Windows users who typically don't set
374 environment variables).
375 environment variables).
375
376
376 This command allows you to conveniently edit multi-line code right in
377 This command allows you to conveniently edit multi-line code right in
377 your IPython session.
378 your IPython session.
378
379
379 If called without arguments, %edit opens up an empty editor with a
380 If called without arguments, %edit opens up an empty editor with a
380 temporary file and will execute the contents of this file when you
381 temporary file and will execute the contents of this file when you
381 close it (don't forget to save it!).
382 close it (don't forget to save it!).
382
383
383
384
384 Options:
385 Options:
385
386
386 -n <number>: open the editor at a specified line number. By default,
387 -n <number>: open the editor at a specified line number. By default,
387 the IPython editor hook uses the unix syntax 'editor +N filename', but
388 the IPython editor hook uses the unix syntax 'editor +N filename', but
388 you can configure this by providing your own modified hook if your
389 you can configure this by providing your own modified hook if your
389 favorite editor supports line-number specifications with a different
390 favorite editor supports line-number specifications with a different
390 syntax.
391 syntax.
391
392
392 -p: this will call the editor with the same data as the previous time
393 -p: this will call the editor with the same data as the previous time
393 it was used, regardless of how long ago (in your current session) it
394 it was used, regardless of how long ago (in your current session) it
394 was.
395 was.
395
396
396 -r: use 'raw' input. This option only applies to input taken from the
397 -r: use 'raw' input. This option only applies to input taken from the
397 user's history. By default, the 'processed' history is used, so that
398 user's history. By default, the 'processed' history is used, so that
398 magics are loaded in their transformed version to valid Python. If
399 magics are loaded in their transformed version to valid Python. If
399 this option is given, the raw input as typed as the command line is
400 this option is given, the raw input as typed as the command line is
400 used instead. When you exit the editor, it will be executed by
401 used instead. When you exit the editor, it will be executed by
401 IPython's own processor.
402 IPython's own processor.
402
403
403 -x: do not execute the edited code immediately upon exit. This is
404 -x: do not execute the edited code immediately upon exit. This is
404 mainly useful if you are editing programs which need to be called with
405 mainly useful if you are editing programs which need to be called with
405 command line arguments, which you can then do using %run.
406 command line arguments, which you can then do using %run.
406
407
407
408
408 Arguments:
409 Arguments:
409
410
410 If arguments are given, the following possibilities exist:
411 If arguments are given, the following possibilities exist:
411
412
412 - If the argument is a filename, IPython will load that into the
413 - If the argument is a filename, IPython will load that into the
413 editor. It will execute its contents with execfile() when you exit,
414 editor. It will execute its contents with execfile() when you exit,
414 loading any code in the file into your interactive namespace.
415 loading any code in the file into your interactive namespace.
415
416
416 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
417 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
417 The syntax is the same as in the %history magic.
418 The syntax is the same as in the %history magic.
418
419
419 - If the argument is a string variable, its contents are loaded
420 - If the argument is a string variable, its contents are loaded
420 into the editor. You can thus edit any string which contains
421 into the editor. You can thus edit any string which contains
421 python code (including the result of previous edits).
422 python code (including the result of previous edits).
422
423
423 - If the argument is the name of an object (other than a string),
424 - If the argument is the name of an object (other than a string),
424 IPython will try to locate the file where it was defined and open the
425 IPython will try to locate the file where it was defined and open the
425 editor at the point where it is defined. You can use `%edit function`
426 editor at the point where it is defined. You can use `%edit function`
426 to load an editor exactly at the point where 'function' is defined,
427 to load an editor exactly at the point where 'function' is defined,
427 edit it and have the file be executed automatically.
428 edit it and have the file be executed automatically.
428
429
429 - If the object is a macro (see %macro for details), this opens up your
430 - If the object is a macro (see %macro for details), this opens up your
430 specified editor with a temporary file containing the macro's data.
431 specified editor with a temporary file containing the macro's data.
431 Upon exit, the macro is reloaded with the contents of the file.
432 Upon exit, the macro is reloaded with the contents of the file.
432
433
433 Note: opening at an exact line is only supported under Unix, and some
434 Note: opening at an exact line is only supported under Unix, and some
434 editors (like kedit and gedit up to Gnome 2.8) do not understand the
435 editors (like kedit and gedit up to Gnome 2.8) do not understand the
435 '+NUMBER' parameter necessary for this feature. Good editors like
436 '+NUMBER' parameter necessary for this feature. Good editors like
436 (X)Emacs, vi, jed, pico and joe all do.
437 (X)Emacs, vi, jed, pico and joe all do.
437
438
438 After executing your code, %edit will return as output the code you
439 After executing your code, %edit will return as output the code you
439 typed in the editor (except when it was an existing file). This way
440 typed in the editor (except when it was an existing file). This way
440 you can reload the code in further invocations of %edit as a variable,
441 you can reload the code in further invocations of %edit as a variable,
441 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
442 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
442 the output.
443 the output.
443
444
444 Note that %edit is also available through the alias %ed.
445 Note that %edit is also available through the alias %ed.
445
446
446 This is an example of creating a simple function inside the editor and
447 This is an example of creating a simple function inside the editor and
447 then modifying it. First, start up the editor::
448 then modifying it. First, start up the editor::
448
449
449 In [1]: edit
450 In [1]: edit
450 Editing... done. Executing edited code...
451 Editing... done. Executing edited code...
451 Out[1]: 'def foo():\\n print "foo() was defined in an editing
452 Out[1]: 'def foo():\\n print "foo() was defined in an editing
452 session"\\n'
453 session"\\n'
453
454
454 We can then call the function foo()::
455 We can then call the function foo()::
455
456
456 In [2]: foo()
457 In [2]: foo()
457 foo() was defined in an editing session
458 foo() was defined in an editing session
458
459
459 Now we edit foo. IPython automatically loads the editor with the
460 Now we edit foo. IPython automatically loads the editor with the
460 (temporary) file where foo() was previously defined::
461 (temporary) file where foo() was previously defined::
461
462
462 In [3]: edit foo
463 In [3]: edit foo
463 Editing... done. Executing edited code...
464 Editing... done. Executing edited code...
464
465
465 And if we call foo() again we get the modified version::
466 And if we call foo() again we get the modified version::
466
467
467 In [4]: foo()
468 In [4]: foo()
468 foo() has now been changed!
469 foo() has now been changed!
469
470
470 Here is an example of how to edit a code snippet successive
471 Here is an example of how to edit a code snippet successive
471 times. First we call the editor::
472 times. First we call the editor::
472
473
473 In [5]: edit
474 In [5]: edit
474 Editing... done. Executing edited code...
475 Editing... done. Executing edited code...
475 hello
476 hello
476 Out[5]: "print 'hello'\\n"
477 Out[5]: "print 'hello'\\n"
477
478
478 Now we call it again with the previous output (stored in _)::
479 Now we call it again with the previous output (stored in _)::
479
480
480 In [6]: edit _
481 In [6]: edit _
481 Editing... done. Executing edited code...
482 Editing... done. Executing edited code...
482 hello world
483 hello world
483 Out[6]: "print 'hello world'\\n"
484 Out[6]: "print 'hello world'\\n"
484
485
485 Now we call it with the output #8 (stored in _8, also as Out[8])::
486 Now we call it with the output #8 (stored in _8, also as Out[8])::
486
487
487 In [7]: edit _8
488 In [7]: edit _8
488 Editing... done. Executing edited code...
489 Editing... done. Executing edited code...
489 hello again
490 hello again
490 Out[7]: "print 'hello again'\\n"
491 Out[7]: "print 'hello again'\\n"
491
492
492
493
493 Changing the default editor hook:
494 Changing the default editor hook:
494
495
495 If you wish to write your own editor hook, you can put it in a
496 If you wish to write your own editor hook, you can put it in a
496 configuration file which you load at startup time. The default hook
497 configuration file which you load at startup time. The default hook
497 is defined in the IPython.core.hooks module, and you can use that as a
498 is defined in the IPython.core.hooks module, and you can use that as a
498 starting example for further modifications. That file also has
499 starting example for further modifications. That file also has
499 general instructions on how to set a new hook for use once you've
500 general instructions on how to set a new hook for use once you've
500 defined it."""
501 defined it."""
501 opts,args = self.parse_options(parameter_s,'prxn:')
502 opts,args = self.parse_options(parameter_s,'prxn:')
502
503
503 try:
504 try:
504 filename, lineno, is_temp = self._find_edit_target(self.shell,
505 filename, lineno, is_temp = self._find_edit_target(self.shell,
505 args, opts, last_call)
506 args, opts, last_call)
506 except MacroToEdit as e:
507 except MacroToEdit as e:
507 self._edit_macro(args, e.args[0])
508 self._edit_macro(args, e.args[0])
508 return
509 return
509 except InteractivelyDefined as e:
510 except InteractivelyDefined as e:
510 print "Editing In[%i]" % e.index
511 print "Editing In[%i]" % e.index
511 args = str(e.index)
512 args = str(e.index)
512 filename, lineno, is_temp = self._find_edit_target(self.shell,
513 filename, lineno, is_temp = self._find_edit_target(self.shell,
513 args, opts, last_call)
514 args, opts, last_call)
514 if filename is None:
515 if filename is None:
515 # nothing was found, warnings have already been issued,
516 # nothing was found, warnings have already been issued,
516 # just give up.
517 # just give up.
517 return
518 return
518
519
519 # do actual editing here
520 # do actual editing here
520 print 'Editing...',
521 print 'Editing...',
521 sys.stdout.flush()
522 sys.stdout.flush()
522 try:
523 try:
523 # Quote filenames that may have spaces in them
524 # Quote filenames that may have spaces in them
524 if ' ' in filename:
525 if ' ' in filename:
525 filename = "'%s'" % filename
526 filename = "'%s'" % filename
526 self.shell.hooks.editor(filename,lineno)
527 self.shell.hooks.editor(filename,lineno)
527 except TryNext:
528 except TryNext:
528 warn('Could not open editor')
529 warn('Could not open editor')
529 return
530 return
530
531
531 # XXX TODO: should this be generalized for all string vars?
532 # XXX TODO: should this be generalized for all string vars?
532 # For now, this is special-cased to blocks created by cpaste
533 # For now, this is special-cased to blocks created by cpaste
533 if args.strip() == 'pasted_block':
534 if args.strip() == 'pasted_block':
534 self.shell.user_ns['pasted_block'] = file_read(filename)
535 self.shell.user_ns['pasted_block'] = file_read(filename)
535
536
536 if 'x' in opts: # -x prevents actual execution
537 if 'x' in opts: # -x prevents actual execution
537 print
538 print
538 else:
539 else:
539 print 'done. Executing edited code...'
540 print 'done. Executing edited code...'
540 with preserve_keys(self.shell.user_ns, '__file__'):
541 with preserve_keys(self.shell.user_ns, '__file__'):
541 if not is_temp:
542 if not is_temp:
542 self.shell.user_ns['__file__'] = filename
543 self.shell.user_ns['__file__'] = filename
543 if 'r' in opts: # Untranslated IPython code
544 if 'r' in opts: # Untranslated IPython code
544 self.shell.run_cell(file_read(filename),
545 self.shell.run_cell(file_read(filename),
545 store_history=False)
546 store_history=False)
546 else:
547 else:
547 self.shell.safe_execfile(filename, self.shell.user_ns,
548 self.shell.safe_execfile(filename, self.shell.user_ns,
548 self.shell.user_ns)
549 self.shell.user_ns)
549
550
550 if is_temp:
551 if is_temp:
551 try:
552 try:
552 return open(filename).read()
553 return open(filename).read()
553 except IOError as msg:
554 except IOError as msg:
554 if msg.filename == filename:
555 if msg.filename == filename:
555 warn('File not found. Did you forget to save?')
556 warn('File not found. Did you forget to save?')
556 return
557 return
557 else:
558 else:
558 self.shell.showtraceback()
559 self.shell.showtraceback()
General Comments 0
You need to be logged in to leave comments. Login now