Show More
@@ -1,1155 +1,1156 b'' | |||||
1 | """Word completion for IPython. |
|
1 | """Word completion for IPython. | |
2 |
|
2 | |||
3 | This module is a fork of the rlcompleter module in the Python standard |
|
3 | This module is a fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
5 | upstream and were accepted as of Python 2.3, but we need a lot more | |
6 | functionality specific to IPython, so this module will continue to live as an |
|
6 | functionality specific to IPython, so this module will continue to live as an | |
7 | IPython-specific utility. |
|
7 | IPython-specific utility. | |
8 |
|
8 | |||
9 | Original rlcompleter documentation: |
|
9 | Original rlcompleter documentation: | |
10 |
|
10 | |||
11 | This requires the latest extension to the readline module (the |
|
11 | This requires the latest extension to the readline module (the | |
12 | completes keywords, built-ins and globals in __main__; when completing |
|
12 | completes keywords, built-ins and globals in __main__; when completing | |
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
14 | completes its attributes. |
|
14 | completes its attributes. | |
15 |
|
15 | |||
16 | It's very cool to do "import string" type "string.", hit the |
|
16 | It's very cool to do "import string" type "string.", hit the | |
17 | completion key (twice), and see the list of names defined by the |
|
17 | completion key (twice), and see the list of names defined by the | |
18 | string module! |
|
18 | string module! | |
19 |
|
19 | |||
20 | Tip: to use the tab key as the completion key, call |
|
20 | Tip: to use the tab key as the completion key, call | |
21 |
|
21 | |||
22 | readline.parse_and_bind("tab: complete") |
|
22 | readline.parse_and_bind("tab: complete") | |
23 |
|
23 | |||
24 | Notes: |
|
24 | Notes: | |
25 |
|
25 | |||
26 | - Exceptions raised by the completer function are *ignored* (and |
|
26 | - Exceptions raised by the completer function are *ignored* (and | |
27 | generally cause the completion to fail). This is a feature -- since |
|
27 | generally cause the completion to fail). This is a feature -- since | |
28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
28 | readline sets the tty device in raw (or cbreak) mode, printing a | |
29 | traceback wouldn't work well without some complicated hoopla to save, |
|
29 | traceback wouldn't work well without some complicated hoopla to save, | |
30 | reset and restore the tty state. |
|
30 | reset and restore the tty state. | |
31 |
|
31 | |||
32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
32 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
33 | application defined code to be executed if an object with a |
|
33 | application defined code to be executed if an object with a | |
34 | ``__getattr__`` hook is found. Since it is the responsibility of the |
|
34 | ``__getattr__`` hook is found. Since it is the responsibility of the | |
35 | application (or the user) to enable this feature, I consider this an |
|
35 | application (or the user) to enable this feature, I consider this an | |
36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
36 | acceptable risk. More complicated expressions (e.g. function calls or | |
37 | indexing operations) are *not* evaluated. |
|
37 | indexing operations) are *not* evaluated. | |
38 |
|
38 | |||
39 | - GNU readline is also used by the built-in functions input() and |
|
39 | - GNU readline is also used by the built-in functions input() and | |
40 | raw_input(), and thus these also benefit/suffer from the completer |
|
40 | raw_input(), and thus these also benefit/suffer from the completer | |
41 | features. Clearly an interactive application can benefit by |
|
41 | features. Clearly an interactive application can benefit by | |
42 | specifying its own completer function and using raw_input() for all |
|
42 | specifying its own completer function and using raw_input() for all | |
43 | its input. |
|
43 | its input. | |
44 |
|
44 | |||
45 | - When the original stdin is not a tty device, GNU readline is never |
|
45 | - When the original stdin is not a tty device, GNU readline is never | |
46 | used, and this module (and the readline module) are silently inactive. |
|
46 | used, and this module (and the readline module) are silently inactive. | |
47 | """ |
|
47 | """ | |
48 |
|
48 | |||
49 | #***************************************************************************** |
|
49 | #***************************************************************************** | |
50 | # |
|
50 | # | |
51 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
51 | # Since this file is essentially a minimally modified copy of the rlcompleter | |
52 | # module which is part of the standard Python distribution, I assume that the |
|
52 | # module which is part of the standard Python distribution, I assume that the | |
53 | # proper procedure is to maintain its copyright as belonging to the Python |
|
53 | # proper procedure is to maintain its copyright as belonging to the Python | |
54 | # Software Foundation (in addition to my own, for all new code). |
|
54 | # Software Foundation (in addition to my own, for all new code). | |
55 | # |
|
55 | # | |
56 | # Copyright (C) 2008 IPython Development Team |
|
56 | # Copyright (C) 2008 IPython Development Team | |
57 | # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu> |
|
57 | # Copyright (C) 2001 Fernando Perez. <fperez@colorado.edu> | |
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
59 | # |
|
59 | # | |
60 | # Distributed under the terms of the BSD License. The full license is in |
|
60 | # Distributed under the terms of the BSD License. The full license is in | |
61 | # the file COPYING, distributed as part of this software. |
|
61 | # the file COPYING, distributed as part of this software. | |
62 | # |
|
62 | # | |
63 | #***************************************************************************** |
|
63 | #***************************************************************************** | |
64 |
|
64 | |||
65 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
66 | # Imports |
|
66 | # Imports | |
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 |
|
68 | |||
69 | import __main__ |
|
69 | import __main__ | |
70 | import glob |
|
70 | import glob | |
71 | import inspect |
|
71 | import inspect | |
72 | import itertools |
|
72 | import itertools | |
73 | import keyword |
|
73 | import keyword | |
74 | import os |
|
74 | import os | |
75 | import re |
|
75 | import re | |
76 | import sys |
|
76 | import sys | |
77 |
|
77 | |||
78 | from IPython.config.configurable import Configurable |
|
78 | from IPython.config.configurable import Configurable | |
79 | from IPython.core.error import TryNext |
|
79 | from IPython.core.error import TryNext | |
80 | from IPython.core.inputsplitter import ESC_MAGIC |
|
80 | from IPython.core.inputsplitter import ESC_MAGIC | |
81 | from IPython.utils import generics |
|
81 | from IPython.utils import generics | |
82 | from IPython.utils import io |
|
82 | from IPython.utils import io | |
83 | from IPython.utils.decorators import undoc |
|
83 | from IPython.utils.decorators import undoc | |
84 | from IPython.utils.dir2 import dir2 |
|
84 | from IPython.utils.dir2 import dir2 | |
85 | from IPython.utils.process import arg_split |
|
85 | from IPython.utils.process import arg_split | |
86 | from IPython.utils.py3compat import builtin_mod, string_types |
|
86 | from IPython.utils.py3compat import builtin_mod, string_types | |
87 | from IPython.utils.traitlets import CBool, Enum |
|
87 | from IPython.utils.traitlets import CBool, Enum | |
88 |
|
88 | |||
89 | #----------------------------------------------------------------------------- |
|
89 | #----------------------------------------------------------------------------- | |
90 | # Globals |
|
90 | # Globals | |
91 | #----------------------------------------------------------------------------- |
|
91 | #----------------------------------------------------------------------------- | |
92 |
|
92 | |||
93 | # Public API |
|
93 | # Public API | |
94 | __all__ = ['Completer','IPCompleter'] |
|
94 | __all__ = ['Completer','IPCompleter'] | |
95 |
|
95 | |||
96 | if sys.platform == 'win32': |
|
96 | if sys.platform == 'win32': | |
97 | PROTECTABLES = ' ' |
|
97 | PROTECTABLES = ' ' | |
98 | else: |
|
98 | else: | |
99 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
99 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | #----------------------------------------------------------------------------- |
|
102 | #----------------------------------------------------------------------------- | |
103 | # Main functions and classes |
|
103 | # Main functions and classes | |
104 | #----------------------------------------------------------------------------- |
|
104 | #----------------------------------------------------------------------------- | |
105 |
|
105 | |||
106 | def has_open_quotes(s): |
|
106 | def has_open_quotes(s): | |
107 | """Return whether a string has open quotes. |
|
107 | """Return whether a string has open quotes. | |
108 |
|
108 | |||
109 | This simply counts whether the number of quote characters of either type in |
|
109 | This simply counts whether the number of quote characters of either type in | |
110 | the string is odd. |
|
110 | the string is odd. | |
111 |
|
111 | |||
112 | Returns |
|
112 | Returns | |
113 | ------- |
|
113 | ------- | |
114 | If there is an open quote, the quote character is returned. Else, return |
|
114 | If there is an open quote, the quote character is returned. Else, return | |
115 | False. |
|
115 | False. | |
116 | """ |
|
116 | """ | |
117 | # We check " first, then ', so complex cases with nested quotes will get |
|
117 | # We check " first, then ', so complex cases with nested quotes will get | |
118 | # the " to take precedence. |
|
118 | # the " to take precedence. | |
119 | if s.count('"') % 2: |
|
119 | if s.count('"') % 2: | |
120 | return '"' |
|
120 | return '"' | |
121 | elif s.count("'") % 2: |
|
121 | elif s.count("'") % 2: | |
122 | return "'" |
|
122 | return "'" | |
123 | else: |
|
123 | else: | |
124 | return False |
|
124 | return False | |
125 |
|
125 | |||
126 |
|
126 | |||
127 | def protect_filename(s): |
|
127 | def protect_filename(s): | |
128 | """Escape a string to protect certain characters.""" |
|
128 | """Escape a string to protect certain characters.""" | |
129 |
|
129 | |||
130 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) |
|
130 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) | |
131 | for ch in s]) |
|
131 | for ch in s]) | |
132 |
|
132 | |||
133 | def expand_user(path): |
|
133 | def expand_user(path): | |
134 | """Expand '~'-style usernames in strings. |
|
134 | """Expand '~'-style usernames in strings. | |
135 |
|
135 | |||
136 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
136 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
137 | extra information that will be useful if the input was being used in |
|
137 | extra information that will be useful if the input was being used in | |
138 | computing completions, and you wish to return the completions with the |
|
138 | computing completions, and you wish to return the completions with the | |
139 | original '~' instead of its expanded value. |
|
139 | original '~' instead of its expanded value. | |
140 |
|
140 | |||
141 | Parameters |
|
141 | Parameters | |
142 | ---------- |
|
142 | ---------- | |
143 | path : str |
|
143 | path : str | |
144 | String to be expanded. If no ~ is present, the output is the same as the |
|
144 | String to be expanded. If no ~ is present, the output is the same as the | |
145 | input. |
|
145 | input. | |
146 |
|
146 | |||
147 | Returns |
|
147 | Returns | |
148 | ------- |
|
148 | ------- | |
149 | newpath : str |
|
149 | newpath : str | |
150 | Result of ~ expansion in the input path. |
|
150 | Result of ~ expansion in the input path. | |
151 | tilde_expand : bool |
|
151 | tilde_expand : bool | |
152 | Whether any expansion was performed or not. |
|
152 | Whether any expansion was performed or not. | |
153 | tilde_val : str |
|
153 | tilde_val : str | |
154 | The value that ~ was replaced with. |
|
154 | The value that ~ was replaced with. | |
155 | """ |
|
155 | """ | |
156 | # Default values |
|
156 | # Default values | |
157 | tilde_expand = False |
|
157 | tilde_expand = False | |
158 | tilde_val = '' |
|
158 | tilde_val = '' | |
159 | newpath = path |
|
159 | newpath = path | |
160 |
|
160 | |||
161 | if path.startswith('~'): |
|
161 | if path.startswith('~'): | |
162 | tilde_expand = True |
|
162 | tilde_expand = True | |
163 | rest = len(path)-1 |
|
163 | rest = len(path)-1 | |
164 | newpath = os.path.expanduser(path) |
|
164 | newpath = os.path.expanduser(path) | |
165 | if rest: |
|
165 | if rest: | |
166 | tilde_val = newpath[:-rest] |
|
166 | tilde_val = newpath[:-rest] | |
167 | else: |
|
167 | else: | |
168 | tilde_val = newpath |
|
168 | tilde_val = newpath | |
169 |
|
169 | |||
170 | return newpath, tilde_expand, tilde_val |
|
170 | return newpath, tilde_expand, tilde_val | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | def compress_user(path, tilde_expand, tilde_val): |
|
173 | def compress_user(path, tilde_expand, tilde_val): | |
174 | """Does the opposite of expand_user, with its outputs. |
|
174 | """Does the opposite of expand_user, with its outputs. | |
175 | """ |
|
175 | """ | |
176 | if tilde_expand: |
|
176 | if tilde_expand: | |
177 | return path.replace(tilde_val, '~') |
|
177 | return path.replace(tilde_val, '~') | |
178 | else: |
|
178 | else: | |
179 | return path |
|
179 | return path | |
180 |
|
180 | |||
181 |
|
181 | |||
182 |
|
182 | |||
183 | def penalize_magics_key(word): |
|
183 | def penalize_magics_key(word): | |
184 | """key for sorting that penalizes magic commands in the ordering |
|
184 | """key for sorting that penalizes magic commands in the ordering | |
185 |
|
185 | |||
186 | Normal words are left alone. |
|
186 | Normal words are left alone. | |
187 |
|
187 | |||
188 | Magic commands have the initial % moved to the end, e.g. |
|
188 | Magic commands have the initial % moved to the end, e.g. | |
189 | %matplotlib is transformed as follows: |
|
189 | %matplotlib is transformed as follows: | |
190 |
|
190 | |||
191 | %matplotlib -> matplotlib% |
|
191 | %matplotlib -> matplotlib% | |
192 |
|
192 | |||
193 | [The choice of the final % is arbitrary.] |
|
193 | [The choice of the final % is arbitrary.] | |
194 |
|
194 | |||
195 | Since "matplotlib" < "matplotlib%" as strings, |
|
195 | Since "matplotlib" < "matplotlib%" as strings, | |
196 | "timeit" will appear before the magic "%timeit" in the ordering |
|
196 | "timeit" will appear before the magic "%timeit" in the ordering | |
197 |
|
197 | |||
198 | For consistency, move "%%" to the end, so cell magics appear *after* |
|
198 | For consistency, move "%%" to the end, so cell magics appear *after* | |
199 | line magics with the same name. |
|
199 | line magics with the same name. | |
200 |
|
200 | |||
201 | A check is performed that there are no other "%" in the string; |
|
201 | A check is performed that there are no other "%" in the string; | |
202 | if there are, then the string is not a magic command and is left unchanged. |
|
202 | if there are, then the string is not a magic command and is left unchanged. | |
203 |
|
203 | |||
204 | """ |
|
204 | """ | |
205 |
|
205 | |||
206 | # Move any % signs from start to end of the key |
|
206 | # Move any % signs from start to end of the key | |
207 | # provided there are no others elsewhere in the string |
|
207 | # provided there are no others elsewhere in the string | |
208 |
|
208 | |||
209 | if word[:2] == "%%": |
|
209 | if word[:2] == "%%": | |
210 | if not "%" in word[2:]: |
|
210 | if not "%" in word[2:]: | |
211 | return word[2:] + "%%" |
|
211 | return word[2:] + "%%" | |
212 |
|
212 | |||
213 | if word[:1] == "%": |
|
213 | if word[:1] == "%": | |
214 | if not "%" in word[1:]: |
|
214 | if not "%" in word[1:]: | |
215 | return word[1:] + "%" |
|
215 | return word[1:] + "%" | |
216 |
|
216 | |||
217 | return word |
|
217 | return word | |
218 |
|
218 | |||
219 |
|
219 | |||
220 | @undoc |
|
220 | @undoc | |
221 | class Bunch(object): pass |
|
221 | class Bunch(object): pass | |
222 |
|
222 | |||
223 |
|
223 | |||
224 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
224 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
225 | GREEDY_DELIMS = ' =\r\n' |
|
225 | GREEDY_DELIMS = ' =\r\n' | |
226 |
|
226 | |||
227 |
|
227 | |||
228 | class CompletionSplitter(object): |
|
228 | class CompletionSplitter(object): | |
229 | """An object to split an input line in a manner similar to readline. |
|
229 | """An object to split an input line in a manner similar to readline. | |
230 |
|
230 | |||
231 | By having our own implementation, we can expose readline-like completion in |
|
231 | By having our own implementation, we can expose readline-like completion in | |
232 | a uniform manner to all frontends. This object only needs to be given the |
|
232 | a uniform manner to all frontends. This object only needs to be given the | |
233 | line of text to be split and the cursor position on said line, and it |
|
233 | line of text to be split and the cursor position on said line, and it | |
234 | returns the 'word' to be completed on at the cursor after splitting the |
|
234 | returns the 'word' to be completed on at the cursor after splitting the | |
235 | entire line. |
|
235 | entire line. | |
236 |
|
236 | |||
237 | What characters are used as splitting delimiters can be controlled by |
|
237 | What characters are used as splitting delimiters can be controlled by | |
238 | setting the `delims` attribute (this is a property that internally |
|
238 | setting the `delims` attribute (this is a property that internally | |
239 | automatically builds the necessary regular expression)""" |
|
239 | automatically builds the necessary regular expression)""" | |
240 |
|
240 | |||
241 | # Private interface |
|
241 | # Private interface | |
242 |
|
242 | |||
243 | # A string of delimiter characters. The default value makes sense for |
|
243 | # A string of delimiter characters. The default value makes sense for | |
244 | # IPython's most typical usage patterns. |
|
244 | # IPython's most typical usage patterns. | |
245 | _delims = DELIMS |
|
245 | _delims = DELIMS | |
246 |
|
246 | |||
247 | # The expression (a normal string) to be compiled into a regular expression |
|
247 | # The expression (a normal string) to be compiled into a regular expression | |
248 | # for actual splitting. We store it as an attribute mostly for ease of |
|
248 | # for actual splitting. We store it as an attribute mostly for ease of | |
249 | # debugging, since this type of code can be so tricky to debug. |
|
249 | # debugging, since this type of code can be so tricky to debug. | |
250 | _delim_expr = None |
|
250 | _delim_expr = None | |
251 |
|
251 | |||
252 | # The regular expression that does the actual splitting |
|
252 | # The regular expression that does the actual splitting | |
253 | _delim_re = None |
|
253 | _delim_re = None | |
254 |
|
254 | |||
255 | def __init__(self, delims=None): |
|
255 | def __init__(self, delims=None): | |
256 | delims = CompletionSplitter._delims if delims is None else delims |
|
256 | delims = CompletionSplitter._delims if delims is None else delims | |
257 | self.delims = delims |
|
257 | self.delims = delims | |
258 |
|
258 | |||
259 | @property |
|
259 | @property | |
260 | def delims(self): |
|
260 | def delims(self): | |
261 | """Return the string of delimiter characters.""" |
|
261 | """Return the string of delimiter characters.""" | |
262 | return self._delims |
|
262 | return self._delims | |
263 |
|
263 | |||
264 | @delims.setter |
|
264 | @delims.setter | |
265 | def delims(self, delims): |
|
265 | def delims(self, delims): | |
266 | """Set the delimiters for line splitting.""" |
|
266 | """Set the delimiters for line splitting.""" | |
267 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
267 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
268 | self._delim_re = re.compile(expr) |
|
268 | self._delim_re = re.compile(expr) | |
269 | self._delims = delims |
|
269 | self._delims = delims | |
270 | self._delim_expr = expr |
|
270 | self._delim_expr = expr | |
271 |
|
271 | |||
272 | def split_line(self, line, cursor_pos=None): |
|
272 | def split_line(self, line, cursor_pos=None): | |
273 | """Split a line of text with a cursor at the given position. |
|
273 | """Split a line of text with a cursor at the given position. | |
274 | """ |
|
274 | """ | |
275 | l = line if cursor_pos is None else line[:cursor_pos] |
|
275 | l = line if cursor_pos is None else line[:cursor_pos] | |
276 | return self._delim_re.split(l)[-1] |
|
276 | return self._delim_re.split(l)[-1] | |
277 |
|
277 | |||
278 |
|
278 | |||
279 | class Completer(Configurable): |
|
279 | class Completer(Configurable): | |
280 |
|
280 | |||
281 | greedy = CBool(False, config=True, |
|
281 | greedy = CBool(False, config=True, | |
282 | help="""Activate greedy completion |
|
282 | help="""Activate greedy completion | |
283 |
|
283 | |||
284 | This will enable completion on elements of lists, results of function calls, etc., |
|
284 | This will enable completion on elements of lists, results of function calls, etc., | |
285 | but can be unsafe because the code is actually evaluated on TAB. |
|
285 | but can be unsafe because the code is actually evaluated on TAB. | |
286 | """ |
|
286 | """ | |
287 | ) |
|
287 | ) | |
288 |
|
288 | |||
289 |
|
289 | |||
290 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
290 | def __init__(self, namespace=None, global_namespace=None, **kwargs): | |
291 | """Create a new completer for the command line. |
|
291 | """Create a new completer for the command line. | |
292 |
|
292 | |||
293 | Completer(namespace=ns,global_namespace=ns2) -> completer instance. |
|
293 | Completer(namespace=ns,global_namespace=ns2) -> completer instance. | |
294 |
|
294 | |||
295 | If unspecified, the default namespace where completions are performed |
|
295 | If unspecified, the default namespace where completions are performed | |
296 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
296 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
297 | given as dictionaries. |
|
297 | given as dictionaries. | |
298 |
|
298 | |||
299 | An optional second namespace can be given. This allows the completer |
|
299 | An optional second namespace can be given. This allows the completer | |
300 | to handle cases where both the local and global scopes need to be |
|
300 | to handle cases where both the local and global scopes need to be | |
301 | distinguished. |
|
301 | distinguished. | |
302 |
|
302 | |||
303 | Completer instances should be used as the completion mechanism of |
|
303 | Completer instances should be used as the completion mechanism of | |
304 | readline via the set_completer() call: |
|
304 | readline via the set_completer() call: | |
305 |
|
305 | |||
306 | readline.set_completer(Completer(my_namespace).complete) |
|
306 | readline.set_completer(Completer(my_namespace).complete) | |
307 | """ |
|
307 | """ | |
308 |
|
308 | |||
309 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
309 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
310 | # specific namespace or to use __main__.__dict__. This will allow us |
|
310 | # specific namespace or to use __main__.__dict__. This will allow us | |
311 | # to bind to __main__.__dict__ at completion time, not now. |
|
311 | # to bind to __main__.__dict__ at completion time, not now. | |
312 | if namespace is None: |
|
312 | if namespace is None: | |
313 | self.use_main_ns = 1 |
|
313 | self.use_main_ns = 1 | |
314 | else: |
|
314 | else: | |
315 | self.use_main_ns = 0 |
|
315 | self.use_main_ns = 0 | |
316 | self.namespace = namespace |
|
316 | self.namespace = namespace | |
317 |
|
317 | |||
318 | # The global namespace, if given, can be bound directly |
|
318 | # The global namespace, if given, can be bound directly | |
319 | if global_namespace is None: |
|
319 | if global_namespace is None: | |
320 | self.global_namespace = {} |
|
320 | self.global_namespace = {} | |
321 | else: |
|
321 | else: | |
322 | self.global_namespace = global_namespace |
|
322 | self.global_namespace = global_namespace | |
323 |
|
323 | |||
324 | super(Completer, self).__init__(**kwargs) |
|
324 | super(Completer, self).__init__(**kwargs) | |
325 |
|
325 | |||
326 | def complete(self, text, state): |
|
326 | def complete(self, text, state): | |
327 | """Return the next possible completion for 'text'. |
|
327 | """Return the next possible completion for 'text'. | |
328 |
|
328 | |||
329 | This is called successively with state == 0, 1, 2, ... until it |
|
329 | This is called successively with state == 0, 1, 2, ... until it | |
330 | returns None. The completion should begin with 'text'. |
|
330 | returns None. The completion should begin with 'text'. | |
331 |
|
331 | |||
332 | """ |
|
332 | """ | |
333 | if self.use_main_ns: |
|
333 | if self.use_main_ns: | |
334 | self.namespace = __main__.__dict__ |
|
334 | self.namespace = __main__.__dict__ | |
335 |
|
335 | |||
336 | if state == 0: |
|
336 | if state == 0: | |
337 | if "." in text: |
|
337 | if "." in text: | |
338 | self.matches = self.attr_matches(text) |
|
338 | self.matches = self.attr_matches(text) | |
339 | else: |
|
339 | else: | |
340 | self.matches = self.global_matches(text) |
|
340 | self.matches = self.global_matches(text) | |
341 | try: |
|
341 | try: | |
342 | return self.matches[state] |
|
342 | return self.matches[state] | |
343 | except IndexError: |
|
343 | except IndexError: | |
344 | return None |
|
344 | return None | |
345 |
|
345 | |||
346 | def global_matches(self, text): |
|
346 | def global_matches(self, text): | |
347 | """Compute matches when text is a simple name. |
|
347 | """Compute matches when text is a simple name. | |
348 |
|
348 | |||
349 | Return a list of all keywords, built-in functions and names currently |
|
349 | Return a list of all keywords, built-in functions and names currently | |
350 | defined in self.namespace or self.global_namespace that match. |
|
350 | defined in self.namespace or self.global_namespace that match. | |
351 |
|
351 | |||
352 | """ |
|
352 | """ | |
353 | #print 'Completer->global_matches, txt=%r' % text # dbg |
|
353 | #print 'Completer->global_matches, txt=%r' % text # dbg | |
354 | matches = [] |
|
354 | matches = [] | |
355 | match_append = matches.append |
|
355 | match_append = matches.append | |
356 | n = len(text) |
|
356 | n = len(text) | |
357 | for lst in [keyword.kwlist, |
|
357 | for lst in [keyword.kwlist, | |
358 | builtin_mod.__dict__.keys(), |
|
358 | builtin_mod.__dict__.keys(), | |
359 | self.namespace.keys(), |
|
359 | self.namespace.keys(), | |
360 | self.global_namespace.keys()]: |
|
360 | self.global_namespace.keys()]: | |
361 | for word in lst: |
|
361 | for word in lst: | |
362 | if word[:n] == text and word != "__builtins__": |
|
362 | if word[:n] == text and word != "__builtins__": | |
363 | match_append(word) |
|
363 | match_append(word) | |
364 | return matches |
|
364 | return matches | |
365 |
|
365 | |||
366 | def attr_matches(self, text): |
|
366 | def attr_matches(self, text): | |
367 | """Compute matches when text contains a dot. |
|
367 | """Compute matches when text contains a dot. | |
368 |
|
368 | |||
369 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
369 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
370 | evaluatable in self.namespace or self.global_namespace, it will be |
|
370 | evaluatable in self.namespace or self.global_namespace, it will be | |
371 | evaluated and its attributes (as revealed by dir()) are used as |
|
371 | evaluated and its attributes (as revealed by dir()) are used as | |
372 | possible completions. (For class instances, class members are are |
|
372 | possible completions. (For class instances, class members are are | |
373 | also considered.) |
|
373 | also considered.) | |
374 |
|
374 | |||
375 | WARNING: this can still invoke arbitrary C code, if an object |
|
375 | WARNING: this can still invoke arbitrary C code, if an object | |
376 | with a __getattr__ hook is evaluated. |
|
376 | with a __getattr__ hook is evaluated. | |
377 |
|
377 | |||
378 | """ |
|
378 | """ | |
379 |
|
379 | |||
380 | #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg |
|
380 | #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg | |
381 | # Another option, seems to work great. Catches things like ''.<tab> |
|
381 | # Another option, seems to work great. Catches things like ''.<tab> | |
382 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
382 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
383 |
|
383 | |||
384 | if m: |
|
384 | if m: | |
385 | expr, attr = m.group(1, 3) |
|
385 | expr, attr = m.group(1, 3) | |
386 | elif self.greedy: |
|
386 | elif self.greedy: | |
387 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
387 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) | |
388 | if not m2: |
|
388 | if not m2: | |
389 | return [] |
|
389 | return [] | |
390 | expr, attr = m2.group(1,2) |
|
390 | expr, attr = m2.group(1,2) | |
391 | else: |
|
391 | else: | |
392 | return [] |
|
392 | return [] | |
393 |
|
393 | |||
394 | try: |
|
394 | try: | |
395 | obj = eval(expr, self.namespace) |
|
395 | obj = eval(expr, self.namespace) | |
396 | except: |
|
396 | except: | |
397 | try: |
|
397 | try: | |
398 | obj = eval(expr, self.global_namespace) |
|
398 | obj = eval(expr, self.global_namespace) | |
399 | except: |
|
399 | except: | |
400 | return [] |
|
400 | return [] | |
401 |
|
401 | |||
402 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
402 | if self.limit_to__all__ and hasattr(obj, '__all__'): | |
403 | words = get__all__entries(obj) |
|
403 | words = get__all__entries(obj) | |
404 | else: |
|
404 | else: | |
405 | words = dir2(obj) |
|
405 | words = dir2(obj) | |
406 |
|
406 | |||
407 | try: |
|
407 | try: | |
408 | words = generics.complete_object(obj, words) |
|
408 | words = generics.complete_object(obj, words) | |
409 | except TryNext: |
|
409 | except TryNext: | |
410 | pass |
|
410 | pass | |
411 | except Exception: |
|
411 | except Exception: | |
412 | # Silence errors from completion function |
|
412 | # Silence errors from completion function | |
413 | #raise # dbg |
|
413 | #raise # dbg | |
414 | pass |
|
414 | pass | |
415 | # Build match list to return |
|
415 | # Build match list to return | |
416 | n = len(attr) |
|
416 | n = len(attr) | |
417 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
417 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
418 | return res |
|
418 | return res | |
419 |
|
419 | |||
420 |
|
420 | |||
421 | def get__all__entries(obj): |
|
421 | def get__all__entries(obj): | |
422 | """returns the strings in the __all__ attribute""" |
|
422 | """returns the strings in the __all__ attribute""" | |
423 | try: |
|
423 | try: | |
424 | words = getattr(obj, '__all__') |
|
424 | words = getattr(obj, '__all__') | |
425 | except: |
|
425 | except: | |
426 | return [] |
|
426 | return [] | |
427 |
|
427 | |||
428 | return [w for w in words if isinstance(w, string_types)] |
|
428 | return [w for w in words if isinstance(w, string_types)] | |
429 |
|
429 | |||
430 |
|
430 | |||
431 | def match_dict_keys(keys, prefix): |
|
431 | def match_dict_keys(keys, prefix): | |
432 | """Used by dict_key_matches, matching the prefix to a list of keys""" |
|
432 | """Used by dict_key_matches, matching the prefix to a list of keys""" | |
433 | if not prefix: |
|
433 | if not prefix: | |
434 | return None, 0, [repr(k) for k in keys |
|
434 | return None, 0, [repr(k) for k in keys | |
435 | if isinstance(k, (string_types, bytes))] |
|
435 | if isinstance(k, (string_types, bytes))] | |
436 | quote_match = re.search('["\']', prefix) |
|
436 | quote_match = re.search('["\']', prefix) | |
437 | quote = quote_match.group() |
|
437 | quote = quote_match.group() | |
438 | try: |
|
438 | try: | |
439 | prefix_str = eval(prefix + quote, {}) |
|
439 | prefix_str = eval(prefix + quote, {}) | |
440 | except Exception: |
|
440 | except Exception: | |
441 | return None, 0, [] |
|
441 | return None, 0, [] | |
442 |
|
442 | |||
443 | token_match = re.search(r'\w*$', prefix, re.UNICODE) |
|
443 | token_match = re.search(r'\w*$', prefix, re.UNICODE) | |
444 | token_start = token_match.start() |
|
444 | token_start = token_match.start() | |
445 | token_prefix = token_match.group() |
|
445 | token_prefix = token_match.group() | |
446 |
|
446 | |||
447 | # TODO: support bytes in Py3k |
|
447 | # TODO: support bytes in Py3k | |
448 | matched = [] |
|
448 | matched = [] | |
449 | for key in keys: |
|
449 | for key in keys: | |
450 | try: |
|
450 | try: | |
451 | if not key.startswith(prefix_str): |
|
451 | if not key.startswith(prefix_str): | |
452 | continue |
|
452 | continue | |
453 | except (AttributeError, TypeError, UnicodeError): |
|
453 | except (AttributeError, TypeError, UnicodeError): | |
454 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
454 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa | |
455 | continue |
|
455 | continue | |
456 |
|
456 | |||
457 | # reformat remainder of key to begin with prefix |
|
457 | # reformat remainder of key to begin with prefix | |
458 | rem = key[len(prefix_str):] |
|
458 | rem = key[len(prefix_str):] | |
459 | # force repr wrapped in ' |
|
459 | # force repr wrapped in ' | |
460 | rem_repr = repr(rem + '"') |
|
460 | rem_repr = repr(rem + '"') | |
461 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
461 | if rem_repr.startswith('u') and prefix[0] not in 'uU': | |
462 | # Found key is unicode, but prefix is Py2 string. |
|
462 | # Found key is unicode, but prefix is Py2 string. | |
463 | # Therefore attempt to interpret key as string. |
|
463 | # Therefore attempt to interpret key as string. | |
464 | try: |
|
464 | try: | |
465 | rem_repr = repr(rem.encode('ascii') + '"') |
|
465 | rem_repr = repr(rem.encode('ascii') + '"') | |
466 | except UnicodeEncodeError: |
|
466 | except UnicodeEncodeError: | |
467 | continue |
|
467 | continue | |
468 |
|
468 | |||
469 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
469 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] | |
470 | if quote == '"': |
|
470 | if quote == '"': | |
471 | # The entered prefix is quoted with ", |
|
471 | # The entered prefix is quoted with ", | |
472 | # but the match is quoted with '. |
|
472 | # but the match is quoted with '. | |
473 | # A contained " hence needs escaping for comparison: |
|
473 | # A contained " hence needs escaping for comparison: | |
474 | rem_repr = rem_repr.replace('"', '\\"') |
|
474 | rem_repr = rem_repr.replace('"', '\\"') | |
475 |
|
475 | |||
476 | # then reinsert prefix from start of token |
|
476 | # then reinsert prefix from start of token | |
477 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
477 | matched.append('%s%s' % (token_prefix, rem_repr)) | |
478 | return quote, token_start, matched |
|
478 | return quote, token_start, matched | |
479 |
|
479 | |||
480 |
|
480 | |||
481 | def _safe_isinstance(obj, module, class_name): |
|
481 | def _safe_isinstance(obj, module, class_name): | |
482 | """Checks if obj is an instance of module.class_name if loaded |
|
482 | """Checks if obj is an instance of module.class_name if loaded | |
483 | """ |
|
483 | """ | |
484 | return (module in sys.modules and |
|
484 | return (module in sys.modules and | |
485 | isinstance(obj, getattr(__import__(module), class_name))) |
|
485 | isinstance(obj, getattr(__import__(module), class_name))) | |
486 |
|
486 | |||
487 |
|
487 | |||
488 |
|
488 | |||
489 | class IPCompleter(Completer): |
|
489 | class IPCompleter(Completer): | |
490 | """Extension of the completer class with IPython-specific features""" |
|
490 | """Extension of the completer class with IPython-specific features""" | |
491 |
|
491 | |||
492 | def _greedy_changed(self, name, old, new): |
|
492 | def _greedy_changed(self, name, old, new): | |
493 | """update the splitter and readline delims when greedy is changed""" |
|
493 | """update the splitter and readline delims when greedy is changed""" | |
494 | if new: |
|
494 | if new: | |
495 | self.splitter.delims = GREEDY_DELIMS |
|
495 | self.splitter.delims = GREEDY_DELIMS | |
496 | else: |
|
496 | else: | |
497 | self.splitter.delims = DELIMS |
|
497 | self.splitter.delims = DELIMS | |
498 |
|
498 | |||
499 | if self.readline: |
|
499 | if self.readline: | |
500 | self.readline.set_completer_delims(self.splitter.delims) |
|
500 | self.readline.set_completer_delims(self.splitter.delims) | |
501 |
|
501 | |||
502 | merge_completions = CBool(True, config=True, |
|
502 | merge_completions = CBool(True, config=True, | |
503 | help="""Whether to merge completion results into a single list |
|
503 | help="""Whether to merge completion results into a single list | |
504 |
|
504 | |||
505 | If False, only the completion results from the first non-empty |
|
505 | If False, only the completion results from the first non-empty | |
506 | completer will be returned. |
|
506 | completer will be returned. | |
507 | """ |
|
507 | """ | |
508 | ) |
|
508 | ) | |
509 | omit__names = Enum((0,1,2), default_value=2, config=True, |
|
509 | omit__names = Enum((0,1,2), default_value=2, config=True, | |
510 | help="""Instruct the completer to omit private method names |
|
510 | help="""Instruct the completer to omit private method names | |
511 |
|
511 | |||
512 | Specifically, when completing on ``object.<tab>``. |
|
512 | Specifically, when completing on ``object.<tab>``. | |
513 |
|
513 | |||
514 | When 2 [default]: all names that start with '_' will be excluded. |
|
514 | When 2 [default]: all names that start with '_' will be excluded. | |
515 |
|
515 | |||
516 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
516 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
517 |
|
517 | |||
518 | When 0: nothing will be excluded. |
|
518 | When 0: nothing will be excluded. | |
519 | """ |
|
519 | """ | |
520 | ) |
|
520 | ) | |
521 | limit_to__all__ = CBool(default_value=False, config=True, |
|
521 | limit_to__all__ = CBool(default_value=False, config=True, | |
522 | help="""Instruct the completer to use __all__ for the completion |
|
522 | help="""Instruct the completer to use __all__ for the completion | |
523 |
|
523 | |||
524 | Specifically, when completing on ``object.<tab>``. |
|
524 | Specifically, when completing on ``object.<tab>``. | |
525 |
|
525 | |||
526 | When True: only those names in obj.__all__ will be included. |
|
526 | When True: only those names in obj.__all__ will be included. | |
527 |
|
527 | |||
528 | When False [default]: the __all__ attribute is ignored |
|
528 | When False [default]: the __all__ attribute is ignored | |
529 | """ |
|
529 | """ | |
530 | ) |
|
530 | ) | |
531 |
|
531 | |||
532 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
532 | def __init__(self, shell=None, namespace=None, global_namespace=None, | |
533 | use_readline=True, config=None, **kwargs): |
|
533 | use_readline=True, config=None, **kwargs): | |
534 | """IPCompleter() -> completer |
|
534 | """IPCompleter() -> completer | |
535 |
|
535 | |||
536 | Return a completer object suitable for use by the readline library |
|
536 | Return a completer object suitable for use by the readline library | |
537 | via readline.set_completer(). |
|
537 | via readline.set_completer(). | |
538 |
|
538 | |||
539 | Inputs: |
|
539 | Inputs: | |
540 |
|
540 | |||
541 | - shell: a pointer to the ipython shell itself. This is needed |
|
541 | - shell: a pointer to the ipython shell itself. This is needed | |
542 | because this completer knows about magic functions, and those can |
|
542 | because this completer knows about magic functions, and those can | |
543 | only be accessed via the ipython instance. |
|
543 | only be accessed via the ipython instance. | |
544 |
|
544 | |||
545 | - namespace: an optional dict where completions are performed. |
|
545 | - namespace: an optional dict where completions are performed. | |
546 |
|
546 | |||
547 | - global_namespace: secondary optional dict for completions, to |
|
547 | - global_namespace: secondary optional dict for completions, to | |
548 | handle cases (such as IPython embedded inside functions) where |
|
548 | handle cases (such as IPython embedded inside functions) where | |
549 | both Python scopes are visible. |
|
549 | both Python scopes are visible. | |
550 |
|
550 | |||
551 | use_readline : bool, optional |
|
551 | use_readline : bool, optional | |
552 | If true, use the readline library. This completer can still function |
|
552 | If true, use the readline library. This completer can still function | |
553 | without readline, though in that case callers must provide some extra |
|
553 | without readline, though in that case callers must provide some extra | |
554 | information on each call about the current line.""" |
|
554 | information on each call about the current line.""" | |
555 |
|
555 | |||
556 | self.magic_escape = ESC_MAGIC |
|
556 | self.magic_escape = ESC_MAGIC | |
557 | self.splitter = CompletionSplitter() |
|
557 | self.splitter = CompletionSplitter() | |
558 |
|
558 | |||
559 | # Readline configuration, only used by the rlcompleter method. |
|
559 | # Readline configuration, only used by the rlcompleter method. | |
560 | if use_readline: |
|
560 | if use_readline: | |
561 | # We store the right version of readline so that later code |
|
561 | # We store the right version of readline so that later code | |
562 | import IPython.utils.rlineimpl as readline |
|
562 | import IPython.utils.rlineimpl as readline | |
563 | self.readline = readline |
|
563 | self.readline = readline | |
564 | else: |
|
564 | else: | |
565 | self.readline = None |
|
565 | self.readline = None | |
566 |
|
566 | |||
567 | # _greedy_changed() depends on splitter and readline being defined: |
|
567 | # _greedy_changed() depends on splitter and readline being defined: | |
568 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
568 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, | |
569 | config=config, **kwargs) |
|
569 | config=config, **kwargs) | |
570 |
|
570 | |||
571 | # List where completion matches will be stored |
|
571 | # List where completion matches will be stored | |
572 | self.matches = [] |
|
572 | self.matches = [] | |
573 | self.shell = shell |
|
573 | self.shell = shell | |
574 | # Regexp to split filenames with spaces in them |
|
574 | # Regexp to split filenames with spaces in them | |
575 | self.space_name_re = re.compile(r'([^\\] )') |
|
575 | self.space_name_re = re.compile(r'([^\\] )') | |
576 | # Hold a local ref. to glob.glob for speed |
|
576 | # Hold a local ref. to glob.glob for speed | |
577 | self.glob = glob.glob |
|
577 | self.glob = glob.glob | |
578 |
|
578 | |||
579 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
579 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
580 | # buffers, to avoid completion problems. |
|
580 | # buffers, to avoid completion problems. | |
581 | term = os.environ.get('TERM','xterm') |
|
581 | term = os.environ.get('TERM','xterm') | |
582 | self.dumb_terminal = term in ['dumb','emacs'] |
|
582 | self.dumb_terminal = term in ['dumb','emacs'] | |
583 |
|
583 | |||
584 | # Special handling of backslashes needed in win32 platforms |
|
584 | # Special handling of backslashes needed in win32 platforms | |
585 | if sys.platform == "win32": |
|
585 | if sys.platform == "win32": | |
586 | self.clean_glob = self._clean_glob_win32 |
|
586 | self.clean_glob = self._clean_glob_win32 | |
587 | else: |
|
587 | else: | |
588 | self.clean_glob = self._clean_glob |
|
588 | self.clean_glob = self._clean_glob | |
589 |
|
589 | |||
590 | #regexp to parse docstring for function signature |
|
590 | #regexp to parse docstring for function signature | |
591 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
591 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
592 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
592 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
593 | #use this if positional argument name is also needed |
|
593 | #use this if positional argument name is also needed | |
594 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
594 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') | |
595 |
|
595 | |||
596 | # All active matcher routines for completion |
|
596 | # All active matcher routines for completion | |
597 | self.matchers = [self.python_matches, |
|
597 | self.matchers = [self.python_matches, | |
598 | self.file_matches, |
|
598 | self.file_matches, | |
599 | self.magic_matches, |
|
599 | self.magic_matches, | |
600 | self.python_func_kw_matches, |
|
600 | self.python_func_kw_matches, | |
601 | self.dict_key_matches, |
|
601 | self.dict_key_matches, | |
602 | ] |
|
602 | ] | |
603 |
|
603 | |||
604 | def all_completions(self, text): |
|
604 | def all_completions(self, text): | |
605 | """ |
|
605 | """ | |
606 | Wrapper around the complete method for the benefit of emacs |
|
606 | Wrapper around the complete method for the benefit of emacs | |
607 | and pydb. |
|
607 | and pydb. | |
608 | """ |
|
608 | """ | |
609 | return self.complete(text)[1] |
|
609 | return self.complete(text)[1] | |
610 |
|
610 | |||
611 | def _clean_glob(self,text): |
|
611 | def _clean_glob(self,text): | |
612 | return self.glob("%s*" % text) |
|
612 | return self.glob("%s*" % text) | |
613 |
|
613 | |||
614 | def _clean_glob_win32(self,text): |
|
614 | def _clean_glob_win32(self,text): | |
615 | return [f.replace("\\","/") |
|
615 | return [f.replace("\\","/") | |
616 | for f in self.glob("%s*" % text)] |
|
616 | for f in self.glob("%s*" % text)] | |
617 |
|
617 | |||
618 | def file_matches(self, text): |
|
618 | def file_matches(self, text): | |
619 | """Match filenames, expanding ~USER type strings. |
|
619 | """Match filenames, expanding ~USER type strings. | |
620 |
|
620 | |||
621 | Most of the seemingly convoluted logic in this completer is an |
|
621 | Most of the seemingly convoluted logic in this completer is an | |
622 | attempt to handle filenames with spaces in them. And yet it's not |
|
622 | attempt to handle filenames with spaces in them. And yet it's not | |
623 | quite perfect, because Python's readline doesn't expose all of the |
|
623 | quite perfect, because Python's readline doesn't expose all of the | |
624 | GNU readline details needed for this to be done correctly. |
|
624 | GNU readline details needed for this to be done correctly. | |
625 |
|
625 | |||
626 | For a filename with a space in it, the printed completions will be |
|
626 | For a filename with a space in it, the printed completions will be | |
627 | only the parts after what's already been typed (instead of the |
|
627 | only the parts after what's already been typed (instead of the | |
628 | full completions, as is normally done). I don't think with the |
|
628 | full completions, as is normally done). I don't think with the | |
629 | current (as of Python 2.3) Python readline it's possible to do |
|
629 | current (as of Python 2.3) Python readline it's possible to do | |
630 | better.""" |
|
630 | better.""" | |
631 |
|
631 | |||
632 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg |
|
632 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg | |
633 |
|
633 | |||
634 | # chars that require escaping with backslash - i.e. chars |
|
634 | # chars that require escaping with backslash - i.e. chars | |
635 | # that readline treats incorrectly as delimiters, but we |
|
635 | # that readline treats incorrectly as delimiters, but we | |
636 | # don't want to treat as delimiters in filename matching |
|
636 | # don't want to treat as delimiters in filename matching | |
637 | # when escaped with backslash |
|
637 | # when escaped with backslash | |
638 | if text.startswith('!'): |
|
638 | if text.startswith('!'): | |
639 | text = text[1:] |
|
639 | text = text[1:] | |
640 | text_prefix = '!' |
|
640 | text_prefix = '!' | |
641 | else: |
|
641 | else: | |
642 | text_prefix = '' |
|
642 | text_prefix = '' | |
643 |
|
643 | |||
644 | text_until_cursor = self.text_until_cursor |
|
644 | text_until_cursor = self.text_until_cursor | |
645 | # track strings with open quotes |
|
645 | # track strings with open quotes | |
646 | open_quotes = has_open_quotes(text_until_cursor) |
|
646 | open_quotes = has_open_quotes(text_until_cursor) | |
647 |
|
647 | |||
648 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
648 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
649 | lsplit = text |
|
649 | lsplit = text | |
650 | else: |
|
650 | else: | |
651 | try: |
|
651 | try: | |
652 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
652 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
653 | lsplit = arg_split(text_until_cursor)[-1] |
|
653 | lsplit = arg_split(text_until_cursor)[-1] | |
654 | except ValueError: |
|
654 | except ValueError: | |
655 | # typically an unmatched ", or backslash without escaped char. |
|
655 | # typically an unmatched ", or backslash without escaped char. | |
656 | if open_quotes: |
|
656 | if open_quotes: | |
657 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
657 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
658 | else: |
|
658 | else: | |
659 | return [] |
|
659 | return [] | |
660 | except IndexError: |
|
660 | except IndexError: | |
661 | # tab pressed on empty line |
|
661 | # tab pressed on empty line | |
662 | lsplit = "" |
|
662 | lsplit = "" | |
663 |
|
663 | |||
664 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
664 | if not open_quotes and lsplit != protect_filename(lsplit): | |
665 | # if protectables are found, do matching on the whole escaped name |
|
665 | # if protectables are found, do matching on the whole escaped name | |
666 | has_protectables = True |
|
666 | has_protectables = True | |
667 | text0,text = text,lsplit |
|
667 | text0,text = text,lsplit | |
668 | else: |
|
668 | else: | |
669 | has_protectables = False |
|
669 | has_protectables = False | |
670 | text = os.path.expanduser(text) |
|
670 | text = os.path.expanduser(text) | |
671 |
|
671 | |||
672 | if text == "": |
|
672 | if text == "": | |
673 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
673 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
674 |
|
674 | |||
675 | # Compute the matches from the filesystem |
|
675 | # Compute the matches from the filesystem | |
676 | m0 = self.clean_glob(text.replace('\\','')) |
|
676 | m0 = self.clean_glob(text.replace('\\','')) | |
677 |
|
677 | |||
678 | if has_protectables: |
|
678 | if has_protectables: | |
679 | # If we had protectables, we need to revert our changes to the |
|
679 | # If we had protectables, we need to revert our changes to the | |
680 | # beginning of filename so that we don't double-write the part |
|
680 | # beginning of filename so that we don't double-write the part | |
681 | # of the filename we have so far |
|
681 | # of the filename we have so far | |
682 | len_lsplit = len(lsplit) |
|
682 | len_lsplit = len(lsplit) | |
683 | matches = [text_prefix + text0 + |
|
683 | matches = [text_prefix + text0 + | |
684 | protect_filename(f[len_lsplit:]) for f in m0] |
|
684 | protect_filename(f[len_lsplit:]) for f in m0] | |
685 | else: |
|
685 | else: | |
686 | if open_quotes: |
|
686 | if open_quotes: | |
687 | # if we have a string with an open quote, we don't need to |
|
687 | # if we have a string with an open quote, we don't need to | |
688 | # protect the names at all (and we _shouldn't_, as it |
|
688 | # protect the names at all (and we _shouldn't_, as it | |
689 | # would cause bugs when the filesystem call is made). |
|
689 | # would cause bugs when the filesystem call is made). | |
690 | matches = m0 |
|
690 | matches = m0 | |
691 | else: |
|
691 | else: | |
692 | matches = [text_prefix + |
|
692 | matches = [text_prefix + | |
693 | protect_filename(f) for f in m0] |
|
693 | protect_filename(f) for f in m0] | |
694 |
|
694 | |||
695 | #io.rprint('mm', matches) # dbg |
|
695 | #io.rprint('mm', matches) # dbg | |
696 |
|
696 | |||
697 | # Mark directories in input list by appending '/' to their names. |
|
697 | # Mark directories in input list by appending '/' to their names. | |
698 | matches = [x+'/' if os.path.isdir(x) else x for x in matches] |
|
698 | matches = [x+'/' if os.path.isdir(x) else x for x in matches] | |
699 | return matches |
|
699 | return matches | |
700 |
|
700 | |||
701 | def magic_matches(self, text): |
|
701 | def magic_matches(self, text): | |
702 | """Match magics""" |
|
702 | """Match magics""" | |
703 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg |
|
703 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg | |
704 | # Get all shell magics now rather than statically, so magics loaded at |
|
704 | # Get all shell magics now rather than statically, so magics loaded at | |
705 | # runtime show up too. |
|
705 | # runtime show up too. | |
706 | lsm = self.shell.magics_manager.lsmagic() |
|
706 | lsm = self.shell.magics_manager.lsmagic() | |
707 | line_magics = lsm['line'] |
|
707 | line_magics = lsm['line'] | |
708 | cell_magics = lsm['cell'] |
|
708 | cell_magics = lsm['cell'] | |
709 | pre = self.magic_escape |
|
709 | pre = self.magic_escape | |
710 | pre2 = pre+pre |
|
710 | pre2 = pre+pre | |
711 |
|
711 | |||
712 | # Completion logic: |
|
712 | # Completion logic: | |
713 | # - user gives %%: only do cell magics |
|
713 | # - user gives %%: only do cell magics | |
714 | # - user gives %: do both line and cell magics |
|
714 | # - user gives %: do both line and cell magics | |
715 | # - no prefix: do both |
|
715 | # - no prefix: do both | |
716 | # In other words, line magics are skipped if the user gives %% explicitly |
|
716 | # In other words, line magics are skipped if the user gives %% explicitly | |
717 | bare_text = text.lstrip(pre) |
|
717 | bare_text = text.lstrip(pre) | |
718 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
718 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] | |
719 | if not text.startswith(pre2): |
|
719 | if not text.startswith(pre2): | |
720 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
720 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] | |
721 | return comp |
|
721 | return comp | |
722 |
|
722 | |||
723 | def python_matches(self,text): |
|
723 | def python_matches(self,text): | |
724 | """Match attributes or global python names""" |
|
724 | """Match attributes or global python names""" | |
725 |
|
725 | |||
726 | #io.rprint('Completer->python_matches, txt=%r' % text) # dbg |
|
726 | #io.rprint('Completer->python_matches, txt=%r' % text) # dbg | |
727 | if "." in text: |
|
727 | if "." in text: | |
728 | try: |
|
728 | try: | |
729 | matches = self.attr_matches(text) |
|
729 | matches = self.attr_matches(text) | |
730 | if text.endswith('.') and self.omit__names: |
|
730 | if text.endswith('.') and self.omit__names: | |
731 | if self.omit__names == 1: |
|
731 | if self.omit__names == 1: | |
732 | # true if txt is _not_ a __ name, false otherwise: |
|
732 | # true if txt is _not_ a __ name, false otherwise: | |
733 | no__name = (lambda txt: |
|
733 | no__name = (lambda txt: | |
734 | re.match(r'.*\.__.*?__',txt) is None) |
|
734 | re.match(r'.*\.__.*?__',txt) is None) | |
735 | else: |
|
735 | else: | |
736 | # true if txt is _not_ a _ name, false otherwise: |
|
736 | # true if txt is _not_ a _ name, false otherwise: | |
737 | no__name = (lambda txt: |
|
737 | no__name = (lambda txt: | |
738 | re.match(r'.*\._.*?',txt) is None) |
|
738 | re.match(r'.*\._.*?',txt) is None) | |
739 | matches = filter(no__name, matches) |
|
739 | matches = filter(no__name, matches) | |
740 | except NameError: |
|
740 | except NameError: | |
741 | # catches <undefined attributes>.<tab> |
|
741 | # catches <undefined attributes>.<tab> | |
742 | matches = [] |
|
742 | matches = [] | |
743 | else: |
|
743 | else: | |
744 | matches = self.global_matches(text) |
|
744 | matches = self.global_matches(text) | |
745 |
|
745 | |||
746 | return matches |
|
746 | return matches | |
747 |
|
747 | |||
748 | def _default_arguments_from_docstring(self, doc): |
|
748 | def _default_arguments_from_docstring(self, doc): | |
749 | """Parse the first line of docstring for call signature. |
|
749 | """Parse the first line of docstring for call signature. | |
750 |
|
750 | |||
751 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
751 | Docstring should be of the form 'min(iterable[, key=func])\n'. | |
752 | It can also parse cython docstring of the form |
|
752 | It can also parse cython docstring of the form | |
753 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
753 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. | |
754 | """ |
|
754 | """ | |
755 | if doc is None: |
|
755 | if doc is None: | |
756 | return [] |
|
756 | return [] | |
757 |
|
757 | |||
758 | #care only the firstline |
|
758 | #care only the firstline | |
759 | line = doc.lstrip().splitlines()[0] |
|
759 | line = doc.lstrip().splitlines()[0] | |
760 |
|
760 | |||
761 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
761 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
762 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
762 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' | |
763 | sig = self.docstring_sig_re.search(line) |
|
763 | sig = self.docstring_sig_re.search(line) | |
764 | if sig is None: |
|
764 | if sig is None: | |
765 | return [] |
|
765 | return [] | |
766 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
766 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] | |
767 | sig = sig.groups()[0].split(',') |
|
767 | sig = sig.groups()[0].split(',') | |
768 | ret = [] |
|
768 | ret = [] | |
769 | for s in sig: |
|
769 | for s in sig: | |
770 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
770 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
771 | ret += self.docstring_kwd_re.findall(s) |
|
771 | ret += self.docstring_kwd_re.findall(s) | |
772 | return ret |
|
772 | return ret | |
773 |
|
773 | |||
774 | def _default_arguments(self, obj): |
|
774 | def _default_arguments(self, obj): | |
775 | """Return the list of default arguments of obj if it is callable, |
|
775 | """Return the list of default arguments of obj if it is callable, | |
776 | or empty list otherwise.""" |
|
776 | or empty list otherwise.""" | |
777 | call_obj = obj |
|
777 | call_obj = obj | |
778 | ret = [] |
|
778 | ret = [] | |
779 | if inspect.isbuiltin(obj): |
|
779 | if inspect.isbuiltin(obj): | |
780 | pass |
|
780 | pass | |
781 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
781 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
782 | if inspect.isclass(obj): |
|
782 | if inspect.isclass(obj): | |
783 | #for cython embededsignature=True the constructor docstring |
|
783 | #for cython embededsignature=True the constructor docstring | |
784 | #belongs to the object itself not __init__ |
|
784 | #belongs to the object itself not __init__ | |
785 | ret += self._default_arguments_from_docstring( |
|
785 | ret += self._default_arguments_from_docstring( | |
786 | getattr(obj, '__doc__', '')) |
|
786 | getattr(obj, '__doc__', '')) | |
787 | # for classes, check for __init__,__new__ |
|
787 | # for classes, check for __init__,__new__ | |
788 | call_obj = (getattr(obj, '__init__', None) or |
|
788 | call_obj = (getattr(obj, '__init__', None) or | |
789 | getattr(obj, '__new__', None)) |
|
789 | getattr(obj, '__new__', None)) | |
790 | # for all others, check if they are __call__able |
|
790 | # for all others, check if they are __call__able | |
791 | elif hasattr(obj, '__call__'): |
|
791 | elif hasattr(obj, '__call__'): | |
792 | call_obj = obj.__call__ |
|
792 | call_obj = obj.__call__ | |
793 |
|
793 | |||
794 | ret += self._default_arguments_from_docstring( |
|
794 | ret += self._default_arguments_from_docstring( | |
795 | getattr(call_obj, '__doc__', '')) |
|
795 | getattr(call_obj, '__doc__', '')) | |
796 |
|
796 | |||
797 | try: |
|
797 | try: | |
798 | args,_,_1,defaults = inspect.getargspec(call_obj) |
|
798 | args,_,_1,defaults = inspect.getargspec(call_obj) | |
799 | if defaults: |
|
799 | if defaults: | |
800 | ret+=args[-len(defaults):] |
|
800 | ret+=args[-len(defaults):] | |
801 | except TypeError: |
|
801 | except TypeError: | |
802 | pass |
|
802 | pass | |
803 |
|
803 | |||
804 | return list(set(ret)) |
|
804 | return list(set(ret)) | |
805 |
|
805 | |||
806 | def python_func_kw_matches(self,text): |
|
806 | def python_func_kw_matches(self,text): | |
807 | """Match named parameters (kwargs) of the last open function""" |
|
807 | """Match named parameters (kwargs) of the last open function""" | |
808 |
|
808 | |||
809 | if "." in text: # a parameter cannot be dotted |
|
809 | if "." in text: # a parameter cannot be dotted | |
810 | return [] |
|
810 | return [] | |
811 | try: regexp = self.__funcParamsRegex |
|
811 | try: regexp = self.__funcParamsRegex | |
812 | except AttributeError: |
|
812 | except AttributeError: | |
813 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
813 | regexp = self.__funcParamsRegex = re.compile(r''' | |
814 | '.*?(?<!\\)' | # single quoted strings or |
|
814 | '.*?(?<!\\)' | # single quoted strings or | |
815 | ".*?(?<!\\)" | # double quoted strings or |
|
815 | ".*?(?<!\\)" | # double quoted strings or | |
816 | \w+ | # identifier |
|
816 | \w+ | # identifier | |
817 | \S # other characters |
|
817 | \S # other characters | |
818 | ''', re.VERBOSE | re.DOTALL) |
|
818 | ''', re.VERBOSE | re.DOTALL) | |
819 | # 1. find the nearest identifier that comes before an unclosed |
|
819 | # 1. find the nearest identifier that comes before an unclosed | |
820 | # parenthesis before the cursor |
|
820 | # parenthesis before the cursor | |
821 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
821 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" | |
822 | tokens = regexp.findall(self.text_until_cursor) |
|
822 | tokens = regexp.findall(self.text_until_cursor) | |
823 | tokens.reverse() |
|
823 | tokens.reverse() | |
824 | iterTokens = iter(tokens); openPar = 0 |
|
824 | iterTokens = iter(tokens); openPar = 0 | |
825 |
|
825 | |||
826 | for token in iterTokens: |
|
826 | for token in iterTokens: | |
827 | if token == ')': |
|
827 | if token == ')': | |
828 | openPar -= 1 |
|
828 | openPar -= 1 | |
829 | elif token == '(': |
|
829 | elif token == '(': | |
830 | openPar += 1 |
|
830 | openPar += 1 | |
831 | if openPar > 0: |
|
831 | if openPar > 0: | |
832 | # found the last unclosed parenthesis |
|
832 | # found the last unclosed parenthesis | |
833 | break |
|
833 | break | |
834 | else: |
|
834 | else: | |
835 | return [] |
|
835 | return [] | |
836 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
836 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
837 | ids = [] |
|
837 | ids = [] | |
838 | isId = re.compile(r'\w+$').match |
|
838 | isId = re.compile(r'\w+$').match | |
839 |
|
839 | |||
840 | while True: |
|
840 | while True: | |
841 | try: |
|
841 | try: | |
842 | ids.append(next(iterTokens)) |
|
842 | ids.append(next(iterTokens)) | |
843 | if not isId(ids[-1]): |
|
843 | if not isId(ids[-1]): | |
844 | ids.pop(); break |
|
844 | ids.pop(); break | |
845 | if not next(iterTokens) == '.': |
|
845 | if not next(iterTokens) == '.': | |
846 | break |
|
846 | break | |
847 | except StopIteration: |
|
847 | except StopIteration: | |
848 | break |
|
848 | break | |
849 | # lookup the candidate callable matches either using global_matches |
|
849 | # lookup the candidate callable matches either using global_matches | |
850 | # or attr_matches for dotted names |
|
850 | # or attr_matches for dotted names | |
851 | if len(ids) == 1: |
|
851 | if len(ids) == 1: | |
852 | callableMatches = self.global_matches(ids[0]) |
|
852 | callableMatches = self.global_matches(ids[0]) | |
853 | else: |
|
853 | else: | |
854 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
854 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
855 | argMatches = [] |
|
855 | argMatches = [] | |
856 | for callableMatch in callableMatches: |
|
856 | for callableMatch in callableMatches: | |
857 | try: |
|
857 | try: | |
858 | namedArgs = self._default_arguments(eval(callableMatch, |
|
858 | namedArgs = self._default_arguments(eval(callableMatch, | |
859 | self.namespace)) |
|
859 | self.namespace)) | |
860 | except: |
|
860 | except: | |
861 | continue |
|
861 | continue | |
862 |
|
862 | |||
863 | for namedArg in namedArgs: |
|
863 | for namedArg in namedArgs: | |
864 | if namedArg.startswith(text): |
|
864 | if namedArg.startswith(text): | |
865 | argMatches.append("%s=" %namedArg) |
|
865 | argMatches.append("%s=" %namedArg) | |
866 | return argMatches |
|
866 | return argMatches | |
867 |
|
867 | |||
868 | def dict_key_matches(self, text): |
|
868 | def dict_key_matches(self, text): | |
|
869 | "Match string keys in a dictionary, after e.g. 'foo[' " | |||
869 | def get_keys(obj): |
|
870 | def get_keys(obj): | |
870 | # Only allow completion for known in-memory dict-like types |
|
871 | # Only allow completion for known in-memory dict-like types | |
871 | if isinstance(obj, dict) or\ |
|
872 | if isinstance(obj, dict) or\ | |
872 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
873 | _safe_isinstance(obj, 'pandas', 'DataFrame'): | |
873 | try: |
|
874 | try: | |
874 | return list(obj.keys()) |
|
875 | return list(obj.keys()) | |
875 | except Exception: |
|
876 | except Exception: | |
876 | return [] |
|
877 | return [] | |
877 | elif _safe_isinstance(obj, 'numpy', 'ndarray'): |
|
878 | elif _safe_isinstance(obj, 'numpy', 'ndarray'): | |
878 | return obj.dtype.names or [] |
|
879 | return obj.dtype.names or [] | |
879 | return [] |
|
880 | return [] | |
880 |
|
881 | |||
881 | try: |
|
882 | try: | |
882 | regexps = self.__dict_key_regexps |
|
883 | regexps = self.__dict_key_regexps | |
883 | except AttributeError: |
|
884 | except AttributeError: | |
884 | dict_key_re_fmt = r'''(?x) |
|
885 | dict_key_re_fmt = r'''(?x) | |
885 | ( # match dict-referring expression wrt greedy setting |
|
886 | ( # match dict-referring expression wrt greedy setting | |
886 | %s |
|
887 | %s | |
887 | ) |
|
888 | ) | |
888 | \[ # open bracket |
|
889 | \[ # open bracket | |
889 | \s* # and optional whitespace |
|
890 | \s* # and optional whitespace | |
890 | ([uUbB]? # string prefix (r not handled) |
|
891 | ([uUbB]? # string prefix (r not handled) | |
891 | (?: # unclosed string |
|
892 | (?: # unclosed string | |
892 | '(?:[^']|(?<!\\)\\')* |
|
893 | '(?:[^']|(?<!\\)\\')* | |
893 | | |
|
894 | | | |
894 | "(?:[^"]|(?<!\\)\\")* |
|
895 | "(?:[^"]|(?<!\\)\\")* | |
895 | ) |
|
896 | ) | |
896 | )? |
|
897 | )? | |
897 | $ |
|
898 | $ | |
898 | ''' |
|
899 | ''' | |
899 | regexps = self.__dict_key_regexps = { |
|
900 | regexps = self.__dict_key_regexps = { | |
900 | False: re.compile(dict_key_re_fmt % ''' |
|
901 | False: re.compile(dict_key_re_fmt % ''' | |
901 | # identifiers separated by . |
|
902 | # identifiers separated by . | |
902 | (?!\d)\w+ |
|
903 | (?!\d)\w+ | |
903 | (?:\.(?!\d)\w+)* |
|
904 | (?:\.(?!\d)\w+)* | |
904 | '''), |
|
905 | '''), | |
905 | True: re.compile(dict_key_re_fmt % ''' |
|
906 | True: re.compile(dict_key_re_fmt % ''' | |
906 | .+ |
|
907 | .+ | |
907 | ''') |
|
908 | ''') | |
908 | } |
|
909 | } | |
909 |
|
910 | |||
910 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
911 | match = regexps[self.greedy].search(self.text_until_cursor) | |
911 | if match is None: |
|
912 | if match is None: | |
912 | return [] |
|
913 | return [] | |
913 |
|
914 | |||
914 | expr, prefix = match.groups() |
|
915 | expr, prefix = match.groups() | |
915 | try: |
|
916 | try: | |
916 | obj = eval(expr, self.namespace) |
|
917 | obj = eval(expr, self.namespace) | |
917 | except Exception: |
|
918 | except Exception: | |
918 | try: |
|
919 | try: | |
919 | obj = eval(expr, self.global_namespace) |
|
920 | obj = eval(expr, self.global_namespace) | |
920 | except Exception: |
|
921 | except Exception: | |
921 | return [] |
|
922 | return [] | |
922 |
|
923 | |||
923 | keys = get_keys(obj) |
|
924 | keys = get_keys(obj) | |
924 | if not keys: |
|
925 | if not keys: | |
925 | return keys |
|
926 | return keys | |
926 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix) |
|
927 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix) | |
927 | if not matches: |
|
928 | if not matches: | |
928 | return matches |
|
929 | return matches | |
929 |
|
930 | |||
930 | # get the cursor position of |
|
931 | # get the cursor position of | |
931 | # - the text being completed |
|
932 | # - the text being completed | |
932 | # - the start of the key text |
|
933 | # - the start of the key text | |
933 | # - the start of the completion |
|
934 | # - the start of the completion | |
934 | text_start = len(self.text_until_cursor) - len(text) |
|
935 | text_start = len(self.text_until_cursor) - len(text) | |
935 | if prefix: |
|
936 | if prefix: | |
936 | key_start = match.start(2) |
|
937 | key_start = match.start(2) | |
937 | completion_start = key_start + token_offset |
|
938 | completion_start = key_start + token_offset | |
938 | else: |
|
939 | else: | |
939 | key_start = completion_start = match.end() |
|
940 | key_start = completion_start = match.end() | |
940 |
|
941 | |||
941 | # grab the leading prefix, to make sure all completions start with `text` |
|
942 | # grab the leading prefix, to make sure all completions start with `text` | |
942 | if text_start > key_start: |
|
943 | if text_start > key_start: | |
943 | leading = '' |
|
944 | leading = '' | |
944 | else: |
|
945 | else: | |
945 | leading = text[text_start:completion_start] |
|
946 | leading = text[text_start:completion_start] | |
946 |
|
947 | |||
947 | # the index of the `[` character |
|
948 | # the index of the `[` character | |
948 | bracket_idx = match.end(1) |
|
949 | bracket_idx = match.end(1) | |
949 |
|
950 | |||
950 | # append closing quote and bracket as appropriate |
|
951 | # append closing quote and bracket as appropriate | |
951 | # this is *not* appropriate if the opening quote or bracket is outside |
|
952 | # this is *not* appropriate if the opening quote or bracket is outside | |
952 | # the text given to this method |
|
953 | # the text given to this method | |
953 | suf = '' |
|
954 | suf = '' | |
954 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
955 | continuation = self.line_buffer[len(self.text_until_cursor):] | |
955 | if key_start > text_start and closing_quote: |
|
956 | if key_start > text_start and closing_quote: | |
956 | # quotes were opened inside text, maybe close them |
|
957 | # quotes were opened inside text, maybe close them | |
957 | if continuation.startswith(closing_quote): |
|
958 | if continuation.startswith(closing_quote): | |
958 | continuation = continuation[len(closing_quote):] |
|
959 | continuation = continuation[len(closing_quote):] | |
959 | else: |
|
960 | else: | |
960 | suf += closing_quote |
|
961 | suf += closing_quote | |
961 | if bracket_idx > text_start: |
|
962 | if bracket_idx > text_start: | |
962 | # brackets were opened inside text, maybe close them |
|
963 | # brackets were opened inside text, maybe close them | |
963 | if not continuation.startswith(']'): |
|
964 | if not continuation.startswith(']'): | |
964 | suf += ']' |
|
965 | suf += ']' | |
965 |
|
966 | |||
966 | return [leading + k + suf for k in matches] |
|
967 | return [leading + k + suf for k in matches] | |
967 |
|
968 | |||
968 | def dispatch_custom_completer(self, text): |
|
969 | def dispatch_custom_completer(self, text): | |
969 | #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg |
|
970 | #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg | |
970 | line = self.line_buffer |
|
971 | line = self.line_buffer | |
971 | if not line.strip(): |
|
972 | if not line.strip(): | |
972 | return None |
|
973 | return None | |
973 |
|
974 | |||
974 | # Create a little structure to pass all the relevant information about |
|
975 | # Create a little structure to pass all the relevant information about | |
975 | # the current completion to any custom completer. |
|
976 | # the current completion to any custom completer. | |
976 | event = Bunch() |
|
977 | event = Bunch() | |
977 | event.line = line |
|
978 | event.line = line | |
978 | event.symbol = text |
|
979 | event.symbol = text | |
979 | cmd = line.split(None,1)[0] |
|
980 | cmd = line.split(None,1)[0] | |
980 | event.command = cmd |
|
981 | event.command = cmd | |
981 | event.text_until_cursor = self.text_until_cursor |
|
982 | event.text_until_cursor = self.text_until_cursor | |
982 |
|
983 | |||
983 | #print "\ncustom:{%s]\n" % event # dbg |
|
984 | #print "\ncustom:{%s]\n" % event # dbg | |
984 |
|
985 | |||
985 | # for foo etc, try also to find completer for %foo |
|
986 | # for foo etc, try also to find completer for %foo | |
986 | if not cmd.startswith(self.magic_escape): |
|
987 | if not cmd.startswith(self.magic_escape): | |
987 | try_magic = self.custom_completers.s_matches( |
|
988 | try_magic = self.custom_completers.s_matches( | |
988 | self.magic_escape + cmd) |
|
989 | self.magic_escape + cmd) | |
989 | else: |
|
990 | else: | |
990 | try_magic = [] |
|
991 | try_magic = [] | |
991 |
|
992 | |||
992 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
993 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
993 | try_magic, |
|
994 | try_magic, | |
994 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
995 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
995 | #print "try",c # dbg |
|
996 | #print "try",c # dbg | |
996 | try: |
|
997 | try: | |
997 | res = c(event) |
|
998 | res = c(event) | |
998 | if res: |
|
999 | if res: | |
999 | # first, try case sensitive match |
|
1000 | # first, try case sensitive match | |
1000 | withcase = [r for r in res if r.startswith(text)] |
|
1001 | withcase = [r for r in res if r.startswith(text)] | |
1001 | if withcase: |
|
1002 | if withcase: | |
1002 | return withcase |
|
1003 | return withcase | |
1003 | # if none, then case insensitive ones are ok too |
|
1004 | # if none, then case insensitive ones are ok too | |
1004 | text_low = text.lower() |
|
1005 | text_low = text.lower() | |
1005 | return [r for r in res if r.lower().startswith(text_low)] |
|
1006 | return [r for r in res if r.lower().startswith(text_low)] | |
1006 | except TryNext: |
|
1007 | except TryNext: | |
1007 | pass |
|
1008 | pass | |
1008 |
|
1009 | |||
1009 | return None |
|
1010 | return None | |
1010 |
|
1011 | |||
1011 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1012 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
1012 | """Find completions for the given text and line context. |
|
1013 | """Find completions for the given text and line context. | |
1013 |
|
1014 | |||
1014 | Note that both the text and the line_buffer are optional, but at least |
|
1015 | Note that both the text and the line_buffer are optional, but at least | |
1015 | one of them must be given. |
|
1016 | one of them must be given. | |
1016 |
|
1017 | |||
1017 | Parameters |
|
1018 | Parameters | |
1018 | ---------- |
|
1019 | ---------- | |
1019 | text : string, optional |
|
1020 | text : string, optional | |
1020 | Text to perform the completion on. If not given, the line buffer |
|
1021 | Text to perform the completion on. If not given, the line buffer | |
1021 | is split using the instance's CompletionSplitter object. |
|
1022 | is split using the instance's CompletionSplitter object. | |
1022 |
|
1023 | |||
1023 | line_buffer : string, optional |
|
1024 | line_buffer : string, optional | |
1024 | If not given, the completer attempts to obtain the current line |
|
1025 | If not given, the completer attempts to obtain the current line | |
1025 | buffer via readline. This keyword allows clients which are |
|
1026 | buffer via readline. This keyword allows clients which are | |
1026 | requesting for text completions in non-readline contexts to inform |
|
1027 | requesting for text completions in non-readline contexts to inform | |
1027 | the completer of the entire text. |
|
1028 | the completer of the entire text. | |
1028 |
|
1029 | |||
1029 | cursor_pos : int, optional |
|
1030 | cursor_pos : int, optional | |
1030 | Index of the cursor in the full line buffer. Should be provided by |
|
1031 | Index of the cursor in the full line buffer. Should be provided by | |
1031 | remote frontends where kernel has no access to frontend state. |
|
1032 | remote frontends where kernel has no access to frontend state. | |
1032 |
|
1033 | |||
1033 | Returns |
|
1034 | Returns | |
1034 | ------- |
|
1035 | ------- | |
1035 | text : str |
|
1036 | text : str | |
1036 | Text that was actually used in the completion. |
|
1037 | Text that was actually used in the completion. | |
1037 |
|
1038 | |||
1038 | matches : list |
|
1039 | matches : list | |
1039 | A list of completion matches. |
|
1040 | A list of completion matches. | |
1040 | """ |
|
1041 | """ | |
1041 | #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
1042 | #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
1042 |
|
1043 | |||
1043 | # if the cursor position isn't given, the only sane assumption we can |
|
1044 | # if the cursor position isn't given, the only sane assumption we can | |
1044 | # make is that it's at the end of the line (the common case) |
|
1045 | # make is that it's at the end of the line (the common case) | |
1045 | if cursor_pos is None: |
|
1046 | if cursor_pos is None: | |
1046 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1047 | cursor_pos = len(line_buffer) if text is None else len(text) | |
1047 |
|
1048 | |||
1048 | # if text is either None or an empty string, rely on the line buffer |
|
1049 | # if text is either None or an empty string, rely on the line buffer | |
1049 | if not text: |
|
1050 | if not text: | |
1050 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1051 | text = self.splitter.split_line(line_buffer, cursor_pos) | |
1051 |
|
1052 | |||
1052 | # If no line buffer is given, assume the input text is all there was |
|
1053 | # If no line buffer is given, assume the input text is all there was | |
1053 | if line_buffer is None: |
|
1054 | if line_buffer is None: | |
1054 | line_buffer = text |
|
1055 | line_buffer = text | |
1055 |
|
1056 | |||
1056 | self.line_buffer = line_buffer |
|
1057 | self.line_buffer = line_buffer | |
1057 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1058 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
1058 | #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
1059 | #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
1059 |
|
1060 | |||
1060 | # Start with a clean slate of completions |
|
1061 | # Start with a clean slate of completions | |
1061 | self.matches[:] = [] |
|
1062 | self.matches[:] = [] | |
1062 | custom_res = self.dispatch_custom_completer(text) |
|
1063 | custom_res = self.dispatch_custom_completer(text) | |
1063 | if custom_res is not None: |
|
1064 | if custom_res is not None: | |
1064 | # did custom completers produce something? |
|
1065 | # did custom completers produce something? | |
1065 | self.matches = custom_res |
|
1066 | self.matches = custom_res | |
1066 | else: |
|
1067 | else: | |
1067 | # Extend the list of completions with the results of each |
|
1068 | # Extend the list of completions with the results of each | |
1068 | # matcher, so we return results to the user from all |
|
1069 | # matcher, so we return results to the user from all | |
1069 | # namespaces. |
|
1070 | # namespaces. | |
1070 | if self.merge_completions: |
|
1071 | if self.merge_completions: | |
1071 | self.matches = [] |
|
1072 | self.matches = [] | |
1072 | for matcher in self.matchers: |
|
1073 | for matcher in self.matchers: | |
1073 | try: |
|
1074 | try: | |
1074 | self.matches.extend(matcher(text)) |
|
1075 | self.matches.extend(matcher(text)) | |
1075 | except: |
|
1076 | except: | |
1076 | # Show the ugly traceback if the matcher causes an |
|
1077 | # Show the ugly traceback if the matcher causes an | |
1077 | # exception, but do NOT crash the kernel! |
|
1078 | # exception, but do NOT crash the kernel! | |
1078 | sys.excepthook(*sys.exc_info()) |
|
1079 | sys.excepthook(*sys.exc_info()) | |
1079 | else: |
|
1080 | else: | |
1080 | for matcher in self.matchers: |
|
1081 | for matcher in self.matchers: | |
1081 | self.matches = matcher(text) |
|
1082 | self.matches = matcher(text) | |
1082 | if self.matches: |
|
1083 | if self.matches: | |
1083 | break |
|
1084 | break | |
1084 | # FIXME: we should extend our api to return a dict with completions for |
|
1085 | # FIXME: we should extend our api to return a dict with completions for | |
1085 | # different types of objects. The rlcomplete() method could then |
|
1086 | # different types of objects. The rlcomplete() method could then | |
1086 | # simply collapse the dict into a list for readline, but we'd have |
|
1087 | # simply collapse the dict into a list for readline, but we'd have | |
1087 | # richer completion semantics in other evironments. |
|
1088 | # richer completion semantics in other evironments. | |
1088 |
|
1089 | |||
1089 | # use penalize_magics_key to put magics after variables with same name |
|
1090 | # use penalize_magics_key to put magics after variables with same name | |
1090 | self.matches = sorted(set(self.matches), key=penalize_magics_key) |
|
1091 | self.matches = sorted(set(self.matches), key=penalize_magics_key) | |
1091 |
|
1092 | |||
1092 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg |
|
1093 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg | |
1093 | return text, self.matches |
|
1094 | return text, self.matches | |
1094 |
|
1095 | |||
1095 | def rlcomplete(self, text, state): |
|
1096 | def rlcomplete(self, text, state): | |
1096 | """Return the state-th possible completion for 'text'. |
|
1097 | """Return the state-th possible completion for 'text'. | |
1097 |
|
1098 | |||
1098 | This is called successively with state == 0, 1, 2, ... until it |
|
1099 | This is called successively with state == 0, 1, 2, ... until it | |
1099 | returns None. The completion should begin with 'text'. |
|
1100 | returns None. The completion should begin with 'text'. | |
1100 |
|
1101 | |||
1101 | Parameters |
|
1102 | Parameters | |
1102 | ---------- |
|
1103 | ---------- | |
1103 | text : string |
|
1104 | text : string | |
1104 | Text to perform the completion on. |
|
1105 | Text to perform the completion on. | |
1105 |
|
1106 | |||
1106 | state : int |
|
1107 | state : int | |
1107 | Counter used by readline. |
|
1108 | Counter used by readline. | |
1108 | """ |
|
1109 | """ | |
1109 | if state==0: |
|
1110 | if state==0: | |
1110 |
|
1111 | |||
1111 | self.line_buffer = line_buffer = self.readline.get_line_buffer() |
|
1112 | self.line_buffer = line_buffer = self.readline.get_line_buffer() | |
1112 | cursor_pos = self.readline.get_endidx() |
|
1113 | cursor_pos = self.readline.get_endidx() | |
1113 |
|
1114 | |||
1114 | #io.rprint("\nRLCOMPLETE: %r %r %r" % |
|
1115 | #io.rprint("\nRLCOMPLETE: %r %r %r" % | |
1115 | # (text, line_buffer, cursor_pos) ) # dbg |
|
1116 | # (text, line_buffer, cursor_pos) ) # dbg | |
1116 |
|
1117 | |||
1117 | # if there is only a tab on a line with only whitespace, instead of |
|
1118 | # if there is only a tab on a line with only whitespace, instead of | |
1118 | # the mostly useless 'do you want to see all million completions' |
|
1119 | # the mostly useless 'do you want to see all million completions' | |
1119 | # message, just do the right thing and give the user his tab! |
|
1120 | # message, just do the right thing and give the user his tab! | |
1120 | # Incidentally, this enables pasting of tabbed text from an editor |
|
1121 | # Incidentally, this enables pasting of tabbed text from an editor | |
1121 | # (as long as autoindent is off). |
|
1122 | # (as long as autoindent is off). | |
1122 |
|
1123 | |||
1123 | # It should be noted that at least pyreadline still shows file |
|
1124 | # It should be noted that at least pyreadline still shows file | |
1124 | # completions - is there a way around it? |
|
1125 | # completions - is there a way around it? | |
1125 |
|
1126 | |||
1126 | # don't apply this on 'dumb' terminals, such as emacs buffers, so |
|
1127 | # don't apply this on 'dumb' terminals, such as emacs buffers, so | |
1127 | # we don't interfere with their own tab-completion mechanism. |
|
1128 | # we don't interfere with their own tab-completion mechanism. | |
1128 | if not (self.dumb_terminal or line_buffer.strip()): |
|
1129 | if not (self.dumb_terminal or line_buffer.strip()): | |
1129 | self.readline.insert_text('\t') |
|
1130 | self.readline.insert_text('\t') | |
1130 | sys.stdout.flush() |
|
1131 | sys.stdout.flush() | |
1131 | return None |
|
1132 | return None | |
1132 |
|
1133 | |||
1133 | # Note: debugging exceptions that may occur in completion is very |
|
1134 | # Note: debugging exceptions that may occur in completion is very | |
1134 | # tricky, because readline unconditionally silences them. So if |
|
1135 | # tricky, because readline unconditionally silences them. So if | |
1135 | # during development you suspect a bug in the completion code, turn |
|
1136 | # during development you suspect a bug in the completion code, turn | |
1136 | # this flag on temporarily by uncommenting the second form (don't |
|
1137 | # this flag on temporarily by uncommenting the second form (don't | |
1137 | # flip the value in the first line, as the '# dbg' marker can be |
|
1138 | # flip the value in the first line, as the '# dbg' marker can be | |
1138 | # automatically detected and is used elsewhere). |
|
1139 | # automatically detected and is used elsewhere). | |
1139 | DEBUG = False |
|
1140 | DEBUG = False | |
1140 | #DEBUG = True # dbg |
|
1141 | #DEBUG = True # dbg | |
1141 | if DEBUG: |
|
1142 | if DEBUG: | |
1142 | try: |
|
1143 | try: | |
1143 | self.complete(text, line_buffer, cursor_pos) |
|
1144 | self.complete(text, line_buffer, cursor_pos) | |
1144 | except: |
|
1145 | except: | |
1145 | import traceback; traceback.print_exc() |
|
1146 | import traceback; traceback.print_exc() | |
1146 | else: |
|
1147 | else: | |
1147 | # The normal production version is here |
|
1148 | # The normal production version is here | |
1148 |
|
1149 | |||
1149 | # This method computes the self.matches array |
|
1150 | # This method computes the self.matches array | |
1150 | self.complete(text, line_buffer, cursor_pos) |
|
1151 | self.complete(text, line_buffer, cursor_pos) | |
1151 |
|
1152 | |||
1152 | try: |
|
1153 | try: | |
1153 | return self.matches[state] |
|
1154 | return self.matches[state] | |
1154 | except IndexError: |
|
1155 | except IndexError: | |
1155 | return None |
|
1156 | return None |
General Comments 0
You need to be logged in to leave comments.
Login now