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