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