##// END OF EJS Templates
Reorganization of readline and completion dependent code....
Fernando Perez -
Show More
@@ -1,789 +1,784 b''
1 """Word completion for IPython.
1 """Word completion for IPython.
2
2
3 This module is a fork of the rlcompleter module in the Python standard
3 This module is a fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3, but we need a lot more
5 upstream and were accepted as of Python 2.3, but we need a lot more
6 functionality specific to IPython, so this module will continue to live as an
6 functionality specific to IPython, so this module will continue to live as an
7 IPython-specific utility.
7 IPython-specific utility.
8
8
9 Original rlcompleter documentation:
9 Original rlcompleter documentation:
10
10
11 This requires the latest extension to the readline module (the
11 This requires the latest extension to the readline module (the
12 completes keywords, built-ins and globals in __main__; when completing
12 completes keywords, built-ins and globals in __main__; when completing
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
13 NAME.NAME..., it evaluates (!) the expression up to the last dot and
14 completes its attributes.
14 completes its attributes.
15
15
16 It's very cool to do "import string" type "string.", hit the
16 It's very cool to do "import string" type "string.", hit the
17 completion key (twice), and see the list of names defined by the
17 completion key (twice), and see the list of names defined by the
18 string module!
18 string module!
19
19
20 Tip: to use the tab key as the completion key, call
20 Tip: to use the tab key as the completion key, call
21
21
22 readline.parse_and_bind("tab: complete")
22 readline.parse_and_bind("tab: complete")
23
23
24 Notes:
24 Notes:
25
25
26 - Exceptions raised by the completer function are *ignored* (and
26 - Exceptions raised by the completer function are *ignored* (and
27 generally cause the completion to fail). This is a feature -- since
27 generally cause the completion to fail). This is a feature -- since
28 readline sets the tty device in raw (or cbreak) mode, printing a
28 readline sets the tty device in raw (or cbreak) mode, printing a
29 traceback wouldn't work well without some complicated hoopla to save,
29 traceback wouldn't work well without some complicated hoopla to save,
30 reset and restore the tty state.
30 reset and restore the tty state.
31
31
32 - The evaluation of the NAME.NAME... form may cause arbitrary
32 - The evaluation of the NAME.NAME... form may cause arbitrary
33 application defined code to be executed if an object with a
33 application defined code to be executed if an object with a
34 __getattr__ hook is found. Since it is the responsibility of the
34 __getattr__ hook is found. Since it is the responsibility of the
35 application (or the user) to enable this feature, I consider this an
35 application (or the user) to enable this feature, I consider this an
36 acceptable risk. More complicated expressions (e.g. function calls or
36 acceptable risk. More complicated expressions (e.g. function calls or
37 indexing operations) are *not* evaluated.
37 indexing operations) are *not* evaluated.
38
38
39 - GNU readline is also used by the built-in functions input() and
39 - GNU readline is also used by the built-in functions input() and
40 raw_input(), and thus these also benefit/suffer from the completer
40 raw_input(), and thus these also benefit/suffer from the completer
41 features. Clearly an interactive application can benefit by
41 features. Clearly an interactive application can benefit by
42 specifying its own completer function and using raw_input() for all
42 specifying its own completer function and using raw_input() for all
43 its input.
43 its input.
44
44
45 - When the original stdin is not a tty device, GNU readline is never
45 - When the original stdin is not a tty device, GNU readline is never
46 used, and this module (and the readline module) are silently inactive.
46 used, and this module (and the readline module) are silently inactive.
47 """
47 """
48
48
49 #*****************************************************************************
49 #*****************************************************************************
50 #
50 #
51 # Since this file is essentially a minimally modified copy of the rlcompleter
51 # Since this file is essentially a minimally modified copy of the rlcompleter
52 # module which is part of the standard Python distribution, I assume that the
52 # module which is part of the standard Python distribution, I assume that the
53 # proper procedure is to maintain its copyright as belonging to the Python
53 # proper procedure is to maintain its copyright as belonging to the Python
54 # Software Foundation (in addition to my own, for all new code).
54 # Software Foundation (in addition to my own, for all new code).
55 #
55 #
56 # Copyright (C) 2008-2010 IPython Development Team
56 # Copyright (C) 2008-2010 IPython Development Team
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
57 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
58 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #
62 #
63 #*****************************************************************************
63 #*****************************************************************************
64 from __future__ import print_function
64 from __future__ import print_function
65
65
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # Imports
67 # Imports
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69
69
70 import __builtin__
70 import __builtin__
71 import __main__
71 import __main__
72 import glob
72 import glob
73 import inspect
73 import inspect
74 import itertools
74 import itertools
75 import keyword
75 import keyword
76 import os
76 import os
77 import re
77 import re
78 import shlex
78 import shlex
79 import sys
79 import sys
80
80
81 from IPython.core.error import TryNext
81 from IPython.core.error import TryNext
82 from IPython.core.prefilter import ESC_MAGIC
82 from IPython.core.prefilter import ESC_MAGIC
83 from IPython.utils import generics, io
83 from IPython.utils import generics, io
84 from IPython.utils.frame import debugx
84 from IPython.utils.frame import debugx
85 from IPython.utils.dir2 import dir2
85 from IPython.utils.dir2 import dir2
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Globals
88 # Globals
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 # Public API
91 # Public API
92 __all__ = ['Completer','IPCompleter']
92 __all__ = ['Completer','IPCompleter']
93
93
94 if sys.platform == 'win32':
94 if sys.platform == 'win32':
95 PROTECTABLES = ' '
95 PROTECTABLES = ' '
96 else:
96 else:
97 PROTECTABLES = ' ()'
97 PROTECTABLES = ' ()'
98
98
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100 # Main functions and classes
100 # Main functions and classes
101 #-----------------------------------------------------------------------------
101 #-----------------------------------------------------------------------------
102
102
103 def protect_filename(s):
103 def protect_filename(s):
104 """Escape a string to protect certain characters."""
104 """Escape a string to protect certain characters."""
105
105
106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
106 return "".join([(ch in PROTECTABLES and '\\' + ch or ch)
107 for ch in s])
107 for ch in s])
108
108
109
109
110 def mark_dirs(matches):
110 def mark_dirs(matches):
111 """Mark directories in input list by appending '/' to their names."""
111 """Mark directories in input list by appending '/' to their names."""
112 out = []
112 out = []
113 isdir = os.path.isdir
113 isdir = os.path.isdir
114 for x in matches:
114 for x in matches:
115 if isdir(x):
115 if isdir(x):
116 out.append(x+'/')
116 out.append(x+'/')
117 else:
117 else:
118 out.append(x)
118 out.append(x)
119 return out
119 return out
120
120
121
121
122 def single_dir_expand(matches):
122 def single_dir_expand(matches):
123 "Recursively expand match lists containing a single dir."
123 "Recursively expand match lists containing a single dir."
124
124
125 if len(matches) == 1 and os.path.isdir(matches[0]):
125 if len(matches) == 1 and os.path.isdir(matches[0]):
126 # Takes care of links to directories also. Use '/'
126 # Takes care of links to directories also. Use '/'
127 # explicitly, even under Windows, so that name completions
127 # explicitly, even under Windows, so that name completions
128 # don't end up escaped.
128 # don't end up escaped.
129 d = matches[0]
129 d = matches[0]
130 if d[-1] in ['/','\\']:
130 if d[-1] in ['/','\\']:
131 d = d[:-1]
131 d = d[:-1]
132
132
133 subdirs = os.listdir(d)
133 subdirs = os.listdir(d)
134 if subdirs:
134 if subdirs:
135 matches = [ (d + '/' + p) for p in subdirs]
135 matches = [ (d + '/' + p) for p in subdirs]
136 return single_dir_expand(matches)
136 return single_dir_expand(matches)
137 else:
137 else:
138 return matches
138 return matches
139 else:
139 else:
140 return matches
140 return matches
141
141
142
142
143 class Bunch(object): pass
143 class Bunch(object): pass
144
144
145
145
146 class CompletionSplitter(object):
146 class CompletionSplitter(object):
147 """An object to split an input line in a manner similar to readline.
147 """An object to split an input line in a manner similar to readline.
148
148
149 By having our own implementation, we can expose readline-like completion in
149 By having our own implementation, we can expose readline-like completion in
150 a uniform manner to all frontends. This object only needs to be given the
150 a uniform manner to all frontends. This object only needs to be given the
151 line of text to be split and the cursor position on said line, and it
151 line of text to be split and the cursor position on said line, and it
152 returns the 'word' to be completed on at the cursor after splitting the
152 returns the 'word' to be completed on at the cursor after splitting the
153 entire line.
153 entire line.
154
154
155 What characters are used as splitting delimiters can be controlled by
155 What characters are used as splitting delimiters can be controlled by
156 setting the `delims` attribute (this is a property that internally
156 setting the `delims` attribute (this is a property that internally
157 automatically builds the necessary """
157 automatically builds the necessary """
158
158
159 # Private interface
159 # Private interface
160
160
161 # A string of delimiter characters. The default value makes sense for
161 # A string of delimiter characters. The default value makes sense for
162 # IPython's most typical usage patterns.
162 # IPython's most typical usage patterns.
163 _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
163 _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
164
164
165 # The expression (a normal string) to be compiled into a regular expression
165 # The expression (a normal string) to be compiled into a regular expression
166 # for actual splitting. We store it as an attribute mostly for ease of
166 # for actual splitting. We store it as an attribute mostly for ease of
167 # debugging, since this type of code can be so tricky to debug.
167 # debugging, since this type of code can be so tricky to debug.
168 _delim_expr = None
168 _delim_expr = None
169
169
170 # The regular expression that does the actual splitting
170 # The regular expression that does the actual splitting
171 _delim_re = None
171 _delim_re = None
172
172
173 def __init__(self, delims=None):
173 def __init__(self, delims=None):
174 delims = CompletionSplitter._delims if delims is None else delims
174 delims = CompletionSplitter._delims if delims is None else delims
175 self.set_delims(delims)
175 self.set_delims(delims)
176
176
177 def set_delims(self, delims):
177 def set_delims(self, delims):
178 """Set the delimiters for line splitting."""
178 """Set the delimiters for line splitting."""
179 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
179 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
180 self._delim_re = re.compile(expr)
180 self._delim_re = re.compile(expr)
181 self._delims = delims
181 self._delims = delims
182 self._delim_expr = expr
182 self._delim_expr = expr
183
183
184 def get_delims(self):
184 def get_delims(self):
185 """Return the string of delimiter characters."""
185 """Return the string of delimiter characters."""
186 return self._delims
186 return self._delims
187
187
188 def split_line(self, line, cursor_pos=None):
188 def split_line(self, line, cursor_pos=None):
189 """Split a line of text with a cursor at the given position.
189 """Split a line of text with a cursor at the given position.
190 """
190 """
191 l = line if cursor_pos is None else line[:cursor_pos]
191 l = line if cursor_pos is None else line[:cursor_pos]
192 return self._delim_re.split(l)[-1]
192 return self._delim_re.split(l)[-1]
193
193
194
194
195 class Completer(object):
195 class Completer(object):
196 def __init__(self, namespace=None, global_namespace=None):
196 def __init__(self, namespace=None, global_namespace=None):
197 """Create a new completer for the command line.
197 """Create a new completer for the command line.
198
198
199 Completer([namespace,global_namespace]) -> completer instance.
199 Completer([namespace,global_namespace]) -> completer instance.
200
200
201 If unspecified, the default namespace where completions are performed
201 If unspecified, the default namespace where completions are performed
202 is __main__ (technically, __main__.__dict__). Namespaces should be
202 is __main__ (technically, __main__.__dict__). Namespaces should be
203 given as dictionaries.
203 given as dictionaries.
204
204
205 An optional second namespace can be given. This allows the completer
205 An optional second namespace can be given. This allows the completer
206 to handle cases where both the local and global scopes need to be
206 to handle cases where both the local and global scopes need to be
207 distinguished.
207 distinguished.
208
208
209 Completer instances should be used as the completion mechanism of
209 Completer instances should be used as the completion mechanism of
210 readline via the set_completer() call:
210 readline via the set_completer() call:
211
211
212 readline.set_completer(Completer(my_namespace).complete)
212 readline.set_completer(Completer(my_namespace).complete)
213 """
213 """
214
214
215 # Don't bind to namespace quite yet, but flag whether the user wants a
215 # Don't bind to namespace quite yet, but flag whether the user wants a
216 # specific namespace or to use __main__.__dict__. This will allow us
216 # specific namespace or to use __main__.__dict__. This will allow us
217 # to bind to __main__.__dict__ at completion time, not now.
217 # to bind to __main__.__dict__ at completion time, not now.
218 if namespace is None:
218 if namespace is None:
219 self.use_main_ns = 1
219 self.use_main_ns = 1
220 else:
220 else:
221 self.use_main_ns = 0
221 self.use_main_ns = 0
222 self.namespace = namespace
222 self.namespace = namespace
223
223
224 # The global namespace, if given, can be bound directly
224 # The global namespace, if given, can be bound directly
225 if global_namespace is None:
225 if global_namespace is None:
226 self.global_namespace = {}
226 self.global_namespace = {}
227 else:
227 else:
228 self.global_namespace = global_namespace
228 self.global_namespace = global_namespace
229
229
230 def complete(self, text, state):
230 def complete(self, text, state):
231 """Return the next possible completion for 'text'.
231 """Return the next possible completion for 'text'.
232
232
233 This is called successively with state == 0, 1, 2, ... until it
233 This is called successively with state == 0, 1, 2, ... until it
234 returns None. The completion should begin with 'text'.
234 returns None. The completion should begin with 'text'.
235
235
236 """
236 """
237 if self.use_main_ns:
237 if self.use_main_ns:
238 self.namespace = __main__.__dict__
238 self.namespace = __main__.__dict__
239
239
240 if state == 0:
240 if state == 0:
241 if "." in text:
241 if "." in text:
242 self.matches = self.attr_matches(text)
242 self.matches = self.attr_matches(text)
243 else:
243 else:
244 self.matches = self.global_matches(text)
244 self.matches = self.global_matches(text)
245 try:
245 try:
246 return self.matches[state]
246 return self.matches[state]
247 except IndexError:
247 except IndexError:
248 return None
248 return None
249
249
250 def global_matches(self, text):
250 def global_matches(self, text):
251 """Compute matches when text is a simple name.
251 """Compute matches when text is a simple name.
252
252
253 Return a list of all keywords, built-in functions and names currently
253 Return a list of all keywords, built-in functions and names currently
254 defined in self.namespace or self.global_namespace that match.
254 defined in self.namespace or self.global_namespace that match.
255
255
256 """
256 """
257 #print 'Completer->global_matches, txt=%r' % text # dbg
257 #print 'Completer->global_matches, txt=%r' % text # dbg
258 matches = []
258 matches = []
259 match_append = matches.append
259 match_append = matches.append
260 n = len(text)
260 n = len(text)
261 for lst in [keyword.kwlist,
261 for lst in [keyword.kwlist,
262 __builtin__.__dict__.keys(),
262 __builtin__.__dict__.keys(),
263 self.namespace.keys(),
263 self.namespace.keys(),
264 self.global_namespace.keys()]:
264 self.global_namespace.keys()]:
265 for word in lst:
265 for word in lst:
266 if word[:n] == text and word != "__builtins__":
266 if word[:n] == text and word != "__builtins__":
267 match_append(word)
267 match_append(word)
268 return matches
268 return matches
269
269
270 def attr_matches(self, text):
270 def attr_matches(self, text):
271 """Compute matches when text contains a dot.
271 """Compute matches when text contains a dot.
272
272
273 Assuming the text is of the form NAME.NAME....[NAME], and is
273 Assuming the text is of the form NAME.NAME....[NAME], and is
274 evaluatable in self.namespace or self.global_namespace, it will be
274 evaluatable in self.namespace or self.global_namespace, it will be
275 evaluated and its attributes (as revealed by dir()) are used as
275 evaluated and its attributes (as revealed by dir()) are used as
276 possible completions. (For class instances, class members are are
276 possible completions. (For class instances, class members are are
277 also considered.)
277 also considered.)
278
278
279 WARNING: this can still invoke arbitrary C code, if an object
279 WARNING: this can still invoke arbitrary C code, if an object
280 with a __getattr__ hook is evaluated.
280 with a __getattr__ hook is evaluated.
281
281
282 """
282 """
283
283
284 #print 'Completer->attr_matches, txt=%r' % text # dbg
284 #print 'Completer->attr_matches, txt=%r' % text # dbg
285 # Another option, seems to work great. Catches things like ''.<tab>
285 # Another option, seems to work great. Catches things like ''.<tab>
286 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
286 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
287
287
288 if not m:
288 if not m:
289 return []
289 return []
290
290
291 expr, attr = m.group(1, 3)
291 expr, attr = m.group(1, 3)
292 try:
292 try:
293 obj = eval(expr, self.namespace)
293 obj = eval(expr, self.namespace)
294 except:
294 except:
295 try:
295 try:
296 obj = eval(expr, self.global_namespace)
296 obj = eval(expr, self.global_namespace)
297 except:
297 except:
298 return []
298 return []
299
299
300 words = dir2(obj)
300 words = dir2(obj)
301
301
302 try:
302 try:
303 words = generics.complete_object(obj, words)
303 words = generics.complete_object(obj, words)
304 except TryNext:
304 except TryNext:
305 pass
305 pass
306 # Build match list to return
306 # Build match list to return
307 n = len(attr)
307 n = len(attr)
308 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
308 res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ]
309 return res
309 return res
310
310
311
311
312 class IPCompleter(Completer):
312 class IPCompleter(Completer):
313 """Extension of the completer class with IPython-specific features"""
313 """Extension of the completer class with IPython-specific features"""
314
314
315 def __init__(self, shell, namespace=None, global_namespace=None,
315 def __init__(self, shell, namespace=None, global_namespace=None,
316 omit__names=0, alias_table=None, use_readline=True):
316 omit__names=0, alias_table=None, use_readline=True):
317 """IPCompleter() -> completer
317 """IPCompleter() -> completer
318
318
319 Return a completer object suitable for use by the readline library
319 Return a completer object suitable for use by the readline library
320 via readline.set_completer().
320 via readline.set_completer().
321
321
322 Inputs:
322 Inputs:
323
323
324 - shell: a pointer to the ipython shell itself. This is needed
324 - shell: a pointer to the ipython shell itself. This is needed
325 because this completer knows about magic functions, and those can
325 because this completer knows about magic functions, and those can
326 only be accessed via the ipython instance.
326 only be accessed via the ipython instance.
327
327
328 - namespace: an optional dict where completions are performed.
328 - namespace: an optional dict where completions are performed.
329
329
330 - global_namespace: secondary optional dict for completions, to
330 - global_namespace: secondary optional dict for completions, to
331 handle cases (such as IPython embedded inside functions) where
331 handle cases (such as IPython embedded inside functions) where
332 both Python scopes are visible.
332 both Python scopes are visible.
333
333
334 - The optional omit__names parameter sets the completer to omit the
334 - The optional omit__names parameter sets the completer to omit the
335 'magic' names (__magicname__) for python objects unless the text
335 'magic' names (__magicname__) for python objects unless the text
336 to be completed explicitly starts with one or more underscores.
336 to be completed explicitly starts with one or more underscores.
337
337
338 - If alias_table is supplied, it should be a dictionary of aliases
338 - If alias_table is supplied, it should be a dictionary of aliases
339 to complete.
339 to complete.
340
340
341 use_readline : bool, optional
341 use_readline : bool, optional
342 If true, use the readline library. This completer can still function
342 If true, use the readline library. This completer can still function
343 without readline, though in that case callers must provide some extra
343 without readline, though in that case callers must provide some extra
344 information on each call about the current line."""
344 information on each call about the current line."""
345
345
346 Completer.__init__(self, namespace, global_namespace)
346 Completer.__init__(self, namespace, global_namespace)
347
347
348 self.magic_escape = ESC_MAGIC
348 self.magic_escape = ESC_MAGIC
349
350 self.splitter = CompletionSplitter()
349 self.splitter = CompletionSplitter()
351
350
352 # Readline-dependent code
351 # Readline configuration, only used by the rlcompleter method.
353 self.use_readline = use_readline
354 if use_readline:
352 if use_readline:
353 # We store the right version of readline so that later code
355 import IPython.utils.rlineimpl as readline
354 import IPython.utils.rlineimpl as readline
356 self.readline = readline
355 self.readline = readline
357 delims = self.readline.get_completer_delims()
356 else:
358 delims = delims.replace(self.magic_escape,'')
357 self.readline = None
359 self.readline.set_completer_delims(delims)
360 self.get_line_buffer = self.readline.get_line_buffer
361 self.get_endidx = self.readline.get_endidx
362 # /end readline-dependent code
363
358
364 # List where completion matches will be stored
359 # List where completion matches will be stored
365 self.matches = []
360 self.matches = []
366 self.omit__names = omit__names
361 self.omit__names = omit__names
367 self.merge_completions = shell.readline_merge_completions
362 self.merge_completions = shell.readline_merge_completions
368 self.shell = shell.shell
363 self.shell = shell.shell
369 if alias_table is None:
364 if alias_table is None:
370 alias_table = {}
365 alias_table = {}
371 self.alias_table = alias_table
366 self.alias_table = alias_table
372 # Regexp to split filenames with spaces in them
367 # Regexp to split filenames with spaces in them
373 self.space_name_re = re.compile(r'([^\\] )')
368 self.space_name_re = re.compile(r'([^\\] )')
374 # Hold a local ref. to glob.glob for speed
369 # Hold a local ref. to glob.glob for speed
375 self.glob = glob.glob
370 self.glob = glob.glob
376
371
377 # Determine if we are running on 'dumb' terminals, like (X)Emacs
372 # Determine if we are running on 'dumb' terminals, like (X)Emacs
378 # buffers, to avoid completion problems.
373 # buffers, to avoid completion problems.
379 term = os.environ.get('TERM','xterm')
374 term = os.environ.get('TERM','xterm')
380 self.dumb_terminal = term in ['dumb','emacs']
375 self.dumb_terminal = term in ['dumb','emacs']
381
376
382 # Special handling of backslashes needed in win32 platforms
377 # Special handling of backslashes needed in win32 platforms
383 if sys.platform == "win32":
378 if sys.platform == "win32":
384 self.clean_glob = self._clean_glob_win32
379 self.clean_glob = self._clean_glob_win32
385 else:
380 else:
386 self.clean_glob = self._clean_glob
381 self.clean_glob = self._clean_glob
387
382
388 # All active matcher routines for completion
383 # All active matcher routines for completion
389 self.matchers = [self.python_matches,
384 self.matchers = [self.python_matches,
390 self.file_matches,
385 self.file_matches,
391 self.magic_matches,
386 self.magic_matches,
392 self.alias_matches,
387 self.alias_matches,
393 self.python_func_kw_matches,
388 self.python_func_kw_matches,
394 ]
389 ]
395
390
396 # Code contributed by Alex Schmolck, for ipython/emacs integration
391 # Code contributed by Alex Schmolck, for ipython/emacs integration
397 def all_completions(self, text):
392 def all_completions(self, text):
398 """Return all possible completions for the benefit of emacs."""
393 """Return all possible completions for the benefit of emacs."""
399
394
400 completions = []
395 completions = []
401 comp_append = completions.append
396 comp_append = completions.append
402 try:
397 try:
403 for i in xrange(sys.maxint):
398 for i in xrange(sys.maxint):
404 res = self.complete(text, i, text)
399 res = self.complete(text, i, text)
405 if not res:
400 if not res:
406 break
401 break
407 comp_append(res)
402 comp_append(res)
408 #XXX workaround for ``notDefined.<tab>``
403 #XXX workaround for ``notDefined.<tab>``
409 except NameError:
404 except NameError:
410 pass
405 pass
411 return completions
406 return completions
412 # /end Alex Schmolck code.
407 # /end Alex Schmolck code.
413
408
414 def _clean_glob(self,text):
409 def _clean_glob(self,text):
415 return self.glob("%s*" % text)
410 return self.glob("%s*" % text)
416
411
417 def _clean_glob_win32(self,text):
412 def _clean_glob_win32(self,text):
418 return [f.replace("\\","/")
413 return [f.replace("\\","/")
419 for f in self.glob("%s*" % text)]
414 for f in self.glob("%s*" % text)]
420
415
421 def file_matches(self, text):
416 def file_matches(self, text):
422 """Match filenames, expanding ~USER type strings.
417 """Match filenames, expanding ~USER type strings.
423
418
424 Most of the seemingly convoluted logic in this completer is an
419 Most of the seemingly convoluted logic in this completer is an
425 attempt to handle filenames with spaces in them. And yet it's not
420 attempt to handle filenames with spaces in them. And yet it's not
426 quite perfect, because Python's readline doesn't expose all of the
421 quite perfect, because Python's readline doesn't expose all of the
427 GNU readline details needed for this to be done correctly.
422 GNU readline details needed for this to be done correctly.
428
423
429 For a filename with a space in it, the printed completions will be
424 For a filename with a space in it, the printed completions will be
430 only the parts after what's already been typed (instead of the
425 only the parts after what's already been typed (instead of the
431 full completions, as is normally done). I don't think with the
426 full completions, as is normally done). I don't think with the
432 current (as of Python 2.3) Python readline it's possible to do
427 current (as of Python 2.3) Python readline it's possible to do
433 better."""
428 better."""
434
429
435 #io.rprint('Completer->file_matches: <%s>' % text) # dbg
430 #io.rprint('Completer->file_matches: <%s>' % text) # dbg
436
431
437 # chars that require escaping with backslash - i.e. chars
432 # chars that require escaping with backslash - i.e. chars
438 # that readline treats incorrectly as delimiters, but we
433 # that readline treats incorrectly as delimiters, but we
439 # don't want to treat as delimiters in filename matching
434 # don't want to treat as delimiters in filename matching
440 # when escaped with backslash
435 # when escaped with backslash
441 if text.startswith('!'):
436 if text.startswith('!'):
442 text = text[1:]
437 text = text[1:]
443 text_prefix = '!'
438 text_prefix = '!'
444 else:
439 else:
445 text_prefix = ''
440 text_prefix = ''
446
441
447 lbuf = self.lbuf
442 text_until_cursor = self.text_until_cursor
448 open_quotes = 0 # track strings with open quotes
443 open_quotes = 0 # track strings with open quotes
449 try:
444 try:
450 lsplit = shlex.split(lbuf)[-1]
445 lsplit = shlex.split(text_until_cursor)[-1]
451 except ValueError:
446 except ValueError:
452 # typically an unmatched ", or backslash without escaped char.
447 # typically an unmatched ", or backslash without escaped char.
453 if lbuf.count('"')==1:
448 if text_until_cursor.count('"')==1:
454 open_quotes = 1
449 open_quotes = 1
455 lsplit = lbuf.split('"')[-1]
450 lsplit = text_until_cursor.split('"')[-1]
456 elif lbuf.count("'")==1:
451 elif text_until_cursor.count("'")==1:
457 open_quotes = 1
452 open_quotes = 1
458 lsplit = lbuf.split("'")[-1]
453 lsplit = text_until_cursor.split("'")[-1]
459 else:
454 else:
460 return []
455 return []
461 except IndexError:
456 except IndexError:
462 # tab pressed on empty line
457 # tab pressed on empty line
463 lsplit = ""
458 lsplit = ""
464
459
465 if not open_quotes and lsplit != protect_filename(lsplit):
460 if not open_quotes and lsplit != protect_filename(lsplit):
466 # if protectables are found, do matching on the whole escaped
461 # if protectables are found, do matching on the whole escaped
467 # name
462 # name
468 has_protectables = 1
463 has_protectables = 1
469 text0,text = text,lsplit
464 text0,text = text,lsplit
470 else:
465 else:
471 has_protectables = 0
466 has_protectables = 0
472 text = os.path.expanduser(text)
467 text = os.path.expanduser(text)
473
468
474 if text == "":
469 if text == "":
475 return [text_prefix + protect_filename(f) for f in self.glob("*")]
470 return [text_prefix + protect_filename(f) for f in self.glob("*")]
476
471
477 m0 = self.clean_glob(text.replace('\\',''))
472 m0 = self.clean_glob(text.replace('\\',''))
478 if has_protectables:
473 if has_protectables:
479 # If we had protectables, we need to revert our changes to the
474 # If we had protectables, we need to revert our changes to the
480 # beginning of filename so that we don't double-write the part
475 # beginning of filename so that we don't double-write the part
481 # of the filename we have so far
476 # of the filename we have so far
482 len_lsplit = len(lsplit)
477 len_lsplit = len(lsplit)
483 matches = [text_prefix + text0 +
478 matches = [text_prefix + text0 +
484 protect_filename(f[len_lsplit:]) for f in m0]
479 protect_filename(f[len_lsplit:]) for f in m0]
485 else:
480 else:
486 if open_quotes:
481 if open_quotes:
487 # if we have a string with an open quote, we don't need to
482 # if we have a string with an open quote, we don't need to
488 # protect the names at all (and we _shouldn't_, as it
483 # protect the names at all (and we _shouldn't_, as it
489 # would cause bugs when the filesystem call is made).
484 # would cause bugs when the filesystem call is made).
490 matches = m0
485 matches = m0
491 else:
486 else:
492 matches = [text_prefix +
487 matches = [text_prefix +
493 protect_filename(f) for f in m0]
488 protect_filename(f) for f in m0]
494
489
495 #io.rprint('mm', matches) # dbg
490 #io.rprint('mm', matches) # dbg
496 return mark_dirs(matches)
491 return mark_dirs(matches)
497
492
498 def magic_matches(self, text):
493 def magic_matches(self, text):
499 """Match magics"""
494 """Match magics"""
500 #print 'Completer->magic_matches:',text,'lb',self.lbuf # dbg
495 #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg
501 # Get all shell magics now rather than statically, so magics loaded at
496 # Get all shell magics now rather than statically, so magics loaded at
502 # runtime show up too
497 # runtime show up too
503 magics = self.shell.lsmagic()
498 magics = self.shell.lsmagic()
504 pre = self.magic_escape
499 pre = self.magic_escape
505 baretext = text.lstrip(pre)
500 baretext = text.lstrip(pre)
506 return [ pre+m for m in magics if m.startswith(baretext)]
501 return [ pre+m for m in magics if m.startswith(baretext)]
507
502
508 def alias_matches(self, text):
503 def alias_matches(self, text):
509 """Match internal system aliases"""
504 """Match internal system aliases"""
510 #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg
505 #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg
511
506
512 # if we are not in the first 'item', alias matching
507 # if we are not in the first 'item', alias matching
513 # doesn't make sense - unless we are starting with 'sudo' command.
508 # doesn't make sense - unless we are starting with 'sudo' command.
514 if ' ' in self.lbuf.lstrip() and \
509 main_text = self.text_until_cursor.lstrip()
515 not self.lbuf.lstrip().startswith('sudo'):
510 if ' ' in main_text and not main_text.startswith('sudo'):
516 return []
511 return []
517 text = os.path.expanduser(text)
512 text = os.path.expanduser(text)
518 aliases = self.alias_table.keys()
513 aliases = self.alias_table.keys()
519 if text == "":
514 if text == '':
520 return aliases
515 return aliases
521 else:
516 else:
522 return [alias for alias in aliases if alias.startswith(text)]
517 return [a for a in aliases if a.startswith(text)]
523
518
524 def python_matches(self,text):
519 def python_matches(self,text):
525 """Match attributes or global python names"""
520 """Match attributes or global python names"""
526
521
527 #print 'Completer->python_matches, txt=%r' % text # dbg
522 #print 'Completer->python_matches, txt=%r' % text # dbg
528 if "." in text:
523 if "." in text:
529 try:
524 try:
530 matches = self.attr_matches(text)
525 matches = self.attr_matches(text)
531 if text.endswith('.') and self.omit__names:
526 if text.endswith('.') and self.omit__names:
532 if self.omit__names == 1:
527 if self.omit__names == 1:
533 # true if txt is _not_ a __ name, false otherwise:
528 # true if txt is _not_ a __ name, false otherwise:
534 no__name = (lambda txt:
529 no__name = (lambda txt:
535 re.match(r'.*\.__.*?__',txt) is None)
530 re.match(r'.*\.__.*?__',txt) is None)
536 else:
531 else:
537 # true if txt is _not_ a _ name, false otherwise:
532 # true if txt is _not_ a _ name, false otherwise:
538 no__name = (lambda txt:
533 no__name = (lambda txt:
539 re.match(r'.*\._.*?',txt) is None)
534 re.match(r'.*\._.*?',txt) is None)
540 matches = filter(no__name, matches)
535 matches = filter(no__name, matches)
541 except NameError:
536 except NameError:
542 # catches <undefined attributes>.<tab>
537 # catches <undefined attributes>.<tab>
543 matches = []
538 matches = []
544 else:
539 else:
545 matches = self.global_matches(text)
540 matches = self.global_matches(text)
546
541
547 return matches
542 return matches
548
543
549 def _default_arguments(self, obj):
544 def _default_arguments(self, obj):
550 """Return the list of default arguments of obj if it is callable,
545 """Return the list of default arguments of obj if it is callable,
551 or empty list otherwise."""
546 or empty list otherwise."""
552
547
553 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
548 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
554 # for classes, check for __init__,__new__
549 # for classes, check for __init__,__new__
555 if inspect.isclass(obj):
550 if inspect.isclass(obj):
556 obj = (getattr(obj,'__init__',None) or
551 obj = (getattr(obj,'__init__',None) or
557 getattr(obj,'__new__',None))
552 getattr(obj,'__new__',None))
558 # for all others, check if they are __call__able
553 # for all others, check if they are __call__able
559 elif hasattr(obj, '__call__'):
554 elif hasattr(obj, '__call__'):
560 obj = obj.__call__
555 obj = obj.__call__
561 # XXX: is there a way to handle the builtins ?
556 # XXX: is there a way to handle the builtins ?
562 try:
557 try:
563 args,_,_1,defaults = inspect.getargspec(obj)
558 args,_,_1,defaults = inspect.getargspec(obj)
564 if defaults:
559 if defaults:
565 return args[-len(defaults):]
560 return args[-len(defaults):]
566 except TypeError: pass
561 except TypeError: pass
567 return []
562 return []
568
563
569 def python_func_kw_matches(self,text):
564 def python_func_kw_matches(self,text):
570 """Match named parameters (kwargs) of the last open function"""
565 """Match named parameters (kwargs) of the last open function"""
571
566
572 if "." in text: # a parameter cannot be dotted
567 if "." in text: # a parameter cannot be dotted
573 return []
568 return []
574 try: regexp = self.__funcParamsRegex
569 try: regexp = self.__funcParamsRegex
575 except AttributeError:
570 except AttributeError:
576 regexp = self.__funcParamsRegex = re.compile(r'''
571 regexp = self.__funcParamsRegex = re.compile(r'''
577 '.*?' | # single quoted strings or
572 '.*?' | # single quoted strings or
578 ".*?" | # double quoted strings or
573 ".*?" | # double quoted strings or
579 \w+ | # identifier
574 \w+ | # identifier
580 \S # other characters
575 \S # other characters
581 ''', re.VERBOSE | re.DOTALL)
576 ''', re.VERBOSE | re.DOTALL)
582 # 1. find the nearest identifier that comes before an unclosed
577 # 1. find the nearest identifier that comes before an unclosed
583 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
578 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
584 tokens = regexp.findall(self.get_line_buffer())
579 tokens = regexp.findall(self.line_buffer)
585 tokens.reverse()
580 tokens.reverse()
586 iterTokens = iter(tokens); openPar = 0
581 iterTokens = iter(tokens); openPar = 0
587 for token in iterTokens:
582 for token in iterTokens:
588 if token == ')':
583 if token == ')':
589 openPar -= 1
584 openPar -= 1
590 elif token == '(':
585 elif token == '(':
591 openPar += 1
586 openPar += 1
592 if openPar > 0:
587 if openPar > 0:
593 # found the last unclosed parenthesis
588 # found the last unclosed parenthesis
594 break
589 break
595 else:
590 else:
596 return []
591 return []
597 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
592 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
598 ids = []
593 ids = []
599 isId = re.compile(r'\w+$').match
594 isId = re.compile(r'\w+$').match
600 while True:
595 while True:
601 try:
596 try:
602 ids.append(iterTokens.next())
597 ids.append(iterTokens.next())
603 if not isId(ids[-1]):
598 if not isId(ids[-1]):
604 ids.pop(); break
599 ids.pop(); break
605 if not iterTokens.next() == '.':
600 if not iterTokens.next() == '.':
606 break
601 break
607 except StopIteration:
602 except StopIteration:
608 break
603 break
609 # lookup the candidate callable matches either using global_matches
604 # lookup the candidate callable matches either using global_matches
610 # or attr_matches for dotted names
605 # or attr_matches for dotted names
611 if len(ids) == 1:
606 if len(ids) == 1:
612 callableMatches = self.global_matches(ids[0])
607 callableMatches = self.global_matches(ids[0])
613 else:
608 else:
614 callableMatches = self.attr_matches('.'.join(ids[::-1]))
609 callableMatches = self.attr_matches('.'.join(ids[::-1]))
615 argMatches = []
610 argMatches = []
616 for callableMatch in callableMatches:
611 for callableMatch in callableMatches:
617 try:
612 try:
618 namedArgs = self._default_arguments(eval(callableMatch,
613 namedArgs = self._default_arguments(eval(callableMatch,
619 self.namespace))
614 self.namespace))
620 except:
615 except:
621 continue
616 continue
622 for namedArg in namedArgs:
617 for namedArg in namedArgs:
623 if namedArg.startswith(text):
618 if namedArg.startswith(text):
624 argMatches.append("%s=" %namedArg)
619 argMatches.append("%s=" %namedArg)
625 return argMatches
620 return argMatches
626
621
627 def dispatch_custom_completer(self,text):
622 def dispatch_custom_completer(self,text):
628 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
623 #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg
629 line = self.full_lbuf
624 line = self.line_buffer
630 if not line.strip():
625 if not line.strip():
631 return None
626 return None
632
627
633 event = Bunch()
628 event = Bunch()
634 event.line = line
629 event.line = line
635 event.symbol = text
630 event.symbol = text
636 cmd = line.split(None,1)[0]
631 cmd = line.split(None,1)[0]
637 event.command = cmd
632 event.command = cmd
638 #print "\ncustom:{%s]\n" % event # dbg
633 #print "\ncustom:{%s]\n" % event # dbg
639
634
640 # for foo etc, try also to find completer for %foo
635 # for foo etc, try also to find completer for %foo
641 if not cmd.startswith(self.magic_escape):
636 if not cmd.startswith(self.magic_escape):
642 try_magic = self.custom_completers.s_matches(
637 try_magic = self.custom_completers.s_matches(
643 self.magic_escape + cmd)
638 self.magic_escape + cmd)
644 else:
639 else:
645 try_magic = []
640 try_magic = []
646
641
647 for c in itertools.chain(self.custom_completers.s_matches(cmd),
642 for c in itertools.chain(self.custom_completers.s_matches(cmd),
648 try_magic,
643 try_magic,
649 self.custom_completers.flat_matches(self.lbuf)):
644 self.custom_completers.flat_matches(self.text_until_cursor)):
650 #print "try",c # dbg
645 #print "try",c # dbg
651 try:
646 try:
652 res = c(event)
647 res = c(event)
653 # first, try case sensitive match
648 # first, try case sensitive match
654 withcase = [r for r in res if r.startswith(text)]
649 withcase = [r for r in res if r.startswith(text)]
655 if withcase:
650 if withcase:
656 return withcase
651 return withcase
657 # if none, then case insensitive ones are ok too
652 # if none, then case insensitive ones are ok too
658 text_low = text.lower()
653 text_low = text.lower()
659 return [r for r in res if r.lower().startswith(text_low)]
654 return [r for r in res if r.lower().startswith(text_low)]
660 except TryNext:
655 except TryNext:
661 pass
656 pass
662
657
663 return None
658 return None
664
659
665 def complete(self, text=None, line_buffer=None, cursor_pos=None):
660 def complete(self, text=None, line_buffer=None, cursor_pos=None):
666 """Return the state-th possible completion for 'text'.
661 """Return the state-th possible completion for 'text'.
667
662
668 This is called successively with state == 0, 1, 2, ... until it
663 This is called successively with state == 0, 1, 2, ... until it
669 returns None. The completion should begin with 'text'.
664 returns None. The completion should begin with 'text'.
670
665
671 Note that both the text and the line_buffer are optional, but at least
666 Note that both the text and the line_buffer are optional, but at least
672 one of them must be given.
667 one of them must be given.
673
668
674 Parameters
669 Parameters
675 ----------
670 ----------
676 text : string, optional
671 text : string, optional
677 Text to perform the completion on. If not given, the line buffer
672 Text to perform the completion on. If not given, the line buffer
678 is split using the instance's CompletionSplitter object.
673 is split using the instance's CompletionSplitter object.
679
674
680 line_buffer : string, optional
675 line_buffer : string, optional
681 If not given, the completer attempts to obtain the current line
676 If not given, the completer attempts to obtain the current line
682 buffer via readline. This keyword allows clients which are
677 buffer via readline. This keyword allows clients which are
683 requesting for text completions in non-readline contexts to inform
678 requesting for text completions in non-readline contexts to inform
684 the completer of the entire text.
679 the completer of the entire text.
685
680
686 cursor_pos : int, optional
681 cursor_pos : int, optional
687 Index of the cursor in the full line buffer. Should be provided by
682 Index of the cursor in the full line buffer. Should be provided by
688 remote frontends where kernel has no access to frontend state.
683 remote frontends where kernel has no access to frontend state.
689 """
684 """
690 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
685 #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
691
686
692 # if the cursor position isn't given, the only sane assumption we can
687 # if the cursor position isn't given, the only sane assumption we can
693 # make is that it's at the end of the line (the common case)
688 # make is that it's at the end of the line (the common case)
694 if cursor_pos is None:
689 if cursor_pos is None:
695 cursor_pos = len(line_buffer) if text is None else len(text)
690 cursor_pos = len(line_buffer) if text is None else len(text)
696
691
697 # if text is either None or an empty string, rely on the line buffer
692 # if text is either None or an empty string, rely on the line buffer
698 if not text:
693 if not text:
699 text = self.splitter.split_line(line_buffer, cursor_pos)
694 text = self.splitter.split_line(line_buffer, cursor_pos)
700
695
701 # If no line buffer is given, assume the input text is all there was
696 # If no line buffer is given, assume the input text is all there was
702 if line_buffer is None:
697 if line_buffer is None:
703 line_buffer = text
698 line_buffer = text
704
699
705 magic_escape = self.magic_escape
700 magic_escape = self.magic_escape
706 self.full_lbuf = line_buffer
701 self.line_buffer = line_buffer
707 self.lbuf = self.full_lbuf[:cursor_pos]
702 self.text_until_cursor = self.line_buffer[:cursor_pos]
708 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
703 #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg
709
704
710 # Start with a clean slate of completions
705 # Start with a clean slate of completions
711 self.matches[:] = []
706 self.matches[:] = []
712 custom_res = self.dispatch_custom_completer(text)
707 custom_res = self.dispatch_custom_completer(text)
713 if custom_res is not None:
708 if custom_res is not None:
714 # did custom completers produce something?
709 # did custom completers produce something?
715 self.matches = custom_res
710 self.matches = custom_res
716 else:
711 else:
717 # Extend the list of completions with the results of each
712 # Extend the list of completions with the results of each
718 # matcher, so we return results to the user from all
713 # matcher, so we return results to the user from all
719 # namespaces.
714 # namespaces.
720 if self.merge_completions:
715 if self.merge_completions:
721 self.matches = []
716 self.matches = []
722 for matcher in self.matchers:
717 for matcher in self.matchers:
723 self.matches.extend(matcher(text))
718 self.matches.extend(matcher(text))
724 else:
719 else:
725 for matcher in self.matchers:
720 for matcher in self.matchers:
726 self.matches = matcher(text)
721 self.matches = matcher(text)
727 if self.matches:
722 if self.matches:
728 break
723 break
729 # FIXME: we should extend our api to return a dict with completions for
724 # FIXME: we should extend our api to return a dict with completions for
730 # different types of objects. The rlcomplete() method could then
725 # different types of objects. The rlcomplete() method could then
731 # simply collapse the dict into a list for readline, but we'd have
726 # simply collapse the dict into a list for readline, but we'd have
732 # richer completion semantics in other evironments.
727 # richer completion semantics in other evironments.
733 self.matches = sorted(set(self.matches))
728 self.matches = sorted(set(self.matches))
734 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
729 #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg
735 return text, self.matches
730 return text, self.matches
736
731
737 def rlcomplete(self, text, state):
732 def rlcomplete(self, text, state):
738 """Return the state-th possible completion for 'text'.
733 """Return the state-th possible completion for 'text'.
739
734
740 This is called successively with state == 0, 1, 2, ... until it
735 This is called successively with state == 0, 1, 2, ... until it
741 returns None. The completion should begin with 'text'.
736 returns None. The completion should begin with 'text'.
742
737
743 Parameters
738 Parameters
744 ----------
739 ----------
745 text : string
740 text : string
746 Text to perform the completion on.
741 Text to perform the completion on.
747
742
748 state : int
743 state : int
749 Counter used by readline.
744 Counter used by readline.
750 """
745 """
751 if state==0:
746 if state==0:
752
747
753 self.full_lbuf = line_buffer = self.get_line_buffer()
748 self.line_buffer = line_buffer = self.readline.get_line_buffer()
754 cursor_pos = self.get_endidx()
749 cursor_pos = self.readline.get_endidx()
755
750
756 #io.rprint("\nRLCOMPLETE: %r %r %r" %
751 #io.rprint("\nRLCOMPLETE: %r %r %r" %
757 # (text, line_buffer, cursor_pos) ) # dbg
752 # (text, line_buffer, cursor_pos) ) # dbg
758
753
759 # if there is only a tab on a line with only whitespace, instead of
754 # if there is only a tab on a line with only whitespace, instead of
760 # the mostly useless 'do you want to see all million completions'
755 # the mostly useless 'do you want to see all million completions'
761 # message, just do the right thing and give the user his tab!
756 # message, just do the right thing and give the user his tab!
762 # Incidentally, this enables pasting of tabbed text from an editor
757 # Incidentally, this enables pasting of tabbed text from an editor
763 # (as long as autoindent is off).
758 # (as long as autoindent is off).
764
759
765 # It should be noted that at least pyreadline still shows file
760 # It should be noted that at least pyreadline still shows file
766 # completions - is there a way around it?
761 # completions - is there a way around it?
767
762
768 # don't apply this on 'dumb' terminals, such as emacs buffers, so
763 # don't apply this on 'dumb' terminals, such as emacs buffers, so
769 # we don't interfere with their own tab-completion mechanism.
764 # we don't interfere with their own tab-completion mechanism.
770 if not (self.dumb_terminal or line_buffer.strip()):
765 if not (self.dumb_terminal or line_buffer.strip()):
771 self.readline.insert_text('\t')
766 self.readline.insert_text('\t')
772 sys.stdout.flush()
767 sys.stdout.flush()
773 return None
768 return None
774
769
775 # This method computes the self.matches array
770 # This method computes the self.matches array
776 self.complete(text, line_buffer, cursor_pos)
771 self.complete(text, line_buffer, cursor_pos)
777
772
778 # Debug version, since readline silences all exceptions making it
773 # Debug version, since readline silences all exceptions making it
779 # impossible to debug any problem in the above code
774 # impossible to debug any problem in the above code
780
775
781 ## try:
776 ## try:
782 ## self.complete(text, line_buffer, cursor_pos)
777 ## self.complete(text, line_buffer, cursor_pos)
783 ## except:
778 ## except:
784 ## import traceback; traceback.print_exc()
779 ## import traceback; traceback.print_exc()
785
780
786 try:
781 try:
787 return self.matches[state]
782 return self.matches[state]
788 except IndexError:
783 except IndexError:
789 return None
784 return None
@@ -1,2374 +1,2390 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.inputlist import InputList
48 from IPython.core.inputlist import InputList
49 from IPython.core.logger import Logger
49 from IPython.core.logger import Logger
50 from IPython.core.magic import Magic
50 from IPython.core.magic import Magic
51 from IPython.core.payload import PayloadManager
51 from IPython.core.payload import PayloadManager
52 from IPython.core.plugin import PluginManager
52 from IPython.core.plugin import PluginManager
53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.external.Itpl import ItplNS
54 from IPython.external.Itpl import ItplNS
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils import io
56 from IPython.utils import io
57 from IPython.utils import pickleshare
57 from IPython.utils import pickleshare
58 from IPython.utils.doctestreload import doctest_reload
58 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.io import ask_yes_no, rprint
59 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.ipstruct import Struct
60 from IPython.utils.ipstruct import Struct
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import system, getoutput
62 from IPython.utils.process import system, getoutput
63 from IPython.utils.strdispatch import StrDispatch
63 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.syspathcontext import prepended_to_syspath
64 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.text import num_ini_spaces, format_screen
65 from IPython.utils.text import num_ini_spaces, format_screen
66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 List, Unicode, Instance, Type)
67 List, Unicode, Instance, Type)
68 from IPython.utils.warn import warn, error, fatal
68 from IPython.utils.warn import warn, error, fatal
69 import IPython.core.hooks
69 import IPython.core.hooks
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Globals
72 # Globals
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 # compiled regexps for autoindent management
75 # compiled regexps for autoindent management
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77
77
78 #-----------------------------------------------------------------------------
78 #-----------------------------------------------------------------------------
79 # Utilities
79 # Utilities
80 #-----------------------------------------------------------------------------
80 #-----------------------------------------------------------------------------
81
81
82 # store the builtin raw_input globally, and use this always, in case user code
82 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
83 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
84 raw_input_original = raw_input
85
85
86 def softspace(file, newvalue):
86 def softspace(file, newvalue):
87 """Copied from code.py, to remove the dependency"""
87 """Copied from code.py, to remove the dependency"""
88
88
89 oldvalue = 0
89 oldvalue = 0
90 try:
90 try:
91 oldvalue = file.softspace
91 oldvalue = file.softspace
92 except AttributeError:
92 except AttributeError:
93 pass
93 pass
94 try:
94 try:
95 file.softspace = newvalue
95 file.softspace = newvalue
96 except (AttributeError, TypeError):
96 except (AttributeError, TypeError):
97 # "attribute-less object" or "read-only attributes"
97 # "attribute-less object" or "read-only attributes"
98 pass
98 pass
99 return oldvalue
99 return oldvalue
100
100
101
101
102 def no_op(*a, **kw): pass
102 def no_op(*a, **kw): pass
103
103
104 class SpaceInInput(exceptions.Exception): pass
104 class SpaceInInput(exceptions.Exception): pass
105
105
106 class Bunch: pass
106 class Bunch: pass
107
107
108
108
109 def get_default_colors():
109 def get_default_colors():
110 if sys.platform=='darwin':
110 if sys.platform=='darwin':
111 return "LightBG"
111 return "LightBG"
112 elif os.name=='nt':
112 elif os.name=='nt':
113 return 'Linux'
113 return 'Linux'
114 else:
114 else:
115 return 'Linux'
115 return 'Linux'
116
116
117
117
118 class SeparateStr(Str):
118 class SeparateStr(Str):
119 """A Str subclass to validate separate_in, separate_out, etc.
119 """A Str subclass to validate separate_in, separate_out, etc.
120
120
121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 """
122 """
123
123
124 def validate(self, obj, value):
124 def validate(self, obj, value):
125 if value == '0': value = ''
125 if value == '0': value = ''
126 value = value.replace('\\n','\n')
126 value = value.replace('\\n','\n')
127 return super(SeparateStr, self).validate(obj, value)
127 return super(SeparateStr, self).validate(obj, value)
128
128
129 class MultipleInstanceError(Exception):
129 class MultipleInstanceError(Exception):
130 pass
130 pass
131
131
132
132
133 #-----------------------------------------------------------------------------
133 #-----------------------------------------------------------------------------
134 # Main IPython class
134 # Main IPython class
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136
136
137
137
138 class InteractiveShell(Configurable, Magic):
138 class InteractiveShell(Configurable, Magic):
139 """An enhanced, interactive shell for Python."""
139 """An enhanced, interactive shell for Python."""
140
140
141 _instance = None
141 _instance = None
142 autocall = Enum((0,1,2), default_value=1, config=True)
142 autocall = Enum((0,1,2), default_value=1, config=True)
143 # TODO: remove all autoindent logic and put into frontends.
143 # TODO: remove all autoindent logic and put into frontends.
144 # We can't do this yet because even runlines uses the autoindent.
144 # We can't do this yet because even runlines uses the autoindent.
145 autoindent = CBool(True, config=True)
145 autoindent = CBool(True, config=True)
146 automagic = CBool(True, config=True)
146 automagic = CBool(True, config=True)
147 cache_size = Int(1000, config=True)
147 cache_size = Int(1000, config=True)
148 color_info = CBool(True, config=True)
148 color_info = CBool(True, config=True)
149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 default_value=get_default_colors(), config=True)
150 default_value=get_default_colors(), config=True)
151 debug = CBool(False, config=True)
151 debug = CBool(False, config=True)
152 deep_reload = CBool(False, config=True)
152 deep_reload = CBool(False, config=True)
153 displayhook_class = Type(DisplayHook)
153 displayhook_class = Type(DisplayHook)
154 exit_now = CBool(False)
154 exit_now = CBool(False)
155 filename = Str("<ipython console>")
155 filename = Str("<ipython console>")
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 logstart = CBool(False, config=True)
157 logstart = CBool(False, config=True)
158 logfile = Str('', config=True)
158 logfile = Str('', config=True)
159 logappend = Str('', config=True)
159 logappend = Str('', config=True)
160 object_info_string_level = Enum((0,1,2), default_value=0,
160 object_info_string_level = Enum((0,1,2), default_value=0,
161 config=True)
161 config=True)
162 pdb = CBool(False, config=True)
162 pdb = CBool(False, config=True)
163 pprint = CBool(True, config=True)
163 pprint = CBool(True, config=True)
164 profile = Str('', config=True)
164 profile = Str('', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
168 prompts_pad_left = CBool(True, config=True)
168 prompts_pad_left = CBool(True, config=True)
169 quiet = CBool(False, config=True)
169 quiet = CBool(False, config=True)
170
170
171 # The readline stuff will eventually be moved to the terminal subclass
171 # The readline stuff will eventually be moved to the terminal subclass
172 # but for now, we can't do that as readline is welded in everywhere.
172 # but for now, we can't do that as readline is welded in everywhere.
173 readline_use = CBool(True, config=True)
173 readline_use = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 readline_remove_delims = Str('-/~', config=True)
176 readline_remove_delims = Str('-/~', config=True)
177 readline_parse_and_bind = List([
177 readline_parse_and_bind = List([
178 'tab: complete',
178 'tab: complete',
179 '"\C-l": clear-screen',
179 '"\C-l": clear-screen',
180 'set show-all-if-ambiguous on',
180 'set show-all-if-ambiguous on',
181 '"\C-o": tab-insert',
181 '"\C-o": tab-insert',
182 '"\M-i": " "',
182 '"\M-i": " "',
183 '"\M-o": "\d\d\d\d"',
183 '"\M-o": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
185 '"\C-r": reverse-search-history',
185 '"\C-r": reverse-search-history',
186 '"\C-s": forward-search-history',
186 '"\C-s": forward-search-history',
187 '"\C-p": history-search-backward',
187 '"\C-p": history-search-backward',
188 '"\C-n": history-search-forward',
188 '"\C-n": history-search-forward',
189 '"\e[A": history-search-backward',
189 '"\e[A": history-search-backward',
190 '"\e[B": history-search-forward',
190 '"\e[B": history-search-forward',
191 '"\C-k": kill-line',
191 '"\C-k": kill-line',
192 '"\C-u": unix-line-discard',
192 '"\C-u": unix-line-discard',
193 ], allow_none=False, config=True)
193 ], allow_none=False, config=True)
194
194
195 # TODO: this part of prompt management should be moved to the frontends.
195 # TODO: this part of prompt management should be moved to the frontends.
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 separate_in = SeparateStr('\n', config=True)
197 separate_in = SeparateStr('\n', config=True)
198 separate_out = SeparateStr('', config=True)
198 separate_out = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
202 default_value='Context', config=True)
202 default_value='Context', config=True)
203
203
204 # Subcomponents of InteractiveShell
204 # Subcomponents of InteractiveShell
205 alias_manager = Instance('IPython.core.alias.AliasManager')
205 alias_manager = Instance('IPython.core.alias.AliasManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
212
212
213 def __init__(self, config=None, ipython_dir=None,
213 def __init__(self, config=None, ipython_dir=None,
214 user_ns=None, user_global_ns=None,
214 user_ns=None, user_global_ns=None,
215 custom_exceptions=((),None)):
215 custom_exceptions=((),None)):
216
216
217 # This is where traits with a config_key argument are updated
217 # This is where traits with a config_key argument are updated
218 # from the values on config.
218 # from the values on config.
219 super(InteractiveShell, self).__init__(config=config)
219 super(InteractiveShell, self).__init__(config=config)
220
220
221 # These are relatively independent and stateless
221 # These are relatively independent and stateless
222 self.init_ipython_dir(ipython_dir)
222 self.init_ipython_dir(ipython_dir)
223 self.init_instance_attrs()
223 self.init_instance_attrs()
224
224
225 # Create namespaces (user_ns, user_global_ns, etc.)
225 # Create namespaces (user_ns, user_global_ns, etc.)
226 self.init_create_namespaces(user_ns, user_global_ns)
226 self.init_create_namespaces(user_ns, user_global_ns)
227 # This has to be done after init_create_namespaces because it uses
227 # This has to be done after init_create_namespaces because it uses
228 # something in self.user_ns, but before init_sys_modules, which
228 # something in self.user_ns, but before init_sys_modules, which
229 # is the first thing to modify sys.
229 # is the first thing to modify sys.
230 # TODO: When we override sys.stdout and sys.stderr before this class
230 # TODO: When we override sys.stdout and sys.stderr before this class
231 # is created, we are saving the overridden ones here. Not sure if this
231 # is created, we are saving the overridden ones here. Not sure if this
232 # is what we want to do.
232 # is what we want to do.
233 self.save_sys_module_state()
233 self.save_sys_module_state()
234 self.init_sys_modules()
234 self.init_sys_modules()
235
235
236 self.init_history()
236 self.init_history()
237 self.init_encoding()
237 self.init_encoding()
238 self.init_prefilter()
238 self.init_prefilter()
239
239
240 Magic.__init__(self, self)
240 Magic.__init__(self, self)
241
241
242 self.init_syntax_highlighting()
242 self.init_syntax_highlighting()
243 self.init_hooks()
243 self.init_hooks()
244 self.init_pushd_popd_magic()
244 self.init_pushd_popd_magic()
245 # self.init_traceback_handlers use to be here, but we moved it below
245 # self.init_traceback_handlers use to be here, but we moved it below
246 # because it and init_io have to come after init_readline.
246 # because it and init_io have to come after init_readline.
247 self.init_user_ns()
247 self.init_user_ns()
248 self.init_logger()
248 self.init_logger()
249 self.init_alias()
249 self.init_alias()
250 self.init_builtins()
250 self.init_builtins()
251
251
252 # pre_config_initialization
252 # pre_config_initialization
253 self.init_shadow_hist()
253 self.init_shadow_hist()
254
254
255 # The next section should contain averything that was in ipmaker.
255 # The next section should contain averything that was in ipmaker.
256 self.init_logstart()
256 self.init_logstart()
257
257
258 # The following was in post_config_initialization
258 # The following was in post_config_initialization
259 self.init_inspector()
259 self.init_inspector()
260 # init_readline() must come before init_io(), because init_io uses
260 # init_readline() must come before init_io(), because init_io uses
261 # readline related things.
261 # readline related things.
262 self.init_readline()
262 self.init_readline()
263 # init_completer must come after init_readline, because it needs to
264 # know whether readline is present or not system-wide to configure the
265 # completers, since the completion machinery can now operate
266 # independently of readline (e.g. over the network)
267 self.init_completer()
263 # TODO: init_io() needs to happen before init_traceback handlers
268 # TODO: init_io() needs to happen before init_traceback handlers
264 # because the traceback handlers hardcode the stdout/stderr streams.
269 # because the traceback handlers hardcode the stdout/stderr streams.
265 # This logic in in debugger.Pdb and should eventually be changed.
270 # This logic in in debugger.Pdb and should eventually be changed.
266 self.init_io()
271 self.init_io()
267 self.init_traceback_handlers(custom_exceptions)
272 self.init_traceback_handlers(custom_exceptions)
268 self.init_prompts()
273 self.init_prompts()
269 self.init_displayhook()
274 self.init_displayhook()
270 self.init_reload_doctest()
275 self.init_reload_doctest()
271 self.init_magics()
276 self.init_magics()
272 self.init_pdb()
277 self.init_pdb()
273 self.init_extension_manager()
278 self.init_extension_manager()
274 self.init_plugin_manager()
279 self.init_plugin_manager()
275 self.init_payload()
280 self.init_payload()
276 self.hooks.late_startup_hook()
281 self.hooks.late_startup_hook()
277 atexit.register(self.atexit_operations)
282 atexit.register(self.atexit_operations)
278
283
279 @classmethod
284 @classmethod
280 def instance(cls, *args, **kwargs):
285 def instance(cls, *args, **kwargs):
281 """Returns a global InteractiveShell instance."""
286 """Returns a global InteractiveShell instance."""
282 if cls._instance is None:
287 if cls._instance is None:
283 inst = cls(*args, **kwargs)
288 inst = cls(*args, **kwargs)
284 # Now make sure that the instance will also be returned by
289 # Now make sure that the instance will also be returned by
285 # the subclasses instance attribute.
290 # the subclasses instance attribute.
286 for subclass in cls.mro():
291 for subclass in cls.mro():
287 if issubclass(cls, subclass) and \
292 if issubclass(cls, subclass) and \
288 issubclass(subclass, InteractiveShell):
293 issubclass(subclass, InteractiveShell):
289 subclass._instance = inst
294 subclass._instance = inst
290 else:
295 else:
291 break
296 break
292 if isinstance(cls._instance, cls):
297 if isinstance(cls._instance, cls):
293 return cls._instance
298 return cls._instance
294 else:
299 else:
295 raise MultipleInstanceError(
300 raise MultipleInstanceError(
296 'Multiple incompatible subclass instances of '
301 'Multiple incompatible subclass instances of '
297 'InteractiveShell are being created.'
302 'InteractiveShell are being created.'
298 )
303 )
299
304
300 @classmethod
305 @classmethod
301 def initialized(cls):
306 def initialized(cls):
302 return hasattr(cls, "_instance")
307 return hasattr(cls, "_instance")
303
308
304 def get_ipython(self):
309 def get_ipython(self):
305 """Return the currently running IPython instance."""
310 """Return the currently running IPython instance."""
306 return self
311 return self
307
312
308 #-------------------------------------------------------------------------
313 #-------------------------------------------------------------------------
309 # Trait changed handlers
314 # Trait changed handlers
310 #-------------------------------------------------------------------------
315 #-------------------------------------------------------------------------
311
316
312 def _ipython_dir_changed(self, name, new):
317 def _ipython_dir_changed(self, name, new):
313 if not os.path.isdir(new):
318 if not os.path.isdir(new):
314 os.makedirs(new, mode = 0777)
319 os.makedirs(new, mode = 0777)
315
320
316 def set_autoindent(self,value=None):
321 def set_autoindent(self,value=None):
317 """Set the autoindent flag, checking for readline support.
322 """Set the autoindent flag, checking for readline support.
318
323
319 If called with no arguments, it acts as a toggle."""
324 If called with no arguments, it acts as a toggle."""
320
325
321 if not self.has_readline:
326 if not self.has_readline:
322 if os.name == 'posix':
327 if os.name == 'posix':
323 warn("The auto-indent feature requires the readline library")
328 warn("The auto-indent feature requires the readline library")
324 self.autoindent = 0
329 self.autoindent = 0
325 return
330 return
326 if value is None:
331 if value is None:
327 self.autoindent = not self.autoindent
332 self.autoindent = not self.autoindent
328 else:
333 else:
329 self.autoindent = value
334 self.autoindent = value
330
335
331 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
332 # init_* methods called by __init__
337 # init_* methods called by __init__
333 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
334
339
335 def init_ipython_dir(self, ipython_dir):
340 def init_ipython_dir(self, ipython_dir):
336 if ipython_dir is not None:
341 if ipython_dir is not None:
337 self.ipython_dir = ipython_dir
342 self.ipython_dir = ipython_dir
338 self.config.Global.ipython_dir = self.ipython_dir
343 self.config.Global.ipython_dir = self.ipython_dir
339 return
344 return
340
345
341 if hasattr(self.config.Global, 'ipython_dir'):
346 if hasattr(self.config.Global, 'ipython_dir'):
342 self.ipython_dir = self.config.Global.ipython_dir
347 self.ipython_dir = self.config.Global.ipython_dir
343 else:
348 else:
344 self.ipython_dir = get_ipython_dir()
349 self.ipython_dir = get_ipython_dir()
345
350
346 # All children can just read this
351 # All children can just read this
347 self.config.Global.ipython_dir = self.ipython_dir
352 self.config.Global.ipython_dir = self.ipython_dir
348
353
349 def init_instance_attrs(self):
354 def init_instance_attrs(self):
350 self.more = False
355 self.more = False
351
356
352 # command compiler
357 # command compiler
353 self.compile = codeop.CommandCompiler()
358 self.compile = codeop.CommandCompiler()
354
359
355 # User input buffer
360 # User input buffer
356 self.buffer = []
361 self.buffer = []
357
362
358 # Make an empty namespace, which extension writers can rely on both
363 # Make an empty namespace, which extension writers can rely on both
359 # existing and NEVER being used by ipython itself. This gives them a
364 # existing and NEVER being used by ipython itself. This gives them a
360 # convenient location for storing additional information and state
365 # convenient location for storing additional information and state
361 # their extensions may require, without fear of collisions with other
366 # their extensions may require, without fear of collisions with other
362 # ipython names that may develop later.
367 # ipython names that may develop later.
363 self.meta = Struct()
368 self.meta = Struct()
364
369
365 # Object variable to store code object waiting execution. This is
370 # Object variable to store code object waiting execution. This is
366 # used mainly by the multithreaded shells, but it can come in handy in
371 # used mainly by the multithreaded shells, but it can come in handy in
367 # other situations. No need to use a Queue here, since it's a single
372 # other situations. No need to use a Queue here, since it's a single
368 # item which gets cleared once run.
373 # item which gets cleared once run.
369 self.code_to_run = None
374 self.code_to_run = None
370
375
371 # Temporary files used for various purposes. Deleted at exit.
376 # Temporary files used for various purposes. Deleted at exit.
372 self.tempfiles = []
377 self.tempfiles = []
373
378
374 # Keep track of readline usage (later set by init_readline)
379 # Keep track of readline usage (later set by init_readline)
375 self.has_readline = False
380 self.has_readline = False
376
381
377 # keep track of where we started running (mainly for crash post-mortem)
382 # keep track of where we started running (mainly for crash post-mortem)
378 # This is not being used anywhere currently.
383 # This is not being used anywhere currently.
379 self.starting_dir = os.getcwd()
384 self.starting_dir = os.getcwd()
380
385
381 # Indentation management
386 # Indentation management
382 self.indent_current_nsp = 0
387 self.indent_current_nsp = 0
383
388
384 def init_encoding(self):
389 def init_encoding(self):
385 # Get system encoding at startup time. Certain terminals (like Emacs
390 # Get system encoding at startup time. Certain terminals (like Emacs
386 # under Win32 have it set to None, and we need to have a known valid
391 # under Win32 have it set to None, and we need to have a known valid
387 # encoding to use in the raw_input() method
392 # encoding to use in the raw_input() method
388 try:
393 try:
389 self.stdin_encoding = sys.stdin.encoding or 'ascii'
394 self.stdin_encoding = sys.stdin.encoding or 'ascii'
390 except AttributeError:
395 except AttributeError:
391 self.stdin_encoding = 'ascii'
396 self.stdin_encoding = 'ascii'
392
397
393 def init_syntax_highlighting(self):
398 def init_syntax_highlighting(self):
394 # Python source parser/formatter for syntax highlighting
399 # Python source parser/formatter for syntax highlighting
395 pyformat = PyColorize.Parser().format
400 pyformat = PyColorize.Parser().format
396 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
401 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
397
402
398 def init_pushd_popd_magic(self):
403 def init_pushd_popd_magic(self):
399 # for pushd/popd management
404 # for pushd/popd management
400 try:
405 try:
401 self.home_dir = get_home_dir()
406 self.home_dir = get_home_dir()
402 except HomeDirError, msg:
407 except HomeDirError, msg:
403 fatal(msg)
408 fatal(msg)
404
409
405 self.dir_stack = []
410 self.dir_stack = []
406
411
407 def init_logger(self):
412 def init_logger(self):
408 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
413 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
409 # local shortcut, this is used a LOT
414 # local shortcut, this is used a LOT
410 self.log = self.logger.log
415 self.log = self.logger.log
411
416
412 def init_logstart(self):
417 def init_logstart(self):
413 if self.logappend:
418 if self.logappend:
414 self.magic_logstart(self.logappend + ' append')
419 self.magic_logstart(self.logappend + ' append')
415 elif self.logfile:
420 elif self.logfile:
416 self.magic_logstart(self.logfile)
421 self.magic_logstart(self.logfile)
417 elif self.logstart:
422 elif self.logstart:
418 self.magic_logstart()
423 self.magic_logstart()
419
424
420 def init_builtins(self):
425 def init_builtins(self):
421 self.builtin_trap = BuiltinTrap(shell=self)
426 self.builtin_trap = BuiltinTrap(shell=self)
422
427
423 def init_inspector(self):
428 def init_inspector(self):
424 # Object inspector
429 # Object inspector
425 self.inspector = oinspect.Inspector(oinspect.InspectColors,
430 self.inspector = oinspect.Inspector(oinspect.InspectColors,
426 PyColorize.ANSICodeColors,
431 PyColorize.ANSICodeColors,
427 'NoColor',
432 'NoColor',
428 self.object_info_string_level)
433 self.object_info_string_level)
429
434
430 def init_io(self):
435 def init_io(self):
431 import IPython.utils.io
436 import IPython.utils.io
432 if sys.platform == 'win32' and self.has_readline:
437 if sys.platform == 'win32' and self.has_readline:
433 Term = io.IOTerm(
438 Term = io.IOTerm(
434 cout=self.readline._outputfile,cerr=self.readline._outputfile
439 cout=self.readline._outputfile,cerr=self.readline._outputfile
435 )
440 )
436 else:
441 else:
437 Term = io.IOTerm()
442 Term = io.IOTerm()
438 io.Term = Term
443 io.Term = Term
439
444
440 def init_prompts(self):
445 def init_prompts(self):
441 # TODO: This is a pass for now because the prompts are managed inside
446 # TODO: This is a pass for now because the prompts are managed inside
442 # the DisplayHook. Once there is a separate prompt manager, this
447 # the DisplayHook. Once there is a separate prompt manager, this
443 # will initialize that object and all prompt related information.
448 # will initialize that object and all prompt related information.
444 pass
449 pass
445
450
446 def init_displayhook(self):
451 def init_displayhook(self):
447 # Initialize displayhook, set in/out prompts and printing system
452 # Initialize displayhook, set in/out prompts and printing system
448 self.displayhook = self.displayhook_class(
453 self.displayhook = self.displayhook_class(
449 shell=self,
454 shell=self,
450 cache_size=self.cache_size,
455 cache_size=self.cache_size,
451 input_sep = self.separate_in,
456 input_sep = self.separate_in,
452 output_sep = self.separate_out,
457 output_sep = self.separate_out,
453 output_sep2 = self.separate_out2,
458 output_sep2 = self.separate_out2,
454 ps1 = self.prompt_in1,
459 ps1 = self.prompt_in1,
455 ps2 = self.prompt_in2,
460 ps2 = self.prompt_in2,
456 ps_out = self.prompt_out,
461 ps_out = self.prompt_out,
457 pad_left = self.prompts_pad_left
462 pad_left = self.prompts_pad_left
458 )
463 )
459 # This is a context manager that installs/revmoes the displayhook at
464 # This is a context manager that installs/revmoes the displayhook at
460 # the appropriate time.
465 # the appropriate time.
461 self.display_trap = DisplayTrap(hook=self.displayhook)
466 self.display_trap = DisplayTrap(hook=self.displayhook)
462
467
463 def init_reload_doctest(self):
468 def init_reload_doctest(self):
464 # Do a proper resetting of doctest, including the necessary displayhook
469 # Do a proper resetting of doctest, including the necessary displayhook
465 # monkeypatching
470 # monkeypatching
466 try:
471 try:
467 doctest_reload()
472 doctest_reload()
468 except ImportError:
473 except ImportError:
469 warn("doctest module does not exist.")
474 warn("doctest module does not exist.")
470
475
471 #-------------------------------------------------------------------------
476 #-------------------------------------------------------------------------
472 # Things related to injections into the sys module
477 # Things related to injections into the sys module
473 #-------------------------------------------------------------------------
478 #-------------------------------------------------------------------------
474
479
475 def save_sys_module_state(self):
480 def save_sys_module_state(self):
476 """Save the state of hooks in the sys module.
481 """Save the state of hooks in the sys module.
477
482
478 This has to be called after self.user_ns is created.
483 This has to be called after self.user_ns is created.
479 """
484 """
480 self._orig_sys_module_state = {}
485 self._orig_sys_module_state = {}
481 self._orig_sys_module_state['stdin'] = sys.stdin
486 self._orig_sys_module_state['stdin'] = sys.stdin
482 self._orig_sys_module_state['stdout'] = sys.stdout
487 self._orig_sys_module_state['stdout'] = sys.stdout
483 self._orig_sys_module_state['stderr'] = sys.stderr
488 self._orig_sys_module_state['stderr'] = sys.stderr
484 self._orig_sys_module_state['excepthook'] = sys.excepthook
489 self._orig_sys_module_state['excepthook'] = sys.excepthook
485 try:
490 try:
486 self._orig_sys_modules_main_name = self.user_ns['__name__']
491 self._orig_sys_modules_main_name = self.user_ns['__name__']
487 except KeyError:
492 except KeyError:
488 pass
493 pass
489
494
490 def restore_sys_module_state(self):
495 def restore_sys_module_state(self):
491 """Restore the state of the sys module."""
496 """Restore the state of the sys module."""
492 try:
497 try:
493 for k, v in self._orig_sys_module_state.items():
498 for k, v in self._orig_sys_module_state.items():
494 setattr(sys, k, v)
499 setattr(sys, k, v)
495 except AttributeError:
500 except AttributeError:
496 pass
501 pass
497 # Reset what what done in self.init_sys_modules
502 # Reset what what done in self.init_sys_modules
498 try:
503 try:
499 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
504 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
500 except (AttributeError, KeyError):
505 except (AttributeError, KeyError):
501 pass
506 pass
502
507
503 #-------------------------------------------------------------------------
508 #-------------------------------------------------------------------------
504 # Things related to hooks
509 # Things related to hooks
505 #-------------------------------------------------------------------------
510 #-------------------------------------------------------------------------
506
511
507 def init_hooks(self):
512 def init_hooks(self):
508 # hooks holds pointers used for user-side customizations
513 # hooks holds pointers used for user-side customizations
509 self.hooks = Struct()
514 self.hooks = Struct()
510
515
511 self.strdispatchers = {}
516 self.strdispatchers = {}
512
517
513 # Set all default hooks, defined in the IPython.hooks module.
518 # Set all default hooks, defined in the IPython.hooks module.
514 hooks = IPython.core.hooks
519 hooks = IPython.core.hooks
515 for hook_name in hooks.__all__:
520 for hook_name in hooks.__all__:
516 # default hooks have priority 100, i.e. low; user hooks should have
521 # default hooks have priority 100, i.e. low; user hooks should have
517 # 0-100 priority
522 # 0-100 priority
518 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
523 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
519
524
520 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
525 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
521 """set_hook(name,hook) -> sets an internal IPython hook.
526 """set_hook(name,hook) -> sets an internal IPython hook.
522
527
523 IPython exposes some of its internal API as user-modifiable hooks. By
528 IPython exposes some of its internal API as user-modifiable hooks. By
524 adding your function to one of these hooks, you can modify IPython's
529 adding your function to one of these hooks, you can modify IPython's
525 behavior to call at runtime your own routines."""
530 behavior to call at runtime your own routines."""
526
531
527 # At some point in the future, this should validate the hook before it
532 # At some point in the future, this should validate the hook before it
528 # accepts it. Probably at least check that the hook takes the number
533 # accepts it. Probably at least check that the hook takes the number
529 # of args it's supposed to.
534 # of args it's supposed to.
530
535
531 f = new.instancemethod(hook,self,self.__class__)
536 f = new.instancemethod(hook,self,self.__class__)
532
537
533 # check if the hook is for strdispatcher first
538 # check if the hook is for strdispatcher first
534 if str_key is not None:
539 if str_key is not None:
535 sdp = self.strdispatchers.get(name, StrDispatch())
540 sdp = self.strdispatchers.get(name, StrDispatch())
536 sdp.add_s(str_key, f, priority )
541 sdp.add_s(str_key, f, priority )
537 self.strdispatchers[name] = sdp
542 self.strdispatchers[name] = sdp
538 return
543 return
539 if re_key is not None:
544 if re_key is not None:
540 sdp = self.strdispatchers.get(name, StrDispatch())
545 sdp = self.strdispatchers.get(name, StrDispatch())
541 sdp.add_re(re.compile(re_key), f, priority )
546 sdp.add_re(re.compile(re_key), f, priority )
542 self.strdispatchers[name] = sdp
547 self.strdispatchers[name] = sdp
543 return
548 return
544
549
545 dp = getattr(self.hooks, name, None)
550 dp = getattr(self.hooks, name, None)
546 if name not in IPython.core.hooks.__all__:
551 if name not in IPython.core.hooks.__all__:
547 print "Warning! Hook '%s' is not one of %s" % \
552 print "Warning! Hook '%s' is not one of %s" % \
548 (name, IPython.core.hooks.__all__ )
553 (name, IPython.core.hooks.__all__ )
549 if not dp:
554 if not dp:
550 dp = IPython.core.hooks.CommandChainDispatcher()
555 dp = IPython.core.hooks.CommandChainDispatcher()
551
556
552 try:
557 try:
553 dp.add(f,priority)
558 dp.add(f,priority)
554 except AttributeError:
559 except AttributeError:
555 # it was not commandchain, plain old func - replace
560 # it was not commandchain, plain old func - replace
556 dp = f
561 dp = f
557
562
558 setattr(self.hooks,name, dp)
563 setattr(self.hooks,name, dp)
559
564
560 #-------------------------------------------------------------------------
565 #-------------------------------------------------------------------------
561 # Things related to the "main" module
566 # Things related to the "main" module
562 #-------------------------------------------------------------------------
567 #-------------------------------------------------------------------------
563
568
564 def new_main_mod(self,ns=None):
569 def new_main_mod(self,ns=None):
565 """Return a new 'main' module object for user code execution.
570 """Return a new 'main' module object for user code execution.
566 """
571 """
567 main_mod = self._user_main_module
572 main_mod = self._user_main_module
568 init_fakemod_dict(main_mod,ns)
573 init_fakemod_dict(main_mod,ns)
569 return main_mod
574 return main_mod
570
575
571 def cache_main_mod(self,ns,fname):
576 def cache_main_mod(self,ns,fname):
572 """Cache a main module's namespace.
577 """Cache a main module's namespace.
573
578
574 When scripts are executed via %run, we must keep a reference to the
579 When scripts are executed via %run, we must keep a reference to the
575 namespace of their __main__ module (a FakeModule instance) around so
580 namespace of their __main__ module (a FakeModule instance) around so
576 that Python doesn't clear it, rendering objects defined therein
581 that Python doesn't clear it, rendering objects defined therein
577 useless.
582 useless.
578
583
579 This method keeps said reference in a private dict, keyed by the
584 This method keeps said reference in a private dict, keyed by the
580 absolute path of the module object (which corresponds to the script
585 absolute path of the module object (which corresponds to the script
581 path). This way, for multiple executions of the same script we only
586 path). This way, for multiple executions of the same script we only
582 keep one copy of the namespace (the last one), thus preventing memory
587 keep one copy of the namespace (the last one), thus preventing memory
583 leaks from old references while allowing the objects from the last
588 leaks from old references while allowing the objects from the last
584 execution to be accessible.
589 execution to be accessible.
585
590
586 Note: we can not allow the actual FakeModule instances to be deleted,
591 Note: we can not allow the actual FakeModule instances to be deleted,
587 because of how Python tears down modules (it hard-sets all their
592 because of how Python tears down modules (it hard-sets all their
588 references to None without regard for reference counts). This method
593 references to None without regard for reference counts). This method
589 must therefore make a *copy* of the given namespace, to allow the
594 must therefore make a *copy* of the given namespace, to allow the
590 original module's __dict__ to be cleared and reused.
595 original module's __dict__ to be cleared and reused.
591
596
592
597
593 Parameters
598 Parameters
594 ----------
599 ----------
595 ns : a namespace (a dict, typically)
600 ns : a namespace (a dict, typically)
596
601
597 fname : str
602 fname : str
598 Filename associated with the namespace.
603 Filename associated with the namespace.
599
604
600 Examples
605 Examples
601 --------
606 --------
602
607
603 In [10]: import IPython
608 In [10]: import IPython
604
609
605 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
610 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
606
611
607 In [12]: IPython.__file__ in _ip._main_ns_cache
612 In [12]: IPython.__file__ in _ip._main_ns_cache
608 Out[12]: True
613 Out[12]: True
609 """
614 """
610 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
615 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
611
616
612 def clear_main_mod_cache(self):
617 def clear_main_mod_cache(self):
613 """Clear the cache of main modules.
618 """Clear the cache of main modules.
614
619
615 Mainly for use by utilities like %reset.
620 Mainly for use by utilities like %reset.
616
621
617 Examples
622 Examples
618 --------
623 --------
619
624
620 In [15]: import IPython
625 In [15]: import IPython
621
626
622 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
627 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
623
628
624 In [17]: len(_ip._main_ns_cache) > 0
629 In [17]: len(_ip._main_ns_cache) > 0
625 Out[17]: True
630 Out[17]: True
626
631
627 In [18]: _ip.clear_main_mod_cache()
632 In [18]: _ip.clear_main_mod_cache()
628
633
629 In [19]: len(_ip._main_ns_cache) == 0
634 In [19]: len(_ip._main_ns_cache) == 0
630 Out[19]: True
635 Out[19]: True
631 """
636 """
632 self._main_ns_cache.clear()
637 self._main_ns_cache.clear()
633
638
634 #-------------------------------------------------------------------------
639 #-------------------------------------------------------------------------
635 # Things related to debugging
640 # Things related to debugging
636 #-------------------------------------------------------------------------
641 #-------------------------------------------------------------------------
637
642
638 def init_pdb(self):
643 def init_pdb(self):
639 # Set calling of pdb on exceptions
644 # Set calling of pdb on exceptions
640 # self.call_pdb is a property
645 # self.call_pdb is a property
641 self.call_pdb = self.pdb
646 self.call_pdb = self.pdb
642
647
643 def _get_call_pdb(self):
648 def _get_call_pdb(self):
644 return self._call_pdb
649 return self._call_pdb
645
650
646 def _set_call_pdb(self,val):
651 def _set_call_pdb(self,val):
647
652
648 if val not in (0,1,False,True):
653 if val not in (0,1,False,True):
649 raise ValueError,'new call_pdb value must be boolean'
654 raise ValueError,'new call_pdb value must be boolean'
650
655
651 # store value in instance
656 # store value in instance
652 self._call_pdb = val
657 self._call_pdb = val
653
658
654 # notify the actual exception handlers
659 # notify the actual exception handlers
655 self.InteractiveTB.call_pdb = val
660 self.InteractiveTB.call_pdb = val
656
661
657 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
662 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
658 'Control auto-activation of pdb at exceptions')
663 'Control auto-activation of pdb at exceptions')
659
664
660 def debugger(self,force=False):
665 def debugger(self,force=False):
661 """Call the pydb/pdb debugger.
666 """Call the pydb/pdb debugger.
662
667
663 Keywords:
668 Keywords:
664
669
665 - force(False): by default, this routine checks the instance call_pdb
670 - force(False): by default, this routine checks the instance call_pdb
666 flag and does not actually invoke the debugger if the flag is false.
671 flag and does not actually invoke the debugger if the flag is false.
667 The 'force' option forces the debugger to activate even if the flag
672 The 'force' option forces the debugger to activate even if the flag
668 is false.
673 is false.
669 """
674 """
670
675
671 if not (force or self.call_pdb):
676 if not (force or self.call_pdb):
672 return
677 return
673
678
674 if not hasattr(sys,'last_traceback'):
679 if not hasattr(sys,'last_traceback'):
675 error('No traceback has been produced, nothing to debug.')
680 error('No traceback has been produced, nothing to debug.')
676 return
681 return
677
682
678 # use pydb if available
683 # use pydb if available
679 if debugger.has_pydb:
684 if debugger.has_pydb:
680 from pydb import pm
685 from pydb import pm
681 else:
686 else:
682 # fallback to our internal debugger
687 # fallback to our internal debugger
683 pm = lambda : self.InteractiveTB.debugger(force=True)
688 pm = lambda : self.InteractiveTB.debugger(force=True)
684 self.history_saving_wrapper(pm)()
689 self.history_saving_wrapper(pm)()
685
690
686 #-------------------------------------------------------------------------
691 #-------------------------------------------------------------------------
687 # Things related to IPython's various namespaces
692 # Things related to IPython's various namespaces
688 #-------------------------------------------------------------------------
693 #-------------------------------------------------------------------------
689
694
690 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
695 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
691 # Create the namespace where the user will operate. user_ns is
696 # Create the namespace where the user will operate. user_ns is
692 # normally the only one used, and it is passed to the exec calls as
697 # normally the only one used, and it is passed to the exec calls as
693 # the locals argument. But we do carry a user_global_ns namespace
698 # the locals argument. But we do carry a user_global_ns namespace
694 # given as the exec 'globals' argument, This is useful in embedding
699 # given as the exec 'globals' argument, This is useful in embedding
695 # situations where the ipython shell opens in a context where the
700 # situations where the ipython shell opens in a context where the
696 # distinction between locals and globals is meaningful. For
701 # distinction between locals and globals is meaningful. For
697 # non-embedded contexts, it is just the same object as the user_ns dict.
702 # non-embedded contexts, it is just the same object as the user_ns dict.
698
703
699 # FIXME. For some strange reason, __builtins__ is showing up at user
704 # FIXME. For some strange reason, __builtins__ is showing up at user
700 # level as a dict instead of a module. This is a manual fix, but I
705 # level as a dict instead of a module. This is a manual fix, but I
701 # should really track down where the problem is coming from. Alex
706 # should really track down where the problem is coming from. Alex
702 # Schmolck reported this problem first.
707 # Schmolck reported this problem first.
703
708
704 # A useful post by Alex Martelli on this topic:
709 # A useful post by Alex Martelli on this topic:
705 # Re: inconsistent value from __builtins__
710 # Re: inconsistent value from __builtins__
706 # Von: Alex Martelli <aleaxit@yahoo.com>
711 # Von: Alex Martelli <aleaxit@yahoo.com>
707 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
712 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
708 # Gruppen: comp.lang.python
713 # Gruppen: comp.lang.python
709
714
710 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
715 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
711 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
716 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
712 # > <type 'dict'>
717 # > <type 'dict'>
713 # > >>> print type(__builtins__)
718 # > >>> print type(__builtins__)
714 # > <type 'module'>
719 # > <type 'module'>
715 # > Is this difference in return value intentional?
720 # > Is this difference in return value intentional?
716
721
717 # Well, it's documented that '__builtins__' can be either a dictionary
722 # Well, it's documented that '__builtins__' can be either a dictionary
718 # or a module, and it's been that way for a long time. Whether it's
723 # or a module, and it's been that way for a long time. Whether it's
719 # intentional (or sensible), I don't know. In any case, the idea is
724 # intentional (or sensible), I don't know. In any case, the idea is
720 # that if you need to access the built-in namespace directly, you
725 # that if you need to access the built-in namespace directly, you
721 # should start with "import __builtin__" (note, no 's') which will
726 # should start with "import __builtin__" (note, no 's') which will
722 # definitely give you a module. Yeah, it's somewhat confusing:-(.
727 # definitely give you a module. Yeah, it's somewhat confusing:-(.
723
728
724 # These routines return properly built dicts as needed by the rest of
729 # These routines return properly built dicts as needed by the rest of
725 # the code, and can also be used by extension writers to generate
730 # the code, and can also be used by extension writers to generate
726 # properly initialized namespaces.
731 # properly initialized namespaces.
727 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
732 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
728 user_global_ns)
733 user_global_ns)
729
734
730 # Assign namespaces
735 # Assign namespaces
731 # This is the namespace where all normal user variables live
736 # This is the namespace where all normal user variables live
732 self.user_ns = user_ns
737 self.user_ns = user_ns
733 self.user_global_ns = user_global_ns
738 self.user_global_ns = user_global_ns
734
739
735 # An auxiliary namespace that checks what parts of the user_ns were
740 # An auxiliary namespace that checks what parts of the user_ns were
736 # loaded at startup, so we can list later only variables defined in
741 # loaded at startup, so we can list later only variables defined in
737 # actual interactive use. Since it is always a subset of user_ns, it
742 # actual interactive use. Since it is always a subset of user_ns, it
738 # doesn't need to be separately tracked in the ns_table.
743 # doesn't need to be separately tracked in the ns_table.
739 self.user_ns_hidden = {}
744 self.user_ns_hidden = {}
740
745
741 # A namespace to keep track of internal data structures to prevent
746 # A namespace to keep track of internal data structures to prevent
742 # them from cluttering user-visible stuff. Will be updated later
747 # them from cluttering user-visible stuff. Will be updated later
743 self.internal_ns = {}
748 self.internal_ns = {}
744
749
745 # Now that FakeModule produces a real module, we've run into a nasty
750 # Now that FakeModule produces a real module, we've run into a nasty
746 # problem: after script execution (via %run), the module where the user
751 # problem: after script execution (via %run), the module where the user
747 # code ran is deleted. Now that this object is a true module (needed
752 # code ran is deleted. Now that this object is a true module (needed
748 # so docetst and other tools work correctly), the Python module
753 # so docetst and other tools work correctly), the Python module
749 # teardown mechanism runs over it, and sets to None every variable
754 # teardown mechanism runs over it, and sets to None every variable
750 # present in that module. Top-level references to objects from the
755 # present in that module. Top-level references to objects from the
751 # script survive, because the user_ns is updated with them. However,
756 # script survive, because the user_ns is updated with them. However,
752 # calling functions defined in the script that use other things from
757 # calling functions defined in the script that use other things from
753 # the script will fail, because the function's closure had references
758 # the script will fail, because the function's closure had references
754 # to the original objects, which are now all None. So we must protect
759 # to the original objects, which are now all None. So we must protect
755 # these modules from deletion by keeping a cache.
760 # these modules from deletion by keeping a cache.
756 #
761 #
757 # To avoid keeping stale modules around (we only need the one from the
762 # To avoid keeping stale modules around (we only need the one from the
758 # last run), we use a dict keyed with the full path to the script, so
763 # last run), we use a dict keyed with the full path to the script, so
759 # only the last version of the module is held in the cache. Note,
764 # only the last version of the module is held in the cache. Note,
760 # however, that we must cache the module *namespace contents* (their
765 # however, that we must cache the module *namespace contents* (their
761 # __dict__). Because if we try to cache the actual modules, old ones
766 # __dict__). Because if we try to cache the actual modules, old ones
762 # (uncached) could be destroyed while still holding references (such as
767 # (uncached) could be destroyed while still holding references (such as
763 # those held by GUI objects that tend to be long-lived)>
768 # those held by GUI objects that tend to be long-lived)>
764 #
769 #
765 # The %reset command will flush this cache. See the cache_main_mod()
770 # The %reset command will flush this cache. See the cache_main_mod()
766 # and clear_main_mod_cache() methods for details on use.
771 # and clear_main_mod_cache() methods for details on use.
767
772
768 # This is the cache used for 'main' namespaces
773 # This is the cache used for 'main' namespaces
769 self._main_ns_cache = {}
774 self._main_ns_cache = {}
770 # And this is the single instance of FakeModule whose __dict__ we keep
775 # And this is the single instance of FakeModule whose __dict__ we keep
771 # copying and clearing for reuse on each %run
776 # copying and clearing for reuse on each %run
772 self._user_main_module = FakeModule()
777 self._user_main_module = FakeModule()
773
778
774 # A table holding all the namespaces IPython deals with, so that
779 # A table holding all the namespaces IPython deals with, so that
775 # introspection facilities can search easily.
780 # introspection facilities can search easily.
776 self.ns_table = {'user':user_ns,
781 self.ns_table = {'user':user_ns,
777 'user_global':user_global_ns,
782 'user_global':user_global_ns,
778 'internal':self.internal_ns,
783 'internal':self.internal_ns,
779 'builtin':__builtin__.__dict__
784 'builtin':__builtin__.__dict__
780 }
785 }
781
786
782 # Similarly, track all namespaces where references can be held and that
787 # Similarly, track all namespaces where references can be held and that
783 # we can safely clear (so it can NOT include builtin). This one can be
788 # we can safely clear (so it can NOT include builtin). This one can be
784 # a simple list.
789 # a simple list.
785 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
790 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
786 self.internal_ns, self._main_ns_cache ]
791 self.internal_ns, self._main_ns_cache ]
787
792
788 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
793 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
789 """Return a valid local and global user interactive namespaces.
794 """Return a valid local and global user interactive namespaces.
790
795
791 This builds a dict with the minimal information needed to operate as a
796 This builds a dict with the minimal information needed to operate as a
792 valid IPython user namespace, which you can pass to the various
797 valid IPython user namespace, which you can pass to the various
793 embedding classes in ipython. The default implementation returns the
798 embedding classes in ipython. The default implementation returns the
794 same dict for both the locals and the globals to allow functions to
799 same dict for both the locals and the globals to allow functions to
795 refer to variables in the namespace. Customized implementations can
800 refer to variables in the namespace. Customized implementations can
796 return different dicts. The locals dictionary can actually be anything
801 return different dicts. The locals dictionary can actually be anything
797 following the basic mapping protocol of a dict, but the globals dict
802 following the basic mapping protocol of a dict, but the globals dict
798 must be a true dict, not even a subclass. It is recommended that any
803 must be a true dict, not even a subclass. It is recommended that any
799 custom object for the locals namespace synchronize with the globals
804 custom object for the locals namespace synchronize with the globals
800 dict somehow.
805 dict somehow.
801
806
802 Raises TypeError if the provided globals namespace is not a true dict.
807 Raises TypeError if the provided globals namespace is not a true dict.
803
808
804 Parameters
809 Parameters
805 ----------
810 ----------
806 user_ns : dict-like, optional
811 user_ns : dict-like, optional
807 The current user namespace. The items in this namespace should
812 The current user namespace. The items in this namespace should
808 be included in the output. If None, an appropriate blank
813 be included in the output. If None, an appropriate blank
809 namespace should be created.
814 namespace should be created.
810 user_global_ns : dict, optional
815 user_global_ns : dict, optional
811 The current user global namespace. The items in this namespace
816 The current user global namespace. The items in this namespace
812 should be included in the output. If None, an appropriate
817 should be included in the output. If None, an appropriate
813 blank namespace should be created.
818 blank namespace should be created.
814
819
815 Returns
820 Returns
816 -------
821 -------
817 A pair of dictionary-like object to be used as the local namespace
822 A pair of dictionary-like object to be used as the local namespace
818 of the interpreter and a dict to be used as the global namespace.
823 of the interpreter and a dict to be used as the global namespace.
819 """
824 """
820
825
821
826
822 # We must ensure that __builtin__ (without the final 's') is always
827 # We must ensure that __builtin__ (without the final 's') is always
823 # available and pointing to the __builtin__ *module*. For more details:
828 # available and pointing to the __builtin__ *module*. For more details:
824 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
829 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
825
830
826 if user_ns is None:
831 if user_ns is None:
827 # Set __name__ to __main__ to better match the behavior of the
832 # Set __name__ to __main__ to better match the behavior of the
828 # normal interpreter.
833 # normal interpreter.
829 user_ns = {'__name__' :'__main__',
834 user_ns = {'__name__' :'__main__',
830 '__builtin__' : __builtin__,
835 '__builtin__' : __builtin__,
831 '__builtins__' : __builtin__,
836 '__builtins__' : __builtin__,
832 }
837 }
833 else:
838 else:
834 user_ns.setdefault('__name__','__main__')
839 user_ns.setdefault('__name__','__main__')
835 user_ns.setdefault('__builtin__',__builtin__)
840 user_ns.setdefault('__builtin__',__builtin__)
836 user_ns.setdefault('__builtins__',__builtin__)
841 user_ns.setdefault('__builtins__',__builtin__)
837
842
838 if user_global_ns is None:
843 if user_global_ns is None:
839 user_global_ns = user_ns
844 user_global_ns = user_ns
840 if type(user_global_ns) is not dict:
845 if type(user_global_ns) is not dict:
841 raise TypeError("user_global_ns must be a true dict; got %r"
846 raise TypeError("user_global_ns must be a true dict; got %r"
842 % type(user_global_ns))
847 % type(user_global_ns))
843
848
844 return user_ns, user_global_ns
849 return user_ns, user_global_ns
845
850
846 def init_sys_modules(self):
851 def init_sys_modules(self):
847 # We need to insert into sys.modules something that looks like a
852 # We need to insert into sys.modules something that looks like a
848 # module but which accesses the IPython namespace, for shelve and
853 # module but which accesses the IPython namespace, for shelve and
849 # pickle to work interactively. Normally they rely on getting
854 # pickle to work interactively. Normally they rely on getting
850 # everything out of __main__, but for embedding purposes each IPython
855 # everything out of __main__, but for embedding purposes each IPython
851 # instance has its own private namespace, so we can't go shoving
856 # instance has its own private namespace, so we can't go shoving
852 # everything into __main__.
857 # everything into __main__.
853
858
854 # note, however, that we should only do this for non-embedded
859 # note, however, that we should only do this for non-embedded
855 # ipythons, which really mimic the __main__.__dict__ with their own
860 # ipythons, which really mimic the __main__.__dict__ with their own
856 # namespace. Embedded instances, on the other hand, should not do
861 # namespace. Embedded instances, on the other hand, should not do
857 # this because they need to manage the user local/global namespaces
862 # this because they need to manage the user local/global namespaces
858 # only, but they live within a 'normal' __main__ (meaning, they
863 # only, but they live within a 'normal' __main__ (meaning, they
859 # shouldn't overtake the execution environment of the script they're
864 # shouldn't overtake the execution environment of the script they're
860 # embedded in).
865 # embedded in).
861
866
862 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
867 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
863
868
864 try:
869 try:
865 main_name = self.user_ns['__name__']
870 main_name = self.user_ns['__name__']
866 except KeyError:
871 except KeyError:
867 raise KeyError('user_ns dictionary MUST have a "__name__" key')
872 raise KeyError('user_ns dictionary MUST have a "__name__" key')
868 else:
873 else:
869 sys.modules[main_name] = FakeModule(self.user_ns)
874 sys.modules[main_name] = FakeModule(self.user_ns)
870
875
871 def init_user_ns(self):
876 def init_user_ns(self):
872 """Initialize all user-visible namespaces to their minimum defaults.
877 """Initialize all user-visible namespaces to their minimum defaults.
873
878
874 Certain history lists are also initialized here, as they effectively
879 Certain history lists are also initialized here, as they effectively
875 act as user namespaces.
880 act as user namespaces.
876
881
877 Notes
882 Notes
878 -----
883 -----
879 All data structures here are only filled in, they are NOT reset by this
884 All data structures here are only filled in, they are NOT reset by this
880 method. If they were not empty before, data will simply be added to
885 method. If they were not empty before, data will simply be added to
881 therm.
886 therm.
882 """
887 """
883 # This function works in two parts: first we put a few things in
888 # This function works in two parts: first we put a few things in
884 # user_ns, and we sync that contents into user_ns_hidden so that these
889 # user_ns, and we sync that contents into user_ns_hidden so that these
885 # initial variables aren't shown by %who. After the sync, we add the
890 # initial variables aren't shown by %who. After the sync, we add the
886 # rest of what we *do* want the user to see with %who even on a new
891 # rest of what we *do* want the user to see with %who even on a new
887 # session (probably nothing, so theye really only see their own stuff)
892 # session (probably nothing, so theye really only see their own stuff)
888
893
889 # The user dict must *always* have a __builtin__ reference to the
894 # The user dict must *always* have a __builtin__ reference to the
890 # Python standard __builtin__ namespace, which must be imported.
895 # Python standard __builtin__ namespace, which must be imported.
891 # This is so that certain operations in prompt evaluation can be
896 # This is so that certain operations in prompt evaluation can be
892 # reliably executed with builtins. Note that we can NOT use
897 # reliably executed with builtins. Note that we can NOT use
893 # __builtins__ (note the 's'), because that can either be a dict or a
898 # __builtins__ (note the 's'), because that can either be a dict or a
894 # module, and can even mutate at runtime, depending on the context
899 # module, and can even mutate at runtime, depending on the context
895 # (Python makes no guarantees on it). In contrast, __builtin__ is
900 # (Python makes no guarantees on it). In contrast, __builtin__ is
896 # always a module object, though it must be explicitly imported.
901 # always a module object, though it must be explicitly imported.
897
902
898 # For more details:
903 # For more details:
899 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
904 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
900 ns = dict(__builtin__ = __builtin__)
905 ns = dict(__builtin__ = __builtin__)
901
906
902 # Put 'help' in the user namespace
907 # Put 'help' in the user namespace
903 try:
908 try:
904 from site import _Helper
909 from site import _Helper
905 ns['help'] = _Helper()
910 ns['help'] = _Helper()
906 except ImportError:
911 except ImportError:
907 warn('help() not available - check site.py')
912 warn('help() not available - check site.py')
908
913
909 # make global variables for user access to the histories
914 # make global variables for user access to the histories
910 ns['_ih'] = self.input_hist
915 ns['_ih'] = self.input_hist
911 ns['_oh'] = self.output_hist
916 ns['_oh'] = self.output_hist
912 ns['_dh'] = self.dir_hist
917 ns['_dh'] = self.dir_hist
913
918
914 ns['_sh'] = shadowns
919 ns['_sh'] = shadowns
915
920
916 # user aliases to input and output histories. These shouldn't show up
921 # user aliases to input and output histories. These shouldn't show up
917 # in %who, as they can have very large reprs.
922 # in %who, as they can have very large reprs.
918 ns['In'] = self.input_hist
923 ns['In'] = self.input_hist
919 ns['Out'] = self.output_hist
924 ns['Out'] = self.output_hist
920
925
921 # Store myself as the public api!!!
926 # Store myself as the public api!!!
922 ns['get_ipython'] = self.get_ipython
927 ns['get_ipython'] = self.get_ipython
923
928
924 # Sync what we've added so far to user_ns_hidden so these aren't seen
929 # Sync what we've added so far to user_ns_hidden so these aren't seen
925 # by %who
930 # by %who
926 self.user_ns_hidden.update(ns)
931 self.user_ns_hidden.update(ns)
927
932
928 # Anything put into ns now would show up in %who. Think twice before
933 # Anything put into ns now would show up in %who. Think twice before
929 # putting anything here, as we really want %who to show the user their
934 # putting anything here, as we really want %who to show the user their
930 # stuff, not our variables.
935 # stuff, not our variables.
931
936
932 # Finally, update the real user's namespace
937 # Finally, update the real user's namespace
933 self.user_ns.update(ns)
938 self.user_ns.update(ns)
934
939
935
940
936 def reset(self):
941 def reset(self):
937 """Clear all internal namespaces.
942 """Clear all internal namespaces.
938
943
939 Note that this is much more aggressive than %reset, since it clears
944 Note that this is much more aggressive than %reset, since it clears
940 fully all namespaces, as well as all input/output lists.
945 fully all namespaces, as well as all input/output lists.
941 """
946 """
942 for ns in self.ns_refs_table:
947 for ns in self.ns_refs_table:
943 ns.clear()
948 ns.clear()
944
949
945 self.alias_manager.clear_aliases()
950 self.alias_manager.clear_aliases()
946
951
947 # Clear input and output histories
952 # Clear input and output histories
948 self.input_hist[:] = []
953 self.input_hist[:] = []
949 self.input_hist_raw[:] = []
954 self.input_hist_raw[:] = []
950 self.output_hist.clear()
955 self.output_hist.clear()
951
956
952 # Restore the user namespaces to minimal usability
957 # Restore the user namespaces to minimal usability
953 self.init_user_ns()
958 self.init_user_ns()
954
959
955 # Restore the default and user aliases
960 # Restore the default and user aliases
956 self.alias_manager.init_aliases()
961 self.alias_manager.init_aliases()
957
962
958 def reset_selective(self, regex=None):
963 def reset_selective(self, regex=None):
959 """Clear selective variables from internal namespaces based on a
964 """Clear selective variables from internal namespaces based on a
960 specified regular expression.
965 specified regular expression.
961
966
962 Parameters
967 Parameters
963 ----------
968 ----------
964 regex : string or compiled pattern, optional
969 regex : string or compiled pattern, optional
965 A regular expression pattern that will be used in searching
970 A regular expression pattern that will be used in searching
966 variable names in the users namespaces.
971 variable names in the users namespaces.
967 """
972 """
968 if regex is not None:
973 if regex is not None:
969 try:
974 try:
970 m = re.compile(regex)
975 m = re.compile(regex)
971 except TypeError:
976 except TypeError:
972 raise TypeError('regex must be a string or compiled pattern')
977 raise TypeError('regex must be a string or compiled pattern')
973 # Search for keys in each namespace that match the given regex
978 # Search for keys in each namespace that match the given regex
974 # If a match is found, delete the key/value pair.
979 # If a match is found, delete the key/value pair.
975 for ns in self.ns_refs_table:
980 for ns in self.ns_refs_table:
976 for var in ns:
981 for var in ns:
977 if m.search(var):
982 if m.search(var):
978 del ns[var]
983 del ns[var]
979
984
980 def push(self, variables, interactive=True):
985 def push(self, variables, interactive=True):
981 """Inject a group of variables into the IPython user namespace.
986 """Inject a group of variables into the IPython user namespace.
982
987
983 Parameters
988 Parameters
984 ----------
989 ----------
985 variables : dict, str or list/tuple of str
990 variables : dict, str or list/tuple of str
986 The variables to inject into the user's namespace. If a dict, a
991 The variables to inject into the user's namespace. If a dict, a
987 simple update is done. If a str, the string is assumed to have
992 simple update is done. If a str, the string is assumed to have
988 variable names separated by spaces. A list/tuple of str can also
993 variable names separated by spaces. A list/tuple of str can also
989 be used to give the variable names. If just the variable names are
994 be used to give the variable names. If just the variable names are
990 give (list/tuple/str) then the variable values looked up in the
995 give (list/tuple/str) then the variable values looked up in the
991 callers frame.
996 callers frame.
992 interactive : bool
997 interactive : bool
993 If True (default), the variables will be listed with the ``who``
998 If True (default), the variables will be listed with the ``who``
994 magic.
999 magic.
995 """
1000 """
996 vdict = None
1001 vdict = None
997
1002
998 # We need a dict of name/value pairs to do namespace updates.
1003 # We need a dict of name/value pairs to do namespace updates.
999 if isinstance(variables, dict):
1004 if isinstance(variables, dict):
1000 vdict = variables
1005 vdict = variables
1001 elif isinstance(variables, (basestring, list, tuple)):
1006 elif isinstance(variables, (basestring, list, tuple)):
1002 if isinstance(variables, basestring):
1007 if isinstance(variables, basestring):
1003 vlist = variables.split()
1008 vlist = variables.split()
1004 else:
1009 else:
1005 vlist = variables
1010 vlist = variables
1006 vdict = {}
1011 vdict = {}
1007 cf = sys._getframe(1)
1012 cf = sys._getframe(1)
1008 for name in vlist:
1013 for name in vlist:
1009 try:
1014 try:
1010 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1015 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1011 except:
1016 except:
1012 print ('Could not get variable %s from %s' %
1017 print ('Could not get variable %s from %s' %
1013 (name,cf.f_code.co_name))
1018 (name,cf.f_code.co_name))
1014 else:
1019 else:
1015 raise ValueError('variables must be a dict/str/list/tuple')
1020 raise ValueError('variables must be a dict/str/list/tuple')
1016
1021
1017 # Propagate variables to user namespace
1022 # Propagate variables to user namespace
1018 self.user_ns.update(vdict)
1023 self.user_ns.update(vdict)
1019
1024
1020 # And configure interactive visibility
1025 # And configure interactive visibility
1021 config_ns = self.user_ns_hidden
1026 config_ns = self.user_ns_hidden
1022 if interactive:
1027 if interactive:
1023 for name, val in vdict.iteritems():
1028 for name, val in vdict.iteritems():
1024 config_ns.pop(name, None)
1029 config_ns.pop(name, None)
1025 else:
1030 else:
1026 for name,val in vdict.iteritems():
1031 for name,val in vdict.iteritems():
1027 config_ns[name] = val
1032 config_ns[name] = val
1028
1033
1029 #-------------------------------------------------------------------------
1034 #-------------------------------------------------------------------------
1030 # Things related to object introspection
1035 # Things related to object introspection
1031 #-------------------------------------------------------------------------
1036 #-------------------------------------------------------------------------
1032 def _ofind(self, oname, namespaces=None):
1037 def _ofind(self, oname, namespaces=None):
1033 """Find an object in the available namespaces.
1038 """Find an object in the available namespaces.
1034
1039
1035 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1040 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1036
1041
1037 Has special code to detect magic functions.
1042 Has special code to detect magic functions.
1038 """
1043 """
1039 #oname = oname.strip()
1044 #oname = oname.strip()
1040 #print '1- oname: <%r>' % oname # dbg
1045 #print '1- oname: <%r>' % oname # dbg
1041 try:
1046 try:
1042 oname = oname.strip().encode('ascii')
1047 oname = oname.strip().encode('ascii')
1043 #print '2- oname: <%r>' % oname # dbg
1048 #print '2- oname: <%r>' % oname # dbg
1044 except UnicodeEncodeError:
1049 except UnicodeEncodeError:
1045 print 'Python identifiers can only contain ascii characters.'
1050 print 'Python identifiers can only contain ascii characters.'
1046 return dict(found=False)
1051 return dict(found=False)
1047
1052
1048 alias_ns = None
1053 alias_ns = None
1049 if namespaces is None:
1054 if namespaces is None:
1050 # Namespaces to search in:
1055 # Namespaces to search in:
1051 # Put them in a list. The order is important so that we
1056 # Put them in a list. The order is important so that we
1052 # find things in the same order that Python finds them.
1057 # find things in the same order that Python finds them.
1053 namespaces = [ ('Interactive', self.user_ns),
1058 namespaces = [ ('Interactive', self.user_ns),
1054 ('IPython internal', self.internal_ns),
1059 ('IPython internal', self.internal_ns),
1055 ('Python builtin', __builtin__.__dict__),
1060 ('Python builtin', __builtin__.__dict__),
1056 ('Alias', self.alias_manager.alias_table),
1061 ('Alias', self.alias_manager.alias_table),
1057 ]
1062 ]
1058 alias_ns = self.alias_manager.alias_table
1063 alias_ns = self.alias_manager.alias_table
1059
1064
1060 # initialize results to 'null'
1065 # initialize results to 'null'
1061 found = False; obj = None; ospace = None; ds = None;
1066 found = False; obj = None; ospace = None; ds = None;
1062 ismagic = False; isalias = False; parent = None
1067 ismagic = False; isalias = False; parent = None
1063
1068
1064 # We need to special-case 'print', which as of python2.6 registers as a
1069 # We need to special-case 'print', which as of python2.6 registers as a
1065 # function but should only be treated as one if print_function was
1070 # function but should only be treated as one if print_function was
1066 # loaded with a future import. In this case, just bail.
1071 # loaded with a future import. In this case, just bail.
1067 if (oname == 'print' and not (self.compile.compiler.flags &
1072 if (oname == 'print' and not (self.compile.compiler.flags &
1068 __future__.CO_FUTURE_PRINT_FUNCTION)):
1073 __future__.CO_FUTURE_PRINT_FUNCTION)):
1069 return {'found':found, 'obj':obj, 'namespace':ospace,
1074 return {'found':found, 'obj':obj, 'namespace':ospace,
1070 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1075 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1071
1076
1072 # Look for the given name by splitting it in parts. If the head is
1077 # Look for the given name by splitting it in parts. If the head is
1073 # found, then we look for all the remaining parts as members, and only
1078 # found, then we look for all the remaining parts as members, and only
1074 # declare success if we can find them all.
1079 # declare success if we can find them all.
1075 oname_parts = oname.split('.')
1080 oname_parts = oname.split('.')
1076 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1081 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1077 for nsname,ns in namespaces:
1082 for nsname,ns in namespaces:
1078 try:
1083 try:
1079 obj = ns[oname_head]
1084 obj = ns[oname_head]
1080 except KeyError:
1085 except KeyError:
1081 continue
1086 continue
1082 else:
1087 else:
1083 #print 'oname_rest:', oname_rest # dbg
1088 #print 'oname_rest:', oname_rest # dbg
1084 for part in oname_rest:
1089 for part in oname_rest:
1085 try:
1090 try:
1086 parent = obj
1091 parent = obj
1087 obj = getattr(obj,part)
1092 obj = getattr(obj,part)
1088 except:
1093 except:
1089 # Blanket except b/c some badly implemented objects
1094 # Blanket except b/c some badly implemented objects
1090 # allow __getattr__ to raise exceptions other than
1095 # allow __getattr__ to raise exceptions other than
1091 # AttributeError, which then crashes IPython.
1096 # AttributeError, which then crashes IPython.
1092 break
1097 break
1093 else:
1098 else:
1094 # If we finish the for loop (no break), we got all members
1099 # If we finish the for loop (no break), we got all members
1095 found = True
1100 found = True
1096 ospace = nsname
1101 ospace = nsname
1097 if ns == alias_ns:
1102 if ns == alias_ns:
1098 isalias = True
1103 isalias = True
1099 break # namespace loop
1104 break # namespace loop
1100
1105
1101 # Try to see if it's magic
1106 # Try to see if it's magic
1102 if not found:
1107 if not found:
1103 if oname.startswith(ESC_MAGIC):
1108 if oname.startswith(ESC_MAGIC):
1104 oname = oname[1:]
1109 oname = oname[1:]
1105 obj = getattr(self,'magic_'+oname,None)
1110 obj = getattr(self,'magic_'+oname,None)
1106 if obj is not None:
1111 if obj is not None:
1107 found = True
1112 found = True
1108 ospace = 'IPython internal'
1113 ospace = 'IPython internal'
1109 ismagic = True
1114 ismagic = True
1110
1115
1111 # Last try: special-case some literals like '', [], {}, etc:
1116 # Last try: special-case some literals like '', [], {}, etc:
1112 if not found and oname_head in ["''",'""','[]','{}','()']:
1117 if not found and oname_head in ["''",'""','[]','{}','()']:
1113 obj = eval(oname_head)
1118 obj = eval(oname_head)
1114 found = True
1119 found = True
1115 ospace = 'Interactive'
1120 ospace = 'Interactive'
1116
1121
1117 return {'found':found, 'obj':obj, 'namespace':ospace,
1122 return {'found':found, 'obj':obj, 'namespace':ospace,
1118 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1123 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1119
1124
1120 def _ofind_property(self, oname, info):
1125 def _ofind_property(self, oname, info):
1121 """Second part of object finding, to look for property details."""
1126 """Second part of object finding, to look for property details."""
1122 if info.found:
1127 if info.found:
1123 # Get the docstring of the class property if it exists.
1128 # Get the docstring of the class property if it exists.
1124 path = oname.split('.')
1129 path = oname.split('.')
1125 root = '.'.join(path[:-1])
1130 root = '.'.join(path[:-1])
1126 if info.parent is not None:
1131 if info.parent is not None:
1127 try:
1132 try:
1128 target = getattr(info.parent, '__class__')
1133 target = getattr(info.parent, '__class__')
1129 # The object belongs to a class instance.
1134 # The object belongs to a class instance.
1130 try:
1135 try:
1131 target = getattr(target, path[-1])
1136 target = getattr(target, path[-1])
1132 # The class defines the object.
1137 # The class defines the object.
1133 if isinstance(target, property):
1138 if isinstance(target, property):
1134 oname = root + '.__class__.' + path[-1]
1139 oname = root + '.__class__.' + path[-1]
1135 info = Struct(self._ofind(oname))
1140 info = Struct(self._ofind(oname))
1136 except AttributeError: pass
1141 except AttributeError: pass
1137 except AttributeError: pass
1142 except AttributeError: pass
1138
1143
1139 # We return either the new info or the unmodified input if the object
1144 # We return either the new info or the unmodified input if the object
1140 # hadn't been found
1145 # hadn't been found
1141 return info
1146 return info
1142
1147
1143 def _object_find(self, oname, namespaces=None):
1148 def _object_find(self, oname, namespaces=None):
1144 """Find an object and return a struct with info about it."""
1149 """Find an object and return a struct with info about it."""
1145 inf = Struct(self._ofind(oname, namespaces))
1150 inf = Struct(self._ofind(oname, namespaces))
1146 return Struct(self._ofind_property(oname, inf))
1151 return Struct(self._ofind_property(oname, inf))
1147
1152
1148 def _inspect(self, meth, oname, namespaces=None, **kw):
1153 def _inspect(self, meth, oname, namespaces=None, **kw):
1149 """Generic interface to the inspector system.
1154 """Generic interface to the inspector system.
1150
1155
1151 This function is meant to be called by pdef, pdoc & friends."""
1156 This function is meant to be called by pdef, pdoc & friends."""
1152 info = self._object_find(oname)
1157 info = self._object_find(oname)
1153 if info.found:
1158 if info.found:
1154 pmethod = getattr(self.inspector, meth)
1159 pmethod = getattr(self.inspector, meth)
1155 formatter = format_screen if info.ismagic else None
1160 formatter = format_screen if info.ismagic else None
1156 if meth == 'pdoc':
1161 if meth == 'pdoc':
1157 pmethod(info.obj, oname, formatter)
1162 pmethod(info.obj, oname, formatter)
1158 elif meth == 'pinfo':
1163 elif meth == 'pinfo':
1159 pmethod(info.obj, oname, formatter, info, **kw)
1164 pmethod(info.obj, oname, formatter, info, **kw)
1160 else:
1165 else:
1161 pmethod(info.obj, oname)
1166 pmethod(info.obj, oname)
1162 else:
1167 else:
1163 print 'Object `%s` not found.' % oname
1168 print 'Object `%s` not found.' % oname
1164 return 'not found' # so callers can take other action
1169 return 'not found' # so callers can take other action
1165
1170
1166 def object_inspect(self, oname):
1171 def object_inspect(self, oname):
1167 info = self._object_find(oname)
1172 info = self._object_find(oname)
1168 if info.found:
1173 if info.found:
1169 return self.inspector.info(info.obj, info=info)
1174 return self.inspector.info(info.obj, info=info)
1170 else:
1175 else:
1171 return oinspect.mk_object_info({'found' : False})
1176 return oinspect.mk_object_info({'found' : False})
1172
1177
1173 #-------------------------------------------------------------------------
1178 #-------------------------------------------------------------------------
1174 # Things related to history management
1179 # Things related to history management
1175 #-------------------------------------------------------------------------
1180 #-------------------------------------------------------------------------
1176
1181
1177 def init_history(self):
1182 def init_history(self):
1178 # List of input with multi-line handling.
1183 # List of input with multi-line handling.
1179 self.input_hist = InputList()
1184 self.input_hist = InputList()
1180 # This one will hold the 'raw' input history, without any
1185 # This one will hold the 'raw' input history, without any
1181 # pre-processing. This will allow users to retrieve the input just as
1186 # pre-processing. This will allow users to retrieve the input just as
1182 # it was exactly typed in by the user, with %hist -r.
1187 # it was exactly typed in by the user, with %hist -r.
1183 self.input_hist_raw = InputList()
1188 self.input_hist_raw = InputList()
1184
1189
1185 # list of visited directories
1190 # list of visited directories
1186 try:
1191 try:
1187 self.dir_hist = [os.getcwd()]
1192 self.dir_hist = [os.getcwd()]
1188 except OSError:
1193 except OSError:
1189 self.dir_hist = []
1194 self.dir_hist = []
1190
1195
1191 # dict of output history
1196 # dict of output history
1192 self.output_hist = {}
1197 self.output_hist = {}
1193
1198
1194 # Now the history file
1199 # Now the history file
1195 if self.profile:
1200 if self.profile:
1196 histfname = 'history-%s' % self.profile
1201 histfname = 'history-%s' % self.profile
1197 else:
1202 else:
1198 histfname = 'history'
1203 histfname = 'history'
1199 self.histfile = os.path.join(self.ipython_dir, histfname)
1204 self.histfile = os.path.join(self.ipython_dir, histfname)
1200
1205
1201 # Fill the history zero entry, user counter starts at 1
1206 # Fill the history zero entry, user counter starts at 1
1202 self.input_hist.append('\n')
1207 self.input_hist.append('\n')
1203 self.input_hist_raw.append('\n')
1208 self.input_hist_raw.append('\n')
1204
1209
1205 def init_shadow_hist(self):
1210 def init_shadow_hist(self):
1206 try:
1211 try:
1207 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1212 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1208 except exceptions.UnicodeDecodeError:
1213 except exceptions.UnicodeDecodeError:
1209 print "Your ipython_dir can't be decoded to unicode!"
1214 print "Your ipython_dir can't be decoded to unicode!"
1210 print "Please set HOME environment variable to something that"
1215 print "Please set HOME environment variable to something that"
1211 print r"only has ASCII characters, e.g. c:\home"
1216 print r"only has ASCII characters, e.g. c:\home"
1212 print "Now it is", self.ipython_dir
1217 print "Now it is", self.ipython_dir
1213 sys.exit()
1218 sys.exit()
1214 self.shadowhist = ipcorehist.ShadowHist(self.db)
1219 self.shadowhist = ipcorehist.ShadowHist(self.db)
1215
1220
1216 def savehist(self):
1221 def savehist(self):
1217 """Save input history to a file (via readline library)."""
1222 """Save input history to a file (via readline library)."""
1218
1223
1219 try:
1224 try:
1220 self.readline.write_history_file(self.histfile)
1225 self.readline.write_history_file(self.histfile)
1221 except:
1226 except:
1222 print 'Unable to save IPython command history to file: ' + \
1227 print 'Unable to save IPython command history to file: ' + \
1223 `self.histfile`
1228 `self.histfile`
1224
1229
1225 def reloadhist(self):
1230 def reloadhist(self):
1226 """Reload the input history from disk file."""
1231 """Reload the input history from disk file."""
1227
1232
1228 try:
1233 try:
1229 self.readline.clear_history()
1234 self.readline.clear_history()
1230 self.readline.read_history_file(self.shell.histfile)
1235 self.readline.read_history_file(self.shell.histfile)
1231 except AttributeError:
1236 except AttributeError:
1232 pass
1237 pass
1233
1238
1234 def history_saving_wrapper(self, func):
1239 def history_saving_wrapper(self, func):
1235 """ Wrap func for readline history saving
1240 """ Wrap func for readline history saving
1236
1241
1237 Convert func into callable that saves & restores
1242 Convert func into callable that saves & restores
1238 history around the call """
1243 history around the call """
1239
1244
1240 if self.has_readline:
1245 if self.has_readline:
1241 from IPython.utils import rlineimpl as readline
1246 from IPython.utils import rlineimpl as readline
1242 else:
1247 else:
1243 return func
1248 return func
1244
1249
1245 def wrapper():
1250 def wrapper():
1246 self.savehist()
1251 self.savehist()
1247 try:
1252 try:
1248 func()
1253 func()
1249 finally:
1254 finally:
1250 readline.read_history_file(self.histfile)
1255 readline.read_history_file(self.histfile)
1251 return wrapper
1256 return wrapper
1252
1257
1253 def get_history(self, index=None, raw=False, output=True):
1258 def get_history(self, index=None, raw=False, output=True):
1254 """Get the history list.
1259 """Get the history list.
1255
1260
1256 Get the input and output history.
1261 Get the input and output history.
1257
1262
1258 Parameters
1263 Parameters
1259 ----------
1264 ----------
1260 index : n or (n1, n2) or None
1265 index : n or (n1, n2) or None
1261 If n, then the last entries. If a tuple, then all in
1266 If n, then the last entries. If a tuple, then all in
1262 range(n1, n2). If None, then all entries. Raises IndexError if
1267 range(n1, n2). If None, then all entries. Raises IndexError if
1263 the format of index is incorrect.
1268 the format of index is incorrect.
1264 raw : bool
1269 raw : bool
1265 If True, return the raw input.
1270 If True, return the raw input.
1266 output : bool
1271 output : bool
1267 If True, then return the output as well.
1272 If True, then return the output as well.
1268
1273
1269 Returns
1274 Returns
1270 -------
1275 -------
1271 If output is True, then return a dict of tuples, keyed by the prompt
1276 If output is True, then return a dict of tuples, keyed by the prompt
1272 numbers and with values of (input, output). If output is False, then
1277 numbers and with values of (input, output). If output is False, then
1273 a dict, keyed by the prompt number with the values of input. Raises
1278 a dict, keyed by the prompt number with the values of input. Raises
1274 IndexError if no history is found.
1279 IndexError if no history is found.
1275 """
1280 """
1276 if raw:
1281 if raw:
1277 input_hist = self.input_hist_raw
1282 input_hist = self.input_hist_raw
1278 else:
1283 else:
1279 input_hist = self.input_hist
1284 input_hist = self.input_hist
1280 if output:
1285 if output:
1281 output_hist = self.user_ns['Out']
1286 output_hist = self.user_ns['Out']
1282 n = len(input_hist)
1287 n = len(input_hist)
1283 if index is None:
1288 if index is None:
1284 start=0; stop=n
1289 start=0; stop=n
1285 elif isinstance(index, int):
1290 elif isinstance(index, int):
1286 start=n-index; stop=n
1291 start=n-index; stop=n
1287 elif isinstance(index, tuple) and len(index) == 2:
1292 elif isinstance(index, tuple) and len(index) == 2:
1288 start=index[0]; stop=index[1]
1293 start=index[0]; stop=index[1]
1289 else:
1294 else:
1290 raise IndexError('Not a valid index for the input history: %r'
1295 raise IndexError('Not a valid index for the input history: %r'
1291 % index)
1296 % index)
1292 hist = {}
1297 hist = {}
1293 for i in range(start, stop):
1298 for i in range(start, stop):
1294 if output:
1299 if output:
1295 hist[i] = (input_hist[i], output_hist.get(i))
1300 hist[i] = (input_hist[i], output_hist.get(i))
1296 else:
1301 else:
1297 hist[i] = input_hist[i]
1302 hist[i] = input_hist[i]
1298 if len(hist)==0:
1303 if len(hist)==0:
1299 raise IndexError('No history for range of indices: %r' % index)
1304 raise IndexError('No history for range of indices: %r' % index)
1300 return hist
1305 return hist
1301
1306
1302 #-------------------------------------------------------------------------
1307 #-------------------------------------------------------------------------
1303 # Things related to exception handling and tracebacks (not debugging)
1308 # Things related to exception handling and tracebacks (not debugging)
1304 #-------------------------------------------------------------------------
1309 #-------------------------------------------------------------------------
1305
1310
1306 def init_traceback_handlers(self, custom_exceptions):
1311 def init_traceback_handlers(self, custom_exceptions):
1307 # Syntax error handler.
1312 # Syntax error handler.
1308 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1313 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1309
1314
1310 # The interactive one is initialized with an offset, meaning we always
1315 # The interactive one is initialized with an offset, meaning we always
1311 # want to remove the topmost item in the traceback, which is our own
1316 # want to remove the topmost item in the traceback, which is our own
1312 # internal code. Valid modes: ['Plain','Context','Verbose']
1317 # internal code. Valid modes: ['Plain','Context','Verbose']
1313 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1318 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1314 color_scheme='NoColor',
1319 color_scheme='NoColor',
1315 tb_offset = 1)
1320 tb_offset = 1)
1316
1321
1317 # The instance will store a pointer to the system-wide exception hook,
1322 # The instance will store a pointer to the system-wide exception hook,
1318 # so that runtime code (such as magics) can access it. This is because
1323 # so that runtime code (such as magics) can access it. This is because
1319 # during the read-eval loop, it may get temporarily overwritten.
1324 # during the read-eval loop, it may get temporarily overwritten.
1320 self.sys_excepthook = sys.excepthook
1325 self.sys_excepthook = sys.excepthook
1321
1326
1322 # and add any custom exception handlers the user may have specified
1327 # and add any custom exception handlers the user may have specified
1323 self.set_custom_exc(*custom_exceptions)
1328 self.set_custom_exc(*custom_exceptions)
1324
1329
1325 # Set the exception mode
1330 # Set the exception mode
1326 self.InteractiveTB.set_mode(mode=self.xmode)
1331 self.InteractiveTB.set_mode(mode=self.xmode)
1327
1332
1328 def set_custom_exc(self, exc_tuple, handler):
1333 def set_custom_exc(self, exc_tuple, handler):
1329 """set_custom_exc(exc_tuple,handler)
1334 """set_custom_exc(exc_tuple,handler)
1330
1335
1331 Set a custom exception handler, which will be called if any of the
1336 Set a custom exception handler, which will be called if any of the
1332 exceptions in exc_tuple occur in the mainloop (specifically, in the
1337 exceptions in exc_tuple occur in the mainloop (specifically, in the
1333 runcode() method.
1338 runcode() method.
1334
1339
1335 Inputs:
1340 Inputs:
1336
1341
1337 - exc_tuple: a *tuple* of valid exceptions to call the defined
1342 - exc_tuple: a *tuple* of valid exceptions to call the defined
1338 handler for. It is very important that you use a tuple, and NOT A
1343 handler for. It is very important that you use a tuple, and NOT A
1339 LIST here, because of the way Python's except statement works. If
1344 LIST here, because of the way Python's except statement works. If
1340 you only want to trap a single exception, use a singleton tuple:
1345 you only want to trap a single exception, use a singleton tuple:
1341
1346
1342 exc_tuple == (MyCustomException,)
1347 exc_tuple == (MyCustomException,)
1343
1348
1344 - handler: this must be defined as a function with the following
1349 - handler: this must be defined as a function with the following
1345 basic interface::
1350 basic interface::
1346
1351
1347 def my_handler(self, etype, value, tb, tb_offset=None)
1352 def my_handler(self, etype, value, tb, tb_offset=None)
1348 ...
1353 ...
1349 # The return value must be
1354 # The return value must be
1350 return structured_traceback
1355 return structured_traceback
1351
1356
1352 This will be made into an instance method (via new.instancemethod)
1357 This will be made into an instance method (via new.instancemethod)
1353 of IPython itself, and it will be called if any of the exceptions
1358 of IPython itself, and it will be called if any of the exceptions
1354 listed in the exc_tuple are caught. If the handler is None, an
1359 listed in the exc_tuple are caught. If the handler is None, an
1355 internal basic one is used, which just prints basic info.
1360 internal basic one is used, which just prints basic info.
1356
1361
1357 WARNING: by putting in your own exception handler into IPython's main
1362 WARNING: by putting in your own exception handler into IPython's main
1358 execution loop, you run a very good chance of nasty crashes. This
1363 execution loop, you run a very good chance of nasty crashes. This
1359 facility should only be used if you really know what you are doing."""
1364 facility should only be used if you really know what you are doing."""
1360
1365
1361 assert type(exc_tuple)==type(()) , \
1366 assert type(exc_tuple)==type(()) , \
1362 "The custom exceptions must be given AS A TUPLE."
1367 "The custom exceptions must be given AS A TUPLE."
1363
1368
1364 def dummy_handler(self,etype,value,tb):
1369 def dummy_handler(self,etype,value,tb):
1365 print '*** Simple custom exception handler ***'
1370 print '*** Simple custom exception handler ***'
1366 print 'Exception type :',etype
1371 print 'Exception type :',etype
1367 print 'Exception value:',value
1372 print 'Exception value:',value
1368 print 'Traceback :',tb
1373 print 'Traceback :',tb
1369 print 'Source code :','\n'.join(self.buffer)
1374 print 'Source code :','\n'.join(self.buffer)
1370
1375
1371 if handler is None: handler = dummy_handler
1376 if handler is None: handler = dummy_handler
1372
1377
1373 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1378 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1374 self.custom_exceptions = exc_tuple
1379 self.custom_exceptions = exc_tuple
1375
1380
1376 def excepthook(self, etype, value, tb):
1381 def excepthook(self, etype, value, tb):
1377 """One more defense for GUI apps that call sys.excepthook.
1382 """One more defense for GUI apps that call sys.excepthook.
1378
1383
1379 GUI frameworks like wxPython trap exceptions and call
1384 GUI frameworks like wxPython trap exceptions and call
1380 sys.excepthook themselves. I guess this is a feature that
1385 sys.excepthook themselves. I guess this is a feature that
1381 enables them to keep running after exceptions that would
1386 enables them to keep running after exceptions that would
1382 otherwise kill their mainloop. This is a bother for IPython
1387 otherwise kill their mainloop. This is a bother for IPython
1383 which excepts to catch all of the program exceptions with a try:
1388 which excepts to catch all of the program exceptions with a try:
1384 except: statement.
1389 except: statement.
1385
1390
1386 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1391 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1387 any app directly invokes sys.excepthook, it will look to the user like
1392 any app directly invokes sys.excepthook, it will look to the user like
1388 IPython crashed. In order to work around this, we can disable the
1393 IPython crashed. In order to work around this, we can disable the
1389 CrashHandler and replace it with this excepthook instead, which prints a
1394 CrashHandler and replace it with this excepthook instead, which prints a
1390 regular traceback using our InteractiveTB. In this fashion, apps which
1395 regular traceback using our InteractiveTB. In this fashion, apps which
1391 call sys.excepthook will generate a regular-looking exception from
1396 call sys.excepthook will generate a regular-looking exception from
1392 IPython, and the CrashHandler will only be triggered by real IPython
1397 IPython, and the CrashHandler will only be triggered by real IPython
1393 crashes.
1398 crashes.
1394
1399
1395 This hook should be used sparingly, only in places which are not likely
1400 This hook should be used sparingly, only in places which are not likely
1396 to be true IPython errors.
1401 to be true IPython errors.
1397 """
1402 """
1398 self.showtraceback((etype,value,tb),tb_offset=0)
1403 self.showtraceback((etype,value,tb),tb_offset=0)
1399
1404
1400 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1405 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1401 exception_only=False):
1406 exception_only=False):
1402 """Display the exception that just occurred.
1407 """Display the exception that just occurred.
1403
1408
1404 If nothing is known about the exception, this is the method which
1409 If nothing is known about the exception, this is the method which
1405 should be used throughout the code for presenting user tracebacks,
1410 should be used throughout the code for presenting user tracebacks,
1406 rather than directly invoking the InteractiveTB object.
1411 rather than directly invoking the InteractiveTB object.
1407
1412
1408 A specific showsyntaxerror() also exists, but this method can take
1413 A specific showsyntaxerror() also exists, but this method can take
1409 care of calling it if needed, so unless you are explicitly catching a
1414 care of calling it if needed, so unless you are explicitly catching a
1410 SyntaxError exception, don't try to analyze the stack manually and
1415 SyntaxError exception, don't try to analyze the stack manually and
1411 simply call this method."""
1416 simply call this method."""
1412
1417
1413 try:
1418 try:
1414 if exc_tuple is None:
1419 if exc_tuple is None:
1415 etype, value, tb = sys.exc_info()
1420 etype, value, tb = sys.exc_info()
1416 else:
1421 else:
1417 etype, value, tb = exc_tuple
1422 etype, value, tb = exc_tuple
1418
1423
1419 if etype is None:
1424 if etype is None:
1420 if hasattr(sys, 'last_type'):
1425 if hasattr(sys, 'last_type'):
1421 etype, value, tb = sys.last_type, sys.last_value, \
1426 etype, value, tb = sys.last_type, sys.last_value, \
1422 sys.last_traceback
1427 sys.last_traceback
1423 else:
1428 else:
1424 self.write_err('No traceback available to show.\n')
1429 self.write_err('No traceback available to show.\n')
1425 return
1430 return
1426
1431
1427 if etype is SyntaxError:
1432 if etype is SyntaxError:
1428 # Though this won't be called by syntax errors in the input
1433 # Though this won't be called by syntax errors in the input
1429 # line, there may be SyntaxError cases whith imported code.
1434 # line, there may be SyntaxError cases whith imported code.
1430 self.showsyntaxerror(filename)
1435 self.showsyntaxerror(filename)
1431 elif etype is UsageError:
1436 elif etype is UsageError:
1432 print "UsageError:", value
1437 print "UsageError:", value
1433 else:
1438 else:
1434 # WARNING: these variables are somewhat deprecated and not
1439 # WARNING: these variables are somewhat deprecated and not
1435 # necessarily safe to use in a threaded environment, but tools
1440 # necessarily safe to use in a threaded environment, but tools
1436 # like pdb depend on their existence, so let's set them. If we
1441 # like pdb depend on their existence, so let's set them. If we
1437 # find problems in the field, we'll need to revisit their use.
1442 # find problems in the field, we'll need to revisit their use.
1438 sys.last_type = etype
1443 sys.last_type = etype
1439 sys.last_value = value
1444 sys.last_value = value
1440 sys.last_traceback = tb
1445 sys.last_traceback = tb
1441
1446
1442 if etype in self.custom_exceptions:
1447 if etype in self.custom_exceptions:
1443 # FIXME: Old custom traceback objects may just return a
1448 # FIXME: Old custom traceback objects may just return a
1444 # string, in that case we just put it into a list
1449 # string, in that case we just put it into a list
1445 stb = self.CustomTB(etype, value, tb, tb_offset)
1450 stb = self.CustomTB(etype, value, tb, tb_offset)
1446 if isinstance(ctb, basestring):
1451 if isinstance(ctb, basestring):
1447 stb = [stb]
1452 stb = [stb]
1448 else:
1453 else:
1449 if exception_only:
1454 if exception_only:
1450 stb = ['An exception has occurred, use %tb to see '
1455 stb = ['An exception has occurred, use %tb to see '
1451 'the full traceback.\n']
1456 'the full traceback.\n']
1452 stb.extend(self.InteractiveTB.get_exception_only(etype,
1457 stb.extend(self.InteractiveTB.get_exception_only(etype,
1453 value))
1458 value))
1454 else:
1459 else:
1455 stb = self.InteractiveTB.structured_traceback(etype,
1460 stb = self.InteractiveTB.structured_traceback(etype,
1456 value, tb, tb_offset=tb_offset)
1461 value, tb, tb_offset=tb_offset)
1457 # FIXME: the pdb calling should be done by us, not by
1462 # FIXME: the pdb calling should be done by us, not by
1458 # the code computing the traceback.
1463 # the code computing the traceback.
1459 if self.InteractiveTB.call_pdb:
1464 if self.InteractiveTB.call_pdb:
1460 # pdb mucks up readline, fix it back
1465 # pdb mucks up readline, fix it back
1461 self.set_readline_completer()
1466 self.set_readline_completer()
1462
1467
1463 # Actually show the traceback
1468 # Actually show the traceback
1464 self._showtraceback(etype, value, stb)
1469 self._showtraceback(etype, value, stb)
1465
1470
1466 except KeyboardInterrupt:
1471 except KeyboardInterrupt:
1467 self.write_err("\nKeyboardInterrupt\n")
1472 self.write_err("\nKeyboardInterrupt\n")
1468
1473
1469 def _showtraceback(self, etype, evalue, stb):
1474 def _showtraceback(self, etype, evalue, stb):
1470 """Actually show a traceback.
1475 """Actually show a traceback.
1471
1476
1472 Subclasses may override this method to put the traceback on a different
1477 Subclasses may override this method to put the traceback on a different
1473 place, like a side channel.
1478 place, like a side channel.
1474 """
1479 """
1475 # FIXME: this should use the proper write channels, but our test suite
1480 # FIXME: this should use the proper write channels, but our test suite
1476 # relies on it coming out of stdout...
1481 # relies on it coming out of stdout...
1477 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1482 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1478
1483
1479 def showsyntaxerror(self, filename=None):
1484 def showsyntaxerror(self, filename=None):
1480 """Display the syntax error that just occurred.
1485 """Display the syntax error that just occurred.
1481
1486
1482 This doesn't display a stack trace because there isn't one.
1487 This doesn't display a stack trace because there isn't one.
1483
1488
1484 If a filename is given, it is stuffed in the exception instead
1489 If a filename is given, it is stuffed in the exception instead
1485 of what was there before (because Python's parser always uses
1490 of what was there before (because Python's parser always uses
1486 "<string>" when reading from a string).
1491 "<string>" when reading from a string).
1487 """
1492 """
1488 etype, value, last_traceback = sys.exc_info()
1493 etype, value, last_traceback = sys.exc_info()
1489
1494
1490 # See note about these variables in showtraceback() above
1495 # See note about these variables in showtraceback() above
1491 sys.last_type = etype
1496 sys.last_type = etype
1492 sys.last_value = value
1497 sys.last_value = value
1493 sys.last_traceback = last_traceback
1498 sys.last_traceback = last_traceback
1494
1499
1495 if filename and etype is SyntaxError:
1500 if filename and etype is SyntaxError:
1496 # Work hard to stuff the correct filename in the exception
1501 # Work hard to stuff the correct filename in the exception
1497 try:
1502 try:
1498 msg, (dummy_filename, lineno, offset, line) = value
1503 msg, (dummy_filename, lineno, offset, line) = value
1499 except:
1504 except:
1500 # Not the format we expect; leave it alone
1505 # Not the format we expect; leave it alone
1501 pass
1506 pass
1502 else:
1507 else:
1503 # Stuff in the right filename
1508 # Stuff in the right filename
1504 try:
1509 try:
1505 # Assume SyntaxError is a class exception
1510 # Assume SyntaxError is a class exception
1506 value = SyntaxError(msg, (filename, lineno, offset, line))
1511 value = SyntaxError(msg, (filename, lineno, offset, line))
1507 except:
1512 except:
1508 # If that failed, assume SyntaxError is a string
1513 # If that failed, assume SyntaxError is a string
1509 value = msg, (filename, lineno, offset, line)
1514 value = msg, (filename, lineno, offset, line)
1510 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1515 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1511 self._showtraceback(etype, value, stb)
1516 self._showtraceback(etype, value, stb)
1512
1517
1513 #-------------------------------------------------------------------------
1518 #-------------------------------------------------------------------------
1514 # Things related to tab completion
1515 #-------------------------------------------------------------------------
1516
1517 def complete(self, text, line=None, cursor_pos=None):
1518 """Return the completed text and a list of completions.
1519
1520 Parameters
1521 ----------
1522
1523 text : string
1524 A string of text to be completed on. It can be given as empty and
1525 instead a line/position pair are given. In this case, the
1526 completer itself will split the line like readline does.
1527
1528 line : string, optional
1529 The complete line that text is part of.
1530
1531 cursor_pos : int, optional
1532 The position of the cursor on the input line.
1533
1534 Returns
1535 -------
1536 text : string
1537 The actual text that was completed.
1538
1539 matches : list
1540 A sorted list with all possible completions.
1541
1542 The optional arguments allow the completion to take more context into
1543 account, and are part of the low-level completion API.
1544
1545 This is a wrapper around the completion mechanism, similar to what
1546 readline does at the command line when the TAB key is hit. By
1547 exposing it as a method, it can be used by other non-readline
1548 environments (such as GUIs) for text completion.
1549
1550 Simple usage example:
1551
1552 In [1]: x = 'hello'
1553
1554 In [2]: _ip.complete('x.l')
1555 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1556 """
1557
1558 # Inject names into __builtin__ so we can complete on the added names.
1559 with self.builtin_trap:
1560 return self.Completer.complete(text, line, cursor_pos)
1561
1562 def set_custom_completer(self, completer, pos=0):
1563 """Adds a new custom completer function.
1564
1565 The position argument (defaults to 0) is the index in the completers
1566 list where you want the completer to be inserted."""
1567
1568 newcomp = new.instancemethod(completer,self.Completer,
1569 self.Completer.__class__)
1570 self.Completer.matchers.insert(pos,newcomp)
1571
1572 def set_readline_completer(self):
1573 """Reset readline's completer to be our own."""
1574 self.readline.set_completer(self.Completer.rlcomplete)
1575
1576 def set_completer_frame(self, frame=None):
1577 """Set the frame of the completer."""
1578 if frame:
1579 self.Completer.namespace = frame.f_locals
1580 self.Completer.global_namespace = frame.f_globals
1581 else:
1582 self.Completer.namespace = self.user_ns
1583 self.Completer.global_namespace = self.user_global_ns
1584
1585 #-------------------------------------------------------------------------
1586 # Things related to readline
1519 # Things related to readline
1587 #-------------------------------------------------------------------------
1520 #-------------------------------------------------------------------------
1588
1521
1589 def init_readline(self):
1522 def init_readline(self):
1590 """Command history completion/saving/reloading."""
1523 """Command history completion/saving/reloading."""
1591
1524
1592 if self.readline_use:
1525 if self.readline_use:
1593 import IPython.utils.rlineimpl as readline
1526 import IPython.utils.rlineimpl as readline
1594
1527
1595 self.rl_next_input = None
1528 self.rl_next_input = None
1596 self.rl_do_indent = False
1529 self.rl_do_indent = False
1597
1530
1598 if not self.readline_use or not readline.have_readline:
1531 if not self.readline_use or not readline.have_readline:
1599 self.has_readline = False
1532 self.has_readline = False
1600 self.readline = None
1533 self.readline = None
1601 # Set a number of methods that depend on readline to be no-op
1534 # Set a number of methods that depend on readline to be no-op
1602 self.savehist = no_op
1535 self.savehist = no_op
1603 self.reloadhist = no_op
1536 self.reloadhist = no_op
1604 self.set_readline_completer = no_op
1537 self.set_readline_completer = no_op
1605 self.set_custom_completer = no_op
1538 self.set_custom_completer = no_op
1606 self.set_completer_frame = no_op
1539 self.set_completer_frame = no_op
1607 warn('Readline services not available or not loaded.')
1540 warn('Readline services not available or not loaded.')
1608 else:
1541 else:
1609 self.has_readline = True
1542 self.has_readline = True
1610 self.readline = readline
1543 self.readline = readline
1611 sys.modules['readline'] = readline
1544 sys.modules['readline'] = readline
1612
1545
1613 from IPython.core.completer import IPCompleter
1614 self.Completer = IPCompleter(self,
1615 self.user_ns,
1616 self.user_global_ns,
1617 self.readline_omit__names,
1618 self.alias_manager.alias_table)
1619 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1620 self.strdispatchers['complete_command'] = sdisp
1621 self.Completer.custom_completers = sdisp
1622
1623 # Platform-specific configuration
1546 # Platform-specific configuration
1624 if os.name == 'nt':
1547 if os.name == 'nt':
1625 # FIXME - check with Frederick to see if we can harmonize
1548 # FIXME - check with Frederick to see if we can harmonize
1626 # naming conventions with pyreadline to avoid this
1549 # naming conventions with pyreadline to avoid this
1627 # platform-dependent check
1550 # platform-dependent check
1628 self.readline_startup_hook = readline.set_pre_input_hook
1551 self.readline_startup_hook = readline.set_pre_input_hook
1629 else:
1552 else:
1630 self.readline_startup_hook = readline.set_startup_hook
1553 self.readline_startup_hook = readline.set_startup_hook
1631
1554
1632 # Load user's initrc file (readline config)
1555 # Load user's initrc file (readline config)
1633 # Or if libedit is used, load editrc.
1556 # Or if libedit is used, load editrc.
1634 inputrc_name = os.environ.get('INPUTRC')
1557 inputrc_name = os.environ.get('INPUTRC')
1635 if inputrc_name is None:
1558 if inputrc_name is None:
1636 home_dir = get_home_dir()
1559 home_dir = get_home_dir()
1637 if home_dir is not None:
1560 if home_dir is not None:
1638 inputrc_name = '.inputrc'
1561 inputrc_name = '.inputrc'
1639 if readline.uses_libedit:
1562 if readline.uses_libedit:
1640 inputrc_name = '.editrc'
1563 inputrc_name = '.editrc'
1641 inputrc_name = os.path.join(home_dir, inputrc_name)
1564 inputrc_name = os.path.join(home_dir, inputrc_name)
1642 if os.path.isfile(inputrc_name):
1565 if os.path.isfile(inputrc_name):
1643 try:
1566 try:
1644 readline.read_init_file(inputrc_name)
1567 readline.read_init_file(inputrc_name)
1645 except:
1568 except:
1646 warn('Problems reading readline initialization file <%s>'
1569 warn('Problems reading readline initialization file <%s>'
1647 % inputrc_name)
1570 % inputrc_name)
1648
1571
1649 self.set_readline_completer()
1650
1651 # Configure readline according to user's prefs
1572 # Configure readline according to user's prefs
1652 # This is only done if GNU readline is being used. If libedit
1573 # This is only done if GNU readline is being used. If libedit
1653 # is being used (as on Leopard) the readline config is
1574 # is being used (as on Leopard) the readline config is
1654 # not run as the syntax for libedit is different.
1575 # not run as the syntax for libedit is different.
1655 if not readline.uses_libedit:
1576 if not readline.uses_libedit:
1656 for rlcommand in self.readline_parse_and_bind:
1577 for rlcommand in self.readline_parse_and_bind:
1657 #print "loading rl:",rlcommand # dbg
1578 #print "loading rl:",rlcommand # dbg
1658 readline.parse_and_bind(rlcommand)
1579 readline.parse_and_bind(rlcommand)
1659
1580
1660 # Remove some chars from the delimiters list. If we encounter
1581 # Remove some chars from the delimiters list. If we encounter
1661 # unicode chars, discard them.
1582 # unicode chars, discard them.
1662 delims = readline.get_completer_delims().encode("ascii", "ignore")
1583 delims = readline.get_completer_delims().encode("ascii", "ignore")
1663 delims = delims.translate(string._idmap,
1584 delims = delims.translate(string._idmap,
1664 self.readline_remove_delims)
1585 self.readline_remove_delims)
1586 delims = delims.replace(ESC_MAGIC, '')
1665 readline.set_completer_delims(delims)
1587 readline.set_completer_delims(delims)
1666 # otherwise we end up with a monster history after a while:
1588 # otherwise we end up with a monster history after a while:
1667 readline.set_history_length(1000)
1589 readline.set_history_length(1000)
1668 try:
1590 try:
1669 #print '*** Reading readline history' # dbg
1591 #print '*** Reading readline history' # dbg
1670 readline.read_history_file(self.histfile)
1592 readline.read_history_file(self.histfile)
1671 except IOError:
1593 except IOError:
1672 pass # It doesn't exist yet.
1594 pass # It doesn't exist yet.
1673
1595
1674 # If we have readline, we want our history saved upon ipython
1596 # If we have readline, we want our history saved upon ipython
1675 # exiting.
1597 # exiting.
1676 atexit.register(self.savehist)
1598 atexit.register(self.savehist)
1677
1599
1678 # Configure auto-indent for all platforms
1600 # Configure auto-indent for all platforms
1679 self.set_autoindent(self.autoindent)
1601 self.set_autoindent(self.autoindent)
1680
1602
1681 def set_next_input(self, s):
1603 def set_next_input(self, s):
1682 """ Sets the 'default' input string for the next command line.
1604 """ Sets the 'default' input string for the next command line.
1683
1605
1684 Requires readline.
1606 Requires readline.
1685
1607
1686 Example:
1608 Example:
1687
1609
1688 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1610 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1689 [D:\ipython]|2> Hello Word_ # cursor is here
1611 [D:\ipython]|2> Hello Word_ # cursor is here
1690 """
1612 """
1691
1613
1692 self.rl_next_input = s
1614 self.rl_next_input = s
1693
1615
1694 # Maybe move this to the terminal subclass?
1616 # Maybe move this to the terminal subclass?
1695 def pre_readline(self):
1617 def pre_readline(self):
1696 """readline hook to be used at the start of each line.
1618 """readline hook to be used at the start of each line.
1697
1619
1698 Currently it handles auto-indent only."""
1620 Currently it handles auto-indent only."""
1699
1621
1700 if self.rl_do_indent:
1622 if self.rl_do_indent:
1701 self.readline.insert_text(self._indent_current_str())
1623 self.readline.insert_text(self._indent_current_str())
1702 if self.rl_next_input is not None:
1624 if self.rl_next_input is not None:
1703 self.readline.insert_text(self.rl_next_input)
1625 self.readline.insert_text(self.rl_next_input)
1704 self.rl_next_input = None
1626 self.rl_next_input = None
1705
1627
1706 def _indent_current_str(self):
1628 def _indent_current_str(self):
1707 """return the current level of indentation as a string"""
1629 """return the current level of indentation as a string"""
1708 return self.indent_current_nsp * ' '
1630 return self.indent_current_nsp * ' '
1709
1631
1710 #-------------------------------------------------------------------------
1632 #-------------------------------------------------------------------------
1633 # Things related to text completion
1634 #-------------------------------------------------------------------------
1635
1636 def init_completer(self):
1637 """Initialize the completion machinery.
1638
1639 This creates completion machinery that can be used by client code,
1640 either interactively in-process (typically triggered by the readline
1641 library), programatically (such as in test suites) or out-of-prcess
1642 (typically over the network by remote frontends).
1643 """
1644 from IPython.core.completer import IPCompleter
1645 self.Completer = IPCompleter(self,
1646 self.user_ns,
1647 self.user_global_ns,
1648 self.readline_omit__names,
1649 self.alias_manager.alias_table,
1650 self.has_readline)
1651 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1652 self.strdispatchers['complete_command'] = sdisp
1653 self.Completer.custom_completers = sdisp
1654
1655 if self.has_readline:
1656 self.set_readline_completer()
1657
1658 def complete(self, text, line=None, cursor_pos=None):
1659 """Return the completed text and a list of completions.
1660
1661 Parameters
1662 ----------
1663
1664 text : string
1665 A string of text to be completed on. It can be given as empty and
1666 instead a line/position pair are given. In this case, the
1667 completer itself will split the line like readline does.
1668
1669 line : string, optional
1670 The complete line that text is part of.
1671
1672 cursor_pos : int, optional
1673 The position of the cursor on the input line.
1674
1675 Returns
1676 -------
1677 text : string
1678 The actual text that was completed.
1679
1680 matches : list
1681 A sorted list with all possible completions.
1682
1683 The optional arguments allow the completion to take more context into
1684 account, and are part of the low-level completion API.
1685
1686 This is a wrapper around the completion mechanism, similar to what
1687 readline does at the command line when the TAB key is hit. By
1688 exposing it as a method, it can be used by other non-readline
1689 environments (such as GUIs) for text completion.
1690
1691 Simple usage example:
1692
1693 In [1]: x = 'hello'
1694
1695 In [2]: _ip.complete('x.l')
1696 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1697 """
1698
1699 # Inject names into __builtin__ so we can complete on the added names.
1700 with self.builtin_trap:
1701 return self.Completer.complete(text, line, cursor_pos)
1702
1703 def set_custom_completer(self, completer, pos=0):
1704 """Adds a new custom completer function.
1705
1706 The position argument (defaults to 0) is the index in the completers
1707 list where you want the completer to be inserted."""
1708
1709 newcomp = new.instancemethod(completer,self.Completer,
1710 self.Completer.__class__)
1711 self.Completer.matchers.insert(pos,newcomp)
1712
1713 def set_readline_completer(self):
1714 """Reset readline's completer to be our own."""
1715 self.readline.set_completer(self.Completer.rlcomplete)
1716
1717 def set_completer_frame(self, frame=None):
1718 """Set the frame of the completer."""
1719 if frame:
1720 self.Completer.namespace = frame.f_locals
1721 self.Completer.global_namespace = frame.f_globals
1722 else:
1723 self.Completer.namespace = self.user_ns
1724 self.Completer.global_namespace = self.user_global_ns
1725
1726 #-------------------------------------------------------------------------
1711 # Things related to magics
1727 # Things related to magics
1712 #-------------------------------------------------------------------------
1728 #-------------------------------------------------------------------------
1713
1729
1714 def init_magics(self):
1730 def init_magics(self):
1715 # FIXME: Move the color initialization to the DisplayHook, which
1731 # FIXME: Move the color initialization to the DisplayHook, which
1716 # should be split into a prompt manager and displayhook. We probably
1732 # should be split into a prompt manager and displayhook. We probably
1717 # even need a centralize colors management object.
1733 # even need a centralize colors management object.
1718 self.magic_colors(self.colors)
1734 self.magic_colors(self.colors)
1719 # History was moved to a separate module
1735 # History was moved to a separate module
1720 from . import history
1736 from . import history
1721 history.init_ipython(self)
1737 history.init_ipython(self)
1722
1738
1723 def magic(self,arg_s):
1739 def magic(self,arg_s):
1724 """Call a magic function by name.
1740 """Call a magic function by name.
1725
1741
1726 Input: a string containing the name of the magic function to call and
1742 Input: a string containing the name of the magic function to call and
1727 any additional arguments to be passed to the magic.
1743 any additional arguments to be passed to the magic.
1728
1744
1729 magic('name -opt foo bar') is equivalent to typing at the ipython
1745 magic('name -opt foo bar') is equivalent to typing at the ipython
1730 prompt:
1746 prompt:
1731
1747
1732 In[1]: %name -opt foo bar
1748 In[1]: %name -opt foo bar
1733
1749
1734 To call a magic without arguments, simply use magic('name').
1750 To call a magic without arguments, simply use magic('name').
1735
1751
1736 This provides a proper Python function to call IPython's magics in any
1752 This provides a proper Python function to call IPython's magics in any
1737 valid Python code you can type at the interpreter, including loops and
1753 valid Python code you can type at the interpreter, including loops and
1738 compound statements.
1754 compound statements.
1739 """
1755 """
1740 args = arg_s.split(' ',1)
1756 args = arg_s.split(' ',1)
1741 magic_name = args[0]
1757 magic_name = args[0]
1742 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1758 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1743
1759
1744 try:
1760 try:
1745 magic_args = args[1]
1761 magic_args = args[1]
1746 except IndexError:
1762 except IndexError:
1747 magic_args = ''
1763 magic_args = ''
1748 fn = getattr(self,'magic_'+magic_name,None)
1764 fn = getattr(self,'magic_'+magic_name,None)
1749 if fn is None:
1765 if fn is None:
1750 error("Magic function `%s` not found." % magic_name)
1766 error("Magic function `%s` not found." % magic_name)
1751 else:
1767 else:
1752 magic_args = self.var_expand(magic_args,1)
1768 magic_args = self.var_expand(magic_args,1)
1753 with nested(self.builtin_trap,):
1769 with nested(self.builtin_trap,):
1754 result = fn(magic_args)
1770 result = fn(magic_args)
1755 return result
1771 return result
1756
1772
1757 def define_magic(self, magicname, func):
1773 def define_magic(self, magicname, func):
1758 """Expose own function as magic function for ipython
1774 """Expose own function as magic function for ipython
1759
1775
1760 def foo_impl(self,parameter_s=''):
1776 def foo_impl(self,parameter_s=''):
1761 'My very own magic!. (Use docstrings, IPython reads them).'
1777 'My very own magic!. (Use docstrings, IPython reads them).'
1762 print 'Magic function. Passed parameter is between < >:'
1778 print 'Magic function. Passed parameter is between < >:'
1763 print '<%s>' % parameter_s
1779 print '<%s>' % parameter_s
1764 print 'The self object is:',self
1780 print 'The self object is:',self
1765
1781
1766 self.define_magic('foo',foo_impl)
1782 self.define_magic('foo',foo_impl)
1767 """
1783 """
1768
1784
1769 import new
1785 import new
1770 im = new.instancemethod(func,self, self.__class__)
1786 im = new.instancemethod(func,self, self.__class__)
1771 old = getattr(self, "magic_" + magicname, None)
1787 old = getattr(self, "magic_" + magicname, None)
1772 setattr(self, "magic_" + magicname, im)
1788 setattr(self, "magic_" + magicname, im)
1773 return old
1789 return old
1774
1790
1775 #-------------------------------------------------------------------------
1791 #-------------------------------------------------------------------------
1776 # Things related to macros
1792 # Things related to macros
1777 #-------------------------------------------------------------------------
1793 #-------------------------------------------------------------------------
1778
1794
1779 def define_macro(self, name, themacro):
1795 def define_macro(self, name, themacro):
1780 """Define a new macro
1796 """Define a new macro
1781
1797
1782 Parameters
1798 Parameters
1783 ----------
1799 ----------
1784 name : str
1800 name : str
1785 The name of the macro.
1801 The name of the macro.
1786 themacro : str or Macro
1802 themacro : str or Macro
1787 The action to do upon invoking the macro. If a string, a new
1803 The action to do upon invoking the macro. If a string, a new
1788 Macro object is created by passing the string to it.
1804 Macro object is created by passing the string to it.
1789 """
1805 """
1790
1806
1791 from IPython.core import macro
1807 from IPython.core import macro
1792
1808
1793 if isinstance(themacro, basestring):
1809 if isinstance(themacro, basestring):
1794 themacro = macro.Macro(themacro)
1810 themacro = macro.Macro(themacro)
1795 if not isinstance(themacro, macro.Macro):
1811 if not isinstance(themacro, macro.Macro):
1796 raise ValueError('A macro must be a string or a Macro instance.')
1812 raise ValueError('A macro must be a string or a Macro instance.')
1797 self.user_ns[name] = themacro
1813 self.user_ns[name] = themacro
1798
1814
1799 #-------------------------------------------------------------------------
1815 #-------------------------------------------------------------------------
1800 # Things related to the running of system commands
1816 # Things related to the running of system commands
1801 #-------------------------------------------------------------------------
1817 #-------------------------------------------------------------------------
1802
1818
1803 def system(self, cmd):
1819 def system(self, cmd):
1804 """Call the given cmd in a subprocess."""
1820 """Call the given cmd in a subprocess."""
1805 # We do not support backgrounding processes because we either use
1821 # We do not support backgrounding processes because we either use
1806 # pexpect or pipes to read from. Users can always just call
1822 # pexpect or pipes to read from. Users can always just call
1807 # os.system() if they really want a background process.
1823 # os.system() if they really want a background process.
1808 if cmd.endswith('&'):
1824 if cmd.endswith('&'):
1809 raise OSError("Background processes not supported.")
1825 raise OSError("Background processes not supported.")
1810
1826
1811 return system(self.var_expand(cmd, depth=2))
1827 return system(self.var_expand(cmd, depth=2))
1812
1828
1813 def getoutput(self, cmd):
1829 def getoutput(self, cmd):
1814 """Get output (possibly including stderr) from a subprocess."""
1830 """Get output (possibly including stderr) from a subprocess."""
1815 if cmd.endswith('&'):
1831 if cmd.endswith('&'):
1816 raise OSError("Background processes not supported.")
1832 raise OSError("Background processes not supported.")
1817 return getoutput(self.var_expand(cmd, depth=2))
1833 return getoutput(self.var_expand(cmd, depth=2))
1818
1834
1819 #-------------------------------------------------------------------------
1835 #-------------------------------------------------------------------------
1820 # Things related to aliases
1836 # Things related to aliases
1821 #-------------------------------------------------------------------------
1837 #-------------------------------------------------------------------------
1822
1838
1823 def init_alias(self):
1839 def init_alias(self):
1824 self.alias_manager = AliasManager(shell=self, config=self.config)
1840 self.alias_manager = AliasManager(shell=self, config=self.config)
1825 self.ns_table['alias'] = self.alias_manager.alias_table,
1841 self.ns_table['alias'] = self.alias_manager.alias_table,
1826
1842
1827 #-------------------------------------------------------------------------
1843 #-------------------------------------------------------------------------
1828 # Things related to extensions and plugins
1844 # Things related to extensions and plugins
1829 #-------------------------------------------------------------------------
1845 #-------------------------------------------------------------------------
1830
1846
1831 def init_extension_manager(self):
1847 def init_extension_manager(self):
1832 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1848 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1833
1849
1834 def init_plugin_manager(self):
1850 def init_plugin_manager(self):
1835 self.plugin_manager = PluginManager(config=self.config)
1851 self.plugin_manager = PluginManager(config=self.config)
1836
1852
1837 #-------------------------------------------------------------------------
1853 #-------------------------------------------------------------------------
1838 # Things related to payloads
1854 # Things related to payloads
1839 #-------------------------------------------------------------------------
1855 #-------------------------------------------------------------------------
1840
1856
1841 def init_payload(self):
1857 def init_payload(self):
1842 self.payload_manager = PayloadManager(config=self.config)
1858 self.payload_manager = PayloadManager(config=self.config)
1843
1859
1844 #-------------------------------------------------------------------------
1860 #-------------------------------------------------------------------------
1845 # Things related to the prefilter
1861 # Things related to the prefilter
1846 #-------------------------------------------------------------------------
1862 #-------------------------------------------------------------------------
1847
1863
1848 def init_prefilter(self):
1864 def init_prefilter(self):
1849 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1865 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1850 # Ultimately this will be refactored in the new interpreter code, but
1866 # Ultimately this will be refactored in the new interpreter code, but
1851 # for now, we should expose the main prefilter method (there's legacy
1867 # for now, we should expose the main prefilter method (there's legacy
1852 # code out there that may rely on this).
1868 # code out there that may rely on this).
1853 self.prefilter = self.prefilter_manager.prefilter_lines
1869 self.prefilter = self.prefilter_manager.prefilter_lines
1854
1870
1855
1871
1856 def auto_rewrite_input(self, cmd):
1872 def auto_rewrite_input(self, cmd):
1857 """Print to the screen the rewritten form of the user's command.
1873 """Print to the screen the rewritten form of the user's command.
1858
1874
1859 This shows visual feedback by rewriting input lines that cause
1875 This shows visual feedback by rewriting input lines that cause
1860 automatic calling to kick in, like::
1876 automatic calling to kick in, like::
1861
1877
1862 /f x
1878 /f x
1863
1879
1864 into::
1880 into::
1865
1881
1866 ------> f(x)
1882 ------> f(x)
1867
1883
1868 after the user's input prompt. This helps the user understand that the
1884 after the user's input prompt. This helps the user understand that the
1869 input line was transformed automatically by IPython.
1885 input line was transformed automatically by IPython.
1870 """
1886 """
1871 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1887 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1872
1888
1873 try:
1889 try:
1874 # plain ascii works better w/ pyreadline, on some machines, so
1890 # plain ascii works better w/ pyreadline, on some machines, so
1875 # we use it and only print uncolored rewrite if we have unicode
1891 # we use it and only print uncolored rewrite if we have unicode
1876 rw = str(rw)
1892 rw = str(rw)
1877 print >> IPython.utils.io.Term.cout, rw
1893 print >> IPython.utils.io.Term.cout, rw
1878 except UnicodeEncodeError:
1894 except UnicodeEncodeError:
1879 print "------> " + cmd
1895 print "------> " + cmd
1880
1896
1881 #-------------------------------------------------------------------------
1897 #-------------------------------------------------------------------------
1882 # Things related to extracting values/expressions from kernel and user_ns
1898 # Things related to extracting values/expressions from kernel and user_ns
1883 #-------------------------------------------------------------------------
1899 #-------------------------------------------------------------------------
1884
1900
1885 def _simple_error(self):
1901 def _simple_error(self):
1886 etype, value = sys.exc_info()[:2]
1902 etype, value = sys.exc_info()[:2]
1887 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1903 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1888
1904
1889 def get_user_variables(self, names):
1905 def get_user_variables(self, names):
1890 """Get a list of variable names from the user's namespace.
1906 """Get a list of variable names from the user's namespace.
1891
1907
1892 The return value is a dict with the repr() of each value.
1908 The return value is a dict with the repr() of each value.
1893 """
1909 """
1894 out = {}
1910 out = {}
1895 user_ns = self.user_ns
1911 user_ns = self.user_ns
1896 for varname in names:
1912 for varname in names:
1897 try:
1913 try:
1898 value = repr(user_ns[varname])
1914 value = repr(user_ns[varname])
1899 except:
1915 except:
1900 value = self._simple_error()
1916 value = self._simple_error()
1901 out[varname] = value
1917 out[varname] = value
1902 return out
1918 return out
1903
1919
1904 def eval_expressions(self, expressions):
1920 def eval_expressions(self, expressions):
1905 """Evaluate a dict of expressions in the user's namespace.
1921 """Evaluate a dict of expressions in the user's namespace.
1906
1922
1907 The return value is a dict with the repr() of each value.
1923 The return value is a dict with the repr() of each value.
1908 """
1924 """
1909 out = {}
1925 out = {}
1910 user_ns = self.user_ns
1926 user_ns = self.user_ns
1911 global_ns = self.user_global_ns
1927 global_ns = self.user_global_ns
1912 for key, expr in expressions.iteritems():
1928 for key, expr in expressions.iteritems():
1913 try:
1929 try:
1914 value = repr(eval(expr, global_ns, user_ns))
1930 value = repr(eval(expr, global_ns, user_ns))
1915 except:
1931 except:
1916 value = self._simple_error()
1932 value = self._simple_error()
1917 out[key] = value
1933 out[key] = value
1918 return out
1934 return out
1919
1935
1920 #-------------------------------------------------------------------------
1936 #-------------------------------------------------------------------------
1921 # Things related to the running of code
1937 # Things related to the running of code
1922 #-------------------------------------------------------------------------
1938 #-------------------------------------------------------------------------
1923
1939
1924 def ex(self, cmd):
1940 def ex(self, cmd):
1925 """Execute a normal python statement in user namespace."""
1941 """Execute a normal python statement in user namespace."""
1926 with nested(self.builtin_trap,):
1942 with nested(self.builtin_trap,):
1927 exec cmd in self.user_global_ns, self.user_ns
1943 exec cmd in self.user_global_ns, self.user_ns
1928
1944
1929 def ev(self, expr):
1945 def ev(self, expr):
1930 """Evaluate python expression expr in user namespace.
1946 """Evaluate python expression expr in user namespace.
1931
1947
1932 Returns the result of evaluation
1948 Returns the result of evaluation
1933 """
1949 """
1934 with nested(self.builtin_trap,):
1950 with nested(self.builtin_trap,):
1935 return eval(expr, self.user_global_ns, self.user_ns)
1951 return eval(expr, self.user_global_ns, self.user_ns)
1936
1952
1937 def safe_execfile(self, fname, *where, **kw):
1953 def safe_execfile(self, fname, *where, **kw):
1938 """A safe version of the builtin execfile().
1954 """A safe version of the builtin execfile().
1939
1955
1940 This version will never throw an exception, but instead print
1956 This version will never throw an exception, but instead print
1941 helpful error messages to the screen. This only works on pure
1957 helpful error messages to the screen. This only works on pure
1942 Python files with the .py extension.
1958 Python files with the .py extension.
1943
1959
1944 Parameters
1960 Parameters
1945 ----------
1961 ----------
1946 fname : string
1962 fname : string
1947 The name of the file to be executed.
1963 The name of the file to be executed.
1948 where : tuple
1964 where : tuple
1949 One or two namespaces, passed to execfile() as (globals,locals).
1965 One or two namespaces, passed to execfile() as (globals,locals).
1950 If only one is given, it is passed as both.
1966 If only one is given, it is passed as both.
1951 exit_ignore : bool (False)
1967 exit_ignore : bool (False)
1952 If True, then silence SystemExit for non-zero status (it is always
1968 If True, then silence SystemExit for non-zero status (it is always
1953 silenced for zero status, as it is so common).
1969 silenced for zero status, as it is so common).
1954 """
1970 """
1955 kw.setdefault('exit_ignore', False)
1971 kw.setdefault('exit_ignore', False)
1956
1972
1957 fname = os.path.abspath(os.path.expanduser(fname))
1973 fname = os.path.abspath(os.path.expanduser(fname))
1958
1974
1959 # Make sure we have a .py file
1975 # Make sure we have a .py file
1960 if not fname.endswith('.py'):
1976 if not fname.endswith('.py'):
1961 warn('File must end with .py to be run using execfile: <%s>' % fname)
1977 warn('File must end with .py to be run using execfile: <%s>' % fname)
1962
1978
1963 # Make sure we can open the file
1979 # Make sure we can open the file
1964 try:
1980 try:
1965 with open(fname) as thefile:
1981 with open(fname) as thefile:
1966 pass
1982 pass
1967 except:
1983 except:
1968 warn('Could not open file <%s> for safe execution.' % fname)
1984 warn('Could not open file <%s> for safe execution.' % fname)
1969 return
1985 return
1970
1986
1971 # Find things also in current directory. This is needed to mimic the
1987 # Find things also in current directory. This is needed to mimic the
1972 # behavior of running a script from the system command line, where
1988 # behavior of running a script from the system command line, where
1973 # Python inserts the script's directory into sys.path
1989 # Python inserts the script's directory into sys.path
1974 dname = os.path.dirname(fname)
1990 dname = os.path.dirname(fname)
1975
1991
1976 with prepended_to_syspath(dname):
1992 with prepended_to_syspath(dname):
1977 try:
1993 try:
1978 execfile(fname,*where)
1994 execfile(fname,*where)
1979 except SystemExit, status:
1995 except SystemExit, status:
1980 # If the call was made with 0 or None exit status (sys.exit(0)
1996 # If the call was made with 0 or None exit status (sys.exit(0)
1981 # or sys.exit() ), don't bother showing a traceback, as both of
1997 # or sys.exit() ), don't bother showing a traceback, as both of
1982 # these are considered normal by the OS:
1998 # these are considered normal by the OS:
1983 # > python -c'import sys;sys.exit(0)'; echo $?
1999 # > python -c'import sys;sys.exit(0)'; echo $?
1984 # 0
2000 # 0
1985 # > python -c'import sys;sys.exit()'; echo $?
2001 # > python -c'import sys;sys.exit()'; echo $?
1986 # 0
2002 # 0
1987 # For other exit status, we show the exception unless
2003 # For other exit status, we show the exception unless
1988 # explicitly silenced, but only in short form.
2004 # explicitly silenced, but only in short form.
1989 if status.code not in (0, None) and not kw['exit_ignore']:
2005 if status.code not in (0, None) and not kw['exit_ignore']:
1990 self.showtraceback(exception_only=True)
2006 self.showtraceback(exception_only=True)
1991 except:
2007 except:
1992 self.showtraceback()
2008 self.showtraceback()
1993
2009
1994 def safe_execfile_ipy(self, fname):
2010 def safe_execfile_ipy(self, fname):
1995 """Like safe_execfile, but for .ipy files with IPython syntax.
2011 """Like safe_execfile, but for .ipy files with IPython syntax.
1996
2012
1997 Parameters
2013 Parameters
1998 ----------
2014 ----------
1999 fname : str
2015 fname : str
2000 The name of the file to execute. The filename must have a
2016 The name of the file to execute. The filename must have a
2001 .ipy extension.
2017 .ipy extension.
2002 """
2018 """
2003 fname = os.path.abspath(os.path.expanduser(fname))
2019 fname = os.path.abspath(os.path.expanduser(fname))
2004
2020
2005 # Make sure we have a .py file
2021 # Make sure we have a .py file
2006 if not fname.endswith('.ipy'):
2022 if not fname.endswith('.ipy'):
2007 warn('File must end with .py to be run using execfile: <%s>' % fname)
2023 warn('File must end with .py to be run using execfile: <%s>' % fname)
2008
2024
2009 # Make sure we can open the file
2025 # Make sure we can open the file
2010 try:
2026 try:
2011 with open(fname) as thefile:
2027 with open(fname) as thefile:
2012 pass
2028 pass
2013 except:
2029 except:
2014 warn('Could not open file <%s> for safe execution.' % fname)
2030 warn('Could not open file <%s> for safe execution.' % fname)
2015 return
2031 return
2016
2032
2017 # Find things also in current directory. This is needed to mimic the
2033 # Find things also in current directory. This is needed to mimic the
2018 # behavior of running a script from the system command line, where
2034 # behavior of running a script from the system command line, where
2019 # Python inserts the script's directory into sys.path
2035 # Python inserts the script's directory into sys.path
2020 dname = os.path.dirname(fname)
2036 dname = os.path.dirname(fname)
2021
2037
2022 with prepended_to_syspath(dname):
2038 with prepended_to_syspath(dname):
2023 try:
2039 try:
2024 with open(fname) as thefile:
2040 with open(fname) as thefile:
2025 script = thefile.read()
2041 script = thefile.read()
2026 # self.runlines currently captures all exceptions
2042 # self.runlines currently captures all exceptions
2027 # raise in user code. It would be nice if there were
2043 # raise in user code. It would be nice if there were
2028 # versions of runlines, execfile that did raise, so
2044 # versions of runlines, execfile that did raise, so
2029 # we could catch the errors.
2045 # we could catch the errors.
2030 self.runlines(script, clean=True)
2046 self.runlines(script, clean=True)
2031 except:
2047 except:
2032 self.showtraceback()
2048 self.showtraceback()
2033 warn('Unknown failure executing file: <%s>' % fname)
2049 warn('Unknown failure executing file: <%s>' % fname)
2034
2050
2035 def runlines(self, lines, clean=False):
2051 def runlines(self, lines, clean=False):
2036 """Run a string of one or more lines of source.
2052 """Run a string of one or more lines of source.
2037
2053
2038 This method is capable of running a string containing multiple source
2054 This method is capable of running a string containing multiple source
2039 lines, as if they had been entered at the IPython prompt. Since it
2055 lines, as if they had been entered at the IPython prompt. Since it
2040 exposes IPython's processing machinery, the given strings can contain
2056 exposes IPython's processing machinery, the given strings can contain
2041 magic calls (%magic), special shell access (!cmd), etc.
2057 magic calls (%magic), special shell access (!cmd), etc.
2042 """
2058 """
2043
2059
2044 if isinstance(lines, (list, tuple)):
2060 if isinstance(lines, (list, tuple)):
2045 lines = '\n'.join(lines)
2061 lines = '\n'.join(lines)
2046
2062
2047 if clean:
2063 if clean:
2048 lines = self._cleanup_ipy_script(lines)
2064 lines = self._cleanup_ipy_script(lines)
2049
2065
2050 # We must start with a clean buffer, in case this is run from an
2066 # We must start with a clean buffer, in case this is run from an
2051 # interactive IPython session (via a magic, for example).
2067 # interactive IPython session (via a magic, for example).
2052 self.resetbuffer()
2068 self.resetbuffer()
2053 lines = lines.splitlines()
2069 lines = lines.splitlines()
2054 more = 0
2070 more = 0
2055 with nested(self.builtin_trap, self.display_trap):
2071 with nested(self.builtin_trap, self.display_trap):
2056 for line in lines:
2072 for line in lines:
2057 # skip blank lines so we don't mess up the prompt counter, but
2073 # skip blank lines so we don't mess up the prompt counter, but
2058 # do NOT skip even a blank line if we are in a code block (more
2074 # do NOT skip even a blank line if we are in a code block (more
2059 # is true)
2075 # is true)
2060
2076
2061 if line or more:
2077 if line or more:
2062 # push to raw history, so hist line numbers stay in sync
2078 # push to raw history, so hist line numbers stay in sync
2063 self.input_hist_raw.append(line + '\n')
2079 self.input_hist_raw.append(line + '\n')
2064 prefiltered = self.prefilter_manager.prefilter_lines(line,
2080 prefiltered = self.prefilter_manager.prefilter_lines(line,
2065 more)
2081 more)
2066 more = self.push_line(prefiltered)
2082 more = self.push_line(prefiltered)
2067 # IPython's runsource returns None if there was an error
2083 # IPython's runsource returns None if there was an error
2068 # compiling the code. This allows us to stop processing
2084 # compiling the code. This allows us to stop processing
2069 # right away, so the user gets the error message at the
2085 # right away, so the user gets the error message at the
2070 # right place.
2086 # right place.
2071 if more is None:
2087 if more is None:
2072 break
2088 break
2073 else:
2089 else:
2074 self.input_hist_raw.append("\n")
2090 self.input_hist_raw.append("\n")
2075 # final newline in case the input didn't have it, so that the code
2091 # final newline in case the input didn't have it, so that the code
2076 # actually does get executed
2092 # actually does get executed
2077 if more:
2093 if more:
2078 self.push_line('\n')
2094 self.push_line('\n')
2079
2095
2080 def runsource(self, source, filename='<input>', symbol='single'):
2096 def runsource(self, source, filename='<input>', symbol='single'):
2081 """Compile and run some source in the interpreter.
2097 """Compile and run some source in the interpreter.
2082
2098
2083 Arguments are as for compile_command().
2099 Arguments are as for compile_command().
2084
2100
2085 One several things can happen:
2101 One several things can happen:
2086
2102
2087 1) The input is incorrect; compile_command() raised an
2103 1) The input is incorrect; compile_command() raised an
2088 exception (SyntaxError or OverflowError). A syntax traceback
2104 exception (SyntaxError or OverflowError). A syntax traceback
2089 will be printed by calling the showsyntaxerror() method.
2105 will be printed by calling the showsyntaxerror() method.
2090
2106
2091 2) The input is incomplete, and more input is required;
2107 2) The input is incomplete, and more input is required;
2092 compile_command() returned None. Nothing happens.
2108 compile_command() returned None. Nothing happens.
2093
2109
2094 3) The input is complete; compile_command() returned a code
2110 3) The input is complete; compile_command() returned a code
2095 object. The code is executed by calling self.runcode() (which
2111 object. The code is executed by calling self.runcode() (which
2096 also handles run-time exceptions, except for SystemExit).
2112 also handles run-time exceptions, except for SystemExit).
2097
2113
2098 The return value is:
2114 The return value is:
2099
2115
2100 - True in case 2
2116 - True in case 2
2101
2117
2102 - False in the other cases, unless an exception is raised, where
2118 - False in the other cases, unless an exception is raised, where
2103 None is returned instead. This can be used by external callers to
2119 None is returned instead. This can be used by external callers to
2104 know whether to continue feeding input or not.
2120 know whether to continue feeding input or not.
2105
2121
2106 The return value can be used to decide whether to use sys.ps1 or
2122 The return value can be used to decide whether to use sys.ps1 or
2107 sys.ps2 to prompt the next line."""
2123 sys.ps2 to prompt the next line."""
2108
2124
2109 # if the source code has leading blanks, add 'if 1:\n' to it
2125 # if the source code has leading blanks, add 'if 1:\n' to it
2110 # this allows execution of indented pasted code. It is tempting
2126 # this allows execution of indented pasted code. It is tempting
2111 # to add '\n' at the end of source to run commands like ' a=1'
2127 # to add '\n' at the end of source to run commands like ' a=1'
2112 # directly, but this fails for more complicated scenarios
2128 # directly, but this fails for more complicated scenarios
2113 source=source.encode(self.stdin_encoding)
2129 source=source.encode(self.stdin_encoding)
2114 if source[:1] in [' ', '\t']:
2130 if source[:1] in [' ', '\t']:
2115 source = 'if 1:\n%s' % source
2131 source = 'if 1:\n%s' % source
2116
2132
2117 try:
2133 try:
2118 code = self.compile(source,filename,symbol)
2134 code = self.compile(source,filename,symbol)
2119 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2135 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2120 # Case 1
2136 # Case 1
2121 self.showsyntaxerror(filename)
2137 self.showsyntaxerror(filename)
2122 return None
2138 return None
2123
2139
2124 if code is None:
2140 if code is None:
2125 # Case 2
2141 # Case 2
2126 return True
2142 return True
2127
2143
2128 # Case 3
2144 # Case 3
2129 # We store the code object so that threaded shells and
2145 # We store the code object so that threaded shells and
2130 # custom exception handlers can access all this info if needed.
2146 # custom exception handlers can access all this info if needed.
2131 # The source corresponding to this can be obtained from the
2147 # The source corresponding to this can be obtained from the
2132 # buffer attribute as '\n'.join(self.buffer).
2148 # buffer attribute as '\n'.join(self.buffer).
2133 self.code_to_run = code
2149 self.code_to_run = code
2134 # now actually execute the code object
2150 # now actually execute the code object
2135 if self.runcode(code) == 0:
2151 if self.runcode(code) == 0:
2136 return False
2152 return False
2137 else:
2153 else:
2138 return None
2154 return None
2139
2155
2140 def runcode(self,code_obj):
2156 def runcode(self,code_obj):
2141 """Execute a code object.
2157 """Execute a code object.
2142
2158
2143 When an exception occurs, self.showtraceback() is called to display a
2159 When an exception occurs, self.showtraceback() is called to display a
2144 traceback.
2160 traceback.
2145
2161
2146 Return value: a flag indicating whether the code to be run completed
2162 Return value: a flag indicating whether the code to be run completed
2147 successfully:
2163 successfully:
2148
2164
2149 - 0: successful execution.
2165 - 0: successful execution.
2150 - 1: an error occurred.
2166 - 1: an error occurred.
2151 """
2167 """
2152
2168
2153 # Set our own excepthook in case the user code tries to call it
2169 # Set our own excepthook in case the user code tries to call it
2154 # directly, so that the IPython crash handler doesn't get triggered
2170 # directly, so that the IPython crash handler doesn't get triggered
2155 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2171 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2156
2172
2157 # we save the original sys.excepthook in the instance, in case config
2173 # we save the original sys.excepthook in the instance, in case config
2158 # code (such as magics) needs access to it.
2174 # code (such as magics) needs access to it.
2159 self.sys_excepthook = old_excepthook
2175 self.sys_excepthook = old_excepthook
2160 outflag = 1 # happens in more places, so it's easier as default
2176 outflag = 1 # happens in more places, so it's easier as default
2161 try:
2177 try:
2162 try:
2178 try:
2163 self.hooks.pre_runcode_hook()
2179 self.hooks.pre_runcode_hook()
2164 #rprint('Running code') # dbg
2180 #rprint('Running code') # dbg
2165 exec code_obj in self.user_global_ns, self.user_ns
2181 exec code_obj in self.user_global_ns, self.user_ns
2166 finally:
2182 finally:
2167 # Reset our crash handler in place
2183 # Reset our crash handler in place
2168 sys.excepthook = old_excepthook
2184 sys.excepthook = old_excepthook
2169 except SystemExit:
2185 except SystemExit:
2170 self.resetbuffer()
2186 self.resetbuffer()
2171 self.showtraceback(exception_only=True)
2187 self.showtraceback(exception_only=True)
2172 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2188 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2173 except self.custom_exceptions:
2189 except self.custom_exceptions:
2174 etype,value,tb = sys.exc_info()
2190 etype,value,tb = sys.exc_info()
2175 self.CustomTB(etype,value,tb)
2191 self.CustomTB(etype,value,tb)
2176 except:
2192 except:
2177 self.showtraceback()
2193 self.showtraceback()
2178 else:
2194 else:
2179 outflag = 0
2195 outflag = 0
2180 if softspace(sys.stdout, 0):
2196 if softspace(sys.stdout, 0):
2181 print
2197 print
2182 # Flush out code object which has been run (and source)
2198 # Flush out code object which has been run (and source)
2183 self.code_to_run = None
2199 self.code_to_run = None
2184 return outflag
2200 return outflag
2185
2201
2186 def push_line(self, line):
2202 def push_line(self, line):
2187 """Push a line to the interpreter.
2203 """Push a line to the interpreter.
2188
2204
2189 The line should not have a trailing newline; it may have
2205 The line should not have a trailing newline; it may have
2190 internal newlines. The line is appended to a buffer and the
2206 internal newlines. The line is appended to a buffer and the
2191 interpreter's runsource() method is called with the
2207 interpreter's runsource() method is called with the
2192 concatenated contents of the buffer as source. If this
2208 concatenated contents of the buffer as source. If this
2193 indicates that the command was executed or invalid, the buffer
2209 indicates that the command was executed or invalid, the buffer
2194 is reset; otherwise, the command is incomplete, and the buffer
2210 is reset; otherwise, the command is incomplete, and the buffer
2195 is left as it was after the line was appended. The return
2211 is left as it was after the line was appended. The return
2196 value is 1 if more input is required, 0 if the line was dealt
2212 value is 1 if more input is required, 0 if the line was dealt
2197 with in some way (this is the same as runsource()).
2213 with in some way (this is the same as runsource()).
2198 """
2214 """
2199
2215
2200 # autoindent management should be done here, and not in the
2216 # autoindent management should be done here, and not in the
2201 # interactive loop, since that one is only seen by keyboard input. We
2217 # interactive loop, since that one is only seen by keyboard input. We
2202 # need this done correctly even for code run via runlines (which uses
2218 # need this done correctly even for code run via runlines (which uses
2203 # push).
2219 # push).
2204
2220
2205 #print 'push line: <%s>' % line # dbg
2221 #print 'push line: <%s>' % line # dbg
2206 for subline in line.splitlines():
2222 for subline in line.splitlines():
2207 self._autoindent_update(subline)
2223 self._autoindent_update(subline)
2208 self.buffer.append(line)
2224 self.buffer.append(line)
2209 more = self.runsource('\n'.join(self.buffer), self.filename)
2225 more = self.runsource('\n'.join(self.buffer), self.filename)
2210 if not more:
2226 if not more:
2211 self.resetbuffer()
2227 self.resetbuffer()
2212 return more
2228 return more
2213
2229
2214 def resetbuffer(self):
2230 def resetbuffer(self):
2215 """Reset the input buffer."""
2231 """Reset the input buffer."""
2216 self.buffer[:] = []
2232 self.buffer[:] = []
2217
2233
2218 def _is_secondary_block_start(self, s):
2234 def _is_secondary_block_start(self, s):
2219 if not s.endswith(':'):
2235 if not s.endswith(':'):
2220 return False
2236 return False
2221 if (s.startswith('elif') or
2237 if (s.startswith('elif') or
2222 s.startswith('else') or
2238 s.startswith('else') or
2223 s.startswith('except') or
2239 s.startswith('except') or
2224 s.startswith('finally')):
2240 s.startswith('finally')):
2225 return True
2241 return True
2226
2242
2227 def _cleanup_ipy_script(self, script):
2243 def _cleanup_ipy_script(self, script):
2228 """Make a script safe for self.runlines()
2244 """Make a script safe for self.runlines()
2229
2245
2230 Currently, IPython is lines based, with blocks being detected by
2246 Currently, IPython is lines based, with blocks being detected by
2231 empty lines. This is a problem for block based scripts that may
2247 empty lines. This is a problem for block based scripts that may
2232 not have empty lines after blocks. This script adds those empty
2248 not have empty lines after blocks. This script adds those empty
2233 lines to make scripts safe for running in the current line based
2249 lines to make scripts safe for running in the current line based
2234 IPython.
2250 IPython.
2235 """
2251 """
2236 res = []
2252 res = []
2237 lines = script.splitlines()
2253 lines = script.splitlines()
2238 level = 0
2254 level = 0
2239
2255
2240 for l in lines:
2256 for l in lines:
2241 lstripped = l.lstrip()
2257 lstripped = l.lstrip()
2242 stripped = l.strip()
2258 stripped = l.strip()
2243 if not stripped:
2259 if not stripped:
2244 continue
2260 continue
2245 newlevel = len(l) - len(lstripped)
2261 newlevel = len(l) - len(lstripped)
2246 if level > 0 and newlevel == 0 and \
2262 if level > 0 and newlevel == 0 and \
2247 not self._is_secondary_block_start(stripped):
2263 not self._is_secondary_block_start(stripped):
2248 # add empty line
2264 # add empty line
2249 res.append('')
2265 res.append('')
2250 res.append(l)
2266 res.append(l)
2251 level = newlevel
2267 level = newlevel
2252
2268
2253 return '\n'.join(res) + '\n'
2269 return '\n'.join(res) + '\n'
2254
2270
2255 def _autoindent_update(self,line):
2271 def _autoindent_update(self,line):
2256 """Keep track of the indent level."""
2272 """Keep track of the indent level."""
2257
2273
2258 #debugx('line')
2274 #debugx('line')
2259 #debugx('self.indent_current_nsp')
2275 #debugx('self.indent_current_nsp')
2260 if self.autoindent:
2276 if self.autoindent:
2261 if line:
2277 if line:
2262 inisp = num_ini_spaces(line)
2278 inisp = num_ini_spaces(line)
2263 if inisp < self.indent_current_nsp:
2279 if inisp < self.indent_current_nsp:
2264 self.indent_current_nsp = inisp
2280 self.indent_current_nsp = inisp
2265
2281
2266 if line[-1] == ':':
2282 if line[-1] == ':':
2267 self.indent_current_nsp += 4
2283 self.indent_current_nsp += 4
2268 elif dedent_re.match(line):
2284 elif dedent_re.match(line):
2269 self.indent_current_nsp -= 4
2285 self.indent_current_nsp -= 4
2270 else:
2286 else:
2271 self.indent_current_nsp = 0
2287 self.indent_current_nsp = 0
2272
2288
2273 #-------------------------------------------------------------------------
2289 #-------------------------------------------------------------------------
2274 # Things related to GUI support and pylab
2290 # Things related to GUI support and pylab
2275 #-------------------------------------------------------------------------
2291 #-------------------------------------------------------------------------
2276
2292
2277 def enable_pylab(self, gui=None):
2293 def enable_pylab(self, gui=None):
2278 raise NotImplementedError('Implement enable_pylab in a subclass')
2294 raise NotImplementedError('Implement enable_pylab in a subclass')
2279
2295
2280 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2281 # Utilities
2297 # Utilities
2282 #-------------------------------------------------------------------------
2298 #-------------------------------------------------------------------------
2283
2299
2284 def var_expand(self,cmd,depth=0):
2300 def var_expand(self,cmd,depth=0):
2285 """Expand python variables in a string.
2301 """Expand python variables in a string.
2286
2302
2287 The depth argument indicates how many frames above the caller should
2303 The depth argument indicates how many frames above the caller should
2288 be walked to look for the local namespace where to expand variables.
2304 be walked to look for the local namespace where to expand variables.
2289
2305
2290 The global namespace for expansion is always the user's interactive
2306 The global namespace for expansion is always the user's interactive
2291 namespace.
2307 namespace.
2292 """
2308 """
2293
2309
2294 return str(ItplNS(cmd,
2310 return str(ItplNS(cmd,
2295 self.user_ns, # globals
2311 self.user_ns, # globals
2296 # Skip our own frame in searching for locals:
2312 # Skip our own frame in searching for locals:
2297 sys._getframe(depth+1).f_locals # locals
2313 sys._getframe(depth+1).f_locals # locals
2298 ))
2314 ))
2299
2315
2300 def mktempfile(self,data=None):
2316 def mktempfile(self,data=None):
2301 """Make a new tempfile and return its filename.
2317 """Make a new tempfile and return its filename.
2302
2318
2303 This makes a call to tempfile.mktemp, but it registers the created
2319 This makes a call to tempfile.mktemp, but it registers the created
2304 filename internally so ipython cleans it up at exit time.
2320 filename internally so ipython cleans it up at exit time.
2305
2321
2306 Optional inputs:
2322 Optional inputs:
2307
2323
2308 - data(None): if data is given, it gets written out to the temp file
2324 - data(None): if data is given, it gets written out to the temp file
2309 immediately, and the file is closed again."""
2325 immediately, and the file is closed again."""
2310
2326
2311 filename = tempfile.mktemp('.py','ipython_edit_')
2327 filename = tempfile.mktemp('.py','ipython_edit_')
2312 self.tempfiles.append(filename)
2328 self.tempfiles.append(filename)
2313
2329
2314 if data:
2330 if data:
2315 tmp_file = open(filename,'w')
2331 tmp_file = open(filename,'w')
2316 tmp_file.write(data)
2332 tmp_file.write(data)
2317 tmp_file.close()
2333 tmp_file.close()
2318 return filename
2334 return filename
2319
2335
2320 # TODO: This should be removed when Term is refactored.
2336 # TODO: This should be removed when Term is refactored.
2321 def write(self,data):
2337 def write(self,data):
2322 """Write a string to the default output"""
2338 """Write a string to the default output"""
2323 io.Term.cout.write(data)
2339 io.Term.cout.write(data)
2324
2340
2325 # TODO: This should be removed when Term is refactored.
2341 # TODO: This should be removed when Term is refactored.
2326 def write_err(self,data):
2342 def write_err(self,data):
2327 """Write a string to the default error output"""
2343 """Write a string to the default error output"""
2328 io.Term.cerr.write(data)
2344 io.Term.cerr.write(data)
2329
2345
2330 def ask_yes_no(self,prompt,default=True):
2346 def ask_yes_no(self,prompt,default=True):
2331 if self.quiet:
2347 if self.quiet:
2332 return True
2348 return True
2333 return ask_yes_no(prompt,default)
2349 return ask_yes_no(prompt,default)
2334
2350
2335 def show_usage(self):
2351 def show_usage(self):
2336 """Show a usage message"""
2352 """Show a usage message"""
2337 page.page(IPython.core.usage.interactive_usage)
2353 page.page(IPython.core.usage.interactive_usage)
2338
2354
2339 #-------------------------------------------------------------------------
2355 #-------------------------------------------------------------------------
2340 # Things related to IPython exiting
2356 # Things related to IPython exiting
2341 #-------------------------------------------------------------------------
2357 #-------------------------------------------------------------------------
2342 def atexit_operations(self):
2358 def atexit_operations(self):
2343 """This will be executed at the time of exit.
2359 """This will be executed at the time of exit.
2344
2360
2345 Cleanup operations and saving of persistent data that is done
2361 Cleanup operations and saving of persistent data that is done
2346 unconditionally by IPython should be performed here.
2362 unconditionally by IPython should be performed here.
2347
2363
2348 For things that may depend on startup flags or platform specifics (such
2364 For things that may depend on startup flags or platform specifics (such
2349 as having readline or not), register a separate atexit function in the
2365 as having readline or not), register a separate atexit function in the
2350 code that has the appropriate information, rather than trying to
2366 code that has the appropriate information, rather than trying to
2351 clutter
2367 clutter
2352 """
2368 """
2353 # Cleanup all tempfiles left around
2369 # Cleanup all tempfiles left around
2354 for tfile in self.tempfiles:
2370 for tfile in self.tempfiles:
2355 try:
2371 try:
2356 os.unlink(tfile)
2372 os.unlink(tfile)
2357 except OSError:
2373 except OSError:
2358 pass
2374 pass
2359
2375
2360 # Clear all user namespaces to release all references cleanly.
2376 # Clear all user namespaces to release all references cleanly.
2361 self.reset()
2377 self.reset()
2362
2378
2363 # Run user hooks
2379 # Run user hooks
2364 self.hooks.shutdown_hook()
2380 self.hooks.shutdown_hook()
2365
2381
2366 def cleanup(self):
2382 def cleanup(self):
2367 self.restore_sys_module_state()
2383 self.restore_sys_module_state()
2368
2384
2369
2385
2370 class InteractiveShellABC(object):
2386 class InteractiveShellABC(object):
2371 """An abstract base class for InteractiveShell."""
2387 """An abstract base class for InteractiveShell."""
2372 __metaclass__ = abc.ABCMeta
2388 __metaclass__ = abc.ABCMeta
2373
2389
2374 InteractiveShellABC.register(InteractiveShell)
2390 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now