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