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