Show More
@@ -1,637 +1,640 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 shlex |
|
72 | import shlex | |
73 | import sys |
|
73 | import sys | |
74 | import IPython.rlineimpl as readline |
|
74 | import IPython.rlineimpl as readline | |
75 | import itertools |
|
75 | import itertools | |
76 | from IPython.ipstruct import Struct |
|
76 | from IPython.ipstruct import Struct | |
77 | from IPython import ipapi |
|
77 | from IPython import ipapi | |
78 | from IPython import generics |
|
78 | from IPython import generics | |
79 | import types |
|
79 | import types | |
80 |
|
80 | |||
81 | # Python 2.4 offers sets as a builtin |
|
81 | # Python 2.4 offers sets as a builtin | |
82 | try: |
|
82 | try: | |
83 | set() |
|
83 | set() | |
84 | except NameError: |
|
84 | except NameError: | |
85 | from sets import Set as set |
|
85 | from sets import Set as set | |
86 |
|
86 | |||
87 | from IPython.genutils import debugx, dir2 |
|
87 | from IPython.genutils import debugx, dir2 | |
88 |
|
88 | |||
89 | __all__ = ['Completer','IPCompleter'] |
|
89 | __all__ = ['Completer','IPCompleter'] | |
90 |
|
90 | |||
91 | class Completer: |
|
91 | class Completer: | |
92 | def __init__(self,namespace=None,global_namespace=None): |
|
92 | def __init__(self,namespace=None,global_namespace=None): | |
93 | """Create a new completer for the command line. |
|
93 | """Create a new completer for the command line. | |
94 |
|
94 | |||
95 | Completer([namespace,global_namespace]) -> completer instance. |
|
95 | Completer([namespace,global_namespace]) -> completer instance. | |
96 |
|
96 | |||
97 | If unspecified, the default namespace where completions are performed |
|
97 | If unspecified, the default namespace where completions are performed | |
98 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
98 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
99 | given as dictionaries. |
|
99 | given as dictionaries. | |
100 |
|
100 | |||
101 | An optional second namespace can be given. This allows the completer |
|
101 | An optional second namespace can be given. This allows the completer | |
102 | to handle cases where both the local and global scopes need to be |
|
102 | to handle cases where both the local and global scopes need to be | |
103 | distinguished. |
|
103 | distinguished. | |
104 |
|
104 | |||
105 | Completer instances should be used as the completion mechanism of |
|
105 | Completer instances should be used as the completion mechanism of | |
106 | readline via the set_completer() call: |
|
106 | readline via the set_completer() call: | |
107 |
|
107 | |||
108 | readline.set_completer(Completer(my_namespace).complete) |
|
108 | readline.set_completer(Completer(my_namespace).complete) | |
109 | """ |
|
109 | """ | |
110 |
|
110 | |||
111 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
111 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
112 | # specific namespace or to use __main__.__dict__. This will allow us |
|
112 | # specific namespace or to use __main__.__dict__. This will allow us | |
113 | # to bind to __main__.__dict__ at completion time, not now. |
|
113 | # to bind to __main__.__dict__ at completion time, not now. | |
114 | if namespace is None: |
|
114 | if namespace is None: | |
115 | self.use_main_ns = 1 |
|
115 | self.use_main_ns = 1 | |
116 | else: |
|
116 | else: | |
117 | self.use_main_ns = 0 |
|
117 | self.use_main_ns = 0 | |
118 | self.namespace = namespace |
|
118 | self.namespace = namespace | |
119 |
|
119 | |||
120 | # The global namespace, if given, can be bound directly |
|
120 | # The global namespace, if given, can be bound directly | |
121 | if global_namespace is None: |
|
121 | if global_namespace is None: | |
122 | self.global_namespace = {} |
|
122 | self.global_namespace = {} | |
123 | else: |
|
123 | else: | |
124 | self.global_namespace = global_namespace |
|
124 | self.global_namespace = global_namespace | |
125 |
|
125 | |||
126 | def complete(self, text, state): |
|
126 | def complete(self, text, state): | |
127 | """Return the next possible completion for 'text'. |
|
127 | """Return the next possible completion for 'text'. | |
128 |
|
128 | |||
129 | This is called successively with state == 0, 1, 2, ... until it |
|
129 | This is called successively with state == 0, 1, 2, ... until it | |
130 | returns None. The completion should begin with 'text'. |
|
130 | returns None. The completion should begin with 'text'. | |
131 |
|
131 | |||
132 | """ |
|
132 | """ | |
133 | if self.use_main_ns: |
|
133 | if self.use_main_ns: | |
134 | self.namespace = __main__.__dict__ |
|
134 | self.namespace = __main__.__dict__ | |
135 |
|
135 | |||
136 | if state == 0: |
|
136 | if state == 0: | |
137 | if "." in text: |
|
137 | if "." in text: | |
138 | self.matches = self.attr_matches(text) |
|
138 | self.matches = self.attr_matches(text) | |
139 | else: |
|
139 | else: | |
140 | self.matches = self.global_matches(text) |
|
140 | self.matches = self.global_matches(text) | |
141 | try: |
|
141 | try: | |
142 | return self.matches[state] |
|
142 | return self.matches[state] | |
143 | except IndexError: |
|
143 | except IndexError: | |
144 | return None |
|
144 | return None | |
145 |
|
145 | |||
146 | def global_matches(self, text): |
|
146 | def global_matches(self, text): | |
147 | """Compute matches when text is a simple name. |
|
147 | """Compute matches when text is a simple name. | |
148 |
|
148 | |||
149 | Return a list of all keywords, built-in functions and names currently |
|
149 | Return a list of all keywords, built-in functions and names currently | |
150 | defined in self.namespace or self.global_namespace that match. |
|
150 | defined in self.namespace or self.global_namespace that match. | |
151 |
|
151 | |||
152 | """ |
|
152 | """ | |
153 | matches = [] |
|
153 | matches = [] | |
154 | match_append = matches.append |
|
154 | match_append = matches.append | |
155 | n = len(text) |
|
155 | n = len(text) | |
156 | for lst in [keyword.kwlist, |
|
156 | for lst in [keyword.kwlist, | |
157 | __builtin__.__dict__.keys(), |
|
157 | __builtin__.__dict__.keys(), | |
158 | self.namespace.keys(), |
|
158 | self.namespace.keys(), | |
159 | self.global_namespace.keys()]: |
|
159 | self.global_namespace.keys()]: | |
160 | for word in lst: |
|
160 | for word in lst: | |
161 | if word[:n] == text and word != "__builtins__": |
|
161 | if word[:n] == text and word != "__builtins__": | |
162 | match_append(word) |
|
162 | match_append(word) | |
163 | return matches |
|
163 | return matches | |
164 |
|
164 | |||
165 | def attr_matches(self, text): |
|
165 | def attr_matches(self, text): | |
166 | """Compute matches when text contains a dot. |
|
166 | """Compute matches when text contains a dot. | |
167 |
|
167 | |||
168 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
168 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
169 | evaluatable in self.namespace or self.global_namespace, it will be |
|
169 | evaluatable in self.namespace or self.global_namespace, it will be | |
170 | evaluated and its attributes (as revealed by dir()) are used as |
|
170 | evaluated and its attributes (as revealed by dir()) are used as | |
171 | possible completions. (For class instances, class members are are |
|
171 | possible completions. (For class instances, class members are are | |
172 | also considered.) |
|
172 | also considered.) | |
173 |
|
173 | |||
174 | WARNING: this can still invoke arbitrary C code, if an object |
|
174 | WARNING: this can still invoke arbitrary C code, if an object | |
175 | with a __getattr__ hook is evaluated. |
|
175 | with a __getattr__ hook is evaluated. | |
176 |
|
176 | |||
177 | """ |
|
177 | """ | |
178 | import re |
|
178 | import re | |
179 |
|
179 | |||
180 | # Another option, seems to work great. Catches things like ''.<tab> |
|
180 | # Another option, seems to work great. Catches things like ''.<tab> | |
181 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
181 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
182 |
|
182 | |||
183 | if not m: |
|
183 | if not m: | |
184 | return [] |
|
184 | return [] | |
185 |
|
185 | |||
186 | expr, attr = m.group(1, 3) |
|
186 | expr, attr = m.group(1, 3) | |
187 | try: |
|
187 | try: | |
188 | obj = eval(expr, self.namespace) |
|
188 | obj = eval(expr, self.namespace) | |
189 | except: |
|
189 | except: | |
190 | try: |
|
190 | try: | |
191 | obj = eval(expr, self.global_namespace) |
|
191 | obj = eval(expr, self.global_namespace) | |
192 | except: |
|
192 | except: | |
193 | return [] |
|
193 | return [] | |
194 |
|
194 | |||
195 | words = dir2(obj) |
|
195 | words = dir2(obj) | |
196 |
|
196 | |||
197 | try: |
|
197 | try: | |
198 | words = generics.complete_object(obj, words) |
|
198 | words = generics.complete_object(obj, words) | |
199 | except ipapi.TryNext: |
|
199 | except ipapi.TryNext: | |
200 | pass |
|
200 | pass | |
201 | # Build match list to return |
|
201 | # Build match list to return | |
202 | n = len(attr) |
|
202 | n = len(attr) | |
203 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
203 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
204 | return res |
|
204 | return res | |
205 |
|
205 | |||
206 | class IPCompleter(Completer): |
|
206 | class IPCompleter(Completer): | |
207 | """Extension of the completer class with IPython-specific features""" |
|
207 | """Extension of the completer class with IPython-specific features""" | |
208 |
|
208 | |||
209 | def __init__(self,shell,namespace=None,global_namespace=None, |
|
209 | def __init__(self,shell,namespace=None,global_namespace=None, | |
210 | omit__names=0,alias_table=None): |
|
210 | omit__names=0,alias_table=None): | |
211 | """IPCompleter() -> completer |
|
211 | """IPCompleter() -> completer | |
212 |
|
212 | |||
213 | Return a completer object suitable for use by the readline library |
|
213 | Return a completer object suitable for use by the readline library | |
214 | via readline.set_completer(). |
|
214 | via readline.set_completer(). | |
215 |
|
215 | |||
216 | Inputs: |
|
216 | Inputs: | |
217 |
|
217 | |||
218 | - shell: a pointer to the ipython shell itself. This is needed |
|
218 | - shell: a pointer to the ipython shell itself. This is needed | |
219 | because this completer knows about magic functions, and those can |
|
219 | because this completer knows about magic functions, and those can | |
220 | only be accessed via the ipython instance. |
|
220 | only be accessed via the ipython instance. | |
221 |
|
221 | |||
222 | - namespace: an optional dict where completions are performed. |
|
222 | - namespace: an optional dict where completions are performed. | |
223 |
|
223 | |||
224 | - global_namespace: secondary optional dict for completions, to |
|
224 | - global_namespace: secondary optional dict for completions, to | |
225 | handle cases (such as IPython embedded inside functions) where |
|
225 | handle cases (such as IPython embedded inside functions) where | |
226 | both Python scopes are visible. |
|
226 | both Python scopes are visible. | |
227 |
|
227 | |||
228 | - The optional omit__names parameter sets the completer to omit the |
|
228 | - The optional omit__names parameter sets the completer to omit the | |
229 | 'magic' names (__magicname__) for python objects unless the text |
|
229 | 'magic' names (__magicname__) for python objects unless the text | |
230 | to be completed explicitly starts with one or more underscores. |
|
230 | to be completed explicitly starts with one or more underscores. | |
231 |
|
231 | |||
232 | - If alias_table is supplied, it should be a dictionary of aliases |
|
232 | - If alias_table is supplied, it should be a dictionary of aliases | |
233 | to complete. """ |
|
233 | to complete. """ | |
234 |
|
234 | |||
235 | Completer.__init__(self,namespace,global_namespace) |
|
235 | Completer.__init__(self,namespace,global_namespace) | |
236 | self.magic_prefix = shell.name+'.magic_' |
|
236 | self.magic_prefix = shell.name+'.magic_' | |
237 | self.magic_escape = shell.ESC_MAGIC |
|
237 | self.magic_escape = shell.ESC_MAGIC | |
238 | self.readline = readline |
|
238 | self.readline = readline | |
239 | delims = self.readline.get_completer_delims() |
|
239 | delims = self.readline.get_completer_delims() | |
240 | delims = delims.replace(self.magic_escape,'') |
|
240 | delims = delims.replace(self.magic_escape,'') | |
241 | self.readline.set_completer_delims(delims) |
|
241 | self.readline.set_completer_delims(delims) | |
242 | self.get_line_buffer = self.readline.get_line_buffer |
|
242 | self.get_line_buffer = self.readline.get_line_buffer | |
243 | self.get_endidx = self.readline.get_endidx |
|
243 | self.get_endidx = self.readline.get_endidx | |
244 | self.omit__names = omit__names |
|
244 | self.omit__names = omit__names | |
245 | self.merge_completions = shell.rc.readline_merge_completions |
|
245 | self.merge_completions = shell.rc.readline_merge_completions | |
246 | if alias_table is None: |
|
246 | if alias_table is None: | |
247 | alias_table = {} |
|
247 | alias_table = {} | |
248 | self.alias_table = alias_table |
|
248 | self.alias_table = alias_table | |
249 | # Regexp to split filenames with spaces in them |
|
249 | # Regexp to split filenames with spaces in them | |
250 | self.space_name_re = re.compile(r'([^\\] )') |
|
250 | self.space_name_re = re.compile(r'([^\\] )') | |
251 | # Hold a local ref. to glob.glob for speed |
|
251 | # Hold a local ref. to glob.glob for speed | |
252 | self.glob = glob.glob |
|
252 | self.glob = glob.glob | |
253 |
|
253 | |||
254 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
254 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
255 | # buffers, to avoid completion problems. |
|
255 | # buffers, to avoid completion problems. | |
256 | term = os.environ.get('TERM','xterm') |
|
256 | term = os.environ.get('TERM','xterm') | |
257 | self.dumb_terminal = term in ['dumb','emacs'] |
|
257 | self.dumb_terminal = term in ['dumb','emacs'] | |
258 |
|
258 | |||
259 | # Special handling of backslashes needed in win32 platforms |
|
259 | # Special handling of backslashes needed in win32 platforms | |
260 | if sys.platform == "win32": |
|
260 | if sys.platform == "win32": | |
261 | self.clean_glob = self._clean_glob_win32 |
|
261 | self.clean_glob = self._clean_glob_win32 | |
262 | else: |
|
262 | else: | |
263 | self.clean_glob = self._clean_glob |
|
263 | self.clean_glob = self._clean_glob | |
264 | self.matchers = [self.python_matches, |
|
264 | self.matchers = [self.python_matches, | |
265 | self.file_matches, |
|
265 | self.file_matches, | |
266 | self.alias_matches, |
|
266 | self.alias_matches, | |
267 | self.python_func_kw_matches] |
|
267 | self.python_func_kw_matches] | |
268 |
|
268 | |||
269 |
|
269 | |||
270 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
270 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
271 | def all_completions(self, text): |
|
271 | def all_completions(self, text): | |
272 | """Return all possible completions for the benefit of emacs.""" |
|
272 | """Return all possible completions for the benefit of emacs.""" | |
273 |
|
273 | |||
274 | completions = [] |
|
274 | completions = [] | |
275 | comp_append = completions.append |
|
275 | comp_append = completions.append | |
276 | try: |
|
276 | try: | |
277 | for i in xrange(sys.maxint): |
|
277 | for i in xrange(sys.maxint): | |
278 | res = self.complete(text, i) |
|
278 | res = self.complete(text, i) | |
279 |
|
279 | |||
280 | if not res: break |
|
280 | if not res: break | |
281 |
|
281 | |||
282 | comp_append(res) |
|
282 | comp_append(res) | |
283 | #XXX workaround for ``notDefined.<tab>`` |
|
283 | #XXX workaround for ``notDefined.<tab>`` | |
284 | except NameError: |
|
284 | except NameError: | |
285 | pass |
|
285 | pass | |
286 | return completions |
|
286 | return completions | |
287 | # /end Alex Schmolck code. |
|
287 | # /end Alex Schmolck code. | |
288 |
|
288 | |||
289 | def _clean_glob(self,text): |
|
289 | def _clean_glob(self,text): | |
290 | return self.glob("%s*" % text) |
|
290 | return self.glob("%s*" % text) | |
291 |
|
291 | |||
292 | def _clean_glob_win32(self,text): |
|
292 | def _clean_glob_win32(self,text): | |
293 | return [f.replace("\\","/") |
|
293 | return [f.replace("\\","/") | |
294 | for f in self.glob("%s*" % text)] |
|
294 | for f in self.glob("%s*" % text)] | |
295 |
|
295 | |||
296 | def file_matches(self, text): |
|
296 | def file_matches(self, text): | |
297 | """Match filenames, expanding ~USER type strings. |
|
297 | """Match filenames, expanding ~USER type strings. | |
298 |
|
298 | |||
299 | Most of the seemingly convoluted logic in this completer is an |
|
299 | Most of the seemingly convoluted logic in this completer is an | |
300 | attempt to handle filenames with spaces in them. And yet it's not |
|
300 | attempt to handle filenames with spaces in them. And yet it's not | |
301 | quite perfect, because Python's readline doesn't expose all of the |
|
301 | quite perfect, because Python's readline doesn't expose all of the | |
302 | GNU readline details needed for this to be done correctly. |
|
302 | GNU readline details needed for this to be done correctly. | |
303 |
|
303 | |||
304 | For a filename with a space in it, the printed completions will be |
|
304 | For a filename with a space in it, the printed completions will be | |
305 | only the parts after what's already been typed (instead of the |
|
305 | only the parts after what's already been typed (instead of the | |
306 | full completions, as is normally done). I don't think with the |
|
306 | full completions, as is normally done). I don't think with the | |
307 | current (as of Python 2.3) Python readline it's possible to do |
|
307 | current (as of Python 2.3) Python readline it's possible to do | |
308 | better.""" |
|
308 | better.""" | |
309 |
|
309 | |||
310 | #print 'Completer->file_matches: <%s>' % text # dbg |
|
310 | #print 'Completer->file_matches: <%s>' % text # dbg | |
311 |
|
311 | |||
312 | # chars that require escaping with backslash - i.e. chars |
|
312 | # chars that require escaping with backslash - i.e. chars | |
313 | # that readline treats incorrectly as delimiters, but we |
|
313 | # that readline treats incorrectly as delimiters, but we | |
314 | # don't want to treat as delimiters in filename matching |
|
314 | # don't want to treat as delimiters in filename matching | |
315 | # when escaped with backslash |
|
315 | # when escaped with backslash | |
316 |
|
316 | |||
317 | protectables = ' ' |
|
317 | if sys.platform == 'win32': | |
|
318 | protectables = ' ' | |||
|
319 | else: | |||
|
320 | protectables = ' ()' | |||
318 |
|
321 | |||
319 | if text.startswith('!'): |
|
322 | if text.startswith('!'): | |
320 | text = text[1:] |
|
323 | text = text[1:] | |
321 | text_prefix = '!' |
|
324 | text_prefix = '!' | |
322 | else: |
|
325 | else: | |
323 | text_prefix = '' |
|
326 | text_prefix = '' | |
324 |
|
327 | |||
325 | def protect_filename(s): |
|
328 | def protect_filename(s): | |
326 | return "".join([(ch in protectables and '\\' + ch or ch) |
|
329 | return "".join([(ch in protectables and '\\' + ch or ch) | |
327 | for ch in s]) |
|
330 | for ch in s]) | |
328 |
|
331 | |||
329 | def single_dir_expand(matches): |
|
332 | def single_dir_expand(matches): | |
330 | "Recursively expand match lists containing a single dir." |
|
333 | "Recursively expand match lists containing a single dir." | |
331 |
|
334 | |||
332 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
335 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
333 | # Takes care of links to directories also. Use '/' |
|
336 | # Takes care of links to directories also. Use '/' | |
334 | # explicitly, even under Windows, so that name completions |
|
337 | # explicitly, even under Windows, so that name completions | |
335 | # don't end up escaped. |
|
338 | # don't end up escaped. | |
336 | d = matches[0] |
|
339 | d = matches[0] | |
337 | if d[-1] in ['/','\\']: |
|
340 | if d[-1] in ['/','\\']: | |
338 | d = d[:-1] |
|
341 | d = d[:-1] | |
339 |
|
342 | |||
340 | subdirs = os.listdir(d) |
|
343 | subdirs = os.listdir(d) | |
341 | if subdirs: |
|
344 | if subdirs: | |
342 | matches = [ (d + '/' + p) for p in subdirs] |
|
345 | matches = [ (d + '/' + p) for p in subdirs] | |
343 | return single_dir_expand(matches) |
|
346 | return single_dir_expand(matches) | |
344 | else: |
|
347 | else: | |
345 | return matches |
|
348 | return matches | |
346 | else: |
|
349 | else: | |
347 | return matches |
|
350 | return matches | |
348 |
|
351 | |||
349 | lbuf = self.lbuf |
|
352 | lbuf = self.lbuf | |
350 | open_quotes = 0 # track strings with open quotes |
|
353 | open_quotes = 0 # track strings with open quotes | |
351 | try: |
|
354 | try: | |
352 | lsplit = shlex.split(lbuf)[-1] |
|
355 | lsplit = shlex.split(lbuf)[-1] | |
353 | except ValueError: |
|
356 | except ValueError: | |
354 | # typically an unmatched ", or backslash without escaped char. |
|
357 | # typically an unmatched ", or backslash without escaped char. | |
355 | if lbuf.count('"')==1: |
|
358 | if lbuf.count('"')==1: | |
356 | open_quotes = 1 |
|
359 | open_quotes = 1 | |
357 | lsplit = lbuf.split('"')[-1] |
|
360 | lsplit = lbuf.split('"')[-1] | |
358 | elif lbuf.count("'")==1: |
|
361 | elif lbuf.count("'")==1: | |
359 | open_quotes = 1 |
|
362 | open_quotes = 1 | |
360 | lsplit = lbuf.split("'")[-1] |
|
363 | lsplit = lbuf.split("'")[-1] | |
361 | else: |
|
364 | else: | |
362 | return [] |
|
365 | return [] | |
363 | except IndexError: |
|
366 | except IndexError: | |
364 | # tab pressed on empty line |
|
367 | # tab pressed on empty line | |
365 | lsplit = "" |
|
368 | lsplit = "" | |
366 |
|
369 | |||
367 | if lsplit != protect_filename(lsplit): |
|
370 | if lsplit != protect_filename(lsplit): | |
368 | # if protectables are found, do matching on the whole escaped |
|
371 | # if protectables are found, do matching on the whole escaped | |
369 | # name |
|
372 | # name | |
370 | has_protectables = 1 |
|
373 | has_protectables = 1 | |
371 | text0,text = text,lsplit |
|
374 | text0,text = text,lsplit | |
372 | else: |
|
375 | else: | |
373 | has_protectables = 0 |
|
376 | has_protectables = 0 | |
374 | text = os.path.expanduser(text) |
|
377 | text = os.path.expanduser(text) | |
375 |
|
378 | |||
376 | if text == "": |
|
379 | if text == "": | |
377 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
380 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
378 |
|
381 | |||
379 | m0 = self.clean_glob(text.replace('\\','')) |
|
382 | m0 = self.clean_glob(text.replace('\\','')) | |
380 | if has_protectables: |
|
383 | if has_protectables: | |
381 | # If we had protectables, we need to revert our changes to the |
|
384 | # If we had protectables, we need to revert our changes to the | |
382 | # beginning of filename so that we don't double-write the part |
|
385 | # beginning of filename so that we don't double-write the part | |
383 | # of the filename we have so far |
|
386 | # of the filename we have so far | |
384 | len_lsplit = len(lsplit) |
|
387 | len_lsplit = len(lsplit) | |
385 | matches = [text_prefix + text0 + |
|
388 | matches = [text_prefix + text0 + | |
386 | protect_filename(f[len_lsplit:]) for f in m0] |
|
389 | protect_filename(f[len_lsplit:]) for f in m0] | |
387 | else: |
|
390 | else: | |
388 | if open_quotes: |
|
391 | if open_quotes: | |
389 | # if we have a string with an open quote, we don't need to |
|
392 | # if we have a string with an open quote, we don't need to | |
390 | # protect the names at all (and we _shouldn't_, as it |
|
393 | # protect the names at all (and we _shouldn't_, as it | |
391 | # would cause bugs when the filesystem call is made). |
|
394 | # would cause bugs when the filesystem call is made). | |
392 | matches = m0 |
|
395 | matches = m0 | |
393 | else: |
|
396 | else: | |
394 | matches = [text_prefix + |
|
397 | matches = [text_prefix + | |
395 | protect_filename(f) for f in m0] |
|
398 | protect_filename(f) for f in m0] | |
396 |
|
399 | |||
397 | #print 'mm',matches # dbg |
|
400 | #print 'mm',matches # dbg | |
398 | return single_dir_expand(matches) |
|
401 | return single_dir_expand(matches) | |
399 |
|
402 | |||
400 | def alias_matches(self, text): |
|
403 | def alias_matches(self, text): | |
401 | """Match internal system aliases""" |
|
404 | """Match internal system aliases""" | |
402 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg |
|
405 | #print 'Completer->alias_matches:',text,'lb',self.lbuf # dbg | |
403 |
|
406 | |||
404 | # if we are not in the first 'item', alias matching |
|
407 | # if we are not in the first 'item', alias matching | |
405 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
408 | # doesn't make sense - unless we are starting with 'sudo' command. | |
406 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): |
|
409 | if ' ' in self.lbuf.lstrip() and not self.lbuf.lstrip().startswith('sudo'): | |
407 | return [] |
|
410 | return [] | |
408 | text = os.path.expanduser(text) |
|
411 | text = os.path.expanduser(text) | |
409 | aliases = self.alias_table.keys() |
|
412 | aliases = self.alias_table.keys() | |
410 | if text == "": |
|
413 | if text == "": | |
411 | return aliases |
|
414 | return aliases | |
412 | else: |
|
415 | else: | |
413 | return [alias for alias in aliases if alias.startswith(text)] |
|
416 | return [alias for alias in aliases if alias.startswith(text)] | |
414 |
|
417 | |||
415 | def python_matches(self,text): |
|
418 | def python_matches(self,text): | |
416 | """Match attributes or global python names""" |
|
419 | """Match attributes or global python names""" | |
417 |
|
420 | |||
418 | #print 'Completer->python_matches, txt=<%s>' % text # dbg |
|
421 | #print 'Completer->python_matches, txt=<%s>' % text # dbg | |
419 | if "." in text: |
|
422 | if "." in text: | |
420 | try: |
|
423 | try: | |
421 | matches = self.attr_matches(text) |
|
424 | matches = self.attr_matches(text) | |
422 | if text.endswith('.') and self.omit__names: |
|
425 | if text.endswith('.') and self.omit__names: | |
423 | if self.omit__names == 1: |
|
426 | if self.omit__names == 1: | |
424 | # true if txt is _not_ a __ name, false otherwise: |
|
427 | # true if txt is _not_ a __ name, false otherwise: | |
425 | no__name = (lambda txt: |
|
428 | no__name = (lambda txt: | |
426 | re.match(r'.*\.__.*?__',txt) is None) |
|
429 | re.match(r'.*\.__.*?__',txt) is None) | |
427 | else: |
|
430 | else: | |
428 | # true if txt is _not_ a _ name, false otherwise: |
|
431 | # true if txt is _not_ a _ name, false otherwise: | |
429 | no__name = (lambda txt: |
|
432 | no__name = (lambda txt: | |
430 | re.match(r'.*\._.*?',txt) is None) |
|
433 | re.match(r'.*\._.*?',txt) is None) | |
431 | matches = filter(no__name, matches) |
|
434 | matches = filter(no__name, matches) | |
432 | except NameError: |
|
435 | except NameError: | |
433 | # catches <undefined attributes>.<tab> |
|
436 | # catches <undefined attributes>.<tab> | |
434 | matches = [] |
|
437 | matches = [] | |
435 | else: |
|
438 | else: | |
436 | matches = self.global_matches(text) |
|
439 | matches = self.global_matches(text) | |
437 | # this is so completion finds magics when automagic is on: |
|
440 | # this is so completion finds magics when automagic is on: | |
438 | if (matches == [] and |
|
441 | if (matches == [] and | |
439 | not text.startswith(os.sep) and |
|
442 | not text.startswith(os.sep) and | |
440 | not ' ' in self.lbuf): |
|
443 | not ' ' in self.lbuf): | |
441 | matches = self.attr_matches(self.magic_prefix+text) |
|
444 | matches = self.attr_matches(self.magic_prefix+text) | |
442 | return matches |
|
445 | return matches | |
443 |
|
446 | |||
444 | def _default_arguments(self, obj): |
|
447 | def _default_arguments(self, obj): | |
445 | """Return the list of default arguments of obj if it is callable, |
|
448 | """Return the list of default arguments of obj if it is callable, | |
446 | or empty list otherwise.""" |
|
449 | or empty list otherwise.""" | |
447 |
|
450 | |||
448 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
451 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
449 | # for classes, check for __init__,__new__ |
|
452 | # for classes, check for __init__,__new__ | |
450 | if inspect.isclass(obj): |
|
453 | if inspect.isclass(obj): | |
451 | obj = (getattr(obj,'__init__',None) or |
|
454 | obj = (getattr(obj,'__init__',None) or | |
452 | getattr(obj,'__new__',None)) |
|
455 | getattr(obj,'__new__',None)) | |
453 | # for all others, check if they are __call__able |
|
456 | # for all others, check if they are __call__able | |
454 | elif hasattr(obj, '__call__'): |
|
457 | elif hasattr(obj, '__call__'): | |
455 | obj = obj.__call__ |
|
458 | obj = obj.__call__ | |
456 | # XXX: is there a way to handle the builtins ? |
|
459 | # XXX: is there a way to handle the builtins ? | |
457 | try: |
|
460 | try: | |
458 | args,_,_1,defaults = inspect.getargspec(obj) |
|
461 | args,_,_1,defaults = inspect.getargspec(obj) | |
459 | if defaults: |
|
462 | if defaults: | |
460 | return args[-len(defaults):] |
|
463 | return args[-len(defaults):] | |
461 | except TypeError: pass |
|
464 | except TypeError: pass | |
462 | return [] |
|
465 | return [] | |
463 |
|
466 | |||
464 | def python_func_kw_matches(self,text): |
|
467 | def python_func_kw_matches(self,text): | |
465 | """Match named parameters (kwargs) of the last open function""" |
|
468 | """Match named parameters (kwargs) of the last open function""" | |
466 |
|
469 | |||
467 | if "." in text: # a parameter cannot be dotted |
|
470 | if "." in text: # a parameter cannot be dotted | |
468 | return [] |
|
471 | return [] | |
469 | try: regexp = self.__funcParamsRegex |
|
472 | try: regexp = self.__funcParamsRegex | |
470 | except AttributeError: |
|
473 | except AttributeError: | |
471 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
474 | regexp = self.__funcParamsRegex = re.compile(r''' | |
472 | '.*?' | # single quoted strings or |
|
475 | '.*?' | # single quoted strings or | |
473 | ".*?" | # double quoted strings or |
|
476 | ".*?" | # double quoted strings or | |
474 | \w+ | # identifier |
|
477 | \w+ | # identifier | |
475 | \S # other characters |
|
478 | \S # other characters | |
476 | ''', re.VERBOSE | re.DOTALL) |
|
479 | ''', re.VERBOSE | re.DOTALL) | |
477 | # 1. find the nearest identifier that comes before an unclosed |
|
480 | # 1. find the nearest identifier that comes before an unclosed | |
478 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
481 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
479 | tokens = regexp.findall(self.get_line_buffer()) |
|
482 | tokens = regexp.findall(self.get_line_buffer()) | |
480 | tokens.reverse() |
|
483 | tokens.reverse() | |
481 | iterTokens = iter(tokens); openPar = 0 |
|
484 | iterTokens = iter(tokens); openPar = 0 | |
482 | for token in iterTokens: |
|
485 | for token in iterTokens: | |
483 | if token == ')': |
|
486 | if token == ')': | |
484 | openPar -= 1 |
|
487 | openPar -= 1 | |
485 | elif token == '(': |
|
488 | elif token == '(': | |
486 | openPar += 1 |
|
489 | openPar += 1 | |
487 | if openPar > 0: |
|
490 | if openPar > 0: | |
488 | # found the last unclosed parenthesis |
|
491 | # found the last unclosed parenthesis | |
489 | break |
|
492 | break | |
490 | else: |
|
493 | else: | |
491 | return [] |
|
494 | return [] | |
492 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
495 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
493 | ids = [] |
|
496 | ids = [] | |
494 | isId = re.compile(r'\w+$').match |
|
497 | isId = re.compile(r'\w+$').match | |
495 | while True: |
|
498 | while True: | |
496 | try: |
|
499 | try: | |
497 | ids.append(iterTokens.next()) |
|
500 | ids.append(iterTokens.next()) | |
498 | if not isId(ids[-1]): |
|
501 | if not isId(ids[-1]): | |
499 | ids.pop(); break |
|
502 | ids.pop(); break | |
500 | if not iterTokens.next() == '.': |
|
503 | if not iterTokens.next() == '.': | |
501 | break |
|
504 | break | |
502 | except StopIteration: |
|
505 | except StopIteration: | |
503 | break |
|
506 | break | |
504 | # lookup the candidate callable matches either using global_matches |
|
507 | # lookup the candidate callable matches either using global_matches | |
505 | # or attr_matches for dotted names |
|
508 | # or attr_matches for dotted names | |
506 | if len(ids) == 1: |
|
509 | if len(ids) == 1: | |
507 | callableMatches = self.global_matches(ids[0]) |
|
510 | callableMatches = self.global_matches(ids[0]) | |
508 | else: |
|
511 | else: | |
509 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
512 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
510 | argMatches = [] |
|
513 | argMatches = [] | |
511 | for callableMatch in callableMatches: |
|
514 | for callableMatch in callableMatches: | |
512 | try: namedArgs = self._default_arguments(eval(callableMatch, |
|
515 | try: namedArgs = self._default_arguments(eval(callableMatch, | |
513 | self.namespace)) |
|
516 | self.namespace)) | |
514 | except: continue |
|
517 | except: continue | |
515 | for namedArg in namedArgs: |
|
518 | for namedArg in namedArgs: | |
516 | if namedArg.startswith(text): |
|
519 | if namedArg.startswith(text): | |
517 | argMatches.append("%s=" %namedArg) |
|
520 | argMatches.append("%s=" %namedArg) | |
518 | return argMatches |
|
521 | return argMatches | |
519 |
|
522 | |||
520 | def dispatch_custom_completer(self,text): |
|
523 | def dispatch_custom_completer(self,text): | |
521 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
524 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg | |
522 | line = self.full_lbuf |
|
525 | line = self.full_lbuf | |
523 | if not line.strip(): |
|
526 | if not line.strip(): | |
524 | return None |
|
527 | return None | |
525 |
|
528 | |||
526 | event = Struct() |
|
529 | event = Struct() | |
527 | event.line = line |
|
530 | event.line = line | |
528 | event.symbol = text |
|
531 | event.symbol = text | |
529 | cmd = line.split(None,1)[0] |
|
532 | cmd = line.split(None,1)[0] | |
530 | event.command = cmd |
|
533 | event.command = cmd | |
531 | #print "\ncustom:{%s]\n" % event # dbg |
|
534 | #print "\ncustom:{%s]\n" % event # dbg | |
532 |
|
535 | |||
533 | # for foo etc, try also to find completer for %foo |
|
536 | # for foo etc, try also to find completer for %foo | |
534 | if not cmd.startswith(self.magic_escape): |
|
537 | if not cmd.startswith(self.magic_escape): | |
535 | try_magic = self.custom_completers.s_matches( |
|
538 | try_magic = self.custom_completers.s_matches( | |
536 | self.magic_escape + cmd) |
|
539 | self.magic_escape + cmd) | |
537 | else: |
|
540 | else: | |
538 | try_magic = [] |
|
541 | try_magic = [] | |
539 |
|
542 | |||
540 |
|
543 | |||
541 | for c in itertools.chain( |
|
544 | for c in itertools.chain( | |
542 | self.custom_completers.s_matches(cmd), |
|
545 | self.custom_completers.s_matches(cmd), | |
543 | try_magic, |
|
546 | try_magic, | |
544 | self.custom_completers.flat_matches(self.lbuf)): |
|
547 | self.custom_completers.flat_matches(self.lbuf)): | |
545 | #print "try",c # dbg |
|
548 | #print "try",c # dbg | |
546 | try: |
|
549 | try: | |
547 | res = c(event) |
|
550 | res = c(event) | |
548 | # first, try case sensitive match |
|
551 | # first, try case sensitive match | |
549 | withcase = [r for r in res if r.startswith(text)] |
|
552 | withcase = [r for r in res if r.startswith(text)] | |
550 | if withcase: |
|
553 | if withcase: | |
551 | return withcase |
|
554 | return withcase | |
552 | # if none, then case insensitive ones are ok too |
|
555 | # if none, then case insensitive ones are ok too | |
553 | return [r for r in res if r.lower().startswith(text.lower())] |
|
556 | return [r for r in res if r.lower().startswith(text.lower())] | |
554 | except ipapi.TryNext: |
|
557 | except ipapi.TryNext: | |
555 | pass |
|
558 | pass | |
556 |
|
559 | |||
557 | return None |
|
560 | return None | |
558 |
|
561 | |||
559 | def complete(self, text, state,line_buffer=None): |
|
562 | def complete(self, text, state,line_buffer=None): | |
560 | """Return the next possible completion for 'text'. |
|
563 | """Return the next possible completion for 'text'. | |
561 |
|
564 | |||
562 | This is called successively with state == 0, 1, 2, ... until it |
|
565 | This is called successively with state == 0, 1, 2, ... until it | |
563 | returns None. The completion should begin with 'text'. |
|
566 | returns None. The completion should begin with 'text'. | |
564 |
|
567 | |||
565 | :Keywords: |
|
568 | :Keywords: | |
566 | - line_buffer: string |
|
569 | - line_buffer: string | |
567 | If not given, the completer attempts to obtain the current line buffer |
|
570 | If not given, the completer attempts to obtain the current line buffer | |
568 | via readline. This keyword allows clients which are requesting for |
|
571 | via readline. This keyword allows clients which are requesting for | |
569 | text completions in non-readline contexts to inform the completer of |
|
572 | text completions in non-readline contexts to inform the completer of | |
570 | the entire text. |
|
573 | the entire text. | |
571 | """ |
|
574 | """ | |
572 |
|
575 | |||
573 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg |
|
576 | #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg | |
574 |
|
577 | |||
575 | # if there is only a tab on a line with only whitespace, instead |
|
578 | # if there is only a tab on a line with only whitespace, instead | |
576 | # of the mostly useless 'do you want to see all million |
|
579 | # of the mostly useless 'do you want to see all million | |
577 | # completions' message, just do the right thing and give the user |
|
580 | # completions' message, just do the right thing and give the user | |
578 | # his tab! Incidentally, this enables pasting of tabbed text from |
|
581 | # his tab! Incidentally, this enables pasting of tabbed text from | |
579 | # an editor (as long as autoindent is off). |
|
582 | # an editor (as long as autoindent is off). | |
580 |
|
583 | |||
581 | # It should be noted that at least pyreadline still shows |
|
584 | # It should be noted that at least pyreadline still shows | |
582 | # file completions - is there a way around it? |
|
585 | # file completions - is there a way around it? | |
583 |
|
586 | |||
584 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we |
|
587 | # don't apply this on 'dumb' terminals, such as emacs buffers, so we | |
585 | # don't interfere with their own tab-completion mechanism. |
|
588 | # don't interfere with their own tab-completion mechanism. | |
586 | if line_buffer is None: |
|
589 | if line_buffer is None: | |
587 | self.full_lbuf = self.get_line_buffer() |
|
590 | self.full_lbuf = self.get_line_buffer() | |
588 | else: |
|
591 | else: | |
589 | self.full_lbuf = line_buffer |
|
592 | self.full_lbuf = line_buffer | |
590 |
|
593 | |||
591 | if not (self.dumb_terminal or self.full_lbuf.strip()): |
|
594 | if not (self.dumb_terminal or self.full_lbuf.strip()): | |
592 | self.readline.insert_text('\t') |
|
595 | self.readline.insert_text('\t') | |
593 | return None |
|
596 | return None | |
594 |
|
597 | |||
595 | magic_escape = self.magic_escape |
|
598 | magic_escape = self.magic_escape | |
596 | magic_prefix = self.magic_prefix |
|
599 | magic_prefix = self.magic_prefix | |
597 |
|
600 | |||
598 | self.lbuf = self.full_lbuf[:self.get_endidx()] |
|
601 | self.lbuf = self.full_lbuf[:self.get_endidx()] | |
599 |
|
602 | |||
600 | try: |
|
603 | try: | |
601 | if text.startswith(magic_escape): |
|
604 | if text.startswith(magic_escape): | |
602 | text = text.replace(magic_escape,magic_prefix) |
|
605 | text = text.replace(magic_escape,magic_prefix) | |
603 | elif text.startswith('~'): |
|
606 | elif text.startswith('~'): | |
604 | text = os.path.expanduser(text) |
|
607 | text = os.path.expanduser(text) | |
605 | if state == 0: |
|
608 | if state == 0: | |
606 | custom_res = self.dispatch_custom_completer(text) |
|
609 | custom_res = self.dispatch_custom_completer(text) | |
607 | if custom_res is not None: |
|
610 | if custom_res is not None: | |
608 | # did custom completers produce something? |
|
611 | # did custom completers produce something? | |
609 | self.matches = custom_res |
|
612 | self.matches = custom_res | |
610 | else: |
|
613 | else: | |
611 | # Extend the list of completions with the results of each |
|
614 | # Extend the list of completions with the results of each | |
612 | # matcher, so we return results to the user from all |
|
615 | # matcher, so we return results to the user from all | |
613 | # namespaces. |
|
616 | # namespaces. | |
614 | if self.merge_completions: |
|
617 | if self.merge_completions: | |
615 | self.matches = [] |
|
618 | self.matches = [] | |
616 | for matcher in self.matchers: |
|
619 | for matcher in self.matchers: | |
617 | self.matches.extend(matcher(text)) |
|
620 | self.matches.extend(matcher(text)) | |
618 | else: |
|
621 | else: | |
619 | for matcher in self.matchers: |
|
622 | for matcher in self.matchers: | |
620 | self.matches = matcher(text) |
|
623 | self.matches = matcher(text) | |
621 | if self.matches: |
|
624 | if self.matches: | |
622 | break |
|
625 | break | |
623 | def uniq(alist): |
|
626 | def uniq(alist): | |
624 | set = {} |
|
627 | set = {} | |
625 | return [set.setdefault(e,e) for e in alist if e not in set] |
|
628 | return [set.setdefault(e,e) for e in alist if e not in set] | |
626 | self.matches = uniq(self.matches) |
|
629 | self.matches = uniq(self.matches) | |
627 | try: |
|
630 | try: | |
628 | ret = self.matches[state].replace(magic_prefix,magic_escape) |
|
631 | ret = self.matches[state].replace(magic_prefix,magic_escape) | |
629 | return ret |
|
632 | return ret | |
630 | except IndexError: |
|
633 | except IndexError: | |
631 | return None |
|
634 | return None | |
632 | except: |
|
635 | except: | |
633 | #from IPython.ultraTB import AutoFormattedTB; # dbg |
|
636 | #from IPython.ultraTB import AutoFormattedTB; # dbg | |
634 | #tb=AutoFormattedTB('Verbose');tb() #dbg |
|
637 | #tb=AutoFormattedTB('Verbose');tb() #dbg | |
635 |
|
638 | |||
636 | # If completion fails, don't annoy the user. |
|
639 | # If completion fails, don't annoy the user. | |
637 | return None |
|
640 | return None |
General Comments 0
You need to be logged in to leave comments.
Login now