##// END OF EJS Templates
%save works again
vivainio -
r199:259422cc
parent child
Show More
@@ -1,2808 +1,2808
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 1166 2006-02-15 19:20:58Z vivainio $"""
4 $Id: Magic.py 1173 2006-02-21 16:24:01Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 #
9 #
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #*****************************************************************************
12 #*****************************************************************************
13
13
14 #****************************************************************************
14 #****************************************************************************
15 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt,GetoptError
36 from getopt import getopt,GetoptError
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54
55 #***************************************************************************
55 #***************************************************************************
56 # Utility functions
56 # Utility functions
57 def on_off(tag):
57 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
60
60
61 class Bunch: pass
61 class Bunch: pass
62
62
63 #***************************************************************************
63 #***************************************************************************
64 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
65 class Magic:
65 class Magic:
66 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
67
67
68 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
69 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
70 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
71 vs. `%cd("../")`
71 vs. `%cd("../")`
72
72
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
74 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
75
75
76 # class globals
76 # class globals
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
79
79
80 #......................................................................
80 #......................................................................
81 # some utility functions
81 # some utility functions
82
82
83 def __init__(self,shell):
83 def __init__(self,shell):
84
84
85 self.options_table = {}
85 self.options_table = {}
86 if profile is None:
86 if profile is None:
87 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
88 self.shell = shell
88 self.shell = shell
89
89
90 # namespace for holding state we may need
90 # namespace for holding state we may need
91 self._magic_state = Bunch()
91 self._magic_state = Bunch()
92
92
93 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
94 error("""\
94 error("""\
95 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
96 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
98
98
99 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
100 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
101
101
102 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
103 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
104 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
105
105
106 def lsmagic(self):
106 def lsmagic(self):
107 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
108
108
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
110 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
111
111
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
113
113
114 # magics in class definition
114 # magics in class definition
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
116 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
117 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
119 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
120 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
122 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
126 out = []
126 out = []
127 for fn in magics:
127 for fn in magics:
128 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
129 out.sort()
129 out.sort()
130 return out
130 return out
131
131
132 def extract_input_slices(self,slices,raw=False):
132 def extract_input_slices(self,slices,raw=False):
133 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
134
134
135 Inputs:
135 Inputs:
136
136
137 - slices: the set of slices is given as a list of strings (like
137 - slices: the set of slices is given as a list of strings (like
138 ['1','4:8','9'], since this function is for use by magic functions
138 ['1','4:8','9'], since this function is for use by magic functions
139 which get their arguments as strings.
139 which get their arguments as strings.
140
140
141 Optional inputs:
141 Optional inputs:
142
142
143 - raw(False): by default, the processed input is used. If this is
143 - raw(False): by default, the processed input is used. If this is
144 true, the raw input history is used instead.
144 true, the raw input history is used instead.
145
145
146 Note that slices can be called with two notations:
146 Note that slices can be called with two notations:
147
147
148 N:M -> standard python form, means including items N...(M-1).
148 N:M -> standard python form, means including items N...(M-1).
149
149
150 N-M -> include items N..M (closed endpoint)."""
150 N-M -> include items N..M (closed endpoint)."""
151
151
152 if raw:
152 if raw:
153 hist = self.shell.input_hist_raw
153 hist = self.shell.input_hist_raw
154 else:
154 else:
155 hist = self.shell.input_hist
155 hist = self.shell.input_hist
156
156
157 cmds = []
157 cmds = []
158 for chunk in slices:
158 for chunk in slices:
159 if ':' in chunk:
159 if ':' in chunk:
160 ini,fin = map(int,chunk.split(':'))
160 ini,fin = map(int,chunk.split(':'))
161 elif '-' in chunk:
161 elif '-' in chunk:
162 ini,fin = map(int,chunk.split('-'))
162 ini,fin = map(int,chunk.split('-'))
163 fin += 1
163 fin += 1
164 else:
164 else:
165 ini = int(chunk)
165 ini = int(chunk)
166 fin = ini+1
166 fin = ini+1
167 cmds.append(hist[ini:fin])
167 cmds.append(hist[ini:fin])
168 return cmds
168 return cmds
169
169
170 def _ofind(self,oname):
170 def _ofind(self,oname):
171 """Find an object in the available namespaces.
171 """Find an object in the available namespaces.
172
172
173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
173 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
174
174
175 Has special code to detect magic functions.
175 Has special code to detect magic functions.
176 """
176 """
177
177
178 oname = oname.strip()
178 oname = oname.strip()
179
179
180 # Namespaces to search in:
180 # Namespaces to search in:
181 user_ns = self.shell.user_ns
181 user_ns = self.shell.user_ns
182 internal_ns = self.shell.internal_ns
182 internal_ns = self.shell.internal_ns
183 builtin_ns = __builtin__.__dict__
183 builtin_ns = __builtin__.__dict__
184 alias_ns = self.shell.alias_table
184 alias_ns = self.shell.alias_table
185
185
186 # Put them in a list. The order is important so that we find things in
186 # Put them in a list. The order is important so that we find things in
187 # the same order that Python finds them.
187 # the same order that Python finds them.
188 namespaces = [ ('Interactive',user_ns),
188 namespaces = [ ('Interactive',user_ns),
189 ('IPython internal',internal_ns),
189 ('IPython internal',internal_ns),
190 ('Python builtin',builtin_ns),
190 ('Python builtin',builtin_ns),
191 ('Alias',alias_ns),
191 ('Alias',alias_ns),
192 ]
192 ]
193
193
194 # initialize results to 'null'
194 # initialize results to 'null'
195 found = 0; obj = None; ospace = None; ds = None;
195 found = 0; obj = None; ospace = None; ds = None;
196 ismagic = 0; isalias = 0
196 ismagic = 0; isalias = 0
197
197
198 # Look for the given name by splitting it in parts. If the head is
198 # Look for the given name by splitting it in parts. If the head is
199 # found, then we look for all the remaining parts as members, and only
199 # found, then we look for all the remaining parts as members, and only
200 # declare success if we can find them all.
200 # declare success if we can find them all.
201 oname_parts = oname.split('.')
201 oname_parts = oname.split('.')
202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
202 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
203 for nsname,ns in namespaces:
203 for nsname,ns in namespaces:
204 try:
204 try:
205 obj = ns[oname_head]
205 obj = ns[oname_head]
206 except KeyError:
206 except KeyError:
207 continue
207 continue
208 else:
208 else:
209 for part in oname_rest:
209 for part in oname_rest:
210 try:
210 try:
211 obj = getattr(obj,part)
211 obj = getattr(obj,part)
212 except:
212 except:
213 # Blanket except b/c some badly implemented objects
213 # Blanket except b/c some badly implemented objects
214 # allow __getattr__ to raise exceptions other than
214 # allow __getattr__ to raise exceptions other than
215 # AttributeError, which then crashes IPython.
215 # AttributeError, which then crashes IPython.
216 break
216 break
217 else:
217 else:
218 # If we finish the for loop (no break), we got all members
218 # If we finish the for loop (no break), we got all members
219 found = 1
219 found = 1
220 ospace = nsname
220 ospace = nsname
221 if ns == alias_ns:
221 if ns == alias_ns:
222 isalias = 1
222 isalias = 1
223 break # namespace loop
223 break # namespace loop
224
224
225 # Try to see if it's magic
225 # Try to see if it's magic
226 if not found:
226 if not found:
227 if oname.startswith(self.shell.ESC_MAGIC):
227 if oname.startswith(self.shell.ESC_MAGIC):
228 oname = oname[1:]
228 oname = oname[1:]
229 obj = getattr(self,'magic_'+oname,None)
229 obj = getattr(self,'magic_'+oname,None)
230 if obj is not None:
230 if obj is not None:
231 found = 1
231 found = 1
232 ospace = 'IPython internal'
232 ospace = 'IPython internal'
233 ismagic = 1
233 ismagic = 1
234
234
235 # Last try: special-case some literals like '', [], {}, etc:
235 # Last try: special-case some literals like '', [], {}, etc:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
236 if not found and oname_head in ["''",'""','[]','{}','()']:
237 obj = eval(oname_head)
237 obj = eval(oname_head)
238 found = 1
238 found = 1
239 ospace = 'Interactive'
239 ospace = 'Interactive'
240
240
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias}
242 'ismagic':ismagic, 'isalias':isalias}
243
243
244 def arg_err(self,func):
244 def arg_err(self,func):
245 """Print docstring if incorrect arguments were passed"""
245 """Print docstring if incorrect arguments were passed"""
246 print 'Error in arguments:'
246 print 'Error in arguments:'
247 print OInspect.getdoc(func)
247 print OInspect.getdoc(func)
248
248
249 def format_latex(self,strng):
249 def format_latex(self,strng):
250 """Format a string for latex inclusion."""
250 """Format a string for latex inclusion."""
251
251
252 # Characters that need to be escaped for latex:
252 # Characters that need to be escaped for latex:
253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
253 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
254 # Magic command names as headers:
254 # Magic command names as headers:
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
255 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
256 re.MULTILINE)
256 re.MULTILINE)
257 # Magic commands
257 # Magic commands
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
258 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
259 re.MULTILINE)
259 re.MULTILINE)
260 # Paragraph continue
260 # Paragraph continue
261 par_re = re.compile(r'\\$',re.MULTILINE)
261 par_re = re.compile(r'\\$',re.MULTILINE)
262
262
263 # The "\n" symbol
263 # The "\n" symbol
264 newline_re = re.compile(r'\\n')
264 newline_re = re.compile(r'\\n')
265
265
266 # Now build the string for output:
266 # Now build the string for output:
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
267 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
268 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
269 strng)
269 strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
270 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
271 strng = par_re.sub(r'\\\\',strng)
271 strng = par_re.sub(r'\\\\',strng)
272 strng = escape_re.sub(r'\\\1',strng)
272 strng = escape_re.sub(r'\\\1',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
273 strng = newline_re.sub(r'\\textbackslash{}n',strng)
274 return strng
274 return strng
275
275
276 def format_screen(self,strng):
276 def format_screen(self,strng):
277 """Format a string for screen printing.
277 """Format a string for screen printing.
278
278
279 This removes some latex-type format codes."""
279 This removes some latex-type format codes."""
280 # Paragraph continue
280 # Paragraph continue
281 par_re = re.compile(r'\\$',re.MULTILINE)
281 par_re = re.compile(r'\\$',re.MULTILINE)
282 strng = par_re.sub('',strng)
282 strng = par_re.sub('',strng)
283 return strng
283 return strng
284
284
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
285 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
286 """Parse options passed to an argument string.
286 """Parse options passed to an argument string.
287
287
288 The interface is similar to that of getopt(), but it returns back a
288 The interface is similar to that of getopt(), but it returns back a
289 Struct with the options as keys and the stripped argument string still
289 Struct with the options as keys and the stripped argument string still
290 as a string.
290 as a string.
291
291
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
292 arg_str is quoted as a true sys.argv vector by using shlex.split.
293 This allows us to easily expand variables, glob files, quote
293 This allows us to easily expand variables, glob files, quote
294 arguments, etc.
294 arguments, etc.
295
295
296 Options:
296 Options:
297 -mode: default 'string'. If given as 'list', the argument string is
297 -mode: default 'string'. If given as 'list', the argument string is
298 returned as a list (split on whitespace) instead of a string.
298 returned as a list (split on whitespace) instead of a string.
299
299
300 -list_all: put all option values in lists. Normally only options
300 -list_all: put all option values in lists. Normally only options
301 appearing more than once are put in a list."""
301 appearing more than once are put in a list."""
302
302
303 # inject default options at the beginning of the input line
303 # inject default options at the beginning of the input line
304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
304 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
305 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
306
306
307 mode = kw.get('mode','string')
307 mode = kw.get('mode','string')
308 if mode not in ['string','list']:
308 if mode not in ['string','list']:
309 raise ValueError,'incorrect mode given: %s' % mode
309 raise ValueError,'incorrect mode given: %s' % mode
310 # Get options
310 # Get options
311 list_all = kw.get('list_all',0)
311 list_all = kw.get('list_all',0)
312
312
313 # Check if we have more than one argument to warrant extra processing:
313 # Check if we have more than one argument to warrant extra processing:
314 odict = {} # Dictionary with options
314 odict = {} # Dictionary with options
315 args = arg_str.split()
315 args = arg_str.split()
316 if len(args) >= 1:
316 if len(args) >= 1:
317 # If the list of inputs only has 0 or 1 thing in it, there's no
317 # If the list of inputs only has 0 or 1 thing in it, there's no
318 # need to look for options
318 # need to look for options
319 argv = shlex_split(arg_str)
319 argv = shlex_split(arg_str)
320 # Do regular option processing
320 # Do regular option processing
321 try:
321 try:
322 opts,args = getopt(argv,opt_str,*long_opts)
322 opts,args = getopt(argv,opt_str,*long_opts)
323 except GetoptError,e:
323 except GetoptError,e:
324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
324 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
325 " ".join(long_opts)))
325 " ".join(long_opts)))
326 for o,a in opts:
326 for o,a in opts:
327 if o.startswith('--'):
327 if o.startswith('--'):
328 o = o[2:]
328 o = o[2:]
329 else:
329 else:
330 o = o[1:]
330 o = o[1:]
331 try:
331 try:
332 odict[o].append(a)
332 odict[o].append(a)
333 except AttributeError:
333 except AttributeError:
334 odict[o] = [odict[o],a]
334 odict[o] = [odict[o],a]
335 except KeyError:
335 except KeyError:
336 if list_all:
336 if list_all:
337 odict[o] = [a]
337 odict[o] = [a]
338 else:
338 else:
339 odict[o] = a
339 odict[o] = a
340
340
341 # Prepare opts,args for return
341 # Prepare opts,args for return
342 opts = Struct(odict)
342 opts = Struct(odict)
343 if mode == 'string':
343 if mode == 'string':
344 args = ' '.join(args)
344 args = ' '.join(args)
345
345
346 return opts,args
346 return opts,args
347
347
348 #......................................................................
348 #......................................................................
349 # And now the actual magic functions
349 # And now the actual magic functions
350
350
351 # Functions for IPython shell work (vars,funcs, config, etc)
351 # Functions for IPython shell work (vars,funcs, config, etc)
352 def magic_lsmagic(self, parameter_s = ''):
352 def magic_lsmagic(self, parameter_s = ''):
353 """List currently available magic functions."""
353 """List currently available magic functions."""
354 mesc = self.shell.ESC_MAGIC
354 mesc = self.shell.ESC_MAGIC
355 print 'Available magic functions:\n'+mesc+\
355 print 'Available magic functions:\n'+mesc+\
356 (' '+mesc).join(self.lsmagic())
356 (' '+mesc).join(self.lsmagic())
357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
357 print '\n' + Magic.auto_status[self.shell.rc.automagic]
358 return None
358 return None
359
359
360 def magic_magic(self, parameter_s = ''):
360 def magic_magic(self, parameter_s = ''):
361 """Print information about the magic function system."""
361 """Print information about the magic function system."""
362
362
363 mode = ''
363 mode = ''
364 try:
364 try:
365 if parameter_s.split()[0] == '-latex':
365 if parameter_s.split()[0] == '-latex':
366 mode = 'latex'
366 mode = 'latex'
367 except:
367 except:
368 pass
368 pass
369
369
370 magic_docs = []
370 magic_docs = []
371 for fname in self.lsmagic():
371 for fname in self.lsmagic():
372 mname = 'magic_' + fname
372 mname = 'magic_' + fname
373 for space in (Magic,self,self.__class__):
373 for space in (Magic,self,self.__class__):
374 try:
374 try:
375 fn = space.__dict__[mname]
375 fn = space.__dict__[mname]
376 except KeyError:
376 except KeyError:
377 pass
377 pass
378 else:
378 else:
379 break
379 break
380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
380 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
381 fname,fn.__doc__))
381 fname,fn.__doc__))
382 magic_docs = ''.join(magic_docs)
382 magic_docs = ''.join(magic_docs)
383
383
384 if mode == 'latex':
384 if mode == 'latex':
385 print self.format_latex(magic_docs)
385 print self.format_latex(magic_docs)
386 return
386 return
387 else:
387 else:
388 magic_docs = self.format_screen(magic_docs)
388 magic_docs = self.format_screen(magic_docs)
389
389
390 outmsg = """
390 outmsg = """
391 IPython's 'magic' functions
391 IPython's 'magic' functions
392 ===========================
392 ===========================
393
393
394 The magic function system provides a series of functions which allow you to
394 The magic function system provides a series of functions which allow you to
395 control the behavior of IPython itself, plus a lot of system-type
395 control the behavior of IPython itself, plus a lot of system-type
396 features. All these functions are prefixed with a % character, but parameters
396 features. All these functions are prefixed with a % character, but parameters
397 are given without parentheses or quotes.
397 are given without parentheses or quotes.
398
398
399 NOTE: If you have 'automagic' enabled (via the command line option or with the
399 NOTE: If you have 'automagic' enabled (via the command line option or with the
400 %automagic function), you don't need to type in the % explicitly. By default,
400 %automagic function), you don't need to type in the % explicitly. By default,
401 IPython ships with automagic on, so you should only rarely need the % escape.
401 IPython ships with automagic on, so you should only rarely need the % escape.
402
402
403 Example: typing '%cd mydir' (without the quotes) changes you working directory
403 Example: typing '%cd mydir' (without the quotes) changes you working directory
404 to 'mydir', if it exists.
404 to 'mydir', if it exists.
405
405
406 You can define your own magic functions to extend the system. See the supplied
406 You can define your own magic functions to extend the system. See the supplied
407 ipythonrc and example-magic.py files for details (in your ipython
407 ipythonrc and example-magic.py files for details (in your ipython
408 configuration directory, typically $HOME/.ipython/).
408 configuration directory, typically $HOME/.ipython/).
409
409
410 You can also define your own aliased names for magic functions. In your
410 You can also define your own aliased names for magic functions. In your
411 ipythonrc file, placing a line like:
411 ipythonrc file, placing a line like:
412
412
413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
413 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
414
414
415 will define %pf as a new name for %profile.
415 will define %pf as a new name for %profile.
416
416
417 You can also call magics in code using the ipmagic() function, which IPython
417 You can also call magics in code using the ipmagic() function, which IPython
418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
418 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
419
419
420 For a list of the available magic functions, use %lsmagic. For a description
420 For a list of the available magic functions, use %lsmagic. For a description
421 of any of them, type %magic_name?, e.g. '%cd?'.
421 of any of them, type %magic_name?, e.g. '%cd?'.
422
422
423 Currently the magic system has the following functions:\n"""
423 Currently the magic system has the following functions:\n"""
424
424
425 mesc = self.shell.ESC_MAGIC
425 mesc = self.shell.ESC_MAGIC
426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
426 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
427 "\n\n%s%s\n\n%s" % (outmsg,
427 "\n\n%s%s\n\n%s" % (outmsg,
428 magic_docs,mesc,mesc,
428 magic_docs,mesc,mesc,
429 (' '+mesc).join(self.lsmagic()),
429 (' '+mesc).join(self.lsmagic()),
430 Magic.auto_status[self.shell.rc.automagic] ) )
430 Magic.auto_status[self.shell.rc.automagic] ) )
431
431
432 page(outmsg,screen_lines=self.shell.rc.screen_length)
432 page(outmsg,screen_lines=self.shell.rc.screen_length)
433
433
434 def magic_automagic(self, parameter_s = ''):
434 def magic_automagic(self, parameter_s = ''):
435 """Make magic functions callable without having to type the initial %.
435 """Make magic functions callable without having to type the initial %.
436
436
437 Toggles on/off (when off, you must call it as %automagic, of
437 Toggles on/off (when off, you must call it as %automagic, of
438 course). Note that magic functions have lowest priority, so if there's
438 course). Note that magic functions have lowest priority, so if there's
439 a variable whose name collides with that of a magic fn, automagic
439 a variable whose name collides with that of a magic fn, automagic
440 won't work for that function (you get the variable instead). However,
440 won't work for that function (you get the variable instead). However,
441 if you delete the variable (del var), the previously shadowed magic
441 if you delete the variable (del var), the previously shadowed magic
442 function becomes visible to automagic again."""
442 function becomes visible to automagic again."""
443
443
444 rc = self.shell.rc
444 rc = self.shell.rc
445 rc.automagic = not rc.automagic
445 rc.automagic = not rc.automagic
446 print '\n' + Magic.auto_status[rc.automagic]
446 print '\n' + Magic.auto_status[rc.automagic]
447
447
448 def magic_autocall(self, parameter_s = ''):
448 def magic_autocall(self, parameter_s = ''):
449 """Make functions callable without having to type parentheses.
449 """Make functions callable without having to type parentheses.
450
450
451 Usage:
451 Usage:
452
452
453 %autocall [mode]
453 %autocall [mode]
454
454
455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
455 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
456 value is toggled on and off (remembering the previous state)."""
456 value is toggled on and off (remembering the previous state)."""
457
457
458 rc = self.shell.rc
458 rc = self.shell.rc
459
459
460 if parameter_s:
460 if parameter_s:
461 arg = int(parameter_s)
461 arg = int(parameter_s)
462 else:
462 else:
463 arg = 'toggle'
463 arg = 'toggle'
464
464
465 if not arg in (0,1,2,'toggle'):
465 if not arg in (0,1,2,'toggle'):
466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
466 error('Valid modes: (0->Off, 1->Smart, 2->Full')
467 return
467 return
468
468
469 if arg in (0,1,2):
469 if arg in (0,1,2):
470 rc.autocall = arg
470 rc.autocall = arg
471 else: # toggle
471 else: # toggle
472 if rc.autocall:
472 if rc.autocall:
473 self._magic_state.autocall_save = rc.autocall
473 self._magic_state.autocall_save = rc.autocall
474 rc.autocall = 0
474 rc.autocall = 0
475 else:
475 else:
476 try:
476 try:
477 rc.autocall = self._magic_state.autocall_save
477 rc.autocall = self._magic_state.autocall_save
478 except AttributeError:
478 except AttributeError:
479 rc.autocall = self._magic_state.autocall_save = 1
479 rc.autocall = self._magic_state.autocall_save = 1
480
480
481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
481 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
482
482
483 def magic_autoindent(self, parameter_s = ''):
483 def magic_autoindent(self, parameter_s = ''):
484 """Toggle autoindent on/off (if available)."""
484 """Toggle autoindent on/off (if available)."""
485
485
486 self.shell.set_autoindent()
486 self.shell.set_autoindent()
487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
487 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
488
488
489 def magic_system_verbose(self, parameter_s = ''):
489 def magic_system_verbose(self, parameter_s = ''):
490 """Toggle verbose printing of system calls on/off."""
490 """Toggle verbose printing of system calls on/off."""
491
491
492 self.shell.rc_set_toggle('system_verbose')
492 self.shell.rc_set_toggle('system_verbose')
493 print "System verbose printing is:",\
493 print "System verbose printing is:",\
494 ['OFF','ON'][self.shell.rc.system_verbose]
494 ['OFF','ON'][self.shell.rc.system_verbose]
495
495
496 def magic_history(self, parameter_s = ''):
496 def magic_history(self, parameter_s = ''):
497 """Print input history (_i<n> variables), with most recent last.
497 """Print input history (_i<n> variables), with most recent last.
498
498
499 %history -> print at most 40 inputs (some may be multi-line)\\
499 %history -> print at most 40 inputs (some may be multi-line)\\
500 %history n -> print at most n inputs\\
500 %history n -> print at most n inputs\\
501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
501 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
502
502
503 Each input's number <n> is shown, and is accessible as the
503 Each input's number <n> is shown, and is accessible as the
504 automatically generated variable _i<n>. Multi-line statements are
504 automatically generated variable _i<n>. Multi-line statements are
505 printed starting at a new line for easy copy/paste.
505 printed starting at a new line for easy copy/paste.
506
506
507
507
508 Options:
508 Options:
509
509
510 -n: do NOT print line numbers. This is useful if you want to get a
510 -n: do NOT print line numbers. This is useful if you want to get a
511 printout of many lines which can be directly pasted into a text
511 printout of many lines which can be directly pasted into a text
512 editor.
512 editor.
513
513
514 This feature is only available if numbered prompts are in use.
514 This feature is only available if numbered prompts are in use.
515
515
516 -r: print the 'raw' history. IPython filters your input and
516 -r: print the 'raw' history. IPython filters your input and
517 converts it all into valid Python source before executing it (things
517 converts it all into valid Python source before executing it (things
518 like magics or aliases are turned into function calls, for
518 like magics or aliases are turned into function calls, for
519 example). With this option, you'll see the unfiltered history
519 example). With this option, you'll see the unfiltered history
520 instead of the filtered version: '%cd /' will be seen as '%cd /'
520 instead of the filtered version: '%cd /' will be seen as '%cd /'
521 instead of '_ip.magic("%cd /")'.
521 instead of '_ip.magic("%cd /")'.
522 """
522 """
523
523
524 shell = self.shell
524 shell = self.shell
525 if not shell.outputcache.do_full_cache:
525 if not shell.outputcache.do_full_cache:
526 print 'This feature is only available if numbered prompts are in use.'
526 print 'This feature is only available if numbered prompts are in use.'
527 return
527 return
528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
528 opts,args = self.parse_options(parameter_s,'nr',mode='list')
529
529
530 if opts.has_key('r'):
530 if opts.has_key('r'):
531 input_hist = shell.input_hist_raw
531 input_hist = shell.input_hist_raw
532 else:
532 else:
533 input_hist = shell.input_hist
533 input_hist = shell.input_hist
534
534
535 default_length = 40
535 default_length = 40
536 if len(args) == 0:
536 if len(args) == 0:
537 final = len(input_hist)
537 final = len(input_hist)
538 init = max(1,final-default_length)
538 init = max(1,final-default_length)
539 elif len(args) == 1:
539 elif len(args) == 1:
540 final = len(input_hist)
540 final = len(input_hist)
541 init = max(1,final-int(args[0]))
541 init = max(1,final-int(args[0]))
542 elif len(args) == 2:
542 elif len(args) == 2:
543 init,final = map(int,args)
543 init,final = map(int,args)
544 else:
544 else:
545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
545 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
546 print self.magic_hist.__doc__
546 print self.magic_hist.__doc__
547 return
547 return
548 width = len(str(final))
548 width = len(str(final))
549 line_sep = ['','\n']
549 line_sep = ['','\n']
550 print_nums = not opts.has_key('n')
550 print_nums = not opts.has_key('n')
551 for in_num in range(init,final):
551 for in_num in range(init,final):
552 inline = input_hist[in_num]
552 inline = input_hist[in_num]
553 multiline = int(inline.count('\n') > 1)
553 multiline = int(inline.count('\n') > 1)
554 if print_nums:
554 if print_nums:
555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
555 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
556 print inline,
556 print inline,
557
557
558 def magic_hist(self, parameter_s=''):
558 def magic_hist(self, parameter_s=''):
559 """Alternate name for %history."""
559 """Alternate name for %history."""
560 return self.magic_history(parameter_s)
560 return self.magic_history(parameter_s)
561
561
562 def magic_p(self, parameter_s=''):
562 def magic_p(self, parameter_s=''):
563 """Just a short alias for Python's 'print'."""
563 """Just a short alias for Python's 'print'."""
564 exec 'print ' + parameter_s in self.shell.user_ns
564 exec 'print ' + parameter_s in self.shell.user_ns
565
565
566 def magic_r(self, parameter_s=''):
566 def magic_r(self, parameter_s=''):
567 """Repeat previous input.
567 """Repeat previous input.
568
568
569 If given an argument, repeats the previous command which starts with
569 If given an argument, repeats the previous command which starts with
570 the same string, otherwise it just repeats the previous input.
570 the same string, otherwise it just repeats the previous input.
571
571
572 Shell escaped commands (with ! as first character) are not recognized
572 Shell escaped commands (with ! as first character) are not recognized
573 by this system, only pure python code and magic commands.
573 by this system, only pure python code and magic commands.
574 """
574 """
575
575
576 start = parameter_s.strip()
576 start = parameter_s.strip()
577 esc_magic = self.shell.ESC_MAGIC
577 esc_magic = self.shell.ESC_MAGIC
578 # Identify magic commands even if automagic is on (which means
578 # Identify magic commands even if automagic is on (which means
579 # the in-memory version is different from that typed by the user).
579 # the in-memory version is different from that typed by the user).
580 if self.shell.rc.automagic:
580 if self.shell.rc.automagic:
581 start_magic = esc_magic+start
581 start_magic = esc_magic+start
582 else:
582 else:
583 start_magic = start
583 start_magic = start
584 # Look through the input history in reverse
584 # Look through the input history in reverse
585 for n in range(len(self.shell.input_hist)-2,0,-1):
585 for n in range(len(self.shell.input_hist)-2,0,-1):
586 input = self.shell.input_hist[n]
586 input = self.shell.input_hist[n]
587 # skip plain 'r' lines so we don't recurse to infinity
587 # skip plain 'r' lines so we don't recurse to infinity
588 if input != '_ip.magic("r")\n' and \
588 if input != '_ip.magic("r")\n' and \
589 (input.startswith(start) or input.startswith(start_magic)):
589 (input.startswith(start) or input.startswith(start_magic)):
590 #print 'match',`input` # dbg
590 #print 'match',`input` # dbg
591 print 'Executing:',input,
591 print 'Executing:',input,
592 self.shell.runlines(input)
592 self.shell.runlines(input)
593 return
593 return
594 print 'No previous input matching `%s` found.' % start
594 print 'No previous input matching `%s` found.' % start
595
595
596 def magic_page(self, parameter_s=''):
596 def magic_page(self, parameter_s=''):
597 """Pretty print the object and display it through a pager.
597 """Pretty print the object and display it through a pager.
598
598
599 If no parameter is given, use _ (last output)."""
599 If no parameter is given, use _ (last output)."""
600 # After a function contributed by Olivier Aubert, slightly modified.
600 # After a function contributed by Olivier Aubert, slightly modified.
601
601
602 oname = parameter_s and parameter_s or '_'
602 oname = parameter_s and parameter_s or '_'
603 info = self._ofind(oname)
603 info = self._ofind(oname)
604 if info['found']:
604 if info['found']:
605 page(pformat(info['obj']))
605 page(pformat(info['obj']))
606 else:
606 else: