Show More
@@ -1,880 +1,880 b'' | |||||
1 | """Word completion for IPython. |
|
1 | """Word completion for IPython. | |
2 |
|
2 | |||
3 | This module is a fork of the rlcompleter module in the Python standard |
|
3 | This module is a fork of the rlcompleter module in the Python standard | |
4 | library. The original enhancements made to rlcompleter have been sent |
|
4 | library. The original enhancements made to rlcompleter have been sent | |
5 | upstream and were accepted as of Python 2.3, but we need a lot more |
|
5 | upstream and were accepted as of Python 2.3, but we need a lot more | |
6 | functionality specific to IPython, so this module will continue to live as an |
|
6 | functionality specific to IPython, so this module will continue to live as an | |
7 | IPython-specific utility. |
|
7 | IPython-specific utility. | |
8 |
|
8 | |||
9 | Original rlcompleter documentation: |
|
9 | Original rlcompleter documentation: | |
10 |
|
10 | |||
11 | This requires the latest extension to the readline module (the |
|
11 | This requires the latest extension to the readline module (the | |
12 | completes keywords, built-ins and globals in __main__; when completing |
|
12 | completes keywords, built-ins and globals in __main__; when completing | |
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
13 | NAME.NAME..., it evaluates (!) the expression up to the last dot and | |
14 | completes its attributes. |
|
14 | completes its attributes. | |
15 |
|
15 | |||
16 | It's very cool to do "import string" type "string.", hit the |
|
16 | It's very cool to do "import string" type "string.", hit the | |
17 | completion key (twice), and see the list of names defined by the |
|
17 | completion key (twice), and see the list of names defined by the | |
18 | string module! |
|
18 | string module! | |
19 |
|
19 | |||
20 | Tip: to use the tab key as the completion key, call |
|
20 | Tip: to use the tab key as the completion key, call | |
21 |
|
21 | |||
22 | readline.parse_and_bind("tab: complete") |
|
22 | readline.parse_and_bind("tab: complete") | |
23 |
|
23 | |||
24 | Notes: |
|
24 | Notes: | |
25 |
|
25 | |||
26 | - Exceptions raised by the completer function are *ignored* (and |
|
26 | - Exceptions raised by the completer function are *ignored* (and | |
27 | generally cause the completion to fail). This is a feature -- since |
|
27 | generally cause the completion to fail). This is a feature -- since | |
28 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
28 | readline sets the tty device in raw (or cbreak) mode, printing a | |
29 | traceback wouldn't work well without some complicated hoopla to save, |
|
29 | traceback wouldn't work well without some complicated hoopla to save, | |
30 | reset and restore the tty state. |
|
30 | reset and restore the tty state. | |
31 |
|
31 | |||
32 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
32 | - The evaluation of the NAME.NAME... form may cause arbitrary | |
33 | application defined code to be executed if an object with a |
|
33 | application defined code to be executed if an object with a | |
34 | __getattr__ hook is found. Since it is the responsibility of the |
|
34 | __getattr__ hook is found. Since it is the responsibility of the | |
35 | application (or the user) to enable this feature, I consider this an |
|
35 | application (or the user) to enable this feature, I consider this an | |
36 | acceptable risk. More complicated expressions (e.g. function calls or |
|
36 | acceptable risk. More complicated expressions (e.g. function calls or | |
37 | indexing operations) are *not* evaluated. |
|
37 | indexing operations) are *not* evaluated. | |
38 |
|
38 | |||
39 | - GNU readline is also used by the built-in functions input() and |
|
39 | - GNU readline is also used by the built-in functions input() and | |
40 | raw_input(), and thus these also benefit/suffer from the completer |
|
40 | raw_input(), and thus these also benefit/suffer from the completer | |
41 | features. Clearly an interactive application can benefit by |
|
41 | features. Clearly an interactive application can benefit by | |
42 | specifying its own completer function and using raw_input() for all |
|
42 | specifying its own completer function and using raw_input() for all | |
43 | its input. |
|
43 | its input. | |
44 |
|
44 | |||
45 | - When the original stdin is not a tty device, GNU readline is never |
|
45 | - When the original stdin is not a tty device, GNU readline is never | |
46 | used, and this module (and the readline module) are silently inactive. |
|
46 | used, and this module (and the readline module) are silently inactive. | |
47 | """ |
|
47 | """ | |
48 |
|
48 | |||
49 | #***************************************************************************** |
|
49 | #***************************************************************************** | |
50 | # |
|
50 | # | |
51 | # Since this file is essentially a minimally modified copy of the rlcompleter |
|
51 | # Since this file is essentially a minimally modified copy of the rlcompleter | |
52 | # module which is part of the standard Python distribution, I assume that the |
|
52 | # module which is part of the standard Python distribution, I assume that the | |
53 | # proper procedure is to maintain its copyright as belonging to the Python |
|
53 | # proper procedure is to maintain its copyright as belonging to the Python | |
54 | # Software Foundation (in addition to my own, for all new code). |
|
54 | # Software Foundation (in addition to my own, for all new code). | |
55 | # |
|
55 | # | |
56 | # Copyright (C) 2008-2010 IPython Development Team |
|
56 | # Copyright (C) 2008-2010 IPython Development Team | |
57 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
57 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
58 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
59 | # |
|
59 | # | |
60 | # Distributed under the terms of the BSD License. The full license is in |
|
60 | # Distributed under the terms of the BSD License. The full license is in | |
61 | # the file COPYING, distributed as part of this software. |
|
61 | # the file COPYING, distributed as part of this software. | |
62 | # |
|
62 | # | |
63 | #***************************************************************************** |
|
63 | #***************************************************************************** | |
64 | from __future__ import print_function |
|
64 | from __future__ import print_function | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Imports |
|
67 | # Imports | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | import __builtin__ |
|
70 | import __builtin__ | |
71 | import __main__ |
|
71 | import __main__ | |
72 | import glob |
|
72 | import glob | |
73 | import inspect |
|
73 | import inspect | |
74 | import itertools |
|
74 | import itertools | |
75 | import keyword |
|
75 | import keyword | |
76 | import os |
|
76 | import os | |
77 | import re |
|
77 | import re | |
78 | import shlex |
|
78 | import shlex | |
79 | import sys |
|
79 | import sys | |
80 |
|
80 | |||
81 | from IPython.core.error import TryNext |
|
81 | from IPython.core.error import TryNext | |
82 | from IPython.core.prefilter import ESC_MAGIC |
|
82 | from IPython.core.prefilter import ESC_MAGIC | |
83 | from IPython.utils import generics |
|
83 | from IPython.utils import generics | |
84 | from IPython.utils import io |
|
84 | from IPython.utils import io | |
85 | from IPython.utils.dir2 import dir2 |
|
85 | from IPython.utils.dir2 import dir2 | |
86 | from IPython.utils.process import arg_split |
|
86 | from IPython.utils.process import arg_split | |
87 |
|
87 | |||
88 | #----------------------------------------------------------------------------- |
|
88 | #----------------------------------------------------------------------------- | |
89 | # Globals |
|
89 | # Globals | |
90 | #----------------------------------------------------------------------------- |
|
90 | #----------------------------------------------------------------------------- | |
91 |
|
91 | |||
92 | # Public API |
|
92 | # Public API | |
93 | __all__ = ['Completer','IPCompleter'] |
|
93 | __all__ = ['Completer','IPCompleter'] | |
94 |
|
94 | |||
95 | if sys.platform == 'win32': |
|
95 | if sys.platform == 'win32': | |
96 | PROTECTABLES = ' ' |
|
96 | PROTECTABLES = ' ' | |
97 | else: |
|
97 | else: | |
98 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
98 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
99 |
|
99 | |||
100 | #----------------------------------------------------------------------------- |
|
100 | #----------------------------------------------------------------------------- | |
101 | # Main functions and classes |
|
101 | # Main functions and classes | |
102 | #----------------------------------------------------------------------------- |
|
102 | #----------------------------------------------------------------------------- | |
103 |
|
103 | |||
104 | def has_open_quotes(s): |
|
104 | def has_open_quotes(s): | |
105 | """Return whether a string has open quotes. |
|
105 | """Return whether a string has open quotes. | |
106 |
|
106 | |||
107 | This simply counts whether the number of quote characters of either type in |
|
107 | This simply counts whether the number of quote characters of either type in | |
108 | the string is odd. |
|
108 | the string is odd. | |
109 |
|
109 | |||
110 | Returns |
|
110 | Returns | |
111 | ------- |
|
111 | ------- | |
112 | If there is an open quote, the quote character is returned. Else, return |
|
112 | If there is an open quote, the quote character is returned. Else, return | |
113 | False. |
|
113 | False. | |
114 | """ |
|
114 | """ | |
115 | # We check " first, then ', so complex cases with nested quotes will get |
|
115 | # We check " first, then ', so complex cases with nested quotes will get | |
116 | # the " to take precedence. |
|
116 | # the " to take precedence. | |
117 | if s.count('"') % 2: |
|
117 | if s.count('"') % 2: | |
118 | return '"' |
|
118 | return '"' | |
119 | elif s.count("'") % 2: |
|
119 | elif s.count("'") % 2: | |
120 | return "'" |
|
120 | return "'" | |
121 | else: |
|
121 | else: | |
122 | return False |
|
122 | return False | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | def protect_filename(s): |
|
125 | def protect_filename(s): | |
126 | """Escape a string to protect certain characters.""" |
|
126 | """Escape a string to protect certain characters.""" | |
127 |
|
127 | |||
128 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) |
|
128 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) | |
129 | for ch in s]) |
|
129 | for ch in s]) | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | def mark_dirs(matches): |
|
132 | def mark_dirs(matches): | |
133 | """Mark directories in input list by appending '/' to their names.""" |
|
133 | """Mark directories in input list by appending '/' to their names.""" | |
134 | out = [] |
|
134 | out = [] | |
135 | isdir = os.path.isdir |
|
135 | isdir = os.path.isdir | |
136 | for x in matches: |
|
136 | for x in matches: | |
137 | if isdir(x): |
|
137 | if isdir(x): | |
138 | out.append(x+'/') |
|
138 | out.append(x+'/') | |
139 | else: |
|
139 | else: | |
140 | out.append(x) |
|
140 | out.append(x) | |
141 | return out |
|
141 | return out | |
142 |
|
142 | |||
143 |
|
143 | |||
144 | def expand_user(path): |
|
144 | def expand_user(path): | |
145 | """Expand '~'-style usernames in strings. |
|
145 | """Expand '~'-style usernames in strings. | |
146 |
|
146 | |||
147 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
147 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
148 | extra information that will be useful if the input was being used in |
|
148 | extra information that will be useful if the input was being used in | |
149 | computing completions, and you wish to return the completions with the |
|
149 | computing completions, and you wish to return the completions with the | |
150 | original '~' instead of its expanded value. |
|
150 | original '~' instead of its expanded value. | |
151 |
|
151 | |||
152 | Parameters |
|
152 | Parameters | |
153 | ---------- |
|
153 | ---------- | |
154 | path : str |
|
154 | path : str | |
155 | String to be expanded. If no ~ is present, the output is the same as the |
|
155 | String to be expanded. If no ~ is present, the output is the same as the | |
156 | input. |
|
156 | input. | |
157 |
|
157 | |||
158 | Returns |
|
158 | Returns | |
159 | ------- |
|
159 | ------- | |
160 | newpath : str |
|
160 | newpath : str | |
161 | Result of ~ expansion in the input path. |
|
161 | Result of ~ expansion in the input path. | |
162 | tilde_expand : bool |
|
162 | tilde_expand : bool | |
163 | Whether any expansion was performed or not. |
|
163 | Whether any expansion was performed or not. | |
164 | tilde_val : str |
|
164 | tilde_val : str | |
165 | The value that ~ was replaced with. |
|
165 | The value that ~ was replaced with. | |
166 | """ |
|
166 | """ | |
167 | # Default values |
|
167 | # Default values | |
168 | tilde_expand = False |
|
168 | tilde_expand = False | |
169 | tilde_val = '' |
|
169 | tilde_val = '' | |
170 | newpath = path |
|
170 | newpath = path | |
171 |
|
171 | |||
172 | if path.startswith('~'): |
|
172 | if path.startswith('~'): | |
173 | tilde_expand = True |
|
173 | tilde_expand = True | |
174 | rest = path[1:] |
|
174 | rest = path[1:] | |
175 | newpath = os.path.expanduser(path) |
|
175 | newpath = os.path.expanduser(path) | |
176 | tilde_val = newpath.replace(rest, '') |
|
176 | tilde_val = newpath.replace(rest, '') | |
177 |
|
177 | |||
178 | return newpath, tilde_expand, tilde_val |
|
178 | return newpath, tilde_expand, tilde_val | |
179 |
|
179 | |||
180 |
|
180 | |||
181 | def compress_user(path, tilde_expand, tilde_val): |
|
181 | def compress_user(path, tilde_expand, tilde_val): | |
182 | """Does the opposite of expand_user, with its outputs. |
|
182 | """Does the opposite of expand_user, with its outputs. | |
183 | """ |
|
183 | """ | |
184 | if tilde_expand: |
|
184 | if tilde_expand: | |
185 | return path.replace(tilde_val, '~') |
|
185 | return path.replace(tilde_val, '~') | |
186 | else: |
|
186 | else: | |
187 | return path |
|
187 | return path | |
188 |
|
188 | |||
189 |
|
189 | |||
190 | def single_dir_expand(matches): |
|
190 | def single_dir_expand(matches): | |
191 | "Recursively expand match lists containing a single dir." |
|
191 | "Recursively expand match lists containing a single dir." | |
192 |
|
192 | |||
193 | if len(matches) == 1 and os.path.isdir(matches[0]): |
|
193 | if len(matches) == 1 and os.path.isdir(matches[0]): | |
194 | # Takes care of links to directories also. Use '/' |
|
194 | # Takes care of links to directories also. Use '/' | |
195 | # explicitly, even under Windows, so that name completions |
|
195 | # explicitly, even under Windows, so that name completions | |
196 | # don't end up escaped. |
|
196 | # don't end up escaped. | |
197 | d = matches[0] |
|
197 | d = matches[0] | |
198 | if d[-1] in ['/','\\']: |
|
198 | if d[-1] in ['/','\\']: | |
199 | d = d[:-1] |
|
199 | d = d[:-1] | |
200 |
|
200 | |||
201 | subdirs = os.listdir(d) |
|
201 | subdirs = os.listdir(d) | |
202 | if subdirs: |
|
202 | if subdirs: | |
203 | matches = [ (d + '/' + p) for p in subdirs] |
|
203 | matches = [ (d + '/' + p) for p in subdirs] | |
204 | return single_dir_expand(matches) |
|
204 | return single_dir_expand(matches) | |
205 | else: |
|
205 | else: | |
206 | return matches |
|
206 | return matches | |
207 | else: |
|
207 | else: | |
208 | return matches |
|
208 | return matches | |
209 |
|
209 | |||
210 |
|
210 | |||
211 | class Bunch(object): pass |
|
211 | class Bunch(object): pass | |
212 |
|
212 | |||
213 |
|
213 | |||
214 | class CompletionSplitter(object): |
|
214 | class CompletionSplitter(object): | |
215 | """An object to split an input line in a manner similar to readline. |
|
215 | """An object to split an input line in a manner similar to readline. | |
216 |
|
216 | |||
217 | By having our own implementation, we can expose readline-like completion in |
|
217 | 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 |
|
218 | 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 |
|
219 | 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 |
|
220 | returns the 'word' to be completed on at the cursor after splitting the | |
221 | entire line. |
|
221 | entire line. | |
222 |
|
222 | |||
223 | What characters are used as splitting delimiters can be controlled by |
|
223 | What characters are used as splitting delimiters can be controlled by | |
224 | setting the `delims` attribute (this is a property that internally |
|
224 | setting the `delims` attribute (this is a property that internally | |
225 | automatically builds the necessary """ |
|
225 | automatically builds the necessary """ | |
226 |
|
226 | |||
227 | # Private interface |
|
227 | # Private interface | |
228 |
|
228 | |||
229 | # A string of delimiter characters. The default value makes sense for |
|
229 | # A string of delimiter characters. The default value makes sense for | |
230 | # IPython's most typical usage patterns. |
|
230 | # IPython's most typical usage patterns. | |
231 | _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
231 | _delims = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
232 |
|
232 | |||
233 | # The expression (a normal string) to be compiled into a regular expression |
|
233 | # 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 |
|
234 | # 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. |
|
235 | # debugging, since this type of code can be so tricky to debug. | |
236 | _delim_expr = None |
|
236 | _delim_expr = None | |
237 |
|
237 | |||
238 | # The regular expression that does the actual splitting |
|
238 | # The regular expression that does the actual splitting | |
239 | _delim_re = None |
|
239 | _delim_re = None | |
240 |
|
240 | |||
241 | def __init__(self, delims=None): |
|
241 | def __init__(self, delims=None): | |
242 | delims = CompletionSplitter._delims if delims is None else delims |
|
242 | delims = CompletionSplitter._delims if delims is None else delims | |
243 | self.set_delims(delims) |
|
243 | self.set_delims(delims) | |
244 |
|
244 | |||
245 | def set_delims(self, delims): |
|
245 | def set_delims(self, delims): | |
246 | """Set the delimiters for line splitting.""" |
|
246 | """Set the delimiters for line splitting.""" | |
247 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
247 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
248 | self._delim_re = re.compile(expr) |
|
248 | self._delim_re = re.compile(expr) | |
249 | self._delims = delims |
|
249 | self._delims = delims | |
250 | self._delim_expr = expr |
|
250 | self._delim_expr = expr | |
251 |
|
251 | |||
252 | def get_delims(self): |
|
252 | def get_delims(self): | |
253 | """Return the string of delimiter characters.""" |
|
253 | """Return the string of delimiter characters.""" | |
254 | return self._delims |
|
254 | return self._delims | |
255 |
|
255 | |||
256 | def split_line(self, line, cursor_pos=None): |
|
256 | def split_line(self, line, cursor_pos=None): | |
257 | """Split a line of text with a cursor at the given position. |
|
257 | """Split a line of text with a cursor at the given position. | |
258 | """ |
|
258 | """ | |
259 | l = line if cursor_pos is None else line[:cursor_pos] |
|
259 | l = line if cursor_pos is None else line[:cursor_pos] | |
260 | return self._delim_re.split(l)[-1] |
|
260 | return self._delim_re.split(l)[-1] | |
261 |
|
261 | |||
262 |
|
262 | |||
263 | class Completer(object): |
|
263 | class Completer(object): | |
264 | def __init__(self, namespace=None, global_namespace=None): |
|
264 | def __init__(self, namespace=None, global_namespace=None): | |
265 | """Create a new completer for the command line. |
|
265 | """Create a new completer for the command line. | |
266 |
|
266 | |||
267 | Completer([namespace,global_namespace]) -> completer instance. |
|
267 | Completer([namespace,global_namespace]) -> completer instance. | |
268 |
|
268 | |||
269 | If unspecified, the default namespace where completions are performed |
|
269 | If unspecified, the default namespace where completions are performed | |
270 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
270 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
271 | given as dictionaries. |
|
271 | given as dictionaries. | |
272 |
|
272 | |||
273 | An optional second namespace can be given. This allows the completer |
|
273 | An optional second namespace can be given. This allows the completer | |
274 | to handle cases where both the local and global scopes need to be |
|
274 | to handle cases where both the local and global scopes need to be | |
275 | distinguished. |
|
275 | distinguished. | |
276 |
|
276 | |||
277 | Completer instances should be used as the completion mechanism of |
|
277 | Completer instances should be used as the completion mechanism of | |
278 | readline via the set_completer() call: |
|
278 | readline via the set_completer() call: | |
279 |
|
279 | |||
280 | readline.set_completer(Completer(my_namespace).complete) |
|
280 | readline.set_completer(Completer(my_namespace).complete) | |
281 | """ |
|
281 | """ | |
282 |
|
282 | |||
283 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
283 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
284 | # specific namespace or to use __main__.__dict__. This will allow us |
|
284 | # specific namespace or to use __main__.__dict__. This will allow us | |
285 | # to bind to __main__.__dict__ at completion time, not now. |
|
285 | # to bind to __main__.__dict__ at completion time, not now. | |
286 | if namespace is None: |
|
286 | if namespace is None: | |
287 | self.use_main_ns = 1 |
|
287 | self.use_main_ns = 1 | |
288 | else: |
|
288 | else: | |
289 | self.use_main_ns = 0 |
|
289 | self.use_main_ns = 0 | |
290 | self.namespace = namespace |
|
290 | self.namespace = namespace | |
291 |
|
291 | |||
292 | # The global namespace, if given, can be bound directly |
|
292 | # The global namespace, if given, can be bound directly | |
293 | if global_namespace is None: |
|
293 | if global_namespace is None: | |
294 | self.global_namespace = {} |
|
294 | self.global_namespace = {} | |
295 | else: |
|
295 | else: | |
296 | self.global_namespace = global_namespace |
|
296 | self.global_namespace = global_namespace | |
297 |
|
297 | |||
298 | def complete(self, text, state): |
|
298 | def complete(self, text, state): | |
299 | """Return the next possible completion for 'text'. |
|
299 | """Return the next possible completion for 'text'. | |
300 |
|
300 | |||
301 | This is called successively with state == 0, 1, 2, ... until it |
|
301 | This is called successively with state == 0, 1, 2, ... until it | |
302 | returns None. The completion should begin with 'text'. |
|
302 | returns None. The completion should begin with 'text'. | |
303 |
|
303 | |||
304 | """ |
|
304 | """ | |
305 | if self.use_main_ns: |
|
305 | if self.use_main_ns: | |
306 | self.namespace = __main__.__dict__ |
|
306 | self.namespace = __main__.__dict__ | |
307 |
|
307 | |||
308 | if state == 0: |
|
308 | if state == 0: | |
309 | if "." in text: |
|
309 | if "." in text: | |
310 | self.matches = self.attr_matches(text) |
|
310 | self.matches = self.attr_matches(text) | |
311 | else: |
|
311 | else: | |
312 | self.matches = self.global_matches(text) |
|
312 | self.matches = self.global_matches(text) | |
313 | try: |
|
313 | try: | |
314 | return self.matches[state] |
|
314 | return self.matches[state] | |
315 | except IndexError: |
|
315 | except IndexError: | |
316 | return None |
|
316 | return None | |
317 |
|
317 | |||
318 | def global_matches(self, text): |
|
318 | def global_matches(self, text): | |
319 | """Compute matches when text is a simple name. |
|
319 | """Compute matches when text is a simple name. | |
320 |
|
320 | |||
321 | Return a list of all keywords, built-in functions and names currently |
|
321 | Return a list of all keywords, built-in functions and names currently | |
322 | defined in self.namespace or self.global_namespace that match. |
|
322 | defined in self.namespace or self.global_namespace that match. | |
323 |
|
323 | |||
324 | """ |
|
324 | """ | |
325 | #print 'Completer->global_matches, txt=%r' % text # dbg |
|
325 | #print 'Completer->global_matches, txt=%r' % text # dbg | |
326 | matches = [] |
|
326 | matches = [] | |
327 | match_append = matches.append |
|
327 | match_append = matches.append | |
328 | n = len(text) |
|
328 | n = len(text) | |
329 | for lst in [keyword.kwlist, |
|
329 | for lst in [keyword.kwlist, | |
330 | __builtin__.__dict__.keys(), |
|
330 | __builtin__.__dict__.keys(), | |
331 | self.namespace.keys(), |
|
331 | self.namespace.keys(), | |
332 | self.global_namespace.keys()]: |
|
332 | self.global_namespace.keys()]: | |
333 | for word in lst: |
|
333 | for word in lst: | |
334 | if word[:n] == text and word != "__builtins__": |
|
334 | if word[:n] == text and word != "__builtins__": | |
335 | match_append(word) |
|
335 | match_append(word) | |
336 | return matches |
|
336 | return matches | |
337 |
|
337 | |||
338 | def attr_matches(self, text): |
|
338 | def attr_matches(self, text): | |
339 | """Compute matches when text contains a dot. |
|
339 | """Compute matches when text contains a dot. | |
340 |
|
340 | |||
341 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
341 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
342 | evaluatable in self.namespace or self.global_namespace, it will be |
|
342 | evaluatable in self.namespace or self.global_namespace, it will be | |
343 | evaluated and its attributes (as revealed by dir()) are used as |
|
343 | evaluated and its attributes (as revealed by dir()) are used as | |
344 | possible completions. (For class instances, class members are are |
|
344 | possible completions. (For class instances, class members are are | |
345 | also considered.) |
|
345 | also considered.) | |
346 |
|
346 | |||
347 | WARNING: this can still invoke arbitrary C code, if an object |
|
347 | WARNING: this can still invoke arbitrary C code, if an object | |
348 | with a __getattr__ hook is evaluated. |
|
348 | with a __getattr__ hook is evaluated. | |
349 |
|
349 | |||
350 | """ |
|
350 | """ | |
351 |
|
351 | |||
352 | #print 'Completer->attr_matches, txt=%r' % text # dbg |
|
352 | #print 'Completer->attr_matches, txt=%r' % text # dbg | |
353 | # Another option, seems to work great. Catches things like ''.<tab> |
|
353 | # Another option, seems to work great. Catches things like ''.<tab> | |
354 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
354 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
355 |
|
355 | |||
356 | if not m: |
|
356 | if not m: | |
357 | return [] |
|
357 | return [] | |
358 |
|
358 | |||
359 | expr, attr = m.group(1, 3) |
|
359 | expr, attr = m.group(1, 3) | |
360 | try: |
|
360 | try: | |
361 | obj = eval(expr, self.namespace) |
|
361 | obj = eval(expr, self.namespace) | |
362 | except: |
|
362 | except: | |
363 | try: |
|
363 | try: | |
364 | obj = eval(expr, self.global_namespace) |
|
364 | obj = eval(expr, self.global_namespace) | |
365 | except: |
|
365 | except: | |
366 | return [] |
|
366 | return [] | |
367 |
|
367 | |||
368 | words = dir2(obj) |
|
368 | words = dir2(obj) | |
369 |
|
369 | |||
370 | try: |
|
370 | try: | |
371 | words = generics.complete_object(obj, words) |
|
371 | words = generics.complete_object(obj, words) | |
372 | except TryNext: |
|
372 | except TryNext: | |
373 | pass |
|
373 | pass | |
374 | # Build match list to return |
|
374 | # Build match list to return | |
375 | n = len(attr) |
|
375 | n = len(attr) | |
376 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
376 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
377 | return res |
|
377 | return res | |
378 |
|
378 | |||
379 |
|
379 | |||
380 | class IPCompleter(Completer): |
|
380 | class IPCompleter(Completer): | |
381 | """Extension of the completer class with IPython-specific features""" |
|
381 | """Extension of the completer class with IPython-specific features""" | |
382 |
|
382 | |||
383 | def __init__(self, shell, namespace=None, global_namespace=None, |
|
383 | def __init__(self, shell, namespace=None, global_namespace=None, | |
384 |
omit__names= |
|
384 | omit__names=True, alias_table=None, use_readline=True): | |
385 | """IPCompleter() -> completer |
|
385 | """IPCompleter() -> completer | |
386 |
|
386 | |||
387 | Return a completer object suitable for use by the readline library |
|
387 | Return a completer object suitable for use by the readline library | |
388 | via readline.set_completer(). |
|
388 | via readline.set_completer(). | |
389 |
|
389 | |||
390 | Inputs: |
|
390 | Inputs: | |
391 |
|
391 | |||
392 | - shell: a pointer to the ipython shell itself. This is needed |
|
392 | - shell: a pointer to the ipython shell itself. This is needed | |
393 | because this completer knows about magic functions, and those can |
|
393 | because this completer knows about magic functions, and those can | |
394 | only be accessed via the ipython instance. |
|
394 | only be accessed via the ipython instance. | |
395 |
|
395 | |||
396 | - namespace: an optional dict where completions are performed. |
|
396 | - namespace: an optional dict where completions are performed. | |
397 |
|
397 | |||
398 | - global_namespace: secondary optional dict for completions, to |
|
398 | - global_namespace: secondary optional dict for completions, to | |
399 | handle cases (such as IPython embedded inside functions) where |
|
399 | handle cases (such as IPython embedded inside functions) where | |
400 | both Python scopes are visible. |
|
400 | both Python scopes are visible. | |
401 |
|
401 | |||
402 | - The optional omit__names parameter sets the completer to omit the |
|
402 | - The optional omit__names parameter sets the completer to omit the | |
403 | 'magic' names (__magicname__) for python objects unless the text |
|
403 | 'magic' names (__magicname__) for python objects unless the text | |
404 | to be completed explicitly starts with one or more underscores. |
|
404 | to be completed explicitly starts with one or more underscores. | |
405 |
|
405 | |||
406 | - If alias_table is supplied, it should be a dictionary of aliases |
|
406 | - If alias_table is supplied, it should be a dictionary of aliases | |
407 | to complete. |
|
407 | to complete. | |
408 |
|
408 | |||
409 | use_readline : bool, optional |
|
409 | use_readline : bool, optional | |
410 | If true, use the readline library. This completer can still function |
|
410 | If true, use the readline library. This completer can still function | |
411 | without readline, though in that case callers must provide some extra |
|
411 | without readline, though in that case callers must provide some extra | |
412 | information on each call about the current line.""" |
|
412 | information on each call about the current line.""" | |
413 |
|
413 | |||
414 | Completer.__init__(self, namespace, global_namespace) |
|
414 | Completer.__init__(self, namespace, global_namespace) | |
415 |
|
415 | |||
416 | self.magic_escape = ESC_MAGIC |
|
416 | self.magic_escape = ESC_MAGIC | |
417 | self.splitter = CompletionSplitter() |
|
417 | self.splitter = CompletionSplitter() | |
418 |
|
418 | |||
419 | # Readline configuration, only used by the rlcompleter method. |
|
419 | # Readline configuration, only used by the rlcompleter method. | |
420 | if use_readline: |
|
420 | if use_readline: | |
421 | # We store the right version of readline so that later code |
|
421 | # We store the right version of readline so that later code | |
422 | import IPython.utils.rlineimpl as readline |
|
422 | import IPython.utils.rlineimpl as readline | |
423 | self.readline = readline |
|
423 | self.readline = readline | |
424 | else: |
|
424 | else: | |
425 | self.readline = None |
|
425 | self.readline = None | |
426 |
|
426 | |||
427 | # List where completion matches will be stored |
|
427 | # List where completion matches will be stored | |
428 | self.matches = [] |
|
428 | self.matches = [] | |
429 | self.omit__names = omit__names |
|
429 | self.omit__names = omit__names | |
430 | self.merge_completions = shell.readline_merge_completions |
|
430 | self.merge_completions = shell.readline_merge_completions | |
431 | self.shell = shell.shell |
|
431 | self.shell = shell.shell | |
432 | if alias_table is None: |
|
432 | if alias_table is None: | |
433 | alias_table = {} |
|
433 | alias_table = {} | |
434 | self.alias_table = alias_table |
|
434 | self.alias_table = alias_table | |
435 | # Regexp to split filenames with spaces in them |
|
435 | # Regexp to split filenames with spaces in them | |
436 | self.space_name_re = re.compile(r'([^\\] )') |
|
436 | self.space_name_re = re.compile(r'([^\\] )') | |
437 | # Hold a local ref. to glob.glob for speed |
|
437 | # Hold a local ref. to glob.glob for speed | |
438 | self.glob = glob.glob |
|
438 | self.glob = glob.glob | |
439 |
|
439 | |||
440 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
440 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
441 | # buffers, to avoid completion problems. |
|
441 | # buffers, to avoid completion problems. | |
442 | term = os.environ.get('TERM','xterm') |
|
442 | term = os.environ.get('TERM','xterm') | |
443 | self.dumb_terminal = term in ['dumb','emacs'] |
|
443 | self.dumb_terminal = term in ['dumb','emacs'] | |
444 |
|
444 | |||
445 | # Special handling of backslashes needed in win32 platforms |
|
445 | # Special handling of backslashes needed in win32 platforms | |
446 | if sys.platform == "win32": |
|
446 | if sys.platform == "win32": | |
447 | self.clean_glob = self._clean_glob_win32 |
|
447 | self.clean_glob = self._clean_glob_win32 | |
448 | else: |
|
448 | else: | |
449 | self.clean_glob = self._clean_glob |
|
449 | self.clean_glob = self._clean_glob | |
450 |
|
450 | |||
451 | # All active matcher routines for completion |
|
451 | # All active matcher routines for completion | |
452 | self.matchers = [self.python_matches, |
|
452 | self.matchers = [self.python_matches, | |
453 | self.file_matches, |
|
453 | self.file_matches, | |
454 | self.magic_matches, |
|
454 | self.magic_matches, | |
455 | self.alias_matches, |
|
455 | self.alias_matches, | |
456 | self.python_func_kw_matches, |
|
456 | self.python_func_kw_matches, | |
457 | ] |
|
457 | ] | |
458 |
|
458 | |||
459 | # Code contributed by Alex Schmolck, for ipython/emacs integration |
|
459 | # Code contributed by Alex Schmolck, for ipython/emacs integration | |
460 | def all_completions(self, text): |
|
460 | def all_completions(self, text): | |
461 | """Return all possible completions for the benefit of emacs.""" |
|
461 | """Return all possible completions for the benefit of emacs.""" | |
462 |
|
462 | |||
463 | completions = [] |
|
463 | completions = [] | |
464 | comp_append = completions.append |
|
464 | comp_append = completions.append | |
465 | try: |
|
465 | try: | |
466 | for i in xrange(sys.maxint): |
|
466 | for i in xrange(sys.maxint): | |
467 | res = self.complete(text, i, text) |
|
467 | res = self.complete(text, i, text) | |
468 | if not res: |
|
468 | if not res: | |
469 | break |
|
469 | break | |
470 | comp_append(res) |
|
470 | comp_append(res) | |
471 | #XXX workaround for ``notDefined.<tab>`` |
|
471 | #XXX workaround for ``notDefined.<tab>`` | |
472 | except NameError: |
|
472 | except NameError: | |
473 | pass |
|
473 | pass | |
474 | return completions |
|
474 | return completions | |
475 | # /end Alex Schmolck code. |
|
475 | # /end Alex Schmolck code. | |
476 |
|
476 | |||
477 | def _clean_glob(self,text): |
|
477 | def _clean_glob(self,text): | |
478 | return self.glob("%s*" % text) |
|
478 | return self.glob("%s*" % text) | |
479 |
|
479 | |||
480 | def _clean_glob_win32(self,text): |
|
480 | def _clean_glob_win32(self,text): | |
481 | return [f.replace("\\","/") |
|
481 | return [f.replace("\\","/") | |
482 | for f in self.glob("%s*" % text)] |
|
482 | for f in self.glob("%s*" % text)] | |
483 |
|
483 | |||
484 | def file_matches(self, text): |
|
484 | def file_matches(self, text): | |
485 | """Match filenames, expanding ~USER type strings. |
|
485 | """Match filenames, expanding ~USER type strings. | |
486 |
|
486 | |||
487 | Most of the seemingly convoluted logic in this completer is an |
|
487 | Most of the seemingly convoluted logic in this completer is an | |
488 | attempt to handle filenames with spaces in them. And yet it's not |
|
488 | attempt to handle filenames with spaces in them. And yet it's not | |
489 | quite perfect, because Python's readline doesn't expose all of the |
|
489 | quite perfect, because Python's readline doesn't expose all of the | |
490 | GNU readline details needed for this to be done correctly. |
|
490 | GNU readline details needed for this to be done correctly. | |
491 |
|
491 | |||
492 | For a filename with a space in it, the printed completions will be |
|
492 | For a filename with a space in it, the printed completions will be | |
493 | only the parts after what's already been typed (instead of the |
|
493 | only the parts after what's already been typed (instead of the | |
494 | full completions, as is normally done). I don't think with the |
|
494 | full completions, as is normally done). I don't think with the | |
495 | current (as of Python 2.3) Python readline it's possible to do |
|
495 | current (as of Python 2.3) Python readline it's possible to do | |
496 | better.""" |
|
496 | better.""" | |
497 |
|
497 | |||
498 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg |
|
498 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg | |
499 |
|
499 | |||
500 | # chars that require escaping with backslash - i.e. chars |
|
500 | # chars that require escaping with backslash - i.e. chars | |
501 | # that readline treats incorrectly as delimiters, but we |
|
501 | # that readline treats incorrectly as delimiters, but we | |
502 | # don't want to treat as delimiters in filename matching |
|
502 | # don't want to treat as delimiters in filename matching | |
503 | # when escaped with backslash |
|
503 | # when escaped with backslash | |
504 | if text.startswith('!'): |
|
504 | if text.startswith('!'): | |
505 | text = text[1:] |
|
505 | text = text[1:] | |
506 | text_prefix = '!' |
|
506 | text_prefix = '!' | |
507 | else: |
|
507 | else: | |
508 | text_prefix = '' |
|
508 | text_prefix = '' | |
509 |
|
509 | |||
510 | text_until_cursor = self.text_until_cursor |
|
510 | text_until_cursor = self.text_until_cursor | |
511 | # track strings with open quotes |
|
511 | # track strings with open quotes | |
512 | open_quotes = has_open_quotes(text_until_cursor) |
|
512 | open_quotes = has_open_quotes(text_until_cursor) | |
513 |
|
513 | |||
514 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
514 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
515 | lsplit = text |
|
515 | lsplit = text | |
516 | else: |
|
516 | else: | |
517 | try: |
|
517 | try: | |
518 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
518 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
519 | lsplit = arg_split(text_until_cursor)[-1] |
|
519 | lsplit = arg_split(text_until_cursor)[-1] | |
520 | except ValueError: |
|
520 | except ValueError: | |
521 | # typically an unmatched ", or backslash without escaped char. |
|
521 | # typically an unmatched ", or backslash without escaped char. | |
522 | if open_quotes: |
|
522 | if open_quotes: | |
523 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
523 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
524 | else: |
|
524 | else: | |
525 | return [] |
|
525 | return [] | |
526 | except IndexError: |
|
526 | except IndexError: | |
527 | # tab pressed on empty line |
|
527 | # tab pressed on empty line | |
528 | lsplit = "" |
|
528 | lsplit = "" | |
529 |
|
529 | |||
530 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
530 | if not open_quotes and lsplit != protect_filename(lsplit): | |
531 | # if protectables are found, do matching on the whole escaped name |
|
531 | # if protectables are found, do matching on the whole escaped name | |
532 | has_protectables = True |
|
532 | has_protectables = True | |
533 | text0,text = text,lsplit |
|
533 | text0,text = text,lsplit | |
534 | else: |
|
534 | else: | |
535 | has_protectables = False |
|
535 | has_protectables = False | |
536 | text = os.path.expanduser(text) |
|
536 | text = os.path.expanduser(text) | |
537 |
|
537 | |||
538 | if text == "": |
|
538 | if text == "": | |
539 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
539 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
540 |
|
540 | |||
541 | # Compute the matches from the filesystem |
|
541 | # Compute the matches from the filesystem | |
542 | m0 = self.clean_glob(text.replace('\\','')) |
|
542 | m0 = self.clean_glob(text.replace('\\','')) | |
543 |
|
543 | |||
544 | if has_protectables: |
|
544 | if has_protectables: | |
545 | # If we had protectables, we need to revert our changes to the |
|
545 | # If we had protectables, we need to revert our changes to the | |
546 | # beginning of filename so that we don't double-write the part |
|
546 | # beginning of filename so that we don't double-write the part | |
547 | # of the filename we have so far |
|
547 | # of the filename we have so far | |
548 | len_lsplit = len(lsplit) |
|
548 | len_lsplit = len(lsplit) | |
549 | matches = [text_prefix + text0 + |
|
549 | matches = [text_prefix + text0 + | |
550 | protect_filename(f[len_lsplit:]) for f in m0] |
|
550 | protect_filename(f[len_lsplit:]) for f in m0] | |
551 | else: |
|
551 | else: | |
552 | if open_quotes: |
|
552 | if open_quotes: | |
553 | # if we have a string with an open quote, we don't need to |
|
553 | # if we have a string with an open quote, we don't need to | |
554 | # protect the names at all (and we _shouldn't_, as it |
|
554 | # protect the names at all (and we _shouldn't_, as it | |
555 | # would cause bugs when the filesystem call is made). |
|
555 | # would cause bugs when the filesystem call is made). | |
556 | matches = m0 |
|
556 | matches = m0 | |
557 | else: |
|
557 | else: | |
558 | matches = [text_prefix + |
|
558 | matches = [text_prefix + | |
559 | protect_filename(f) for f in m0] |
|
559 | protect_filename(f) for f in m0] | |
560 |
|
560 | |||
561 | #io.rprint('mm', matches) # dbg |
|
561 | #io.rprint('mm', matches) # dbg | |
562 | return mark_dirs(matches) |
|
562 | return mark_dirs(matches) | |
563 |
|
563 | |||
564 | def magic_matches(self, text): |
|
564 | def magic_matches(self, text): | |
565 | """Match magics""" |
|
565 | """Match magics""" | |
566 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg |
|
566 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg | |
567 | # Get all shell magics now rather than statically, so magics loaded at |
|
567 | # Get all shell magics now rather than statically, so magics loaded at | |
568 | # runtime show up too |
|
568 | # runtime show up too | |
569 | magics = self.shell.lsmagic() |
|
569 | magics = self.shell.lsmagic() | |
570 | pre = self.magic_escape |
|
570 | pre = self.magic_escape | |
571 | baretext = text.lstrip(pre) |
|
571 | baretext = text.lstrip(pre) | |
572 | return [ pre+m for m in magics if m.startswith(baretext)] |
|
572 | return [ pre+m for m in magics if m.startswith(baretext)] | |
573 |
|
573 | |||
574 | def alias_matches(self, text): |
|
574 | def alias_matches(self, text): | |
575 | """Match internal system aliases""" |
|
575 | """Match internal system aliases""" | |
576 | #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg |
|
576 | #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg | |
577 |
|
577 | |||
578 | # if we are not in the first 'item', alias matching |
|
578 | # if we are not in the first 'item', alias matching | |
579 | # doesn't make sense - unless we are starting with 'sudo' command. |
|
579 | # doesn't make sense - unless we are starting with 'sudo' command. | |
580 | main_text = self.text_until_cursor.lstrip() |
|
580 | main_text = self.text_until_cursor.lstrip() | |
581 | if ' ' in main_text and not main_text.startswith('sudo'): |
|
581 | if ' ' in main_text and not main_text.startswith('sudo'): | |
582 | return [] |
|
582 | return [] | |
583 | text = os.path.expanduser(text) |
|
583 | text = os.path.expanduser(text) | |
584 | aliases = self.alias_table.keys() |
|
584 | aliases = self.alias_table.keys() | |
585 | if text == '': |
|
585 | if text == '': | |
586 | return aliases |
|
586 | return aliases | |
587 | else: |
|
587 | else: | |
588 | return [a for a in aliases if a.startswith(text)] |
|
588 | return [a for a in aliases if a.startswith(text)] | |
589 |
|
589 | |||
590 | def python_matches(self,text): |
|
590 | def python_matches(self,text): | |
591 | """Match attributes or global python names""" |
|
591 | """Match attributes or global python names""" | |
592 |
|
592 | |||
593 | #print 'Completer->python_matches, txt=%r' % text # dbg |
|
593 | #print 'Completer->python_matches, txt=%r' % text # dbg | |
594 | if "." in text: |
|
594 | if "." in text: | |
595 | try: |
|
595 | try: | |
596 | matches = self.attr_matches(text) |
|
596 | matches = self.attr_matches(text) | |
597 | if text.endswith('.') and self.omit__names: |
|
597 | if text.endswith('.') and self.omit__names: | |
598 | if self.omit__names == 1: |
|
598 | if self.omit__names == 1: | |
599 | # true if txt is _not_ a __ name, false otherwise: |
|
599 | # true if txt is _not_ a __ name, false otherwise: | |
600 | no__name = (lambda txt: |
|
600 | no__name = (lambda txt: | |
601 | re.match(r'.*\.__.*?__',txt) is None) |
|
601 | re.match(r'.*\.__.*?__',txt) is None) | |
602 | else: |
|
602 | else: | |
603 | # true if txt is _not_ a _ name, false otherwise: |
|
603 | # true if txt is _not_ a _ name, false otherwise: | |
604 | no__name = (lambda txt: |
|
604 | no__name = (lambda txt: | |
605 | re.match(r'.*\._.*?',txt) is None) |
|
605 | re.match(r'.*\._.*?',txt) is None) | |
606 | matches = filter(no__name, matches) |
|
606 | matches = filter(no__name, matches) | |
607 | except NameError: |
|
607 | except NameError: | |
608 | # catches <undefined attributes>.<tab> |
|
608 | # catches <undefined attributes>.<tab> | |
609 | matches = [] |
|
609 | matches = [] | |
610 | else: |
|
610 | else: | |
611 | matches = self.global_matches(text) |
|
611 | matches = self.global_matches(text) | |
612 |
|
612 | |||
613 | return matches |
|
613 | return matches | |
614 |
|
614 | |||
615 | def _default_arguments(self, obj): |
|
615 | def _default_arguments(self, obj): | |
616 | """Return the list of default arguments of obj if it is callable, |
|
616 | """Return the list of default arguments of obj if it is callable, | |
617 | or empty list otherwise.""" |
|
617 | or empty list otherwise.""" | |
618 |
|
618 | |||
619 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
619 | if not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
620 | # for classes, check for __init__,__new__ |
|
620 | # for classes, check for __init__,__new__ | |
621 | if inspect.isclass(obj): |
|
621 | if inspect.isclass(obj): | |
622 | obj = (getattr(obj,'__init__',None) or |
|
622 | obj = (getattr(obj,'__init__',None) or | |
623 | getattr(obj,'__new__',None)) |
|
623 | getattr(obj,'__new__',None)) | |
624 | # for all others, check if they are __call__able |
|
624 | # for all others, check if they are __call__able | |
625 | elif hasattr(obj, '__call__'): |
|
625 | elif hasattr(obj, '__call__'): | |
626 | obj = obj.__call__ |
|
626 | obj = obj.__call__ | |
627 | # XXX: is there a way to handle the builtins ? |
|
627 | # XXX: is there a way to handle the builtins ? | |
628 | try: |
|
628 | try: | |
629 | args,_,_1,defaults = inspect.getargspec(obj) |
|
629 | args,_,_1,defaults = inspect.getargspec(obj) | |
630 | if defaults: |
|
630 | if defaults: | |
631 | return args[-len(defaults):] |
|
631 | return args[-len(defaults):] | |
632 | except TypeError: pass |
|
632 | except TypeError: pass | |
633 | return [] |
|
633 | return [] | |
634 |
|
634 | |||
635 | def python_func_kw_matches(self,text): |
|
635 | def python_func_kw_matches(self,text): | |
636 | """Match named parameters (kwargs) of the last open function""" |
|
636 | """Match named parameters (kwargs) of the last open function""" | |
637 |
|
637 | |||
638 | if "." in text: # a parameter cannot be dotted |
|
638 | if "." in text: # a parameter cannot be dotted | |
639 | return [] |
|
639 | return [] | |
640 | try: regexp = self.__funcParamsRegex |
|
640 | try: regexp = self.__funcParamsRegex | |
641 | except AttributeError: |
|
641 | except AttributeError: | |
642 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
642 | regexp = self.__funcParamsRegex = re.compile(r''' | |
643 | '.*?' | # single quoted strings or |
|
643 | '.*?' | # single quoted strings or | |
644 | ".*?" | # double quoted strings or |
|
644 | ".*?" | # double quoted strings or | |
645 | \w+ | # identifier |
|
645 | \w+ | # identifier | |
646 | \S # other characters |
|
646 | \S # other characters | |
647 | ''', re.VERBOSE | re.DOTALL) |
|
647 | ''', re.VERBOSE | re.DOTALL) | |
648 | # 1. find the nearest identifier that comes before an unclosed |
|
648 | # 1. find the nearest identifier that comes before an unclosed | |
649 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" |
|
649 | # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo" | |
650 | tokens = regexp.findall(self.line_buffer) |
|
650 | tokens = regexp.findall(self.line_buffer) | |
651 | tokens.reverse() |
|
651 | tokens.reverse() | |
652 | iterTokens = iter(tokens); openPar = 0 |
|
652 | iterTokens = iter(tokens); openPar = 0 | |
653 | for token in iterTokens: |
|
653 | for token in iterTokens: | |
654 | if token == ')': |
|
654 | if token == ')': | |
655 | openPar -= 1 |
|
655 | openPar -= 1 | |
656 | elif token == '(': |
|
656 | elif token == '(': | |
657 | openPar += 1 |
|
657 | openPar += 1 | |
658 | if openPar > 0: |
|
658 | if openPar > 0: | |
659 | # found the last unclosed parenthesis |
|
659 | # found the last unclosed parenthesis | |
660 | break |
|
660 | break | |
661 | else: |
|
661 | else: | |
662 | return [] |
|
662 | return [] | |
663 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
663 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
664 | ids = [] |
|
664 | ids = [] | |
665 | isId = re.compile(r'\w+$').match |
|
665 | isId = re.compile(r'\w+$').match | |
666 | while True: |
|
666 | while True: | |
667 | try: |
|
667 | try: | |
668 | ids.append(iterTokens.next()) |
|
668 | ids.append(iterTokens.next()) | |
669 | if not isId(ids[-1]): |
|
669 | if not isId(ids[-1]): | |
670 | ids.pop(); break |
|
670 | ids.pop(); break | |
671 | if not iterTokens.next() == '.': |
|
671 | if not iterTokens.next() == '.': | |
672 | break |
|
672 | break | |
673 | except StopIteration: |
|
673 | except StopIteration: | |
674 | break |
|
674 | break | |
675 | # lookup the candidate callable matches either using global_matches |
|
675 | # lookup the candidate callable matches either using global_matches | |
676 | # or attr_matches for dotted names |
|
676 | # or attr_matches for dotted names | |
677 | if len(ids) == 1: |
|
677 | if len(ids) == 1: | |
678 | callableMatches = self.global_matches(ids[0]) |
|
678 | callableMatches = self.global_matches(ids[0]) | |
679 | else: |
|
679 | else: | |
680 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
680 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
681 | argMatches = [] |
|
681 | argMatches = [] | |
682 | for callableMatch in callableMatches: |
|
682 | for callableMatch in callableMatches: | |
683 | try: |
|
683 | try: | |
684 | namedArgs = self._default_arguments(eval(callableMatch, |
|
684 | namedArgs = self._default_arguments(eval(callableMatch, | |
685 | self.namespace)) |
|
685 | self.namespace)) | |
686 | except: |
|
686 | except: | |
687 | continue |
|
687 | continue | |
688 | for namedArg in namedArgs: |
|
688 | for namedArg in namedArgs: | |
689 | if namedArg.startswith(text): |
|
689 | if namedArg.startswith(text): | |
690 | argMatches.append("%s=" %namedArg) |
|
690 | argMatches.append("%s=" %namedArg) | |
691 | return argMatches |
|
691 | return argMatches | |
692 |
|
692 | |||
693 | def dispatch_custom_completer(self, text): |
|
693 | def dispatch_custom_completer(self, text): | |
694 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg |
|
694 | #print "Custom! '%s' %s" % (text, self.custom_completers) # dbg | |
695 | line = self.line_buffer |
|
695 | line = self.line_buffer | |
696 | if not line.strip(): |
|
696 | if not line.strip(): | |
697 | return None |
|
697 | return None | |
698 |
|
698 | |||
699 | # Create a little structure to pass all the relevant information about |
|
699 | # Create a little structure to pass all the relevant information about | |
700 | # the current completion to any custom completer. |
|
700 | # the current completion to any custom completer. | |
701 | event = Bunch() |
|
701 | event = Bunch() | |
702 | event.line = line |
|
702 | event.line = line | |
703 | event.symbol = text |
|
703 | event.symbol = text | |
704 | cmd = line.split(None,1)[0] |
|
704 | cmd = line.split(None,1)[0] | |
705 | event.command = cmd |
|
705 | event.command = cmd | |
706 | event.text_until_cursor = self.text_until_cursor |
|
706 | event.text_until_cursor = self.text_until_cursor | |
707 |
|
707 | |||
708 | #print "\ncustom:{%s]\n" % event # dbg |
|
708 | #print "\ncustom:{%s]\n" % event # dbg | |
709 |
|
709 | |||
710 | # for foo etc, try also to find completer for %foo |
|
710 | # for foo etc, try also to find completer for %foo | |
711 | if not cmd.startswith(self.magic_escape): |
|
711 | if not cmd.startswith(self.magic_escape): | |
712 | try_magic = self.custom_completers.s_matches( |
|
712 | try_magic = self.custom_completers.s_matches( | |
713 | self.magic_escape + cmd) |
|
713 | self.magic_escape + cmd) | |
714 | else: |
|
714 | else: | |
715 | try_magic = [] |
|
715 | try_magic = [] | |
716 |
|
716 | |||
717 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
717 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
718 | try_magic, |
|
718 | try_magic, | |
719 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
719 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
720 | #print "try",c # dbg |
|
720 | #print "try",c # dbg | |
721 | try: |
|
721 | try: | |
722 | res = c(event) |
|
722 | res = c(event) | |
723 | if res: |
|
723 | if res: | |
724 | # first, try case sensitive match |
|
724 | # first, try case sensitive match | |
725 | withcase = [r for r in res if r.startswith(text)] |
|
725 | withcase = [r for r in res if r.startswith(text)] | |
726 | if withcase: |
|
726 | if withcase: | |
727 | return withcase |
|
727 | return withcase | |
728 | # if none, then case insensitive ones are ok too |
|
728 | # if none, then case insensitive ones are ok too | |
729 | text_low = text.lower() |
|
729 | text_low = text.lower() | |
730 | return [r for r in res if r.lower().startswith(text_low)] |
|
730 | return [r for r in res if r.lower().startswith(text_low)] | |
731 | except TryNext: |
|
731 | except TryNext: | |
732 | pass |
|
732 | pass | |
733 |
|
733 | |||
734 | return None |
|
734 | return None | |
735 |
|
735 | |||
736 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
736 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
737 | """Find completions for the given text and line context. |
|
737 | """Find completions for the given text and line context. | |
738 |
|
738 | |||
739 | This is called successively with state == 0, 1, 2, ... until it |
|
739 | This is called successively with state == 0, 1, 2, ... until it | |
740 | returns None. The completion should begin with 'text'. |
|
740 | returns None. The completion should begin with 'text'. | |
741 |
|
741 | |||
742 | Note that both the text and the line_buffer are optional, but at least |
|
742 | Note that both the text and the line_buffer are optional, but at least | |
743 | one of them must be given. |
|
743 | one of them must be given. | |
744 |
|
744 | |||
745 | Parameters |
|
745 | Parameters | |
746 | ---------- |
|
746 | ---------- | |
747 | text : string, optional |
|
747 | text : string, optional | |
748 | Text to perform the completion on. If not given, the line buffer |
|
748 | Text to perform the completion on. If not given, the line buffer | |
749 | is split using the instance's CompletionSplitter object. |
|
749 | is split using the instance's CompletionSplitter object. | |
750 |
|
750 | |||
751 | line_buffer : string, optional |
|
751 | line_buffer : string, optional | |
752 | If not given, the completer attempts to obtain the current line |
|
752 | If not given, the completer attempts to obtain the current line | |
753 | buffer via readline. This keyword allows clients which are |
|
753 | buffer via readline. This keyword allows clients which are | |
754 | requesting for text completions in non-readline contexts to inform |
|
754 | requesting for text completions in non-readline contexts to inform | |
755 | the completer of the entire text. |
|
755 | the completer of the entire text. | |
756 |
|
756 | |||
757 | cursor_pos : int, optional |
|
757 | cursor_pos : int, optional | |
758 | Index of the cursor in the full line buffer. Should be provided by |
|
758 | Index of the cursor in the full line buffer. Should be provided by | |
759 | remote frontends where kernel has no access to frontend state. |
|
759 | remote frontends where kernel has no access to frontend state. | |
760 |
|
760 | |||
761 | Returns |
|
761 | Returns | |
762 | ------- |
|
762 | ------- | |
763 | text : str |
|
763 | text : str | |
764 | Text that was actually used in the completion. |
|
764 | Text that was actually used in the completion. | |
765 |
|
765 | |||
766 | matches : list |
|
766 | matches : list | |
767 | A list of completion matches. |
|
767 | A list of completion matches. | |
768 | """ |
|
768 | """ | |
769 | #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
769 | #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
770 |
|
770 | |||
771 | # if the cursor position isn't given, the only sane assumption we can |
|
771 | # if the cursor position isn't given, the only sane assumption we can | |
772 | # make is that it's at the end of the line (the common case) |
|
772 | # make is that it's at the end of the line (the common case) | |
773 | if cursor_pos is None: |
|
773 | if cursor_pos is None: | |
774 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
774 | cursor_pos = len(line_buffer) if text is None else len(text) | |
775 |
|
775 | |||
776 | # if text is either None or an empty string, rely on the line buffer |
|
776 | # if text is either None or an empty string, rely on the line buffer | |
777 | if not text: |
|
777 | if not text: | |
778 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
778 | text = self.splitter.split_line(line_buffer, cursor_pos) | |
779 |
|
779 | |||
780 | # If no line buffer is given, assume the input text is all there was |
|
780 | # If no line buffer is given, assume the input text is all there was | |
781 | if line_buffer is None: |
|
781 | if line_buffer is None: | |
782 | line_buffer = text |
|
782 | line_buffer = text | |
783 |
|
783 | |||
784 | self.line_buffer = line_buffer |
|
784 | self.line_buffer = line_buffer | |
785 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
785 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
786 | #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
786 | #io.rprint('\nCOMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
787 |
|
787 | |||
788 | # Start with a clean slate of completions |
|
788 | # Start with a clean slate of completions | |
789 | self.matches[:] = [] |
|
789 | self.matches[:] = [] | |
790 | custom_res = self.dispatch_custom_completer(text) |
|
790 | custom_res = self.dispatch_custom_completer(text) | |
791 | if custom_res is not None: |
|
791 | if custom_res is not None: | |
792 | # did custom completers produce something? |
|
792 | # did custom completers produce something? | |
793 | self.matches = custom_res |
|
793 | self.matches = custom_res | |
794 | else: |
|
794 | else: | |
795 | # Extend the list of completions with the results of each |
|
795 | # Extend the list of completions with the results of each | |
796 | # matcher, so we return results to the user from all |
|
796 | # matcher, so we return results to the user from all | |
797 | # namespaces. |
|
797 | # namespaces. | |
798 | if self.merge_completions: |
|
798 | if self.merge_completions: | |
799 | self.matches = [] |
|
799 | self.matches = [] | |
800 | for matcher in self.matchers: |
|
800 | for matcher in self.matchers: | |
801 | try: |
|
801 | try: | |
802 | self.matches.extend(matcher(text)) |
|
802 | self.matches.extend(matcher(text)) | |
803 | except: |
|
803 | except: | |
804 | # Show the ugly traceback if the matcher causes an |
|
804 | # Show the ugly traceback if the matcher causes an | |
805 | # exception, but do NOT crash the kernel! |
|
805 | # exception, but do NOT crash the kernel! | |
806 | sys.excepthook(*sys.exc_info()) |
|
806 | sys.excepthook(*sys.exc_info()) | |
807 | else: |
|
807 | else: | |
808 | for matcher in self.matchers: |
|
808 | for matcher in self.matchers: | |
809 | self.matches = matcher(text) |
|
809 | self.matches = matcher(text) | |
810 | if self.matches: |
|
810 | if self.matches: | |
811 | break |
|
811 | break | |
812 | # FIXME: we should extend our api to return a dict with completions for |
|
812 | # FIXME: we should extend our api to return a dict with completions for | |
813 | # different types of objects. The rlcomplete() method could then |
|
813 | # different types of objects. The rlcomplete() method could then | |
814 | # simply collapse the dict into a list for readline, but we'd have |
|
814 | # simply collapse the dict into a list for readline, but we'd have | |
815 | # richer completion semantics in other evironments. |
|
815 | # richer completion semantics in other evironments. | |
816 | self.matches = sorted(set(self.matches)) |
|
816 | self.matches = sorted(set(self.matches)) | |
817 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg |
|
817 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg | |
818 | return text, self.matches |
|
818 | return text, self.matches | |
819 |
|
819 | |||
820 | def rlcomplete(self, text, state): |
|
820 | def rlcomplete(self, text, state): | |
821 | """Return the state-th possible completion for 'text'. |
|
821 | """Return the state-th possible completion for 'text'. | |
822 |
|
822 | |||
823 | This is called successively with state == 0, 1, 2, ... until it |
|
823 | This is called successively with state == 0, 1, 2, ... until it | |
824 | returns None. The completion should begin with 'text'. |
|
824 | returns None. The completion should begin with 'text'. | |
825 |
|
825 | |||
826 | Parameters |
|
826 | Parameters | |
827 | ---------- |
|
827 | ---------- | |
828 | text : string |
|
828 | text : string | |
829 | Text to perform the completion on. |
|
829 | Text to perform the completion on. | |
830 |
|
830 | |||
831 | state : int |
|
831 | state : int | |
832 | Counter used by readline. |
|
832 | Counter used by readline. | |
833 | """ |
|
833 | """ | |
834 | if state==0: |
|
834 | if state==0: | |
835 |
|
835 | |||
836 | self.line_buffer = line_buffer = self.readline.get_line_buffer() |
|
836 | self.line_buffer = line_buffer = self.readline.get_line_buffer() | |
837 | cursor_pos = self.readline.get_endidx() |
|
837 | cursor_pos = self.readline.get_endidx() | |
838 |
|
838 | |||
839 | #io.rprint("\nRLCOMPLETE: %r %r %r" % |
|
839 | #io.rprint("\nRLCOMPLETE: %r %r %r" % | |
840 | # (text, line_buffer, cursor_pos) ) # dbg |
|
840 | # (text, line_buffer, cursor_pos) ) # dbg | |
841 |
|
841 | |||
842 | # if there is only a tab on a line with only whitespace, instead of |
|
842 | # if there is only a tab on a line with only whitespace, instead of | |
843 | # the mostly useless 'do you want to see all million completions' |
|
843 | # the mostly useless 'do you want to see all million completions' | |
844 | # message, just do the right thing and give the user his tab! |
|
844 | # message, just do the right thing and give the user his tab! | |
845 | # Incidentally, this enables pasting of tabbed text from an editor |
|
845 | # Incidentally, this enables pasting of tabbed text from an editor | |
846 | # (as long as autoindent is off). |
|
846 | # (as long as autoindent is off). | |
847 |
|
847 | |||
848 | # It should be noted that at least pyreadline still shows file |
|
848 | # It should be noted that at least pyreadline still shows file | |
849 | # completions - is there a way around it? |
|
849 | # completions - is there a way around it? | |
850 |
|
850 | |||
851 | # don't apply this on 'dumb' terminals, such as emacs buffers, so |
|
851 | # don't apply this on 'dumb' terminals, such as emacs buffers, so | |
852 | # we don't interfere with their own tab-completion mechanism. |
|
852 | # we don't interfere with their own tab-completion mechanism. | |
853 | if not (self.dumb_terminal or line_buffer.strip()): |
|
853 | if not (self.dumb_terminal or line_buffer.strip()): | |
854 | self.readline.insert_text('\t') |
|
854 | self.readline.insert_text('\t') | |
855 | sys.stdout.flush() |
|
855 | sys.stdout.flush() | |
856 | return None |
|
856 | return None | |
857 |
|
857 | |||
858 | # Note: debugging exceptions that may occur in completion is very |
|
858 | # Note: debugging exceptions that may occur in completion is very | |
859 | # tricky, because readline unconditionally silences them. So if |
|
859 | # tricky, because readline unconditionally silences them. So if | |
860 | # during development you suspect a bug in the completion code, turn |
|
860 | # during development you suspect a bug in the completion code, turn | |
861 | # this flag on temporarily by uncommenting the second form (don't |
|
861 | # this flag on temporarily by uncommenting the second form (don't | |
862 | # flip the value in the first line, as the '# dbg' marker can be |
|
862 | # flip the value in the first line, as the '# dbg' marker can be | |
863 | # automatically detected and is used elsewhere). |
|
863 | # automatically detected and is used elsewhere). | |
864 | DEBUG = False |
|
864 | DEBUG = False | |
865 | #DEBUG = True # dbg |
|
865 | #DEBUG = True # dbg | |
866 | if DEBUG: |
|
866 | if DEBUG: | |
867 | try: |
|
867 | try: | |
868 | self.complete(text, line_buffer, cursor_pos) |
|
868 | self.complete(text, line_buffer, cursor_pos) | |
869 | except: |
|
869 | except: | |
870 | import traceback; traceback.print_exc() |
|
870 | import traceback; traceback.print_exc() | |
871 | else: |
|
871 | else: | |
872 | # The normal production version is here |
|
872 | # The normal production version is here | |
873 |
|
873 | |||
874 | # This method computes the self.matches array |
|
874 | # This method computes the self.matches array | |
875 | self.complete(text, line_buffer, cursor_pos) |
|
875 | self.complete(text, line_buffer, cursor_pos) | |
876 |
|
876 | |||
877 | try: |
|
877 | try: | |
878 | return self.matches[state] |
|
878 | return self.matches[state] | |
879 | except IndexError: |
|
879 | except IndexError: | |
880 | return None |
|
880 | return None |
@@ -1,202 +1,208 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Pylab (matplotlib) support utilities. |
|
2 | """Pylab (matplotlib) support utilities. | |
3 |
|
3 | |||
4 | Authors |
|
4 | Authors | |
5 | ------- |
|
5 | ------- | |
6 |
|
6 | |||
7 | * Fernando Perez. |
|
7 | * Fernando Perez. | |
8 | * Brian Granger |
|
8 | * Brian Granger | |
9 | """ |
|
9 | """ | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Copyright (C) 2009 The IPython Development Team |
|
12 | # Copyright (C) 2009 The IPython Development Team | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 | # Imports |
|
19 | # Imports | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | from IPython.utils.decorators import flag_calls |
|
22 | from IPython.utils.decorators import flag_calls | |
23 |
|
23 | |||
24 | # If user specifies a GUI, that dictates the backend, otherwise we read the |
|
24 | # If user specifies a GUI, that dictates the backend, otherwise we read the | |
25 | # user's mpl default from the mpl rc structure |
|
25 | # user's mpl default from the mpl rc structure | |
26 | backends = {'tk': 'TkAgg', |
|
26 | backends = {'tk': 'TkAgg', | |
27 | 'gtk': 'GTKAgg', |
|
27 | 'gtk': 'GTKAgg', | |
28 | 'wx': 'WXAgg', |
|
28 | 'wx': 'WXAgg', | |
29 | 'qt': 'Qt4Agg', # qt3 not supported |
|
29 | 'qt': 'Qt4Agg', # qt3 not supported | |
30 | 'qt4': 'Qt4Agg', |
|
30 | 'qt4': 'Qt4Agg', | |
31 | 'inline' : 'module://IPython.zmq.pylab.backend_inline'} |
|
31 | 'inline' : 'module://IPython.zmq.pylab.backend_inline'} | |
32 |
|
32 | |||
33 | #----------------------------------------------------------------------------- |
|
33 | #----------------------------------------------------------------------------- | |
34 | # Main classes and functions |
|
34 | # Main classes and functions | |
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 |
|
36 | |||
37 |
|
37 | |||
38 | def find_gui_and_backend(gui=None): |
|
38 | def find_gui_and_backend(gui=None): | |
39 | """Given a gui string return the gui and mpl backend. |
|
39 | """Given a gui string return the gui and mpl backend. | |
40 |
|
40 | |||
41 | Parameters |
|
41 | Parameters | |
42 | ---------- |
|
42 | ---------- | |
43 | gui : str |
|
43 | gui : str | |
44 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
|
44 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). | |
45 |
|
45 | |||
46 | Returns |
|
46 | Returns | |
47 | ------- |
|
47 | ------- | |
48 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', |
|
48 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', | |
49 | 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). |
|
49 | 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). | |
50 | """ |
|
50 | """ | |
51 |
|
51 | |||
52 | import matplotlib |
|
52 | import matplotlib | |
53 |
|
53 | |||
54 | if gui: |
|
54 | if gui: | |
55 | # select backend based on requested gui |
|
55 | # select backend based on requested gui | |
56 | backend = backends[gui] |
|
56 | backend = backends[gui] | |
57 | else: |
|
57 | else: | |
58 | backend = matplotlib.rcParams['backend'] |
|
58 | backend = matplotlib.rcParams['backend'] | |
59 | # In this case, we need to find what the appropriate gui selection call |
|
59 | # In this case, we need to find what the appropriate gui selection call | |
60 | # should be for IPython, so we can activate inputhook accordingly |
|
60 | # should be for IPython, so we can activate inputhook accordingly | |
61 | g2b = backends # maps gui names to mpl backend names |
|
61 | g2b = backends # maps gui names to mpl backend names | |
62 | b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict |
|
62 | b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict | |
63 | gui = b2g.get(backend, None) |
|
63 | gui = b2g.get(backend, None) | |
64 | return gui, backend |
|
64 | return gui, backend | |
65 |
|
65 | |||
66 |
|
66 | |||
67 | def activate_matplotlib(backend): |
|
67 | def activate_matplotlib(backend): | |
68 | """Activate the given backend and set interactive to True.""" |
|
68 | """Activate the given backend and set interactive to True.""" | |
69 |
|
69 | |||
70 | import matplotlib |
|
70 | import matplotlib | |
71 | if backend.startswith('module://'): |
|
71 | if backend.startswith('module://'): | |
72 | # Work around bug in matplotlib: matplotlib.use converts the |
|
72 | # Work around bug in matplotlib: matplotlib.use converts the | |
73 | # backend_id to lowercase even if a module name is specified! |
|
73 | # backend_id to lowercase even if a module name is specified! | |
74 | matplotlib.rcParams['backend'] = backend |
|
74 | matplotlib.rcParams['backend'] = backend | |
75 | else: |
|
75 | else: | |
76 | matplotlib.use(backend) |
|
76 | matplotlib.use(backend) | |
77 | matplotlib.interactive(True) |
|
77 | matplotlib.interactive(True) | |
78 |
|
78 | |||
79 | # This must be imported last in the matplotlib series, after |
|
79 | # This must be imported last in the matplotlib series, after | |
80 | # backend/interactivity choices have been made |
|
80 | # backend/interactivity choices have been made | |
81 | import matplotlib.pylab as pylab |
|
81 | import matplotlib.pylab as pylab | |
82 |
|
82 | |||
83 | # XXX For now leave this commented out, but depending on discussions with |
|
83 | # XXX For now leave this commented out, but depending on discussions with | |
84 | # mpl-dev, we may be able to allow interactive switching... |
|
84 | # mpl-dev, we may be able to allow interactive switching... | |
85 | #import matplotlib.pyplot |
|
85 | #import matplotlib.pyplot | |
86 | #matplotlib.pyplot.switch_backend(backend) |
|
86 | #matplotlib.pyplot.switch_backend(backend) | |
87 |
|
87 | |||
88 | pylab.show._needmain = False |
|
88 | pylab.show._needmain = False | |
89 | # We need to detect at runtime whether show() is called by the user. |
|
89 | # We need to detect at runtime whether show() is called by the user. | |
90 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
90 | # For this, we wrap it into a decorator which adds a 'called' flag. | |
91 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) |
|
91 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) | |
92 |
|
92 | |||
93 |
|
93 | |||
94 | def import_pylab(user_ns, backend, import_all=True, shell=None): |
|
94 | def import_pylab(user_ns, backend, import_all=True, shell=None): | |
95 | """Import the standard pylab symbols into user_ns.""" |
|
95 | """Import the standard pylab symbols into user_ns.""" | |
96 |
|
96 | |||
97 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
97 | # Import numpy as np/pyplot as plt are conventions we're trying to | |
98 | # somewhat standardize on. Making them available to users by default |
|
98 | # somewhat standardize on. Making them available to users by default | |
99 |
# will greatly help this. |
|
99 | # will greatly help this. | |
100 |
|
|
100 | s = ("import numpy\n" | |
101 | "import matplotlib\n" |
|
101 | "import matplotlib\n" | |
102 | "from matplotlib import pylab, mlab, pyplot\n" |
|
102 | "from matplotlib import pylab, mlab, pyplot\n" | |
103 | "np = numpy\n" |
|
103 | "np = numpy\n" | |
104 | "plt = pyplot\n" |
|
104 | "plt = pyplot\n" | |
105 |
) |
|
105 | ) | |
|
106 | exec s in user_ns | |||
106 |
|
107 | |||
107 | if shell is not None: |
|
108 | if shell is not None: | |
|
109 | exec s in shell.user_ns_hidden | |||
108 | # If using our svg payload backend, register the post-execution |
|
110 | # If using our svg payload backend, register the post-execution | |
109 | # function that will pick up the results for display. This can only be |
|
111 | # function that will pick up the results for display. This can only be | |
110 | # done with access to the real shell object. |
|
112 | # done with access to the real shell object. | |
111 | if backend == backends['inline']: |
|
113 | if backend == backends['inline']: | |
112 | from IPython.zmq.pylab.backend_inline import flush_svg, figsize |
|
114 | from IPython.zmq.pylab.backend_inline import flush_svg, figsize | |
113 | from matplotlib import pyplot |
|
115 | from matplotlib import pyplot | |
114 | shell.register_post_execute(flush_svg) |
|
116 | shell.register_post_execute(flush_svg) | |
115 | # The typical default figure size is too large for inline use. We |
|
117 | # The typical default figure size is too large for inline use. We | |
116 | # might make this a user-configurable parameter later. |
|
118 | # might make this a user-configurable parameter later. | |
117 | figsize(6.0, 4.0) |
|
119 | figsize(6.0, 4.0) | |
118 | # Add 'figsize' to pyplot and to the user's namespace |
|
120 | # Add 'figsize' to pyplot and to the user's namespace | |
119 | user_ns['figsize'] = pyplot.figsize = figsize |
|
121 | user_ns['figsize'] = pyplot.figsize = figsize | |
|
122 | shell.user_ns_hidden['figsize'] = figsize | |||
120 | else: |
|
123 | else: | |
121 | from IPython.zmq.pylab.backend_inline import pastefig |
|
124 | from IPython.zmq.pylab.backend_inline import pastefig | |
122 | from matplotlib import pyplot |
|
125 | from matplotlib import pyplot | |
123 | # Add 'paste' to pyplot and to the user's namespace |
|
126 | # Add 'paste' to pyplot and to the user's namespace | |
124 | user_ns['pastefig'] = pyplot.pastefig = pastefig |
|
127 | user_ns['pastefig'] = pyplot.pastefig = pastefig | |
125 |
|
128 | |||
126 | if import_all: |
|
129 | if import_all: | |
127 |
|
|
130 | s = ("from matplotlib.pylab import *\n" | |
128 |
"from numpy import *\n") |
|
131 | "from numpy import *\n") | |
|
132 | exec s in user_ns | |||
|
133 | if shell is not None: | |||
|
134 | exec s in shell.user_ns_hidden | |||
129 |
|
135 | |||
130 |
|
136 | |||
131 | def pylab_activate(user_ns, gui=None, import_all=True): |
|
137 | def pylab_activate(user_ns, gui=None, import_all=True): | |
132 | """Activate pylab mode in the user's namespace. |
|
138 | """Activate pylab mode in the user's namespace. | |
133 |
|
139 | |||
134 | Loads and initializes numpy, matplotlib and friends for interactive use. |
|
140 | Loads and initializes numpy, matplotlib and friends for interactive use. | |
135 |
|
141 | |||
136 | Parameters |
|
142 | Parameters | |
137 | ---------- |
|
143 | ---------- | |
138 | user_ns : dict |
|
144 | user_ns : dict | |
139 | Namespace where the imports will occur. |
|
145 | Namespace where the imports will occur. | |
140 |
|
146 | |||
141 | gui : optional, string |
|
147 | gui : optional, string | |
142 | A valid gui name following the conventions of the %gui magic. |
|
148 | A valid gui name following the conventions of the %gui magic. | |
143 |
|
149 | |||
144 | import_all : optional, boolean |
|
150 | import_all : optional, boolean | |
145 | If true, an 'import *' is done from numpy and pylab. |
|
151 | If true, an 'import *' is done from numpy and pylab. | |
146 |
|
152 | |||
147 | Returns |
|
153 | Returns | |
148 | ------- |
|
154 | ------- | |
149 | The actual gui used (if not given as input, it was obtained from matplotlib |
|
155 | The actual gui used (if not given as input, it was obtained from matplotlib | |
150 | itself, and will be needed next to configure IPython's gui integration. |
|
156 | itself, and will be needed next to configure IPython's gui integration. | |
151 | """ |
|
157 | """ | |
152 | gui, backend = find_gui_and_backend(gui) |
|
158 | gui, backend = find_gui_and_backend(gui) | |
153 | activate_matplotlib(backend) |
|
159 | activate_matplotlib(backend) | |
154 | import_pylab(user_ns, backend) |
|
160 | import_pylab(user_ns, backend) | |
155 |
|
161 | |||
156 | print """ |
|
162 | print """ | |
157 | Welcome to pylab, a matplotlib-based Python environment [backend: %s]. |
|
163 | Welcome to pylab, a matplotlib-based Python environment [backend: %s]. | |
158 | For more information, type 'help(pylab)'.""" % backend |
|
164 | For more information, type 'help(pylab)'.""" % backend | |
159 |
|
165 | |||
160 | return gui |
|
166 | return gui | |
161 |
|
167 | |||
162 | # We need a little factory function here to create the closure where |
|
168 | # We need a little factory function here to create the closure where | |
163 | # safe_execfile can live. |
|
169 | # safe_execfile can live. | |
164 | def mpl_runner(safe_execfile): |
|
170 | def mpl_runner(safe_execfile): | |
165 | """Factory to return a matplotlib-enabled runner for %run. |
|
171 | """Factory to return a matplotlib-enabled runner for %run. | |
166 |
|
172 | |||
167 | Parameters |
|
173 | Parameters | |
168 | ---------- |
|
174 | ---------- | |
169 | safe_execfile : function |
|
175 | safe_execfile : function | |
170 | This must be a function with the same interface as the |
|
176 | This must be a function with the same interface as the | |
171 | :meth:`safe_execfile` method of IPython. |
|
177 | :meth:`safe_execfile` method of IPython. | |
172 |
|
178 | |||
173 | Returns |
|
179 | Returns | |
174 | ------- |
|
180 | ------- | |
175 | A function suitable for use as the ``runner`` argument of the %run magic |
|
181 | A function suitable for use as the ``runner`` argument of the %run magic | |
176 | function. |
|
182 | function. | |
177 | """ |
|
183 | """ | |
178 |
|
184 | |||
179 | def mpl_execfile(fname,*where,**kw): |
|
185 | def mpl_execfile(fname,*where,**kw): | |
180 | """matplotlib-aware wrapper around safe_execfile. |
|
186 | """matplotlib-aware wrapper around safe_execfile. | |
181 |
|
187 | |||
182 | Its interface is identical to that of the :func:`execfile` builtin. |
|
188 | Its interface is identical to that of the :func:`execfile` builtin. | |
183 |
|
189 | |||
184 | This is ultimately a call to execfile(), but wrapped in safeties to |
|
190 | This is ultimately a call to execfile(), but wrapped in safeties to | |
185 | properly handle interactive rendering.""" |
|
191 | properly handle interactive rendering.""" | |
186 |
|
192 | |||
187 | import matplotlib |
|
193 | import matplotlib | |
188 | import matplotlib.pylab as pylab |
|
194 | import matplotlib.pylab as pylab | |
189 |
|
195 | |||
190 | #print '*** Matplotlib runner ***' # dbg |
|
196 | #print '*** Matplotlib runner ***' # dbg | |
191 | # turn off rendering until end of script |
|
197 | # turn off rendering until end of script | |
192 | is_interactive = matplotlib.rcParams['interactive'] |
|
198 | is_interactive = matplotlib.rcParams['interactive'] | |
193 | matplotlib.interactive(False) |
|
199 | matplotlib.interactive(False) | |
194 | safe_execfile(fname,*where,**kw) |
|
200 | safe_execfile(fname,*where,**kw) | |
195 | matplotlib.interactive(is_interactive) |
|
201 | matplotlib.interactive(is_interactive) | |
196 | # make rendering call now, if the user tried to do it |
|
202 | # make rendering call now, if the user tried to do it | |
197 | if pylab.draw_if_interactive.called: |
|
203 | if pylab.draw_if_interactive.called: | |
198 | pylab.draw() |
|
204 | pylab.draw() | |
199 | pylab.draw_if_interactive.called = False |
|
205 | pylab.draw_if_interactive.called = False | |
200 |
|
206 | |||
201 | return mpl_execfile |
|
207 | return mpl_execfile | |
202 |
|
208 |
General Comments 0
You need to be logged in to leave comments.
Login now