Show More
This diff has been collapsed as it changes many lines, (523 lines changed) Show them Hide them | |||||
@@ -0,0 +1,523 b'' | |||||
|
1 | """Word completion for IPython. | |||
|
2 | ||||
|
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 | |||
|
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 | |||
|
7 | IPython-specific utility. | |||
|
8 | ||||
|
9 | --------------------------------------------------------------------------- | |||
|
10 | Original rlcompleter documentation: | |||
|
11 | ||||
|
12 | This requires the latest extension to the readline module (the | |||
|
13 | completes keywords, built-ins and globals in __main__; when completing | |||
|
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |||
|
15 | completes its attributes. | |||
|
16 | ||||
|
17 | It's very cool to do "import string" type "string.", hit the | |||
|
18 | completion key (twice), and see the list of names defined by the | |||
|
19 | string module! | |||
|
20 | ||||
|
21 | Tip: to use the tab key as the completion key, call | |||
|
22 | ||||
|
23 | readline.parse_and_bind("tab: complete") | |||
|
24 | ||||
|
25 | Notes: | |||
|
26 | ||||
|
27 | - Exceptions raised by the completer function are *ignored* (and | |||
|
28 | generally cause the completion to fail). This is a feature -- since | |||
|
29 | readline sets the tty device in raw (or cbreak) mode, printing a | |||
|
30 | traceback wouldn't work well without some complicated hoopla to save, | |||
|
31 | reset and restore the tty state. | |||
|
32 | ||||
|
33 | - The evaluation of the NAME.NAME... form may cause arbitrary | |||
|
34 | application defined code to be executed if an object with a | |||
|
35 | __getattr__ hook is found. Since it is the responsibility of the | |||
|
36 | application (or the user) to enable this feature, I consider this an | |||
|
37 | acceptable risk. More complicated expressions (e.g. function calls or | |||
|
38 | indexing operations) are *not* evaluated. | |||
|
39 | ||||
|
40 | - GNU readline is also used by the built-in functions input() and | |||
|
41 | raw_input(), and thus these also benefit/suffer from the completer | |||
|
42 | features. Clearly an interactive application can benefit by | |||
|
43 | specifying its own completer function and using raw_input() for all | |||
|
44 | its input. | |||
|
45 | ||||
|
46 | - When the original stdin is not a tty device, GNU readline is never | |||
|
47 | used, and this module (and the readline module) are silently inactive. | |||
|
48 | ||||
|
49 | """ | |||
|
50 | ||||
|
51 | #***************************************************************************** | |||
|
52 | # | |||
|
53 | # Since this file is essentially a minimally modified copy of the rlcompleter | |||
|
54 | # module which is part of the standard Python distribution, I assume that the | |||
|
55 | # proper procedure is to maintain its copyright as belonging to the Python | |||
|
56 | # Software Foundation (in addition to my own, for all new code). | |||
|
57 | # | |||
|
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |||
|
59 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> | |||
|
60 | # | |||
|
61 | # Distributed under the terms of the BSD License. The full license is in | |||
|
62 | # the file COPYING, distributed as part of this software. | |||
|
63 | # | |||
|
64 | #***************************************************************************** | |||
|
65 | ||||
|
66 | import __builtin__ | |||
|
67 | import __main__ | |||
|
68 | import glob | |||
|
69 | import keyword | |||
|
70 | import os | |||
|
71 | import re | |||
|
72 | import readline | |||
|
73 | import sys | |||
|
74 | import types | |||
|
75 | ||||
|
76 | from IPython.genutils import shlex_split | |||
|
77 | ||||
|
78 | __all__ = ['Completer','IPCompleter'] | |||
|
79 | ||||
|
80 | def get_class_members(klass): | |||
|
81 | ret = dir(klass) | |||
|
82 | if hasattr(klass,'__bases__'): | |||
|
83 | for base in klass.__bases__: | |||
|
84 | ret.extend(get_class_members(base)) | |||
|
85 | return ret | |||
|
86 | ||||
|
87 | class Completer: | |||
|
88 | def __init__(self,namespace=None,global_namespace=None): | |||
|
89 | """Create a new completer for the command line. | |||
|
90 | ||||
|
91 | Completer([namespace,global_namespace]) -> completer instance. | |||
|
92 | ||||
|
93 | If unspecified, the default namespace where completions are performed | |||
|
94 | is __main__ (technically, __main__.__dict__). Namespaces should be | |||
|
95 | given as dictionaries. | |||
|
96 | ||||
|
97 | An optional second namespace can be given. This allows the completer | |||
|
98 | to handle cases where both the local and global scopes need to be | |||
|
99 | distinguished. | |||
|
100 | ||||
|
101 | Completer instances should be used as the completion mechanism of | |||
|
102 | readline via the set_completer() call: | |||
|
103 | ||||
|
104 | readline.set_completer(Completer(my_namespace).complete) | |||
|
105 | """ | |||
|
106 | ||||
|
107 | if namespace and type(namespace) != types.DictType: | |||
|
108 | raise TypeError,'namespace must be a dictionary' | |||
|
109 | ||||
|
110 | if global_namespace and type(global_namespace) != types.DictType: | |||
|
111 | raise TypeError,'global_namespace must be a dictionary' | |||
|
112 | ||||
|
113 | # Don't bind to namespace quite yet, but flag whether the user wants a | |||
|
114 | # specific namespace or to use __main__.__dict__. This will allow us | |||
|
115 | # to bind to __main__.__dict__ at completion time, not now. | |||
|
116 | if namespace is None: | |||
|
117 | self.use_main_ns = 1 | |||
|
118 | else: | |||
|
119 | self.use_main_ns = 0 | |||
|
120 | self.namespace = namespace | |||
|
121 | ||||
|
122 | # The global namespace, if given, can be bound directly | |||
|
123 | if global_namespace is None: | |||
|
124 | self.global_namespace = {} | |||
|
125 | else: | |||
|
126 | self.global_namespace = global_namespace | |||
|
127 | ||||
|
128 | def complete(self, text, state): | |||
|
129 | """Return the next possible completion for 'text'. | |||
|
130 | ||||
|
131 | This is called successively with state == 0, 1, 2, ... until it | |||
|
132 | returns None. The completion should begin with 'text'. | |||
|
133 | ||||
|
134 | """ | |||
|
135 | if self.use_main_ns: | |||
|
136 | self.namespace = __main__.__dict__ | |||
|
137 | ||||
|
138 | if state == 0: | |||
|
139 | if "." in text: | |||
|
140 | self.matches = self.attr_matches(text) | |||
|
141 | else: | |||
|
142 | self.matches = self.global_matches(text) | |||
|
143 | try: | |||
|
144 | return self.matches[state] | |||
|
145 | except IndexError: | |||
|
146 | return None | |||
|
147 | ||||
|
148 | def global_matches(self, text): | |||
|
149 | """Compute matches when text is a simple name. | |||
|
150 | ||||
|
151 | Return a list of all keywords, built-in functions and names currently | |||
|
152 | defined in self.namespace or self.global_namespace that match. | |||
|
153 | ||||
|
154 | """ | |||
|
155 | matches = [] | |||
|
156 | match_append = matches.append | |||
|
157 | n = len(text) | |||
|
158 | for lst in [keyword.kwlist, | |||
|
159 | __builtin__.__dict__.keys(), | |||
|
160 | self.namespace.keys(), | |||
|
161 | self.global_namespace.keys()]: | |||
|
162 | for word in lst: | |||
|
163 | if word[:n] == text and word != "__builtins__": | |||
|
164 | match_append(word) | |||
|
165 | return matches | |||
|
166 | ||||
|
167 | def attr_matches(self, text): | |||
|
168 | """Compute matches when text contains a dot. | |||
|
169 | ||||
|
170 | Assuming the text is of the form NAME.NAME....[NAME], and is | |||
|
171 | evaluatable in self.namespace or self.global_namespace, it will be | |||
|
172 | evaluated and its attributes (as revealed by dir()) are used as | |||
|
173 | possible completions. (For class instances, class members are are | |||
|
174 | also considered.) | |||
|
175 | ||||
|
176 | WARNING: this can still invoke arbitrary C code, if an object | |||
|
177 | with a __getattr__ hook is evaluated. | |||
|
178 | ||||
|
179 | """ | |||
|
180 | import re | |||
|
181 | ||||
|
182 | # Another option, seems to work great. Catches things like ''.<tab> | |||
|
183 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |||
|
184 | ||||
|
185 | if not m: | |||
|
186 | return [] | |||
|
187 | expr, attr = m.group(1, 3) | |||
|
188 | try: | |||
|
189 | object = eval(expr, self.namespace) | |||
|
190 | except: | |||
|
191 | object = eval(expr, self.global_namespace) | |||
|
192 | words = [w for w in dir(object) if isinstance(w, basestring)] | |||
|
193 | if hasattr(object,'__class__'): | |||
|
194 | words.append('__class__') | |||
|
195 | words.extend(get_class_members(object.__class__)) | |||
|
196 | n = len(attr) | |||
|
197 | matches = [] | |||
|
198 | for word in words: | |||
|
199 | if word[:n] == attr and word != "__builtins__": | |||
|
200 | matches.append("%s.%s" % (expr, word)) | |||
|
201 | return matches | |||
|
202 | ||||
|
203 | class IPCompleter(Completer): | |||
|
204 | """Extension of the completer class with IPython-specific features""" | |||
|
205 | ||||
|
206 | def __init__(self,shell,namespace=None,global_namespace=None, | |||
|
207 | omit__names=0,alias_table=None): | |||
|
208 | """IPCompleter() -> completer | |||
|
209 | ||||
|
210 | Return a completer object suitable for use by the readline library | |||
|
211 | via readline.set_completer(). | |||
|
212 | ||||
|
213 | Inputs: | |||
|
214 | ||||
|
215 | - shell: a pointer to the ipython shell itself. This is needed | |||
|
216 | because this completer knows about magic functions, and those can | |||
|
217 | only be accessed via the ipython instance. | |||
|
218 | ||||
|
219 | - namespace: an optional dict where completions are performed. | |||
|
220 | ||||
|
221 | - global_namespace: secondary optional dict for completions, to | |||
|
222 | handle cases (such as IPython embedded inside functions) where | |||
|
223 | both Python scopes are visible. | |||
|
224 | ||||
|
225 | - The optional omit__names parameter sets the completer to omit the | |||
|
226 | 'magic' names (__magicname__) for python objects unless the text | |||
|
227 | to be completed explicitly starts with one or more underscores. | |||
|
228 | ||||
|
229 | - If alias_table is supplied, it should be a dictionary of aliases | |||
|
230 | to complete. """ | |||
|
231 | ||||
|
232 | Completer.__init__(self,namespace,global_namespace) | |||
|
233 | self.magic_prefix = shell.name+'.magic_' | |||
|
234 | self.magic_escape = shell.ESC_MAGIC | |||
|
235 | self.readline = readline | |||
|
236 | delims = self.readline.get_completer_delims() | |||
|
237 | delims = delims.replace(self.magic_escape,'') | |||
|
238 | self.readline.set_completer_delims(delims) | |||
|
239 | self.get_line_buffer = self.readline.get_line_buffer | |||
|
240 | self.omit__names = omit__names | |||
|
241 | self.merge_completions = shell.rc.readline_merge_completions | |||
|
242 | ||||
|
243 | if alias_table is None: | |||
|
244 | alias_table = {} | |||
|
245 | self.alias_table = alias_table | |||
|
246 | # Regexp to split filenames with spaces in them | |||
|
247 | self.space_name_re = re.compile(r'([^\\] )') | |||
|
248 | # Hold a local ref. to glob.glob for speed | |||
|
249 | self.glob = glob.glob | |||
|
250 | # Special handling of backslashes needed in win32 platforms | |||
|
251 | if sys.platform == "win32": | |||
|
252 | self.clean_glob = self._clean_glob_win32 | |||
|
253 | else: | |||
|
254 | self.clean_glob = self._clean_glob | |||
|
255 | self.matchers = [self.python_matches, | |||
|
256 | self.file_matches, | |||
|
257 | self.alias_matches, | |||
|
258 | self.python_func_kw_matches] | |||
|
259 | ||||
|
260 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |||
|
261 | def all_completions(self, text): | |||
|
262 | """Return all possible completions for the benefit of emacs.""" | |||
|
263 | ||||
|
264 | completions = [] | |||
|
265 | comp_append = completions.append | |||
|
266 | try: | |||
|
267 | for i in xrange(sys.maxint): | |||
|
268 | res = self.complete(text, i) | |||
|
269 | ||||
|
270 | if not res: break | |||
|
271 | ||||
|
272 | comp_append(res) | |||
|
273 | #XXX workaround for ``notDefined.<tab>`` | |||
|
274 | except NameError: | |||
|
275 | pass | |||
|
276 | return completions | |||
|
277 | # /end Alex Schmolck code. | |||
|
278 | ||||
|
279 | def _clean_glob(self,text): | |||
|
280 | return self.glob("%s*" % text) | |||
|
281 | ||||
|
282 | def _clean_glob_win32(self,text): | |||
|
283 | return [f.replace("\\","/") | |||
|
284 | for f in self.glob("%s*" % text)] | |||
|
285 | ||||
|
286 | def file_matches(self, text): | |||
|
287 | """Match filneames, expanding ~USER type strings. | |||
|
288 | ||||
|
289 | Most of the seemingly convoluted logic in this completer is an | |||
|
290 | attempt to handle filenames with spaces in them. And yet it's not | |||
|
291 | quite perfect, because Python's readline doesn't expose all of the | |||
|
292 | GNU readline details needed for this to be done correctly. | |||
|
293 | ||||
|
294 | For a filename with a space in it, the printed completions will be | |||
|
295 | only the parts after what's already been typed (instead of the | |||
|
296 | full completions, as is normally done). I don't think with the | |||
|
297 | current (as of Python 2.3) Python readline it's possible to do | |||
|
298 | better.""" | |||
|
299 | ||||
|
300 | #print 'Completer->file_matches: <%s>' % text # dbg | |||
|
301 | ||||
|
302 | # chars that require escaping with backslash - i.e. chars | |||
|
303 | # that readline treats incorrectly as delimiters, but we | |||
|
304 | # don't want to treat as delimiters in filename matching | |||
|
305 | # when escaped with backslash | |||
|
306 | ||||
|
307 | protectables = ' ()[]{}' | |||
|
308 | ||||
|
309 | def protect_filename(s): | |||
|
310 | return "".join([(ch in protectables and '\\' + ch or ch) | |||
|
311 | for ch in s]) | |||
|
312 | ||||
|
313 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] | |||
|
314 | open_quotes = 0 # track strings with open quotes | |||
|
315 | try: | |||
|
316 | lsplit = shlex_split(lbuf)[-1] | |||
|
317 | except ValueError: | |||
|
318 | # typically an unmatched ", or backslash without escaped char. | |||
|
319 | if lbuf.count('"')==1: | |||
|
320 | open_quotes = 1 | |||
|
321 | lsplit = lbuf.split('"')[-1] | |||
|
322 | elif lbuf.count("'")==1: | |||
|
323 | open_quotes = 1 | |||
|
324 | lsplit = lbuf.split("'")[-1] | |||
|
325 | else: | |||
|
326 | return None | |||
|
327 | except IndexError: | |||
|
328 | # tab pressed on empty line | |||
|
329 | lsplit = "" | |||
|
330 | ||||
|
331 | if lsplit != protect_filename(lsplit): | |||
|
332 | # if protectables are found, do matching on the whole escaped | |||
|
333 | # name | |||
|
334 | has_protectables = 1 | |||
|
335 | text0,text = text,lsplit | |||
|
336 | else: | |||
|
337 | has_protectables = 0 | |||
|
338 | text = os.path.expanduser(text) | |||
|
339 | ||||
|
340 | if text == "": | |||
|
341 | return [protect_filename(f) for f in self.glob("*")] | |||
|
342 | ||||
|
343 | m0 = self.clean_glob(text.replace('\\','')) | |||
|
344 | if has_protectables: | |||
|
345 | # If we had protectables, we need to revert our changes to the | |||
|
346 | # beginning of filename so that we don't double-write the part | |||
|
347 | # of the filename we have so far | |||
|
348 | len_lsplit = len(lsplit) | |||
|
349 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] | |||
|
350 | else: | |||
|
351 | if open_quotes: | |||
|
352 | # if we have a string with an open quote, we don't need to | |||
|
353 | # protect the names at all (and we _shouldn't_, as it | |||
|
354 | # would cause bugs when the filesystem call is made). | |||
|
355 | matches = m0 | |||
|
356 | else: | |||
|
357 | matches = [protect_filename(f) for f in m0] | |||
|
358 | if len(matches) == 1 and os.path.isdir(matches[0]): | |||
|
359 | # Takes care of links to directories also. Use '/' | |||
|
360 | # explicitly, even under Windows, so that name completions | |||
|
361 | # don't end up escaped. | |||
|
362 | matches[0] += '/' | |||
|
363 | return matches | |||
|
364 | ||||
|
365 | def alias_matches(self, text): | |||
|
366 | """Match internal system aliases""" | |||
|
367 | #print 'Completer->alias_matches:',text # dbg | |||
|
368 | text = os.path.expanduser(text) | |||
|
369 | aliases = self.alias_table.keys() | |||
|
370 | if text == "": | |||
|
371 | return aliases | |||
|
372 | else: | |||
|
373 | return [alias for alias in aliases if alias.startswith(text)] | |||
|
374 | ||||
|
375 | def python_matches(self,text): | |||
|
376 | """Match attributes or global python names""" | |||
|
377 | #print 'Completer->python_matches' # dbg | |||
|
378 | if "." in text: | |||
|
379 | try: | |||
|
380 | matches = self.attr_matches(text) | |||
|
381 | if text.endswith('.') and self.omit__names: | |||
|
382 | if self.omit__names == 1: | |||
|
383 | # true if txt is _not_ a __ name, false otherwise: | |||
|
384 | no__name = (lambda txt: | |||
|
385 | re.match(r'.*\.__.*?__',txt) is None) | |||
|
386 | else: | |||
|
387 | # true if txt is _not_ a _ name, false otherwise: | |||
|
388 | no__name = (lambda txt: | |||
|
389 | re.match(r'.*\._.*?',txt) is None) | |||
|
390 | matches = filter(no__name, matches) | |||
|
391 | except NameError: | |||
|
392 | # catches <undefined attributes>.<tab> | |||
|
393 | matches = [] | |||
|
394 | else: | |||
|
395 | matches = self.global_matches(text) | |||
|
396 | # this is so completion finds magics when automagic is on: | |||
|
397 | if matches == [] and not text.startswith(os.sep): | |||
|
398 | matches = self.attr_matches(self.magic_prefix+text) | |||
|
399 | return matches | |||
|
400 | ||||
|
401 | def _default_arguments(self, obj): | |||
|
402 | """Return the list of default arguments of obj if it is callable, | |||
|
403 | or empty list otherwise.""" | |||
|
404 | ||||
|
405 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |||
|
406 | # for classes, check for __init__,__new__ | |||
|
407 | if inspect.isclass(obj): | |||
|
408 | obj = (getattr(obj,'__init__',None) or | |||
|
409 | getattr(obj,'__new__',None)) | |||
|
410 | # for all others, check if they are __call__able | |||
|
411 | elif hasattr(obj, '__call__'): | |||
|
412 | obj = obj.__call__ | |||
|
413 | # XXX: is there a way to handle the builtins ? | |||
|
414 | try: | |||
|
415 | args,_,_1,defaults = inspect.getargspec(obj) | |||
|
416 | if defaults: | |||
|
417 | return args[-len(defaults):] | |||
|
418 | except TypeError: pass | |||
|
419 | return [] | |||
|
420 | ||||
|
421 | def python_func_kw_matches(self,text): | |||
|
422 | """Match named parameters (kwargs) of the last open function""" | |||
|
423 | ||||
|
424 | if "." in text: # a parameter cannot be dotted | |||
|
425 | return [] | |||
|
426 | try: regexp = self.__funcParamsRegex | |||
|
427 | except AttributeError: | |||
|
428 | regexp = self.__funcParamsRegex = re.compile(r''' | |||
|
429 | '.*?' | # single quoted strings or | |||
|
430 | ".*?" | # double quoted strings or | |||
|
431 | \w+ | # identifier | |||
|
432 | \S # other characters | |||
|
433 | ''', re.VERBOSE | re.DOTALL) | |||
|
434 | # 1. find the nearest identifier that comes before an unclosed | |||
|
435 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |||
|
436 | tokens = regexp.findall(self.get_line_buffer()) | |||
|
437 | tokens.reverse() | |||
|
438 | iterTokens = iter(tokens); openPar = 0 | |||
|
439 | for token in iterTokens: | |||
|
440 | if token == ')': | |||
|
441 | openPar -= 1 | |||
|
442 | elif token == '(': | |||
|
443 | openPar += 1 | |||
|
444 | if openPar > 0: | |||
|
445 | # found the last unclosed parenthesis | |||
|
446 | break | |||
|
447 | else: | |||
|
448 | return [] | |||
|
449 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |||
|
450 | ids = [] | |||
|
451 | isId = re.compile(r'\w+$').match | |||
|
452 | while True: | |||
|
453 | try: | |||
|
454 | ids.append(iterTokens.next()) | |||
|
455 | if not isId(ids[-1]): | |||
|
456 | ids.pop(); break | |||
|
457 | if not iterTokens.next() == '.': | |||
|
458 | break | |||
|
459 | except StopIteration: | |||
|
460 | break | |||
|
461 | # lookup the candidate callable matches either using global_matches | |||
|
462 | # or attr_matches for dotted names | |||
|
463 | if len(ids) == 1: | |||
|
464 | callableMatches = self.global_matches(ids[0]) | |||
|
465 | else: | |||
|
466 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |||
|
467 | argMatches = [] | |||
|
468 | for callableMatch in callableMatches: | |||
|
469 | try: namedArgs = self._default_arguments(eval(callableMatch, | |||
|
470 | self.namespace)) | |||
|
471 | except: continue | |||
|
472 | for namedArg in namedArgs: | |||
|
473 | if namedArg.startswith(text): | |||
|
474 | argMatches.append("%s=" %namedArg) | |||
|
475 | return argMatches | |||
|
476 | ||||
|
477 | def complete(self, text, state): | |||
|
478 | """Return the next possible completion for 'text'. | |||
|
479 | ||||
|
480 | This is called successively with state == 0, 1, 2, ... until it | |||
|
481 | returns None. The completion should begin with 'text'. """ | |||
|
482 | ||||
|
483 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |||
|
484 | ||||
|
485 | # if there is only a tab on a line with only whitespace, instead | |||
|
486 | # of the mostly useless 'do you want to see all million | |||
|
487 | # completions' message, just do the right thing and give the user | |||
|
488 | # his tab! Incidentally, this enables pasting of tabbed text from | |||
|
489 | # an editor (as long as autoindent is off). | |||
|
490 | if not self.get_line_buffer().strip(): | |||
|
491 | self.readline.insert_text('\t') | |||
|
492 | return None | |||
|
493 | ||||
|
494 | magic_escape = self.magic_escape | |||
|
495 | magic_prefix = self.magic_prefix | |||
|
496 | ||||
|
497 | try: | |||
|
498 | if text.startswith(magic_escape): | |||
|
499 | text = text.replace(magic_escape,magic_prefix) | |||
|
500 | elif text.startswith('~'): | |||
|
501 | text = os.path.expanduser(text) | |||
|
502 | if state == 0: | |||
|
503 | # Extend the list of completions with the results of each | |||
|
504 | # matcher, so we return results to the user from all | |||
|
505 | # namespaces. | |||
|
506 | if self.merge_completions: | |||
|
507 | self.matches = [] | |||
|
508 | for matcher in self.matchers: | |||
|
509 | self.matches.extend(matcher(text)) | |||
|
510 | else: | |||
|
511 | for matcher in self.matchers: | |||
|
512 | self.matches = matcher(text) | |||
|
513 | if self.matches: | |||
|
514 | break | |||
|
515 | ||||
|
516 | try: | |||
|
517 | return self.matches[state].replace(magic_prefix,magic_escape) | |||
|
518 | except IndexError: | |||
|
519 | return None | |||
|
520 | except: | |||
|
521 | #import traceback; traceback.print_exc() # dbg | |||
|
522 | # If completion fails, don't annoy the user. | |||
|
523 | return None |
This diff has been collapsed as it changes many lines, (512 lines changed) Show them Hide them | |||||
@@ -6,21 +6,23 b' Requires Python 2.1 or newer.' | |||||
6 |
|
6 | |||
7 | This file contains all the classes and helper functions specific to IPython. |
|
7 | This file contains all the classes and helper functions specific to IPython. | |
8 |
|
8 | |||
9 |
$Id: iplib.py 95 |
|
9 | $Id: iplib.py 957 2005-12-27 22:33:22Z fperez $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
13 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
14 |
# Copyright (C) 2001-200 |
|
14 | # Copyright (C) 2001-2005 Fernando Perez. <fperez@colorado.edu> | |
15 | # |
|
15 | # | |
16 | # Distributed under the terms of the BSD License. The full license is in |
|
16 | # Distributed under the terms of the BSD License. The full license is in | |
17 | # the file COPYING, distributed as part of this software. |
|
17 | # the file COPYING, distributed as part of this software. | |
18 | # |
|
18 | # | |
19 | # Note: this code originally subclassed code.InteractiveConsole from the |
|
19 | # Note: this code originally subclassed code.InteractiveConsole from the | |
20 |
# Python standard library. Over time, |
|
20 | # Python standard library. Over time, all of that class has been copied | |
21 | # verbatim here for modifications which could not be accomplished by |
|
21 | # verbatim here for modifications which could not be accomplished by | |
22 | # subclassing. The Python License (sec. 2) allows for this, but it's always |
|
22 | # subclassing. At this point, there are no dependencies at all on the code | |
23 | # nice to acknowledge credit where credit is due. |
|
23 | # module anymore (it is not even imported). The Python License (sec. 2) | |
|
24 | # allows for this, but it's always nice to acknowledge credit where credit is | |||
|
25 | # due. | |||
24 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
25 |
|
27 | |||
26 | #**************************************************************************** |
|
28 | #**************************************************************************** | |
@@ -37,26 +39,33 b' __version__ = Release.version' | |||||
37 | # Python standard modules |
|
39 | # Python standard modules | |
38 | import __main__ |
|
40 | import __main__ | |
39 | import __builtin__ |
|
41 | import __builtin__ | |
|
42 | import bdb | |||
|
43 | import codeop | |||
|
44 | import cPickle as pickle | |||
40 | import exceptions |
|
45 | import exceptions | |
|
46 | import glob | |||
|
47 | import inspect | |||
41 | import keyword |
|
48 | import keyword | |
42 | import new |
|
49 | import new | |
43 | import os, sys, shutil |
|
50 | import os | |
44 | import code, glob, types, re |
|
51 | import pdb | |
45 | import string, StringIO |
|
52 | import pydoc | |
46 | import inspect, pydoc |
|
53 | import re | |
47 | import bdb, pdb |
|
54 | import shutil | |
48 | import UserList # don't subclass list so this works with Python2.1 |
|
55 | import string | |
49 | from pprint import pprint, pformat |
|
56 | import StringIO | |
50 | import cPickle as pickle |
|
57 | import sys | |
51 | import traceback |
|
58 | import traceback | |
52 | from codeop import CommandCompiler |
|
59 | import types | |
|
60 | ||||
|
61 | from pprint import pprint, pformat | |||
53 |
|
62 | |||
54 | # IPython's own modules |
|
63 | # IPython's own modules | |
55 | import IPython |
|
64 | import IPython | |
56 | from IPython import OInspect,PyColorize,ultraTB |
|
65 | from IPython import OInspect,PyColorize,ultraTB | |
57 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names |
|
66 | from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names | |
58 | from IPython.Logger import Logger |
|
67 | from IPython.Logger import Logger | |
59 |
from IPython.Magic import Magic,magic2python |
|
68 | from IPython.Magic import Magic,magic2python | |
60 | from IPython.usage import cmd_line_usage,interactive_usage |
|
69 | from IPython.usage import cmd_line_usage,interactive_usage | |
61 | from IPython.Struct import Struct |
|
70 | from IPython.Struct import Struct | |
62 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns |
|
71 | from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns | |
@@ -74,8 +83,6 b' raw_input_original = raw_input' | |||||
74 | #**************************************************************************** |
|
83 | #**************************************************************************** | |
75 | # Some utility function definitions |
|
84 | # Some utility function definitions | |
76 |
|
85 | |||
77 | class Bunch: pass |
|
|||
78 |
|
||||
79 | def esc_quotes(strng): |
|
86 | def esc_quotes(strng): | |
80 | """Return the input string with single and double quotes escaped out""" |
|
87 | """Return the input string with single and double quotes escaped out""" | |
81 |
|
88 | |||
@@ -163,340 +170,32 b' def ipalias(arg_s):' | |||||
163 | else: |
|
170 | else: | |
164 | error("Alias `%s` not found." % alias_name) |
|
171 | error("Alias `%s` not found." % alias_name) | |
165 |
|
172 | |||
166 | #----------------------------------------------------------------------------- |
|
173 | def softspace(file, newvalue): | |
167 | # Local use classes |
|
174 | """Copied from code.py, to remove the dependency""" | |
168 | try: |
|
175 | oldvalue = 0 | |
169 | from IPython import FlexCompleter |
|
|||
170 |
|
||||
171 | class MagicCompleter(FlexCompleter.Completer): |
|
|||
172 | """Extension of the completer class to work on %-prefixed lines.""" |
|
|||
173 |
|
||||
174 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
|||
175 | omit__names=0,alias_table=None): |
|
|||
176 | """MagicCompleter() -> completer |
|
|||
177 |
|
||||
178 | Return a completer object suitable for use by the readline library |
|
|||
179 | via readline.set_completer(). |
|
|||
180 |
|
||||
181 | Inputs: |
|
|||
182 |
|
||||
183 | - shell: a pointer to the ipython shell itself. This is needed |
|
|||
184 | because this completer knows about magic functions, and those can |
|
|||
185 | only be accessed via the ipython instance. |
|
|||
186 |
|
||||
187 | - namespace: an optional dict where completions are performed. |
|
|||
188 |
|
||||
189 | - global_namespace: secondary optional dict for completions, to |
|
|||
190 | handle cases (such as IPython embedded inside functions) where |
|
|||
191 | both Python scopes are visible. |
|
|||
192 |
|
||||
193 | - The optional omit__names parameter sets the completer to omit the |
|
|||
194 | 'magic' names (__magicname__) for python objects unless the text |
|
|||
195 | to be completed explicitly starts with one or more underscores. |
|
|||
196 |
|
||||
197 | - If alias_table is supplied, it should be a dictionary of aliases |
|
|||
198 | to complete. """ |
|
|||
199 |
|
||||
200 | FlexCompleter.Completer.__init__(self,namespace) |
|
|||
201 | self.magic_prefix = shell.name+'.magic_' |
|
|||
202 | self.magic_escape = shell.ESC_MAGIC |
|
|||
203 | self.readline = FlexCompleter.readline |
|
|||
204 | delims = self.readline.get_completer_delims() |
|
|||
205 | delims = delims.replace(self.magic_escape,'') |
|
|||
206 | self.readline.set_completer_delims(delims) |
|
|||
207 | self.get_line_buffer = self.readline.get_line_buffer |
|
|||
208 | self.omit__names = omit__names |
|
|||
209 | self.merge_completions = shell.rc.readline_merge_completions |
|
|||
210 |
|
||||
211 | if alias_table is None: |
|
|||
212 | alias_table = {} |
|
|||
213 | self.alias_table = alias_table |
|
|||
214 | # Regexp to split filenames with spaces in them |
|
|||
215 | self.space_name_re = re.compile(r'([^\\] )') |
|
|||
216 | # Hold a local ref. to glob.glob for speed |
|
|||
217 | self.glob = glob.glob |
|
|||
218 | # Special handling of backslashes needed in win32 platforms |
|
|||
219 | if sys.platform == "win32": |
|
|||
220 | self.clean_glob = self._clean_glob_win32 |
|
|||
221 | else: |
|
|||
222 | self.clean_glob = self._clean_glob |
|
|||
223 | self.matchers = [self.python_matches, |
|
|||
224 | self.file_matches, |
|
|||
225 | self.alias_matches, |
|
|||
226 | self.python_func_kw_matches] |
|
|||
227 |
|
||||
228 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
|||
229 | def all_completions(self, text): |
|
|||
230 | """Return all possible completions for the benefit of emacs.""" |
|
|||
231 |
|
||||
232 | completions = [] |
|
|||
233 | comp_append = completions.append |
|
|||
234 | try: |
|
|||
235 | for i in xrange(sys.maxint): |
|
|||
236 | res = self.complete(text, i) |
|
|||
237 |
|
||||
238 | if not res: break |
|
|||
239 |
|
||||
240 | comp_append(res) |
|
|||
241 | #XXX workaround for ``notDefined.<tab>`` |
|
|||
242 | except NameError: |
|
|||
243 | pass |
|
|||
244 | return completions |
|
|||
245 | # /end Alex Schmolck code. |
|
|||
246 |
|
||||
247 | def _clean_glob(self,text): |
|
|||
248 | return self.glob("%s*" % text) |
|
|||
249 |
|
||||
250 | def _clean_glob_win32(self,text): |
|
|||
251 | return [f.replace("\\","/") |
|
|||
252 | for f in self.glob("%s*" % text)] |
|
|||
253 |
|
||||
254 | def file_matches(self, text): |
|
|||
255 | """Match filneames, expanding ~USER type strings. |
|
|||
256 |
|
||||
257 | Most of the seemingly convoluted logic in this completer is an |
|
|||
258 | attempt to handle filenames with spaces in them. And yet it's not |
|
|||
259 | quite perfect, because Python's readline doesn't expose all of the |
|
|||
260 | GNU readline details needed for this to be done correctly. |
|
|||
261 |
|
||||
262 | For a filename with a space in it, the printed completions will be |
|
|||
263 | only the parts after what's already been typed (instead of the |
|
|||
264 | full completions, as is normally done). I don't think with the |
|
|||
265 | current (as of Python 2.3) Python readline it's possible to do |
|
|||
266 | better.""" |
|
|||
267 |
|
||||
268 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
|||
269 |
|
||||
270 | # chars that require escaping with backslash - i.e. chars |
|
|||
271 | # that readline treats incorrectly as delimiters, but we |
|
|||
272 | # don't want to treat as delimiters in filename matching |
|
|||
273 | # when escaped with backslash |
|
|||
274 |
|
||||
275 | protectables = ' ()[]{}' |
|
|||
276 |
|
||||
277 | def protect_filename(s): |
|
|||
278 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
|||
279 | for ch in s]) |
|
|||
280 |
|
||||
281 | lbuf = self.get_line_buffer()[:self.readline.get_endidx()] |
|
|||
282 | open_quotes = 0 # track strings with open quotes |
|
|||
283 | try: |
|
|||
284 | lsplit = shlex_split(lbuf)[-1] |
|
|||
285 | except ValueError: |
|
|||
286 | # typically an unmatched ", or backslash without escaped char. |
|
|||
287 | if lbuf.count('"')==1: |
|
|||
288 | open_quotes = 1 |
|
|||
289 | lsplit = lbuf.split('"')[-1] |
|
|||
290 | elif lbuf.count("'")==1: |
|
|||
291 | open_quotes = 1 |
|
|||
292 | lsplit = lbuf.split("'")[-1] |
|
|||
293 | else: |
|
|||
294 | return None |
|
|||
295 | except IndexError: |
|
|||
296 | # tab pressed on empty line |
|
|||
297 | lsplit = "" |
|
|||
298 |
|
||||
299 | if lsplit != protect_filename(lsplit): |
|
|||
300 | # if protectables are found, do matching on the whole escaped |
|
|||
301 | # name |
|
|||
302 | has_protectables = 1 |
|
|||
303 | text0,text = text,lsplit |
|
|||
304 | else: |
|
|||
305 | has_protectables = 0 |
|
|||
306 | text = os.path.expanduser(text) |
|
|||
307 |
|
||||
308 | if text == "": |
|
|||
309 | return [protect_filename(f) for f in self.glob("*")] |
|
|||
310 |
|
||||
311 | m0 = self.clean_glob(text.replace('\\','')) |
|
|||
312 | if has_protectables: |
|
|||
313 | # If we had protectables, we need to revert our changes to the |
|
|||
314 | # beginning of filename so that we don't double-write the part |
|
|||
315 | # of the filename we have so far |
|
|||
316 | len_lsplit = len(lsplit) |
|
|||
317 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] |
|
|||
318 | else: |
|
|||
319 | if open_quotes: |
|
|||
320 | # if we have a string with an open quote, we don't need to |
|
|||
321 | # protect the names at all (and we _shouldn't_, as it |
|
|||
322 | # would cause bugs when the filesystem call is made). |
|
|||
323 | matches = m0 |
|
|||
324 | else: |
|
|||
325 | matches = [protect_filename(f) for f in m0] |
|
|||
326 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
|||
327 | # Takes care of links to directories also. Use '/' |
|
|||
328 | # explicitly, even under Windows, so that name completions |
|
|||
329 | # don't end up escaped. |
|
|||
330 | matches[0] += '/' |
|
|||
331 | return matches |
|
|||
332 |
|
||||
333 | def alias_matches(self, text): |
|
|||
334 | """Match internal system aliases""" |
|
|||
335 | #print 'Completer->alias_matches:',text # dbg |
|
|||
336 | text = os.path.expanduser(text) |
|
|||
337 | aliases = self.alias_table.keys() |
|
|||
338 | if text == "": |
|
|||
339 | return aliases |
|
|||
340 | else: |
|
|||
341 | return [alias for alias in aliases if alias.startswith(text)] |
|
|||
342 |
|
||||
343 | def python_matches(self,text): |
|
|||
344 | """Match attributes or global python names""" |
|
|||
345 | #print 'Completer->python_matches' # dbg |
|
|||
346 | if "." in text: |
|
|||
347 | try: |
|
176 | try: | |
348 | matches = self.attr_matches(text) |
|
177 | oldvalue = file.softspace | |
349 | if text.endswith('.') and self.omit__names: |
|
|||
350 | if self.omit__names == 1: |
|
|||
351 | # true if txt is _not_ a __ name, false otherwise: |
|
|||
352 | no__name = (lambda txt: |
|
|||
353 | re.match(r'.*\.__.*?__',txt) is None) |
|
|||
354 | else: |
|
|||
355 | # true if txt is _not_ a _ name, false otherwise: |
|
|||
356 | no__name = (lambda txt: |
|
|||
357 | re.match(r'.*\._.*?',txt) is None) |
|
|||
358 | matches = filter(no__name, matches) |
|
|||
359 | except NameError: |
|
|||
360 | # catches <undefined attributes>.<tab> |
|
|||
361 | matches = [] |
|
|||
362 | else: |
|
|||
363 | matches = self.global_matches(text) |
|
|||
364 | # this is so completion finds magics when automagic is on: |
|
|||
365 | if matches == [] and not text.startswith(os.sep): |
|
|||
366 | matches = self.attr_matches(self.magic_prefix+text) |
|
|||
367 | return matches |
|
|||
368 |
|
||||
369 | def _default_arguments(self, obj): |
|
|||
370 | """Return the list of default arguments of obj if it is callable, |
|
|||
371 | or empty list otherwise.""" |
|
|||
372 |
|
||||
373 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
|||
374 | # for classes, check for __init__,__new__ |
|
|||
375 | if inspect.isclass(obj): |
|
|||
376 | obj = (getattr(obj,'__init__',None) or |
|
|||
377 | getattr(obj,'__new__',None)) |
|
|||
378 | # for all others, check if they are __call__able |
|
|||
379 | elif hasattr(obj, '__call__'): |
|
|||
380 | obj = obj.__call__ |
|
|||
381 | # XXX: is there a way to handle the builtins ? |
|
|||
382 | try: |
|
|||
383 | args,_,_1,defaults = inspect.getargspec(obj) |
|
|||
384 | if defaults: |
|
|||
385 | return args[-len(defaults):] |
|
|||
386 | except TypeError: pass |
|
|||
387 | return [] |
|
|||
388 |
|
||||
389 | def python_func_kw_matches(self,text): |
|
|||
390 | """Match named parameters (kwargs) of the last open function""" |
|
|||
391 |
|
||||
392 | if "." in text: # a parameter cannot be dotted |
|
|||
393 | return [] |
|
|||
394 | try: regexp = self.__funcParamsRegex |
|
|||
395 |
|
|
178 | except AttributeError: | |
396 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
179 | pass | |
397 | '.*?' | # single quoted strings or |
|
|||
398 | ".*?" | # double quoted strings or |
|
|||
399 | \w+ | # identifier |
|
|||
400 | \S # other characters |
|
|||
401 | ''', re.VERBOSE | re.DOTALL) |
|
|||
402 | # 1. find the nearest identifier that comes before an unclosed |
|
|||
403 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
|||
404 | tokens = regexp.findall(self.get_line_buffer()) |
|
|||
405 | tokens.reverse() |
|
|||
406 | iterTokens = iter(tokens); openPar = 0 |
|
|||
407 | for token in iterTokens: |
|
|||
408 | if token == ')': |
|
|||
409 | openPar -= 1 |
|
|||
410 | elif token == '(': |
|
|||
411 | openPar += 1 |
|
|||
412 | if openPar > 0: |
|
|||
413 | # found the last unclosed parenthesis |
|
|||
414 | break |
|
|||
415 | else: |
|
|||
416 | return [] |
|
|||
417 | # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" ) |
|
|||
418 | ids = [] |
|
|||
419 | isId = re.compile(r'\w+$').match |
|
|||
420 | while True: |
|
|||
421 | try: |
|
|||
422 | ids.append(iterTokens.next()) |
|
|||
423 | if not isId(ids[-1]): |
|
|||
424 | ids.pop(); break |
|
|||
425 | if not iterTokens.next() == '.': |
|
|||
426 | break |
|
|||
427 | except StopIteration: |
|
|||
428 | break |
|
|||
429 | # lookup the candidate callable matches either using global_matches |
|
|||
430 | # or attr_matches for dotted names |
|
|||
431 | if len(ids) == 1: |
|
|||
432 | callableMatches = self.global_matches(ids[0]) |
|
|||
433 | else: |
|
|||
434 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
|||
435 | argMatches = [] |
|
|||
436 | for callableMatch in callableMatches: |
|
|||
437 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
|||
438 | self.namespace)) |
|
|||
439 | except: continue |
|
|||
440 | for namedArg in namedArgs: |
|
|||
441 | if namedArg.startswith(text): |
|
|||
442 | argMatches.append("%s=" %namedArg) |
|
|||
443 | return argMatches |
|
|||
444 |
|
||||
445 | def complete(self, text, state): |
|
|||
446 | """Return the next possible completion for 'text'. |
|
|||
447 |
|
||||
448 | This is called successively with state == 0, 1, 2, ... until it |
|
|||
449 | returns None. The completion should begin with 'text'. """ |
|
|||
450 |
|
||||
451 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
|||
452 |
|
||||
453 | # if there is only a tab on a line with only whitespace, instead |
|
|||
454 | # of the mostly useless 'do you want to see all million |
|
|||
455 | # completions' message, just do the right thing and give the user |
|
|||
456 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
|||
457 | # an editor (as long as autoindent is off). |
|
|||
458 | if not self.get_line_buffer().strip(): |
|
|||
459 | self.readline.insert_text('\t') |
|
|||
460 | return None |
|
|||
461 |
|
||||
462 | magic_escape = self.magic_escape |
|
|||
463 | magic_prefix = self.magic_prefix |
|
|||
464 |
|
||||
465 |
|
|
180 | try: | |
466 | if text.startswith(magic_escape): |
|
181 | file.softspace = newvalue | |
467 | text = text.replace(magic_escape,magic_prefix) |
|
182 | except (AttributeError, TypeError): | |
468 | elif text.startswith('~'): |
|
183 | # "attribute-less object" or "read-only attributes" | |
469 | text = os.path.expanduser(text) |
|
184 | pass | |
470 | if state == 0: |
|
185 | return oldvalue | |
471 | # Extend the list of completions with the results of each |
|
|||
472 | # matcher, so we return results to the user from all |
|
|||
473 | # namespaces. |
|
|||
474 | if self.merge_completions: |
|
|||
475 | self.matches = [] |
|
|||
476 | for matcher in self.matchers: |
|
|||
477 | self.matches.extend(matcher(text)) |
|
|||
478 | else: |
|
|||
479 | for matcher in self.matchers: |
|
|||
480 | self.matches = matcher(text) |
|
|||
481 | if self.matches: |
|
|||
482 | break |
|
|||
483 |
|
186 | |||
484 | try: |
|
|||
485 | return self.matches[state].replace(magic_prefix,magic_escape) |
|
|||
486 | except IndexError: |
|
|||
487 | return None |
|
|||
488 | except: |
|
|||
489 | # If completion fails, don't annoy the user. |
|
|||
490 | return None |
|
|||
491 |
|
187 | |||
492 | except ImportError: |
|
188 | #**************************************************************************** | |
493 | pass # no readline support |
|
189 | # Local use exceptions | |
|
190 | class SpaceInInput(exceptions.Exception): pass | |||
494 |
|
191 | |||
495 | except KeyError: |
|
192 | class IPythonExit(exceptions.Exception): pass | |
496 | pass # Windows doesn't set TERM, it doesn't matter |
|
|||
497 |
|
193 | |||
|
194 | #**************************************************************************** | |||
|
195 | # Local use classes | |||
|
196 | class Bunch: pass | |||
498 |
|
197 | |||
499 |
class InputList( |
|
198 | class InputList(list): | |
500 | """Class to store user input. |
|
199 | """Class to store user input. | |
501 |
|
200 | |||
502 | It's basically a list, but slices return a string instead of a list, thus |
|
201 | It's basically a list, but slices return a string instead of a list, thus | |
@@ -509,17 +208,11 b' class InputList(UserList.UserList):' | |||||
509 | exec In[5:9] + In[14] + In[21:25]""" |
|
208 | exec In[5:9] + In[14] + In[21:25]""" | |
510 |
|
209 | |||
511 | def __getslice__(self,i,j): |
|
210 | def __getslice__(self,i,j): | |
512 |
return ''.join( |
|
211 | return ''.join(list.__getslice__(self,i,j)) | |
513 |
|
||||
514 | #**************************************************************************** |
|
|||
515 | # Local use exceptions |
|
|||
516 | class SpaceInInput(exceptions.Exception): |
|
|||
517 | pass |
|
|||
518 |
|
212 | |||
519 | #**************************************************************************** |
|
213 | #**************************************************************************** | |
520 | # Main IPython class |
|
214 | # Main IPython class | |
521 |
|
215 | class InteractiveShell(Logger, Magic): | ||
522 | class InteractiveShell(code.InteractiveConsole, Logger, Magic): |
|
|||
523 | """An enhanced console for Python.""" |
|
216 | """An enhanced console for Python.""" | |
524 |
|
217 | |||
525 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), |
|
218 | def __init__(self,name,usage=None,rc=Struct(opts=None,args=None), | |
@@ -543,17 +236,20 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
543 | # which also gives us a way to determine the nesting level. |
|
236 | # which also gives us a way to determine the nesting level. | |
544 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) |
|
237 | __builtin__.__dict__.setdefault('__IPYTHON__active',0) | |
545 |
|
238 | |||
546 | # Inform the user of ipython's fast exit magics. |
|
239 | # Do the intuitively correct thing for quit/exit: we remove the | |
547 | _exit = ' Use %Exit or %Quit to exit without confirmation.' |
|
240 | # builtins if they exist, and our own prefilter routine will handle | |
548 | __builtin__.exit += _exit |
|
241 | # these special cases | |
549 | __builtin__.quit += _exit |
|
242 | try: | |
|
243 | del __builtin__.exit, __builtin__.quit | |||
|
244 | except AttributeError: | |||
|
245 | pass | |||
550 |
|
246 | |||
551 | # We need to know whether the instance is meant for embedding, since |
|
247 | # We need to know whether the instance is meant for embedding, since | |
552 | # global/local namespaces need to be handled differently in that case |
|
248 | # global/local namespaces need to be handled differently in that case | |
553 | self.embedded = embedded |
|
249 | self.embedded = embedded | |
554 |
|
250 | |||
555 | # compiler command |
|
251 | # compiler command | |
556 | self.compile = CommandCompiler() |
|
252 | self.compile = codeop.CommandCompiler() | |
557 |
|
253 | |||
558 | # User input buffer |
|
254 | # User input buffer | |
559 | self.buffer = [] |
|
255 | self.buffer = [] | |
@@ -589,10 +285,10 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
589 |
|
285 | |||
590 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
286 | # Well, it's documented that '__builtins__' can be either a dictionary | |
591 | # or a module, and it's been that way for a long time. Whether it's |
|
287 | # or a module, and it's been that way for a long time. Whether it's | |
592 |
# intentional (or sensible), I don't know. In any case, the idea is |
|
288 | # intentional (or sensible), I don't know. In any case, the idea is | |
593 |
# if you need to access the built-in namespace directly, you |
|
289 | # that if you need to access the built-in namespace directly, you | |
594 |
# with "import __builtin__" (note, no 's') which will |
|
290 | # should start with "import __builtin__" (note, no 's') which will | |
595 | # a module. Yeah, it's somewhat confusing:-(. |
|
291 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
596 |
|
292 | |||
597 | if user_ns is None: |
|
293 | if user_ns is None: | |
598 | # Set __name__ to __main__ to better match the behavior of the |
|
294 | # Set __name__ to __main__ to better match the behavior of the | |
@@ -668,7 +364,7 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
668 | # dict of output history |
|
364 | # dict of output history | |
669 | self.output_hist = {} |
|
365 | self.output_hist = {} | |
670 |
|
366 | |||
671 |
# dict of things NOT to alias (keywords, builtins and some |
|
367 | # dict of things NOT to alias (keywords, builtins and some magics) | |
672 | no_alias = {} |
|
368 | no_alias = {} | |
673 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] |
|
369 | no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias'] | |
674 | for key in keyword.kwlist + no_alias_magics: |
|
370 | for key in keyword.kwlist + no_alias_magics: | |
@@ -762,7 +458,7 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
762 | self.tempfiles = [] |
|
458 | self.tempfiles = [] | |
763 |
|
459 | |||
764 | # Keep track of readline usage (later set by init_readline) |
|
460 | # Keep track of readline usage (later set by init_readline) | |
765 |
self.has_readline = |
|
461 | self.has_readline = False | |
766 |
|
462 | |||
767 | # for pushd/popd management |
|
463 | # for pushd/popd management | |
768 | try: |
|
464 | try: | |
@@ -816,6 +512,7 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
816 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
512 | self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
817 | # RegExp to exclude strings with this start from autocalling |
|
513 | # RegExp to exclude strings with this start from autocalling | |
818 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') |
|
514 | self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ') | |
|
515 | ||||
819 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
516 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
820 | # (experimental). For this to work, the line_split regexp would need |
|
517 | # (experimental). For this to work, the line_split regexp would need | |
821 | # to be modified so it wouldn't break things at '['. That line is |
|
518 | # to be modified so it wouldn't break things at '['. That line is | |
@@ -826,7 +523,7 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
826 | self.starting_dir = os.getcwd() |
|
523 | self.starting_dir = os.getcwd() | |
827 |
|
524 | |||
828 | # Attributes for Logger mixin class, make defaults here |
|
525 | # Attributes for Logger mixin class, make defaults here | |
829 |
self._dolog = |
|
526 | self._dolog = False | |
830 | self.LOG = '' |
|
527 | self.LOG = '' | |
831 | self.LOGDEF = '.InteractiveShell.log' |
|
528 | self.LOGDEF = '.InteractiveShell.log' | |
832 | self.LOGMODE = 'over' |
|
529 | self.LOGMODE = 'over' | |
@@ -859,7 +556,7 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
859 | ins_colors = OInspect.InspectColors |
|
556 | ins_colors = OInspect.InspectColors | |
860 | code_colors = PyColorize.ANSICodeColors |
|
557 | code_colors = PyColorize.ANSICodeColors | |
861 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') |
|
558 | self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor') | |
862 |
self.autoindent = |
|
559 | self.autoindent = False | |
863 |
|
560 | |||
864 | # Make some aliases automatically |
|
561 | # Make some aliases automatically | |
865 | # Prepare list of shell aliases to auto-define |
|
562 | # Prepare list of shell aliases to auto-define | |
@@ -1015,8 +712,8 b' class InteractiveShell(code.InteractiveConsole, Logger, Magic):' | |||||
1015 | if rc.readline: |
|
712 | if rc.readline: | |
1016 | self.init_readline() |
|
713 | self.init_readline() | |
1017 |
|
714 | |||
1018 |
# Set user colors (don't do it in the constructor above so that it |
|
715 | # Set user colors (don't do it in the constructor above so that it | |
1019 | # crash if colors option is invalid) |
|
716 | # doesn't crash if colors option is invalid) | |
1020 | self.magic_colors(rc.colors) |
|
717 | self.magic_colors(rc.colors) | |
1021 |
|
718 | |||
1022 | # Load user aliases |
|
719 | # Load user aliases | |
@@ -1257,28 +954,23 b' want to merge them back into the new files.""" % locals()' | |||||
1257 | """Command history completion/saving/reloading.""" |
|
954 | """Command history completion/saving/reloading.""" | |
1258 | try: |
|
955 | try: | |
1259 | import readline |
|
956 | import readline | |
1260 | self.Completer = MagicCompleter(self, |
|
957 | except ImportError: | |
1261 | self.user_ns, |
|
|||
1262 | self.user_global_ns, |
|
|||
1263 | self.rc.readline_omit__names, |
|
|||
1264 | self.alias_table) |
|
|||
1265 | except ImportError,NameError: |
|
|||
1266 | # If FlexCompleter failed to import, MagicCompleter won't be |
|
|||
1267 | # defined. This can happen because of a problem with readline |
|
|||
1268 | self.has_readline = 0 |
|
958 | self.has_readline = 0 | |
|
959 | self.readline = None | |||
1269 | # no point in bugging windows users with this every time: |
|
960 | # no point in bugging windows users with this every time: | |
1270 | if os.name == 'posix': |
|
961 | if os.name == 'posix': | |
1271 | warn('Readline services not available on this platform.') |
|
962 | warn('Readline services not available on this platform.') | |
1272 | else: |
|
963 | else: | |
1273 | import atexit |
|
964 | import atexit | |
|
965 | from IPython.completer import IPCompleter | |||
|
966 | self.Completer = IPCompleter(self, | |||
|
967 | self.user_ns, | |||
|
968 | self.user_global_ns, | |||
|
969 | self.rc.readline_omit__names, | |||
|
970 | self.alias_table) | |||
1274 |
|
971 | |||
1275 | # Platform-specific configuration |
|
972 | # Platform-specific configuration | |
1276 | if os.name == 'nt': |
|
973 | if os.name == 'nt': | |
1277 | # readline under Windows modifies the default exit behavior |
|
|||
1278 | # from being Ctrl-Z/Return to the Unix Ctrl-D one. |
|
|||
1279 | __builtin__.exit = __builtin__.quit = \ |
|
|||
1280 | ('Use Ctrl-D (i.e. EOF) to exit. ' |
|
|||
1281 | 'Use %Exit or %Quit to exit without confirmation.') |
|
|||
1282 | self.readline_startup_hook = readline.set_pre_input_hook |
|
974 | self.readline_startup_hook = readline.set_pre_input_hook | |
1283 | else: |
|
975 | else: | |
1284 | self.readline_startup_hook = readline.set_startup_hook |
|
976 | self.readline_startup_hook = readline.set_startup_hook | |
@@ -1386,7 +1078,7 b' want to merge them back into the new files.""" % locals()' | |||||
1386 | """puts line into cache""" |
|
1078 | """puts line into cache""" | |
1387 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( |
|
1079 | self.inputcache.insert(0, line) # This copies the cache every time ... :-( | |
1388 | if len(self.inputcache) >= self.CACHELENGTH: |
|
1080 | if len(self.inputcache) >= self.CACHELENGTH: | |
1389 |
self.inputcache.pop() # This |
|
1081 | self.inputcache.pop() # This doesn't :-) | |
1390 |
|
1082 | |||
1391 | def mainloop(self,banner=None): |
|
1083 | def mainloop(self,banner=None): | |
1392 | """Creates the local namespace and starts the mainloop. |
|
1084 | """Creates the local namespace and starts the mainloop. | |
@@ -1504,11 +1196,9 b' want to merge them back into the new files.""" % locals()' | |||||
1504 | if self.autoindent: |
|
1196 | if self.autoindent: | |
1505 | self.readline_startup_hook(None) |
|
1197 | self.readline_startup_hook(None) | |
1506 | self.write("\n") |
|
1198 | self.write("\n") | |
1507 |
|
|
1199 | self.exit() | |
1508 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
1200 | except IPythonExit: | |
1509 |
|
|
1201 | self.exit() | |
1510 | else: |
|
|||
1511 | break |
|
|||
1512 | else: |
|
1202 | else: | |
1513 | more = self.push(line) |
|
1203 | more = self.push(line) | |
1514 | # Auto-indent management |
|
1204 | # Auto-indent management | |
@@ -1720,7 +1410,8 b' want to merge them back into the new files.""" % locals()' | |||||
1720 | except SystemExit: |
|
1410 | except SystemExit: | |
1721 | self.resetbuffer() |
|
1411 | self.resetbuffer() | |
1722 | self.showtraceback() |
|
1412 | self.showtraceback() | |
1723 | warn( __builtin__.exit,level=1) |
|
1413 | warn("Type exit or quit to exit IPython " | |
|
1414 | "(%Exit or %Quit do so unconditionally).",level=1) | |||
1724 | except self.custom_exceptions: |
|
1415 | except self.custom_exceptions: | |
1725 | etype,value,tb = sys.exc_info() |
|
1416 | etype,value,tb = sys.exc_info() | |
1726 | self.CustomTB(etype,value,tb) |
|
1417 | self.CustomTB(etype,value,tb) | |
@@ -1728,12 +1419,37 b' want to merge them back into the new files.""" % locals()' | |||||
1728 | self.showtraceback() |
|
1419 | self.showtraceback() | |
1729 | else: |
|
1420 | else: | |
1730 | outflag = 0 |
|
1421 | outflag = 0 | |
1731 |
if |
|
1422 | if softspace(sys.stdout, 0): | |
1732 |
|
1423 | |||
1733 | # Flush out code object which has been run (and source) |
|
1424 | # Flush out code object which has been run (and source) | |
1734 | self.code_to_run = None |
|
1425 | self.code_to_run = None | |
1735 | return outflag |
|
1426 | return outflag | |
1736 |
|
1427 | |||
|
1428 | def push(self, line): | |||
|
1429 | """Push a line to the interpreter. | |||
|
1430 | ||||
|
1431 | The line should not have a trailing newline; it may have | |||
|
1432 | internal newlines. The line is appended to a buffer and the | |||
|
1433 | interpreter's runsource() method is called with the | |||
|
1434 | concatenated contents of the buffer as source. If this | |||
|
1435 | indicates that the command was executed or invalid, the buffer | |||
|
1436 | is reset; otherwise, the command is incomplete, and the buffer | |||
|
1437 | is left as it was after the line was appended. The return | |||
|
1438 | value is 1 if more input is required, 0 if the line was dealt | |||
|
1439 | with in some way (this is the same as runsource()). | |||
|
1440 | ||||
|
1441 | """ | |||
|
1442 | self.buffer.append(line) | |||
|
1443 | source = "\n".join(self.buffer) | |||
|
1444 | more = self.runsource(source, self.filename) | |||
|
1445 | if not more: | |||
|
1446 | self.resetbuffer() | |||
|
1447 | return more | |||
|
1448 | ||||
|
1449 | def resetbuffer(self): | |||
|
1450 | """Reset the input buffer.""" | |||
|
1451 | self.buffer[:] = [] | |||
|
1452 | ||||
1737 | def raw_input(self,prompt='',continue_prompt=False): |
|
1453 | def raw_input(self,prompt='',continue_prompt=False): | |
1738 | """Write a prompt and read a line. |
|
1454 | """Write a prompt and read a line. | |
1739 |
|
1455 | |||
@@ -1871,6 +1587,8 b' want to merge them back into the new files.""" % locals()' | |||||
1871 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic |
|
1587 | oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic | |
1872 |
|
1588 | |||
1873 | if not oinfo['found']: |
|
1589 | if not oinfo['found']: | |
|
1590 | if iFun in ('quit','exit'): | |||
|
1591 | raise IPythonExit | |||
1874 | return self.handle_normal(line,continue_prompt) |
|
1592 | return self.handle_normal(line,continue_prompt) | |
1875 | else: |
|
1593 | else: | |
1876 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg |
|
1594 | #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg | |
@@ -2008,7 +1726,7 b' want to merge them back into the new files.""" % locals()' | |||||
2008 | # We need to make sure that we don't process lines which would be |
|
1726 | # We need to make sure that we don't process lines which would be | |
2009 | # otherwise valid python, such as "x=1 # what?" |
|
1727 | # otherwise valid python, such as "x=1 # what?" | |
2010 | try: |
|
1728 | try: | |
2011 | code.compile_command(line) |
|
1729 | codeop.compile_command(line) | |
2012 | except SyntaxError: |
|
1730 | except SyntaxError: | |
2013 | # We should only handle as help stuff which is NOT valid syntax |
|
1731 | # We should only handle as help stuff which is NOT valid syntax | |
2014 | if line[0]==self.ESC_HELP: |
|
1732 | if line[0]==self.ESC_HELP: | |
@@ -2048,6 +1766,18 b' want to merge them back into the new files.""" % locals()' | |||||
2048 | """Write a string to the default error output""" |
|
1766 | """Write a string to the default error output""" | |
2049 | Term.cerr.write(data) |
|
1767 | Term.cerr.write(data) | |
2050 |
|
1768 | |||
|
1769 | def exit(self): | |||
|
1770 | """Handle interactive exit. | |||
|
1771 | ||||
|
1772 | This method sets the exit_now attribute.""" | |||
|
1773 | ||||
|
1774 | if self.rc.confirm_exit: | |||
|
1775 | if ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |||
|
1776 | self.exit_now = True | |||
|
1777 | else: | |||
|
1778 | self.exit_now = True | |||
|
1779 | return self.exit_now | |||
|
1780 | ||||
2051 | def safe_execfile(self,fname,*where,**kw): |
|
1781 | def safe_execfile(self,fname,*where,**kw): | |
2052 | fname = os.path.expanduser(fname) |
|
1782 | fname = os.path.expanduser(fname) | |
2053 |
|
1783 | |||
@@ -2134,9 +1864,9 b' want to merge them back into the new files.""" % locals()' | |||||
2134 | sys.stdout = stdout_save |
|
1864 | sys.stdout = stdout_save | |
2135 | print 'Finished replaying log file <%s>' % fname |
|
1865 | print 'Finished replaying log file <%s>' % fname | |
2136 | if badblocks: |
|
1866 | if badblocks: | |
2137 | print >> sys.stderr, \ |
|
1867 | print >> sys.stderr, ('\nThe following lines/blocks in file ' | |
2138 | '\nThe following lines/blocks in file <%s> reported errors:' \ |
|
1868 | '<%s> reported errors:' % fname) | |
2139 |
|
|
1869 | ||
2140 | for badline in badblocks: |
|
1870 | for badline in badblocks: | |
2141 | print >> sys.stderr, badline |
|
1871 | print >> sys.stderr, badline | |
2142 | else: # regular file execution |
|
1872 | else: # regular file execution |
@@ -1,5 +1,9 b'' | |||||
1 | 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu> |
|
1 | 2005-12-27 Fernando Perez <Fernando.Perez@colorado.edu> | |
2 |
|
2 | |||
|
3 | * IPython/completer.py (MagicCompleter.__init__): new 'completer' | |||
|
4 | module to better organize all readline-related functionality. | |||
|
5 | I've deleted FlexCompleter and put all completion clases here. | |||
|
6 | ||||
3 | * IPython/iplib.py (raw_input): improve indentation management. |
|
7 | * IPython/iplib.py (raw_input): improve indentation management. | |
4 | It is now possible to paste indented code with autoindent on, and |
|
8 | It is now possible to paste indented code with autoindent on, and | |
5 | the code is interpreted correctly (though it still looks bad on |
|
9 | the code is interpreted correctly (though it still looks bad on | |
@@ -9,6 +13,17 b'' | |||||
9 | on the entire global namespace. This makes it easier to use the |
|
13 | on the entire global namespace. This makes it easier to use the | |
10 | TAB key for indentation. After a request by Hans Meine |
|
14 | TAB key for indentation. After a request by Hans Meine | |
11 | <hans_meine-AT-gmx.net> |
|
15 | <hans_meine-AT-gmx.net> | |
|
16 | (_prefilter): add support so that typing plain 'exit' or 'quit' | |||
|
17 | does a sensible thing. Originally I tried to deviate as little as | |||
|
18 | possible from the default python behavior, but even that one may | |||
|
19 | change in this direction (thread on python-dev to that effect). | |||
|
20 | Regardless, ipython should do the right thing even if CPython's | |||
|
21 | '>>>' prompt doesn't. | |||
|
22 | (InteractiveShell): removed subclassing code.InteractiveConsole | |||
|
23 | class. By now we'd overridden just about all of its methods: I've | |||
|
24 | copied the remaining two over, and now ipython is a standalone | |||
|
25 | class. This will provide a clearer picture for the chainsaw | |||
|
26 | branch refactoring. | |||
12 |
|
27 | |||
13 | 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu> |
|
28 | 2005-12-26 Fernando Perez <Fernando.Perez@colorado.edu> | |
14 |
|
29 |
1 | NO CONTENT: file was removed |
|
NO CONTENT: file was removed |
General Comments 0
You need to be logged in to leave comments.
Login now