Show More
@@ -1,568 +1,570 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 | --------------------------------------------------------------------------- |
|
9 | --------------------------------------------------------------------------- | |
10 | Original rlcompleter documentation: |
|
10 | Original rlcompleter documentation: | |
11 |
|
11 | |||
12 | This requires the latest extension to the readline module (the |
|
12 | This requires the latest extension to the readline module (the | |
13 | completes keywords, built-ins and globals in __main__; when completing |
|
13 | completes keywords, built-ins and globals in __main__; when completing | |
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
15 | completes its attributes. |
|
15 | completes its attributes. | |
16 |
|
16 | |||
17 | It's very cool to do "import string" type "string.", hit the |
|
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 |
|
18 | completion key (twice), and see the list of names defined by the | |
19 | string module! |
|
19 | string module! | |
20 |
|
20 | |||
21 | Tip: to use the tab key as the completion key, call |
|
21 | Tip: to use the tab key as the completion key, call | |
22 |
|
22 | |||
23 | readline.parse_and_bind("tab: complete") |
|
23 | readline.parse_and_bind("tab: complete") | |
24 |
|
24 | |||
25 | Notes: |
|
25 | Notes: | |
26 |
|
26 | |||
27 | - Exceptions raised by the completer function are *ignored* (and |
|
27 | - Exceptions raised by the completer function are *ignored* (and | |
28 | generally cause the completion to fail). This is a feature -- since |
|
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 |
|
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, |
|
30 | traceback wouldn't work well without some complicated hoopla to save, | |
31 | reset and restore the tty state. |
|
31 | reset and restore the tty state. | |
32 |
|
32 | |||
33 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
33 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
34 | application defined code to be executed if an object with a |
|
34 | application defined code to be executed if an object with a | |
35 | __getattr__ hook is found. Since it is the responsibility of the |
|
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 |
|
36 | application (or the user) to enable this feature, I consider this an | |
37 | acceptable risk. More complicated expressions (e.g. function calls or |
|
37 | acceptable risk. More complicated expressions (e.g. function calls or | |
38 | indexing operations) are *not* evaluated. |
|
38 | indexing operations) are *not* evaluated. | |
39 |
|
39 | |||
40 | - GNU readline is also used by the built-in functions input() and |
|
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 |
|
41 | raw_input(), and thus these also benefit/suffer from the completer | |
42 | features. Clearly an interactive application can benefit by |
|
42 | features. Clearly an interactive application can benefit by | |
43 | specifying its own completer function and using raw_input() for all |
|
43 | specifying its own completer function and using raw_input() for all | |
44 | its input. |
|
44 | its input. | |
45 |
|
45 | |||
46 | - When the original stdin is not a tty device, GNU readline is never |
|
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. |
|
47 | used, and this module (and the readline module) are silently inactive. | |
48 |
|
48 | |||
49 | """ |
|
49 | """ | |
50 |
|
50 | |||
51 | #***************************************************************************** |
|
51 | #***************************************************************************** | |
52 | # |
|
52 | # | |
53 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
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 |
|
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 |
|
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). |
|
56 | # Software Foundation (in addition to my own, for all new code). | |
57 | # |
|
57 | # | |
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
59 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
59 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
60 | # |
|
60 | # | |
61 | # Distributed under the terms of the BSD License. The full license is in |
|
61 | # Distributed under the terms of the BSD License. The full license is in | |
62 | # the file COPYING, distributed as part of this software. |
|
62 | # the file COPYING, distributed as part of this software. | |
63 | # |
|
63 | # | |
64 | #***************************************************************************** |
|
64 | #***************************************************************************** | |
65 |
|
65 | |||
66 | import __builtin__ |
|
66 | import __builtin__ | |
67 | import __main__ |
|
67 | import __main__ | |
68 | import glob |
|
68 | import glob | |
69 | import keyword |
|
69 | import keyword | |
70 | import os |
|
70 | import os | |
71 | import re |
|
71 | import re | |
72 | import sys |
|
72 | import sys | |
73 | import IPython.rlineimpl as readline |
|
73 | import IPython.rlineimpl as readline | |
74 |
|
74 | |||
75 | import types |
|
75 | import types | |
76 |
|
76 | |||
77 | # Python 2.4 offers sets as a builtin |
|
77 | # Python 2.4 offers sets as a builtin | |
78 | try: |
|
78 | try: | |
79 | set([1,2]) |
|
79 | set([1,2]) | |
80 | except NameError: |
|
80 | except NameError: | |
81 | from sets import Set as set |
|
81 | from sets import Set as set | |
82 |
|
82 | |||
83 |
|
83 | |||
84 | from IPython.genutils import shlex_split,debugx |
|
84 | from IPython.genutils import shlex_split,debugx | |
85 |
|
85 | |||
86 | __all__ = ['Completer','IPCompleter'] |
|
86 | __all__ = ['Completer','IPCompleter'] | |
87 |
|
87 | |||
88 | def get_class_members(cls): |
|
88 | def get_class_members(cls): | |
89 | ret = dir(cls) |
|
89 | ret = dir(cls) | |
90 | if hasattr(cls,'__bases__'): |
|
90 | if hasattr(cls,'__bases__'): | |
91 | for base in cls.__bases__: |
|
91 | for base in cls.__bases__: | |
92 | ret.extend(get_class_members(base)) |
|
92 | ret.extend(get_class_members(base)) | |
93 | return ret |
|
93 | return ret | |
94 |
|
94 | |||
95 | class Completer: |
|
95 | class Completer: | |
96 | def __init__(self,namespace=None,global_namespace=None): |
|
96 | def __init__(self,namespace=None,global_namespace=None): | |
97 | """Create a new completer for the command line. |
|
97 | """Create a new completer for the command line. | |
98 |
|
98 | |||
99 | Completer([namespace,global_namespace]) -> completer instance. |
|
99 | Completer([namespace,global_namespace]) -> completer instance. | |
100 |
|
100 | |||
101 | If unspecified, the default namespace where completions are performed |
|
101 | If unspecified, the default namespace where completions are performed | |
102 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
102 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
103 | given as dictionaries. |
|
103 | given as dictionaries. | |
104 |
|
104 | |||
105 | An optional second namespace can be given. This allows the completer |
|
105 | An optional second namespace can be given. This allows the completer | |
106 | to handle cases where both the local and global scopes need to be |
|
106 | to handle cases where both the local and global scopes need to be | |
107 | distinguished. |
|
107 | distinguished. | |
108 |
|
108 | |||
109 | Completer instances should be used as the completion mechanism of |
|
109 | Completer instances should be used as the completion mechanism of | |
110 | readline via the set_completer() call: |
|
110 | readline via the set_completer() call: | |
111 |
|
111 | |||
112 | readline.set_completer(Completer(my_namespace).complete) |
|
112 | readline.set_completer(Completer(my_namespace).complete) | |
113 | """ |
|
113 | """ | |
114 |
|
114 | |||
115 | # some minimal strict typechecks. For some core data structures, I |
|
115 | # some minimal strict typechecks. For some core data structures, I | |
116 | # want actual basic python types, not just anything that looks like |
|
116 | # want actual basic python types, not just anything that looks like | |
117 | # one. This is especially true for namespaces. |
|
117 | # one. This is especially true for namespaces. | |
118 | for ns in (namespace,global_namespace): |
|
118 | for ns in (namespace,global_namespace): | |
119 | if ns is not None and type(ns) != types.DictType: |
|
119 | if ns is not None and type(ns) != types.DictType: | |
120 | raise TypeError,'namespace must be a dictionary' |
|
120 | raise TypeError,'namespace must be a dictionary' | |
121 |
|
121 | |||
122 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
122 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
123 | # specific namespace or to use __main__.__dict__. This will allow us |
|
123 | # specific namespace or to use __main__.__dict__. This will allow us | |
124 | # to bind to __main__.__dict__ at completion time, not now. |
|
124 | # to bind to __main__.__dict__ at completion time, not now. | |
125 | if namespace is None: |
|
125 | if namespace is None: | |
126 | self.use_main_ns = 1 |
|
126 | self.use_main_ns = 1 | |
127 | else: |
|
127 | else: | |
128 | self.use_main_ns = 0 |
|
128 | self.use_main_ns = 0 | |
129 | self.namespace = namespace |
|
129 | self.namespace = namespace | |
130 |
|
130 | |||
131 | # The global namespace, if given, can be bound directly |
|
131 | # The global namespace, if given, can be bound directly | |
132 | if global_namespace is None: |
|
132 | if global_namespace is None: | |
133 | self.global_namespace = {} |
|
133 | self.global_namespace = {} | |
134 | else: |
|
134 | else: | |
135 | self.global_namespace = global_namespace |
|
135 | self.global_namespace = global_namespace | |
136 |
|
136 | |||
137 | def complete(self, text, state): |
|
137 | def complete(self, text, state): | |
138 | """Return the next possible completion for 'text'. |
|
138 | """Return the next possible completion for 'text'. | |
139 |
|
139 | |||
140 | This is called successively with state == 0, 1, 2, ... until it |
|
140 | This is called successively with state == 0, 1, 2, ... until it | |
141 | returns None. The completion should begin with 'text'. |
|
141 | returns None. The completion should begin with 'text'. | |
142 |
|
142 | |||
143 | """ |
|
143 | """ | |
144 | if self.use_main_ns: |
|
144 | if self.use_main_ns: | |
145 | self.namespace = __main__.__dict__ |
|
145 | self.namespace = __main__.__dict__ | |
146 |
|
146 | |||
147 | if state == 0: |
|
147 | if state == 0: | |
148 | if "." in text: |
|
148 | if "." in text: | |
149 | self.matches = self.attr_matches(text) |
|
149 | self.matches = self.attr_matches(text) | |
150 | else: |
|
150 | else: | |
151 | self.matches = self.global_matches(text) |
|
151 | self.matches = self.global_matches(text) | |
152 | try: |
|
152 | try: | |
153 | return self.matches[state] |
|
153 | return self.matches[state] | |
154 | except IndexError: |
|
154 | except IndexError: | |
155 | return None |
|
155 | return None | |
156 |
|
156 | |||
157 | def global_matches(self, text): |
|
157 | def global_matches(self, text): | |
158 | """Compute matches when text is a simple name. |
|
158 | """Compute matches when text is a simple name. | |
159 |
|
159 | |||
160 | Return a list of all keywords, built-in functions and names currently |
|
160 | Return a list of all keywords, built-in functions and names currently | |
161 | defined in self.namespace or self.global_namespace that match. |
|
161 | defined in self.namespace or self.global_namespace that match. | |
162 |
|
162 | |||
163 | """ |
|
163 | """ | |
164 | matches = [] |
|
164 | matches = [] | |
165 | match_append = matches.append |
|
165 | match_append = matches.append | |
166 | n = len(text) |
|
166 | n = len(text) | |
167 | for lst in [keyword.kwlist, |
|
167 | for lst in [keyword.kwlist, | |
168 | __builtin__.__dict__.keys(), |
|
168 | __builtin__.__dict__.keys(), | |
169 | self.namespace.keys(), |
|
169 | self.namespace.keys(), | |
170 | self.global_namespace.keys()]: |
|
170 | self.global_namespace.keys()]: | |
171 | for word in lst: |
|
171 | for word in lst: | |
172 | if word[:n] == text and word != "__builtins__": |
|
172 | if word[:n] == text and word != "__builtins__": | |
173 | match_append(word) |
|
173 | match_append(word) | |
174 | return matches |
|
174 | return matches | |
175 |
|
175 | |||
176 | def attr_matches(self, text): |
|
176 | def attr_matches(self, text): | |
177 | """Compute matches when text contains a dot. |
|
177 | """Compute matches when text contains a dot. | |
178 |
|
178 | |||
179 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
179 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
180 | evaluatable in self.namespace or self.global_namespace, it will be |
|
180 | evaluatable in self.namespace or self.global_namespace, it will be | |
181 | evaluated and its attributes (as revealed by dir()) are used as |
|
181 | evaluated and its attributes (as revealed by dir()) are used as | |
182 | possible completions. (For class instances, class members are are |
|
182 | possible completions. (For class instances, class members are are | |
183 | also considered.) |
|
183 | also considered.) | |
184 |
|
184 | |||
185 | WARNING: this can still invoke arbitrary C code, if an object |
|
185 | WARNING: this can still invoke arbitrary C code, if an object | |
186 | with a __getattr__ hook is evaluated. |
|
186 | with a __getattr__ hook is evaluated. | |
187 |
|
187 | |||
188 | """ |
|
188 | """ | |
189 | import re |
|
189 | import re | |
190 |
|
190 | |||
191 | # Another option, seems to work great. Catches things like ''.<tab> |
|
191 | # Another option, seems to work great. Catches things like ''.<tab> | |
192 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
192 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
193 |
|
193 | |||
194 | if not m: |
|
194 | if not m: | |
195 | return [] |
|
195 | return [] | |
196 |
|
196 | |||
197 | expr, attr = m.group(1, 3) |
|
197 | expr, attr = m.group(1, 3) | |
198 | try: |
|
198 | try: | |
199 | object = eval(expr, self.namespace) |
|
199 | object = eval(expr, self.namespace) | |
200 | except: |
|
200 | except: | |
201 | object = eval(expr, self.global_namespace) |
|
201 | object = eval(expr, self.global_namespace) | |
202 |
|
202 | |||
203 | # Start building the attribute list via dir(), and then complete it |
|
203 | # Start building the attribute list via dir(), and then complete it | |
204 | # with a few extra special-purpose calls. |
|
204 | # with a few extra special-purpose calls. | |
205 | words = dir(object) |
|
205 | words = dir(object) | |
206 |
|
206 | |||
207 | if hasattr(object,'__class__'): |
|
207 | if hasattr(object,'__class__'): | |
208 | words.append('__class__') |
|
208 | words.append('__class__') | |
209 | words.extend(get_class_members(object.__class__)) |
|
209 | words.extend(get_class_members(object.__class__)) | |
210 |
|
210 | |||
211 | # this is the 'dir' function for objects with Enthought's traits |
|
211 | # this is the 'dir' function for objects with Enthought's traits | |
212 | if hasattr(object, 'trait_names'): |
|
212 | if hasattr(object, 'trait_names'): | |
213 | try: |
|
213 | try: | |
214 | words.extend(object.trait_names()) |
|
214 | words.extend(object.trait_names()) | |
215 | # eliminate possible duplicates, as some traits may also |
|
215 | # eliminate possible duplicates, as some traits may also | |
216 | # appear as normal attributes in the dir() call. |
|
216 | # appear as normal attributes in the dir() call. | |
217 | words = set(words) |
|
217 | words = set(words) | |
218 | except TypeError: |
|
218 | except TypeError: | |
219 | # This will happen if `object` is a class and not an instance. |
|
219 | # This will happen if `object` is a class and not an instance. | |
220 | pass |
|
220 | pass | |
221 |
|
221 | |||
222 | # filter out non-string attributes which may be stuffed by dir() calls |
|
222 | # filter out non-string attributes which may be stuffed by dir() calls | |
223 | # and poor coding in third-party modules |
|
223 | # and poor coding in third-party modules | |
224 | words = [w for w in words |
|
224 | words = [w for w in words | |
225 | if isinstance(w, basestring) and w != "__builtins__"] |
|
225 | if isinstance(w, basestring) and w != "__builtins__"] | |
226 | # Build match list to return |
|
226 | # Build match list to return | |
227 | n = len(attr) |
|
227 | n = len(attr) | |
228 | return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
228 | return ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
229 |
|
229 | |||
230 | class IPCompleter(Completer): |
|
230 | class IPCompleter(Completer): | |
231 | """Extension of the completer class with IPython-specific features""" |
|
231 | """Extension of the completer class with IPython-specific features""" | |
232 |
|
232 | |||
233 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
233 | def __init__(self,shell,namespace=None,global_namespace=None, | |
234 | omit__names=0,alias_table=None): |
|
234 | omit__names=0,alias_table=None): | |
235 | """IPCompleter() -> completer |
|
235 | """IPCompleter() -> completer | |
236 |
|
236 | |||
237 | Return a completer object suitable for use by the readline library |
|
237 | Return a completer object suitable for use by the readline library | |
238 | via readline.set_completer(). |
|
238 | via readline.set_completer(). | |
239 |
|
239 | |||
240 | Inputs: |
|
240 | Inputs: | |
241 |
|
241 | |||
242 | - shell: a pointer to the ipython shell itself. This is needed |
|
242 | - shell: a pointer to the ipython shell itself. This is needed | |
243 | because this completer knows about magic functions, and those can |
|
243 | because this completer knows about magic functions, and those can | |
244 | only be accessed via the ipython instance. |
|
244 | only be accessed via the ipython instance. | |
245 |
|
245 | |||
246 | - namespace: an optional dict where completions are performed. |
|
246 | - namespace: an optional dict where completions are performed. | |
247 |
|
247 | |||
248 | - global_namespace: secondary optional dict for completions, to |
|
248 | - global_namespace: secondary optional dict for completions, to | |
249 | handle cases (such as IPython embedded inside functions) where |
|
249 | handle cases (such as IPython embedded inside functions) where | |
250 | both Python scopes are visible. |
|
250 | both Python scopes are visible. | |
251 |
|
251 | |||
252 | - The optional omit__names parameter sets the completer to omit the |
|
252 | - The optional omit__names parameter sets the completer to omit the | |
253 | 'magic' names (__magicname__) for python objects unless the text |
|
253 | 'magic' names (__magicname__) for python objects unless the text | |
254 | to be completed explicitly starts with one or more underscores. |
|
254 | to be completed explicitly starts with one or more underscores. | |
255 |
|
255 | |||
256 | - If alias_table is supplied, it should be a dictionary of aliases |
|
256 | - If alias_table is supplied, it should be a dictionary of aliases | |
257 | to complete. """ |
|
257 | to complete. """ | |
258 |
|
258 | |||
259 | Completer.__init__(self,namespace,global_namespace) |
|
259 | Completer.__init__(self,namespace,global_namespace) | |
260 | self.magic_prefix = shell.name+'.magic_' |
|
260 | self.magic_prefix = shell.name+'.magic_' | |
261 | self.magic_escape = shell.ESC_MAGIC |
|
261 | self.magic_escape = shell.ESC_MAGIC | |
262 | self.readline = readline |
|
262 | self.readline = readline | |
263 | delims = self.readline.get_completer_delims() |
|
263 | delims = self.readline.get_completer_delims() | |
264 | delims = delims.replace(self.magic_escape,'') |
|
264 | delims = delims.replace(self.magic_escape,'') | |
265 | self.readline.set_completer_delims(delims) |
|
265 | self.readline.set_completer_delims(delims) | |
266 | self.get_line_buffer = self.readline.get_line_buffer |
|
266 | self.get_line_buffer = self.readline.get_line_buffer | |
267 | self.omit__names = omit__names |
|
267 | self.omit__names = omit__names | |
268 | self.merge_completions = shell.rc.readline_merge_completions |
|
268 | self.merge_completions = shell.rc.readline_merge_completions | |
269 |
|
269 | |||
270 | if alias_table is None: |
|
270 | if alias_table is None: | |
271 | alias_table = {} |
|
271 | alias_table = {} | |
272 | self.alias_table = alias_table |
|
272 | self.alias_table = alias_table | |
273 | # Regexp to split filenames with spaces in them |
|
273 | # Regexp to split filenames with spaces in them | |
274 | self.space_name_re = re.compile(r'([^\\] )') |
|
274 | self.space_name_re = re.compile(r'([^\\] )') | |
275 | # Hold a local ref. to glob.glob for speed |
|
275 | # Hold a local ref. to glob.glob for speed | |
276 | self.glob = glob.glob |
|
276 | self.glob = glob.glob | |
277 |
|
277 | |||
278 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
278 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
279 | # buffers, to avoid completion problems. |
|
279 | # buffers, to avoid completion problems. | |
280 | term = os.environ.get('TERM','xterm') |
|
280 | term = os.environ.get('TERM','xterm') | |
281 | self.dumb_terminal = term in ['dumb','emacs'] |
|
281 | self.dumb_terminal = term in ['dumb','emacs'] | |
282 |
|
282 | |||
283 | # Special handling of backslashes needed in win32 platforms |
|
283 | # Special handling of backslashes needed in win32 platforms | |
284 | if sys.platform == "win32": |
|
284 | if sys.platform == "win32": | |
285 | self.clean_glob = self._clean_glob_win32 |
|
285 | self.clean_glob = self._clean_glob_win32 | |
286 | else: |
|
286 | else: | |
287 | self.clean_glob = self._clean_glob |
|
287 | self.clean_glob = self._clean_glob | |
288 | self.matchers = [self.python_matches, |
|
288 | self.matchers = [self.python_matches, | |
289 | self.file_matches, |
|
289 | self.file_matches, | |
290 | self.alias_matches, |
|
290 | self.alias_matches, | |
291 | self.python_func_kw_matches] |
|
291 | self.python_func_kw_matches] | |
292 |
|
292 | |||
293 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
293 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
294 | def all_completions(self, text): |
|
294 | def all_completions(self, text): | |
295 | """Return all possible completions for the benefit of emacs.""" |
|
295 | """Return all possible completions for the benefit of emacs.""" | |
296 |
|
296 | |||
297 | completions = [] |
|
297 | completions = [] | |
298 | comp_append = completions.append |
|
298 | comp_append = completions.append | |
299 | try: |
|
299 | try: | |
300 | for i in xrange(sys.maxint): |
|
300 | for i in xrange(sys.maxint): | |
301 | res = self.complete(text, i) |
|
301 | res = self.complete(text, i) | |
302 |
|
302 | |||
303 | if not res: break |
|
303 | if not res: break | |
304 |
|
304 | |||
305 | comp_append(res) |
|
305 | comp_append(res) | |
306 | #XXX workaround for ``notDefined.<tab>`` |
|
306 | #XXX workaround for ``notDefined.<tab>`` | |
307 | except NameError: |
|
307 | except NameError: | |
308 | pass |
|
308 | pass | |
309 | return completions |
|
309 | return completions | |
310 | # /end Alex Schmolck code. |
|
310 | # /end Alex Schmolck code. | |
311 |
|
311 | |||
312 | def _clean_glob(self,text): |
|
312 | def _clean_glob(self,text): | |
313 | return self.glob("%s*" % text) |
|
313 | return self.glob("%s*" % text) | |
314 |
|
314 | |||
315 | def _clean_glob_win32(self,text): |
|
315 | def _clean_glob_win32(self,text): | |
316 | return [f.replace("\\","/") |
|
316 | return [f.replace("\\","/") | |
317 | for f in self.glob("%s*" % text)] |
|
317 | for f in self.glob("%s*" % text)] | |
318 |
|
318 | |||
319 | def file_matches(self, text): |
|
319 | def file_matches(self, text): | |
320 | """Match filneames, expanding ~USER type strings. |
|
320 | """Match filneames, expanding ~USER type strings. | |
321 |
|
321 | |||
322 | Most of the seemingly convoluted logic in this completer is an |
|
322 | Most of the seemingly convoluted logic in this completer is an | |
323 | attempt to handle filenames with spaces in them. And yet it's not |
|
323 | attempt to handle filenames with spaces in them. And yet it's not | |
324 | quite perfect, because Python's readline doesn't expose all of the |
|
324 | quite perfect, because Python's readline doesn't expose all of the | |
325 | GNU readline details needed for this to be done correctly. |
|
325 | GNU readline details needed for this to be done correctly. | |
326 |
|
326 | |||
327 | For a filename with a space in it, the printed completions will be |
|
327 | For a filename with a space in it, the printed completions will be | |
328 | only the parts after what's already been typed (instead of the |
|
328 | only the parts after what's already been typed (instead of the | |
329 | full completions, as is normally done). I don't think with the |
|
329 | full completions, as is normally done). I don't think with the | |
330 | current (as of Python 2.3) Python readline it's possible to do |
|
330 | current (as of Python 2.3) Python readline it's possible to do | |
331 | better.""" |
|
331 | better.""" | |
332 |
|
332 | |||
333 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
333 | #print 'Completer->file_matches: <%s>' % text # dbg | |
334 |
|
334 | |||
335 | # chars that require escaping with backslash - i.e. chars |
|
335 | # chars that require escaping with backslash - i.e. chars | |
336 | # that readline treats incorrectly as delimiters, but we |
|
336 | # that readline treats incorrectly as delimiters, but we | |
337 | # don't want to treat as delimiters in filename matching |
|
337 | # don't want to treat as delimiters in filename matching | |
338 | # when escaped with backslash |
|
338 | # when escaped with backslash | |
339 |
|
339 | |||
340 | protectables = ' ()[]{}' |
|
340 | protectables = ' ()[]{}' | |
341 |
|
341 | |||
342 | def protect_filename(s): |
|
342 | def protect_filename(s): | |
343 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
343 | return "".join([(ch in protectables and '\\' + ch or ch) | |
344 | for ch in s]) |
|
344 | for ch in s]) | |
345 |
|
345 | |||
346 | lbuf = self.lbuf |
|
346 | lbuf = self.lbuf | |
347 | open_quotes = 0 # track strings with open quotes |
|
347 | open_quotes = 0 # track strings with open quotes | |
348 | try: |
|
348 | try: | |
349 | lsplit = shlex_split(lbuf)[-1] |
|
349 | lsplit = shlex_split(lbuf)[-1] | |
350 | except ValueError: |
|
350 | except ValueError: | |
351 | # typically an unmatched ", or backslash without escaped char. |
|
351 | # typically an unmatched ", or backslash without escaped char. | |
352 | if lbuf.count('"')==1: |
|
352 | if lbuf.count('"')==1: | |
353 | open_quotes = 1 |
|
353 | open_quotes = 1 | |
354 | lsplit = lbuf.split('"')[-1] |
|
354 | lsplit = lbuf.split('"')[-1] | |
355 | elif lbuf.count("'")==1: |
|
355 | elif lbuf.count("'")==1: | |
356 | open_quotes = 1 |
|
356 | open_quotes = 1 | |
357 | lsplit = lbuf.split("'")[-1] |
|
357 | lsplit = lbuf.split("'")[-1] | |
358 | else: |
|
358 | else: | |
359 | return None |
|
359 | return None | |
360 | except IndexError: |
|
360 | except IndexError: | |
361 | # tab pressed on empty line |
|
361 | # tab pressed on empty line | |
362 | lsplit = "" |
|
362 | lsplit = "" | |
363 |
|
363 | |||
364 | if lsplit != protect_filename(lsplit): |
|
364 | if lsplit != protect_filename(lsplit): | |
365 | # if protectables are found, do matching on the whole escaped |
|
365 | # if protectables are found, do matching on the whole escaped | |
366 | # name |
|
366 | # name | |
367 | has_protectables = 1 |
|
367 | has_protectables = 1 | |
368 | text0,text = text,lsplit |
|
368 | text0,text = text,lsplit | |
369 | else: |
|
369 | else: | |
370 | has_protectables = 0 |
|
370 | has_protectables = 0 | |
371 | text = os.path.expanduser(text) |
|
371 | text = os.path.expanduser(text) | |
372 |
|
372 | |||
373 | if text == "": |
|
373 | if text == "": | |
374 | return [protect_filename(f) for f in self.glob("*")] |
|
374 | return [protect_filename(f) for f in self.glob("*")] | |
375 |
|
375 | |||
376 | m0 = self.clean_glob(text.replace('\\','')) |
|
376 | m0 = self.clean_glob(text.replace('\\','')) | |
377 | if has_protectables: |
|
377 | if has_protectables: | |
378 | # If we had protectables, we need to revert our changes to the |
|
378 | # If we had protectables, we need to revert our changes to the | |
379 | # beginning of filename so that we don't double-write the part |
|
379 | # beginning of filename so that we don't double-write the part | |
380 | # of the filename we have so far |
|
380 | # of the filename we have so far | |
381 | len_lsplit = len(lsplit) |
|
381 | len_lsplit = len(lsplit) | |
382 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] |
|
382 | matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0] | |
383 | else: |
|
383 | else: | |
384 | if open_quotes: |
|
384 | if open_quotes: | |
385 | # if we have a string with an open quote, we don't need to |
|
385 | # if we have a string with an open quote, we don't need to | |
386 | # protect the names at all (and we _shouldn't_, as it |
|
386 | # protect the names at all (and we _shouldn't_, as it | |
387 | # would cause bugs when the filesystem call is made). |
|
387 | # would cause bugs when the filesystem call is made). | |
388 | matches = m0 |
|
388 | matches = m0 | |
389 | else: |
|
389 | else: | |
390 | matches = [protect_filename(f) for f in m0] |
|
390 | matches = [protect_filename(f) for f in m0] | |
391 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
391 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
392 | # Takes care of links to directories also. Use '/' |
|
392 | # Takes care of links to directories also. Use '/' | |
393 | # explicitly, even under Windows, so that name completions |
|
393 | # explicitly, even under Windows, so that name completions | |
394 | # don't end up escaped. |
|
394 | # don't end up escaped. | |
395 | matches[0] += '/' |
|
395 | matches[0] += '/' | |
396 | return matches |
|
396 | return matches | |
397 |
|
397 | |||
398 | def alias_matches(self, text): |
|
398 | def alias_matches(self, text): | |
399 | """Match internal system aliases""" |
|
399 | """Match internal system aliases""" | |
400 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
400 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg | |
401 |
|
401 | |||
402 | # if we are not in the first 'item', alias matching |
|
402 | # if we are not in the first 'item', alias matching | |
403 | # doesn't make sense |
|
403 | # doesn't make sense | |
404 | if ' ' in self.lbuf: |
|
404 | if ' ' in self.lbuf: | |
405 | return [] |
|
405 | return [] | |
406 | text = os.path.expanduser(text) |
|
406 | text = os.path.expanduser(text) | |
407 | aliases = self.alias_table.keys() |
|
407 | aliases = self.alias_table.keys() | |
408 | if text == "": |
|
408 | if text == "": | |
409 | return aliases |
|
409 | return aliases | |
410 | else: |
|
410 | else: | |
411 | return [alias for alias in aliases if alias.startswith(text)] |
|
411 | return [alias for alias in aliases if alias.startswith(text)] | |
412 |
|
412 | |||
413 | def python_matches(self,text): |
|
413 | def python_matches(self,text): | |
414 | """Match attributes or global python names""" |
|
414 | """Match attributes or global python names""" | |
415 |
|
415 | |||
416 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
416 | #print 'Completer->python_matches, txt=<%s>' % text # dbg | |
417 | if "." in text: |
|
417 | if "." in text: | |
418 | try: |
|
418 | try: | |
419 | matches = self.attr_matches(text) |
|
419 | matches = self.attr_matches(text) | |
420 | if text.endswith('.') and self.omit__names: |
|
420 | if text.endswith('.') and self.omit__names: | |
421 | if self.omit__names == 1: |
|
421 | if self.omit__names == 1: | |
422 | # true if txt is _not_ a __ name, false otherwise: |
|
422 | # true if txt is _not_ a __ name, false otherwise: | |
423 | no__name = (lambda txt: |
|
423 | no__name = (lambda txt: | |
424 | re.match(r'.*\.__.*?__',txt) is None) |
|
424 | re.match(r'.*\.__.*?__',txt) is None) | |
425 | else: |
|
425 | else: | |
426 | # true if txt is _not_ a _ name, false otherwise: |
|
426 | # true if txt is _not_ a _ name, false otherwise: | |
427 | no__name = (lambda txt: |
|
427 | no__name = (lambda txt: | |
428 | re.match(r'.*\._.*?',txt) is None) |
|
428 | re.match(r'.*\._.*?',txt) is None) | |
429 | matches = filter(no__name, matches) |
|
429 | matches = filter(no__name, matches) | |
430 | except NameError: |
|
430 | except NameError: | |
431 | # catches <undefined attributes>.<tab> |
|
431 | # catches <undefined attributes>.<tab> | |
432 | matches = [] |
|
432 | matches = [] | |
433 | else: |
|
433 | else: | |
434 | matches = self.global_matches(text) |
|
434 | matches = self.global_matches(text) | |
435 | # this is so completion finds magics when automagic is on: |
|
435 | # this is so completion finds magics when automagic is on: | |
436 |
if matches == [] and |
|
436 | if (matches == [] and | |
|
437 | not text.startswith(os.sep) and | |||
|
438 | not ' ' in self.lbuf): | |||
437 | matches = self.attr_matches(self.magic_prefix+text) |
|
439 | matches = self.attr_matches(self.magic_prefix+text) | |
438 | return matches |
|
440 | return matches | |
439 |
|
441 | |||
440 | def _default_arguments(self, obj): |
|
442 | def _default_arguments(self, obj): | |
441 | """Return the list of default arguments of obj if it is callable, |
|
443 | """Return the list of default arguments of obj if it is callable, | |
442 | or empty list otherwise.""" |
|
444 | or empty list otherwise.""" | |
443 |
|
445 | |||
444 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
446 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
445 | # for classes, check for __init__,__new__ |
|
447 | # for classes, check for __init__,__new__ | |
446 | if inspect.isclass(obj): |
|
448 | if inspect.isclass(obj): | |
447 | obj = (getattr(obj,'__init__',None) or |
|
449 | obj = (getattr(obj,'__init__',None) or | |
448 | getattr(obj,'__new__',None)) |
|
450 | getattr(obj,'__new__',None)) | |
449 | # for all others, check if they are __call__able |
|
451 | # for all others, check if they are __call__able | |
450 | elif hasattr(obj, '__call__'): |
|
452 | elif hasattr(obj, '__call__'): | |
451 | obj = obj.__call__ |
|
453 | obj = obj.__call__ | |
452 | # XXX: is there a way to handle the builtins ? |
|
454 | # XXX: is there a way to handle the builtins ? | |
453 | try: |
|
455 | try: | |
454 | args,_,_1,defaults = inspect.getargspec(obj) |
|
456 | args,_,_1,defaults = inspect.getargspec(obj) | |
455 | if defaults: |
|
457 | if defaults: | |
456 | return args[-len(defaults):] |
|
458 | return args[-len(defaults):] | |
457 | except TypeError: pass |
|
459 | except TypeError: pass | |
458 | return [] |
|
460 | return [] | |
459 |
|
461 | |||
460 | def python_func_kw_matches(self,text): |
|
462 | def python_func_kw_matches(self,text): | |
461 | """Match named parameters (kwargs) of the last open function""" |
|
463 | """Match named parameters (kwargs) of the last open function""" | |
462 |
|
464 | |||
463 | if "." in text: # a parameter cannot be dotted |
|
465 | if "." in text: # a parameter cannot be dotted | |
464 | return [] |
|
466 | return [] | |
465 | try: regexp = self.__funcParamsRegex |
|
467 | try: regexp = self.__funcParamsRegex | |
466 | except AttributeError: |
|
468 | except AttributeError: | |
467 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
469 | regexp = self.__funcParamsRegex = re.compile(r''' | |
468 | '.*?' | # single quoted strings or |
|
470 | '.*?' | # single quoted strings or | |
469 | ".*?" | # double quoted strings or |
|
471 | ".*?" | # double quoted strings or | |
470 | \w+ | # identifier |
|
472 | \w+ | # identifier | |
471 | \S # other characters |
|
473 | \S # other characters | |
472 | ''', re.VERBOSE | re.DOTALL) |
|
474 | ''', re.VERBOSE | re.DOTALL) | |
473 | # 1. find the nearest identifier that comes before an unclosed |
|
475 | # 1. find the nearest identifier that comes before an unclosed | |
474 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
476 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
475 | tokens = regexp.findall(self.get_line_buffer()) |
|
477 | tokens = regexp.findall(self.get_line_buffer()) | |
476 | tokens.reverse() |
|
478 | tokens.reverse() | |
477 | iterTokens = iter(tokens); openPar = 0 |
|
479 | iterTokens = iter(tokens); openPar = 0 | |
478 | for token in iterTokens: |
|
480 | for token in iterTokens: | |
479 | if token == ')': |
|
481 | if token == ')': | |
480 | openPar -= 1 |
|
482 | openPar -= 1 | |
481 | elif token == '(': |
|
483 | elif token == '(': | |
482 | openPar += 1 |
|
484 | openPar += 1 | |
483 | if openPar > 0: |
|
485 | if openPar > 0: | |
484 | # found the last unclosed parenthesis |
|
486 | # found the last unclosed parenthesis | |
485 | break |
|
487 | break | |
486 | else: |
|
488 | else: | |
487 | return [] |
|
489 | return [] | |
488 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
490 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
489 | ids = [] |
|
491 | ids = [] | |
490 | isId = re.compile(r'\w+$').match |
|
492 | isId = re.compile(r'\w+$').match | |
491 | while True: |
|
493 | while True: | |
492 | try: |
|
494 | try: | |
493 | ids.append(iterTokens.next()) |
|
495 | ids.append(iterTokens.next()) | |
494 | if not isId(ids[-1]): |
|
496 | if not isId(ids[-1]): | |
495 | ids.pop(); break |
|
497 | ids.pop(); break | |
496 | if not iterTokens.next() == '.': |
|
498 | if not iterTokens.next() == '.': | |
497 | break |
|
499 | break | |
498 | except StopIteration: |
|
500 | except StopIteration: | |
499 | break |
|
501 | break | |
500 | # lookup the candidate callable matches either using global_matches |
|
502 | # lookup the candidate callable matches either using global_matches | |
501 | # or attr_matches for dotted names |
|
503 | # or attr_matches for dotted names | |
502 | if len(ids) == 1: |
|
504 | if len(ids) == 1: | |
503 | callableMatches = self.global_matches(ids[0]) |
|
505 | callableMatches = self.global_matches(ids[0]) | |
504 | else: |
|
506 | else: | |
505 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
507 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
506 | argMatches = [] |
|
508 | argMatches = [] | |
507 | for callableMatch in callableMatches: |
|
509 | for callableMatch in callableMatches: | |
508 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
510 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
509 | self.namespace)) |
|
511 | self.namespace)) | |
510 | except: continue |
|
512 | except: continue | |
511 | for namedArg in namedArgs: |
|
513 | for namedArg in namedArgs: | |
512 | if namedArg.startswith(text): |
|
514 | if namedArg.startswith(text): | |
513 | argMatches.append("%s=" %namedArg) |
|
515 | argMatches.append("%s=" %namedArg) | |
514 | return argMatches |
|
516 | return argMatches | |
515 |
|
517 | |||
516 | def complete(self, text, state): |
|
518 | def complete(self, text, state): | |
517 | """Return the next possible completion for 'text'. |
|
519 | """Return the next possible completion for 'text'. | |
518 |
|
520 | |||
519 | This is called successively with state == 0, 1, 2, ... until it |
|
521 | This is called successively with state == 0, 1, 2, ... until it | |
520 | returns None. The completion should begin with 'text'. """ |
|
522 | returns None. The completion should begin with 'text'. """ | |
521 |
|
523 | |||
522 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
524 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
523 |
|
525 | |||
524 | # if there is only a tab on a line with only whitespace, instead |
|
526 | # if there is only a tab on a line with only whitespace, instead | |
525 | # of the mostly useless 'do you want to see all million |
|
527 | # of the mostly useless 'do you want to see all million | |
526 | # completions' message, just do the right thing and give the user |
|
528 | # completions' message, just do the right thing and give the user | |
527 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
529 | # his tab! Incidentally, this enables pasting of tabbed text from | |
528 | # an editor (as long as autoindent is off). |
|
530 | # an editor (as long as autoindent is off). | |
529 |
|
531 | |||
530 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
532 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we | |
531 | # don't interfere with their own tab-completion mechanism. |
|
533 | # don't interfere with their own tab-completion mechanism. | |
532 | self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()] |
|
534 | self.lbuf = self.get_line_buffer()[:self.readline.get_endidx()] | |
533 | if not (self.dumb_terminal or self.get_line_buffer().strip()): |
|
535 | if not (self.dumb_terminal or self.get_line_buffer().strip()): | |
534 | self.readline.insert_text('\t') |
|
536 | self.readline.insert_text('\t') | |
535 | return None |
|
537 | return None | |
536 |
|
538 | |||
537 | magic_escape = self.magic_escape |
|
539 | magic_escape = self.magic_escape | |
538 | magic_prefix = self.magic_prefix |
|
540 | magic_prefix = self.magic_prefix | |
539 |
|
541 | |||
540 | try: |
|
542 | try: | |
541 | if text.startswith(magic_escape): |
|
543 | if text.startswith(magic_escape): | |
542 | text = text.replace(magic_escape,magic_prefix) |
|
544 | text = text.replace(magic_escape,magic_prefix) | |
543 | elif text.startswith('~'): |
|
545 | elif text.startswith('~'): | |
544 | text = os.path.expanduser(text) |
|
546 | text = os.path.expanduser(text) | |
545 | if state == 0: |
|
547 | if state == 0: | |
546 | # Extend the list of completions with the results of each |
|
548 | # Extend the list of completions with the results of each | |
547 | # matcher, so we return results to the user from all |
|
549 | # matcher, so we return results to the user from all | |
548 | # namespaces. |
|
550 | # namespaces. | |
549 | if self.merge_completions: |
|
551 | if self.merge_completions: | |
550 | self.matches = [] |
|
552 | self.matches = [] | |
551 | for matcher in self.matchers: |
|
553 | for matcher in self.matchers: | |
552 | self.matches.extend(matcher(text)) |
|
554 | self.matches.extend(matcher(text)) | |
553 | else: |
|
555 | else: | |
554 | for matcher in self.matchers: |
|
556 | for matcher in self.matchers: | |
555 | self.matches = matcher(text) |
|
557 | self.matches = matcher(text) | |
556 | if self.matches: |
|
558 | if self.matches: | |
557 | break |
|
559 | break | |
558 |
|
560 | |||
559 | try: |
|
561 | try: | |
560 | return self.matches[state].replace(magic_prefix,magic_escape) |
|
562 | return self.matches[state].replace(magic_prefix,magic_escape) | |
561 | except IndexError: |
|
563 | except IndexError: | |
562 | return None |
|
564 | return None | |
563 | except: |
|
565 | except: | |
564 | #from IPython.ultraTB import AutoFormattedTB; # dbg |
|
566 | #from IPython.ultraTB import AutoFormattedTB; # dbg | |
565 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
567 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
566 |
|
568 | |||
567 | # If completion fails, don't annoy the user. |
|
569 | # If completion fails, don't annoy the user. | |
568 | return None |
|
570 | return None |
General Comments 0
You need to be logged in to leave comments.
Login now