Show More
@@ -1,1289 +1,1277 b'' | |||||
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 import io |
|
72 | from IPython.utils import io | |
73 | from IPython.utils.decorators import undoc |
|
73 | from IPython.utils.decorators import undoc | |
74 |
from IPython.utils.dir2 import dir2, |
|
74 | from IPython.utils.dir2 import dir2, get_real_method | |
75 | from IPython.utils.process import arg_split |
|
75 | from IPython.utils.process import arg_split | |
76 | from IPython.utils.py3compat import builtin_mod, string_types, PY3 |
|
76 | from IPython.utils.py3compat import builtin_mod, string_types, PY3 | |
77 | from traitlets import CBool, Enum |
|
77 | from traitlets import CBool, Enum | |
78 |
|
78 | |||
79 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
80 | # Globals |
|
80 | # Globals | |
81 | #----------------------------------------------------------------------------- |
|
81 | #----------------------------------------------------------------------------- | |
82 |
|
82 | |||
83 | # Public API |
|
83 | # Public API | |
84 | __all__ = ['Completer','IPCompleter'] |
|
84 | __all__ = ['Completer','IPCompleter'] | |
85 |
|
85 | |||
86 | if sys.platform == 'win32': |
|
86 | if sys.platform == 'win32': | |
87 | PROTECTABLES = ' ' |
|
87 | PROTECTABLES = ' ' | |
88 | else: |
|
88 | else: | |
89 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
89 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | #----------------------------------------------------------------------------- |
|
92 | #----------------------------------------------------------------------------- | |
93 | # Main functions and classes |
|
93 | # Main functions and classes | |
94 | #----------------------------------------------------------------------------- |
|
94 | #----------------------------------------------------------------------------- | |
95 |
|
95 | |||
96 | def has_open_quotes(s): |
|
96 | def has_open_quotes(s): | |
97 | """Return whether a string has open quotes. |
|
97 | """Return whether a string has open quotes. | |
98 |
|
98 | |||
99 | This simply counts whether the number of quote characters of either type in |
|
99 | This simply counts whether the number of quote characters of either type in | |
100 | the string is odd. |
|
100 | the string is odd. | |
101 |
|
101 | |||
102 | Returns |
|
102 | Returns | |
103 | ------- |
|
103 | ------- | |
104 | If there is an open quote, the quote character is returned. Else, return |
|
104 | If there is an open quote, the quote character is returned. Else, return | |
105 | False. |
|
105 | False. | |
106 | """ |
|
106 | """ | |
107 | # We check " first, then ', so complex cases with nested quotes will get |
|
107 | # We check " first, then ', so complex cases with nested quotes will get | |
108 | # the " to take precedence. |
|
108 | # the " to take precedence. | |
109 | if s.count('"') % 2: |
|
109 | if s.count('"') % 2: | |
110 | return '"' |
|
110 | return '"' | |
111 | elif s.count("'") % 2: |
|
111 | elif s.count("'") % 2: | |
112 | return "'" |
|
112 | return "'" | |
113 | else: |
|
113 | else: | |
114 | return False |
|
114 | return False | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | def protect_filename(s): |
|
117 | def protect_filename(s): | |
118 | """Escape a string to protect certain characters.""" |
|
118 | """Escape a string to protect certain characters.""" | |
119 |
|
119 | |||
120 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) |
|
120 | return "".join([(ch in PROTECTABLES and '\\' + ch or ch) | |
121 | for ch in s]) |
|
121 | for ch in s]) | |
122 |
|
122 | |||
123 | def expand_user(path): |
|
123 | def expand_user(path): | |
124 | """Expand '~'-style usernames in strings. |
|
124 | """Expand '~'-style usernames in strings. | |
125 |
|
125 | |||
126 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
126 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
127 | extra information that will be useful if the input was being used in |
|
127 | extra information that will be useful if the input was being used in | |
128 | computing completions, and you wish to return the completions with the |
|
128 | computing completions, and you wish to return the completions with the | |
129 | original '~' instead of its expanded value. |
|
129 | original '~' instead of its expanded value. | |
130 |
|
130 | |||
131 | Parameters |
|
131 | Parameters | |
132 | ---------- |
|
132 | ---------- | |
133 | path : str |
|
133 | path : str | |
134 | String to be expanded. If no ~ is present, the output is the same as the |
|
134 | String to be expanded. If no ~ is present, the output is the same as the | |
135 | input. |
|
135 | input. | |
136 |
|
136 | |||
137 | Returns |
|
137 | Returns | |
138 | ------- |
|
138 | ------- | |
139 | newpath : str |
|
139 | newpath : str | |
140 | Result of ~ expansion in the input path. |
|
140 | Result of ~ expansion in the input path. | |
141 | tilde_expand : bool |
|
141 | tilde_expand : bool | |
142 | Whether any expansion was performed or not. |
|
142 | Whether any expansion was performed or not. | |
143 | tilde_val : str |
|
143 | tilde_val : str | |
144 | The value that ~ was replaced with. |
|
144 | The value that ~ was replaced with. | |
145 | """ |
|
145 | """ | |
146 | # Default values |
|
146 | # Default values | |
147 | tilde_expand = False |
|
147 | tilde_expand = False | |
148 | tilde_val = '' |
|
148 | tilde_val = '' | |
149 | newpath = path |
|
149 | newpath = path | |
150 |
|
150 | |||
151 | if path.startswith('~'): |
|
151 | if path.startswith('~'): | |
152 | tilde_expand = True |
|
152 | tilde_expand = True | |
153 | rest = len(path)-1 |
|
153 | rest = len(path)-1 | |
154 | newpath = os.path.expanduser(path) |
|
154 | newpath = os.path.expanduser(path) | |
155 | if rest: |
|
155 | if rest: | |
156 | tilde_val = newpath[:-rest] |
|
156 | tilde_val = newpath[:-rest] | |
157 | else: |
|
157 | else: | |
158 | tilde_val = newpath |
|
158 | tilde_val = newpath | |
159 |
|
159 | |||
160 | return newpath, tilde_expand, tilde_val |
|
160 | return newpath, tilde_expand, tilde_val | |
161 |
|
161 | |||
162 |
|
162 | |||
163 | def compress_user(path, tilde_expand, tilde_val): |
|
163 | def compress_user(path, tilde_expand, tilde_val): | |
164 | """Does the opposite of expand_user, with its outputs. |
|
164 | """Does the opposite of expand_user, with its outputs. | |
165 | """ |
|
165 | """ | |
166 | if tilde_expand: |
|
166 | if tilde_expand: | |
167 | return path.replace(tilde_val, '~') |
|
167 | return path.replace(tilde_val, '~') | |
168 | else: |
|
168 | else: | |
169 | return path |
|
169 | return path | |
170 |
|
170 | |||
171 |
|
171 | |||
172 |
|
172 | |||
173 | def completions_sorting_key(word): |
|
173 | def completions_sorting_key(word): | |
174 | """key for sorting completions |
|
174 | """key for sorting completions | |
175 |
|
175 | |||
176 | This does several things: |
|
176 | This does several things: | |
177 |
|
177 | |||
178 | - Lowercase all completions, so they are sorted alphabetically with |
|
178 | - Lowercase all completions, so they are sorted alphabetically with | |
179 | upper and lower case words mingled |
|
179 | upper and lower case words mingled | |
180 | - Demote any completions starting with underscores to the end |
|
180 | - Demote any completions starting with underscores to the end | |
181 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
181 | - Insert any %magic and %%cellmagic completions in the alphabetical order | |
182 | by their name |
|
182 | by their name | |
183 | """ |
|
183 | """ | |
184 | # Case insensitive sort |
|
184 | # Case insensitive sort | |
185 | word = word.lower() |
|
185 | word = word.lower() | |
186 |
|
186 | |||
187 | prio1, prio2 = 0, 0 |
|
187 | prio1, prio2 = 0, 0 | |
188 |
|
188 | |||
189 | if word.startswith('__'): |
|
189 | if word.startswith('__'): | |
190 | prio1 = 2 |
|
190 | prio1 = 2 | |
191 | elif word.startswith('_'): |
|
191 | elif word.startswith('_'): | |
192 | prio1 = 1 |
|
192 | prio1 = 1 | |
193 |
|
193 | |||
194 | if word.startswith('%%'): |
|
194 | if word.startswith('%%'): | |
195 | # If there's another % in there, this is something else, so leave it alone |
|
195 | # If there's another % in there, this is something else, so leave it alone | |
196 | if not "%" in word[2:]: |
|
196 | if not "%" in word[2:]: | |
197 | word = word[2:] |
|
197 | word = word[2:] | |
198 | prio2 = 2 |
|
198 | prio2 = 2 | |
199 | elif word.startswith('%'): |
|
199 | elif word.startswith('%'): | |
200 | if not "%" in word[1:]: |
|
200 | if not "%" in word[1:]: | |
201 | word = word[1:] |
|
201 | word = word[1:] | |
202 | prio2 = 1 |
|
202 | prio2 = 1 | |
203 |
|
203 | |||
204 | return prio1, word, prio2 |
|
204 | return prio1, word, prio2 | |
205 |
|
205 | |||
206 |
|
206 | |||
207 | @undoc |
|
207 | @undoc | |
208 | class Bunch(object): pass |
|
208 | class Bunch(object): pass | |
209 |
|
209 | |||
210 |
|
210 | |||
211 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
211 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
212 | GREEDY_DELIMS = ' =\r\n' |
|
212 | GREEDY_DELIMS = ' =\r\n' | |
213 |
|
213 | |||
214 |
|
214 | |||
215 | class CompletionSplitter(object): |
|
215 | class CompletionSplitter(object): | |
216 | """An object to split an input line in a manner similar to readline. |
|
216 | """An object to split an input line in a manner similar to readline. | |
217 |
|
217 | |||
218 | By having our own implementation, we can expose readline-like completion in |
|
218 | By having our own implementation, we can expose readline-like completion in | |
219 | a uniform manner to all frontends. This object only needs to be given the |
|
219 | a uniform manner to all frontends. This object only needs to be given the | |
220 | line of text to be split and the cursor position on said line, and it |
|
220 | line of text to be split and the cursor position on said line, and it | |
221 | returns the 'word' to be completed on at the cursor after splitting the |
|
221 | returns the 'word' to be completed on at the cursor after splitting the | |
222 | entire line. |
|
222 | entire line. | |
223 |
|
223 | |||
224 | What characters are used as splitting delimiters can be controlled by |
|
224 | What characters are used as splitting delimiters can be controlled by | |
225 | setting the `delims` attribute (this is a property that internally |
|
225 | setting the `delims` attribute (this is a property that internally | |
226 | automatically builds the necessary regular expression)""" |
|
226 | automatically builds the necessary regular expression)""" | |
227 |
|
227 | |||
228 | # Private interface |
|
228 | # Private interface | |
229 |
|
229 | |||
230 | # A string of delimiter characters. The default value makes sense for |
|
230 | # A string of delimiter characters. The default value makes sense for | |
231 | # IPython's most typical usage patterns. |
|
231 | # IPython's most typical usage patterns. | |
232 | _delims = DELIMS |
|
232 | _delims = DELIMS | |
233 |
|
233 | |||
234 | # The expression (a normal string) to be compiled into a regular expression |
|
234 | # The expression (a normal string) to be compiled into a regular expression | |
235 | # for actual splitting. We store it as an attribute mostly for ease of |
|
235 | # for actual splitting. We store it as an attribute mostly for ease of | |
236 | # debugging, since this type of code can be so tricky to debug. |
|
236 | # debugging, since this type of code can be so tricky to debug. | |
237 | _delim_expr = None |
|
237 | _delim_expr = None | |
238 |
|
238 | |||
239 | # The regular expression that does the actual splitting |
|
239 | # The regular expression that does the actual splitting | |
240 | _delim_re = None |
|
240 | _delim_re = None | |
241 |
|
241 | |||
242 | def __init__(self, delims=None): |
|
242 | def __init__(self, delims=None): | |
243 | delims = CompletionSplitter._delims if delims is None else delims |
|
243 | delims = CompletionSplitter._delims if delims is None else delims | |
244 | self.delims = delims |
|
244 | self.delims = delims | |
245 |
|
245 | |||
246 | @property |
|
246 | @property | |
247 | def delims(self): |
|
247 | def delims(self): | |
248 | """Return the string of delimiter characters.""" |
|
248 | """Return the string of delimiter characters.""" | |
249 | return self._delims |
|
249 | return self._delims | |
250 |
|
250 | |||
251 | @delims.setter |
|
251 | @delims.setter | |
252 | def delims(self, delims): |
|
252 | def delims(self, delims): | |
253 | """Set the delimiters for line splitting.""" |
|
253 | """Set the delimiters for line splitting.""" | |
254 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
254 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
255 | self._delim_re = re.compile(expr) |
|
255 | self._delim_re = re.compile(expr) | |
256 | self._delims = delims |
|
256 | self._delims = delims | |
257 | self._delim_expr = expr |
|
257 | self._delim_expr = expr | |
258 |
|
258 | |||
259 | def split_line(self, line, cursor_pos=None): |
|
259 | def split_line(self, line, cursor_pos=None): | |
260 | """Split a line of text with a cursor at the given position. |
|
260 | """Split a line of text with a cursor at the given position. | |
261 | """ |
|
261 | """ | |
262 | l = line if cursor_pos is None else line[:cursor_pos] |
|
262 | l = line if cursor_pos is None else line[:cursor_pos] | |
263 | return self._delim_re.split(l)[-1] |
|
263 | return self._delim_re.split(l)[-1] | |
264 |
|
264 | |||
265 |
|
265 | |||
266 | class Completer(Configurable): |
|
266 | class Completer(Configurable): | |
267 |
|
267 | |||
268 | greedy = CBool(False, config=True, |
|
268 | greedy = CBool(False, config=True, | |
269 | help="""Activate greedy completion |
|
269 | help="""Activate greedy completion | |
270 |
|
270 | |||
271 | This will enable completion on elements of lists, results of function calls, etc., |
|
271 | This will enable completion on elements of lists, results of function calls, etc., | |
272 | but can be unsafe because the code is actually evaluated on TAB. |
|
272 | but can be unsafe because the code is actually evaluated on TAB. | |
273 | """ |
|
273 | """ | |
274 | ) |
|
274 | ) | |
275 |
|
275 | |||
276 |
|
276 | |||
277 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
277 | def __init__(self, namespace=None, global_namespace=None, **kwargs): | |
278 | """Create a new completer for the command line. |
|
278 | """Create a new completer for the command line. | |
279 |
|
279 | |||
280 | Completer(namespace=ns,global_namespace=ns2) -> completer instance. |
|
280 | Completer(namespace=ns,global_namespace=ns2) -> completer instance. | |
281 |
|
281 | |||
282 | If unspecified, the default namespace where completions are performed |
|
282 | If unspecified, the default namespace where completions are performed | |
283 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
283 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
284 | given as dictionaries. |
|
284 | given as dictionaries. | |
285 |
|
285 | |||
286 | An optional second namespace can be given. This allows the completer |
|
286 | An optional second namespace can be given. This allows the completer | |
287 | to handle cases where both the local and global scopes need to be |
|
287 | to handle cases where both the local and global scopes need to be | |
288 | distinguished. |
|
288 | distinguished. | |
289 |
|
289 | |||
290 | Completer instances should be used as the completion mechanism of |
|
290 | Completer instances should be used as the completion mechanism of | |
291 | readline via the set_completer() call: |
|
291 | readline via the set_completer() call: | |
292 |
|
292 | |||
293 | readline.set_completer(Completer(my_namespace).complete) |
|
293 | readline.set_completer(Completer(my_namespace).complete) | |
294 | """ |
|
294 | """ | |
295 |
|
295 | |||
296 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
296 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
297 | # specific namespace or to use __main__.__dict__. This will allow us |
|
297 | # specific namespace or to use __main__.__dict__. This will allow us | |
298 | # to bind to __main__.__dict__ at completion time, not now. |
|
298 | # to bind to __main__.__dict__ at completion time, not now. | |
299 | if namespace is None: |
|
299 | if namespace is None: | |
300 | self.use_main_ns = 1 |
|
300 | self.use_main_ns = 1 | |
301 | else: |
|
301 | else: | |
302 | self.use_main_ns = 0 |
|
302 | self.use_main_ns = 0 | |
303 | self.namespace = namespace |
|
303 | self.namespace = namespace | |
304 |
|
304 | |||
305 | # The global namespace, if given, can be bound directly |
|
305 | # The global namespace, if given, can be bound directly | |
306 | if global_namespace is None: |
|
306 | if global_namespace is None: | |
307 | self.global_namespace = {} |
|
307 | self.global_namespace = {} | |
308 | else: |
|
308 | else: | |
309 | self.global_namespace = global_namespace |
|
309 | self.global_namespace = global_namespace | |
310 |
|
310 | |||
311 | super(Completer, self).__init__(**kwargs) |
|
311 | super(Completer, self).__init__(**kwargs) | |
312 |
|
312 | |||
313 | def complete(self, text, state): |
|
313 | def complete(self, text, state): | |
314 | """Return the next possible completion for 'text'. |
|
314 | """Return the next possible completion for 'text'. | |
315 |
|
315 | |||
316 | This is called successively with state == 0, 1, 2, ... until it |
|
316 | This is called successively with state == 0, 1, 2, ... until it | |
317 | returns None. The completion should begin with 'text'. |
|
317 | returns None. The completion should begin with 'text'. | |
318 |
|
318 | |||
319 | """ |
|
319 | """ | |
320 | if self.use_main_ns: |
|
320 | if self.use_main_ns: | |
321 | self.namespace = __main__.__dict__ |
|
321 | self.namespace = __main__.__dict__ | |
322 |
|
322 | |||
323 | if state == 0: |
|
323 | if state == 0: | |
324 | if "." in text: |
|
324 | if "." in text: | |
325 | self.matches = self.attr_matches(text) |
|
325 | self.matches = self.attr_matches(text) | |
326 | else: |
|
326 | else: | |
327 | self.matches = self.global_matches(text) |
|
327 | self.matches = self.global_matches(text) | |
328 | try: |
|
328 | try: | |
329 | return self.matches[state] |
|
329 | return self.matches[state] | |
330 | except IndexError: |
|
330 | except IndexError: | |
331 | return None |
|
331 | return None | |
332 |
|
332 | |||
333 | def global_matches(self, text): |
|
333 | def global_matches(self, text): | |
334 | """Compute matches when text is a simple name. |
|
334 | """Compute matches when text is a simple name. | |
335 |
|
335 | |||
336 | Return a list of all keywords, built-in functions and names currently |
|
336 | Return a list of all keywords, built-in functions and names currently | |
337 | defined in self.namespace or self.global_namespace that match. |
|
337 | defined in self.namespace or self.global_namespace that match. | |
338 |
|
338 | |||
339 | """ |
|
339 | """ | |
340 | #print 'Completer->global_matches, txt=%r' % text # dbg |
|
340 | #print 'Completer->global_matches, txt=%r' % text # dbg | |
341 | matches = [] |
|
341 | matches = [] | |
342 | match_append = matches.append |
|
342 | match_append = matches.append | |
343 | n = len(text) |
|
343 | n = len(text) | |
344 | for lst in [keyword.kwlist, |
|
344 | for lst in [keyword.kwlist, | |
345 | builtin_mod.__dict__.keys(), |
|
345 | builtin_mod.__dict__.keys(), | |
346 | self.namespace.keys(), |
|
346 | self.namespace.keys(), | |
347 | self.global_namespace.keys()]: |
|
347 | self.global_namespace.keys()]: | |
348 | for word in lst: |
|
348 | for word in lst: | |
349 | if word[:n] == text and word != "__builtins__": |
|
349 | if word[:n] == text and word != "__builtins__": | |
350 | match_append(word) |
|
350 | match_append(word) | |
351 | return matches |
|
351 | return matches | |
352 |
|
352 | |||
353 | def attr_matches(self, text): |
|
353 | def attr_matches(self, text): | |
354 | """Compute matches when text contains a dot. |
|
354 | """Compute matches when text contains a dot. | |
355 |
|
355 | |||
356 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
356 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
357 | evaluatable in self.namespace or self.global_namespace, it will be |
|
357 | evaluatable in self.namespace or self.global_namespace, it will be | |
358 | evaluated and its attributes (as revealed by dir()) are used as |
|
358 | evaluated and its attributes (as revealed by dir()) are used as | |
359 | possible completions. (For class instances, class members are are |
|
359 | possible completions. (For class instances, class members are are | |
360 | also considered.) |
|
360 | also considered.) | |
361 |
|
361 | |||
362 | WARNING: this can still invoke arbitrary C code, if an object |
|
362 | WARNING: this can still invoke arbitrary C code, if an object | |
363 | with a __getattr__ hook is evaluated. |
|
363 | with a __getattr__ hook is evaluated. | |
364 |
|
364 | |||
365 | """ |
|
365 | """ | |
366 |
|
366 | |||
367 | #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg |
|
367 | #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg | |
368 | # Another option, seems to work great. Catches things like ''.<tab> |
|
368 | # Another option, seems to work great. Catches things like ''.<tab> | |
369 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
369 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
370 |
|
370 | |||
371 | if m: |
|
371 | if m: | |
372 | expr, attr = m.group(1, 3) |
|
372 | expr, attr = m.group(1, 3) | |
373 | elif self.greedy: |
|
373 | elif self.greedy: | |
374 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
374 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) | |
375 | if not m2: |
|
375 | if not m2: | |
376 | return [] |
|
376 | return [] | |
377 | expr, attr = m2.group(1,2) |
|
377 | expr, attr = m2.group(1,2) | |
378 | else: |
|
378 | else: | |
379 | return [] |
|
379 | return [] | |
380 |
|
380 | |||
381 | try: |
|
381 | try: | |
382 | obj = eval(expr, self.namespace) |
|
382 | obj = eval(expr, self.namespace) | |
383 | except: |
|
383 | except: | |
384 | try: |
|
384 | try: | |
385 | obj = eval(expr, self.global_namespace) |
|
385 | obj = eval(expr, self.global_namespace) | |
386 | except: |
|
386 | except: | |
387 | return [] |
|
387 | return [] | |
388 |
|
388 | |||
389 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
389 | if self.limit_to__all__ and hasattr(obj, '__all__'): | |
390 | words = get__all__entries(obj) |
|
390 | words = get__all__entries(obj) | |
391 | else: |
|
391 | else: | |
392 | words = dir2(obj) |
|
392 | words = dir2(obj) | |
393 |
|
393 | |||
394 | try: |
|
394 | try: | |
395 | words = generics.complete_object(obj, words) |
|
395 | words = generics.complete_object(obj, words) | |
396 | except TryNext: |
|
396 | except TryNext: | |
397 | pass |
|
397 | pass | |
398 | except Exception: |
|
398 | except Exception: | |
399 | # Silence errors from completion function |
|
399 | # Silence errors from completion function | |
400 | #raise # dbg |
|
400 | #raise # dbg | |
401 | pass |
|
401 | pass | |
402 | # Build match list to return |
|
402 | # Build match list to return | |
403 | n = len(attr) |
|
403 | n = len(attr) | |
404 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
404 | res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
405 | return res |
|
405 | return res | |
406 |
|
406 | |||
407 |
|
407 | |||
408 | def get__all__entries(obj): |
|
408 | def get__all__entries(obj): | |
409 | """returns the strings in the __all__ attribute""" |
|
409 | """returns the strings in the __all__ attribute""" | |
410 | try: |
|
410 | try: | |
411 | words = getattr(obj, '__all__') |
|
411 | words = getattr(obj, '__all__') | |
412 | except: |
|
412 | except: | |
413 | return [] |
|
413 | return [] | |
414 |
|
414 | |||
415 | return [w for w in words if isinstance(w, string_types)] |
|
415 | return [w for w in words if isinstance(w, string_types)] | |
416 |
|
416 | |||
417 |
|
417 | |||
418 | def match_dict_keys(keys, prefix, delims): |
|
418 | def match_dict_keys(keys, prefix, delims): | |
419 | """Used by dict_key_matches, matching the prefix to a list of keys""" |
|
419 | """Used by dict_key_matches, matching the prefix to a list of keys""" | |
420 | if not prefix: |
|
420 | if not prefix: | |
421 | return None, 0, [repr(k) for k in keys |
|
421 | return None, 0, [repr(k) for k in keys | |
422 | if isinstance(k, (string_types, bytes))] |
|
422 | if isinstance(k, (string_types, bytes))] | |
423 | quote_match = re.search('["\']', prefix) |
|
423 | quote_match = re.search('["\']', prefix) | |
424 | quote = quote_match.group() |
|
424 | quote = quote_match.group() | |
425 | try: |
|
425 | try: | |
426 | prefix_str = eval(prefix + quote, {}) |
|
426 | prefix_str = eval(prefix + quote, {}) | |
427 | except Exception: |
|
427 | except Exception: | |
428 | return None, 0, [] |
|
428 | return None, 0, [] | |
429 |
|
429 | |||
430 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
430 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' | |
431 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
431 | token_match = re.search(pattern, prefix, re.UNICODE) | |
432 | token_start = token_match.start() |
|
432 | token_start = token_match.start() | |
433 | token_prefix = token_match.group() |
|
433 | token_prefix = token_match.group() | |
434 |
|
434 | |||
435 | # TODO: support bytes in Py3k |
|
435 | # TODO: support bytes in Py3k | |
436 | matched = [] |
|
436 | matched = [] | |
437 | for key in keys: |
|
437 | for key in keys: | |
438 | try: |
|
438 | try: | |
439 | if not key.startswith(prefix_str): |
|
439 | if not key.startswith(prefix_str): | |
440 | continue |
|
440 | continue | |
441 | except (AttributeError, TypeError, UnicodeError): |
|
441 | except (AttributeError, TypeError, UnicodeError): | |
442 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
442 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa | |
443 | continue |
|
443 | continue | |
444 |
|
444 | |||
445 | # reformat remainder of key to begin with prefix |
|
445 | # reformat remainder of key to begin with prefix | |
446 | rem = key[len(prefix_str):] |
|
446 | rem = key[len(prefix_str):] | |
447 | # force repr wrapped in ' |
|
447 | # force repr wrapped in ' | |
448 | rem_repr = repr(rem + '"') |
|
448 | rem_repr = repr(rem + '"') | |
449 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
449 | if rem_repr.startswith('u') and prefix[0] not in 'uU': | |
450 | # Found key is unicode, but prefix is Py2 string. |
|
450 | # Found key is unicode, but prefix is Py2 string. | |
451 | # Therefore attempt to interpret key as string. |
|
451 | # Therefore attempt to interpret key as string. | |
452 | try: |
|
452 | try: | |
453 | rem_repr = repr(rem.encode('ascii') + '"') |
|
453 | rem_repr = repr(rem.encode('ascii') + '"') | |
454 | except UnicodeEncodeError: |
|
454 | except UnicodeEncodeError: | |
455 | continue |
|
455 | continue | |
456 |
|
456 | |||
457 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
457 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] | |
458 | if quote == '"': |
|
458 | if quote == '"': | |
459 | # The entered prefix is quoted with ", |
|
459 | # The entered prefix is quoted with ", | |
460 | # but the match is quoted with '. |
|
460 | # but the match is quoted with '. | |
461 | # A contained " hence needs escaping for comparison: |
|
461 | # A contained " hence needs escaping for comparison: | |
462 | rem_repr = rem_repr.replace('"', '\\"') |
|
462 | rem_repr = rem_repr.replace('"', '\\"') | |
463 |
|
463 | |||
464 | # then reinsert prefix from start of token |
|
464 | # then reinsert prefix from start of token | |
465 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
465 | matched.append('%s%s' % (token_prefix, rem_repr)) | |
466 | return quote, token_start, matched |
|
466 | return quote, token_start, matched | |
467 |
|
467 | |||
468 |
|
468 | |||
469 | def _safe_isinstance(obj, module, class_name): |
|
469 | def _safe_isinstance(obj, module, class_name): | |
470 | """Checks if obj is an instance of module.class_name if loaded |
|
470 | """Checks if obj is an instance of module.class_name if loaded | |
471 | """ |
|
471 | """ | |
472 | return (module in sys.modules and |
|
472 | return (module in sys.modules and | |
473 | isinstance(obj, getattr(__import__(module), class_name))) |
|
473 | isinstance(obj, getattr(__import__(module), class_name))) | |
474 |
|
474 | |||
475 | def _safe_really_hasattr(obj, name): |
|
|||
476 | """Checks that an object genuinely has a given attribute. |
|
|||
477 |
|
||||
478 | Some objects claim to have any attribute that's requested, to act as a lazy |
|
|||
479 | proxy for something else. We want to catch these cases and ignore their |
|
|||
480 | claim to have the attribute we're interested in. |
|
|||
481 | """ |
|
|||
482 | if safe_hasattr(obj, '_ipy_proxy_check_dont_define_this_'): |
|
|||
483 | # If it claims this exists, don't trust it |
|
|||
484 | return False |
|
|||
485 |
|
||||
486 | return safe_hasattr(obj, name) |
|
|||
487 |
|
||||
488 |
|
475 | |||
489 | def back_unicode_name_matches(text): |
|
476 | def back_unicode_name_matches(text): | |
490 | u"""Match unicode characters back to unicode name |
|
477 | u"""Match unicode characters back to unicode name | |
491 |
|
478 | |||
492 | This does β -> \\snowman |
|
479 | This does β -> \\snowman | |
493 |
|
480 | |||
494 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
481 | Note that snowman is not a valid python3 combining character but will be expanded. | |
495 | Though it will not recombine back to the snowman character by the completion machinery. |
|
482 | Though it will not recombine back to the snowman character by the completion machinery. | |
496 |
|
483 | |||
497 | This will not either back-complete standard sequences like \\n, \\b ... |
|
484 | This will not either back-complete standard sequences like \\n, \\b ... | |
498 |
|
485 | |||
499 | Used on Python 3 only. |
|
486 | Used on Python 3 only. | |
500 | """ |
|
487 | """ | |
501 | if len(text)<2: |
|
488 | if len(text)<2: | |
502 | return u'', () |
|
489 | return u'', () | |
503 | maybe_slash = text[-2] |
|
490 | maybe_slash = text[-2] | |
504 | if maybe_slash != '\\': |
|
491 | if maybe_slash != '\\': | |
505 | return u'', () |
|
492 | return u'', () | |
506 |
|
493 | |||
507 | char = text[-1] |
|
494 | char = text[-1] | |
508 | # no expand on quote for completion in strings. |
|
495 | # no expand on quote for completion in strings. | |
509 | # nor backcomplete standard ascii keys |
|
496 | # nor backcomplete standard ascii keys | |
510 | if char in string.ascii_letters or char in ['"',"'"]: |
|
497 | if char in string.ascii_letters or char in ['"',"'"]: | |
511 | return u'', () |
|
498 | return u'', () | |
512 | try : |
|
499 | try : | |
513 | unic = unicodedata.name(char) |
|
500 | unic = unicodedata.name(char) | |
514 | return '\\'+char,['\\'+unic] |
|
501 | return '\\'+char,['\\'+unic] | |
515 | except KeyError as e: |
|
502 | except KeyError as e: | |
516 | pass |
|
503 | pass | |
517 | return u'', () |
|
504 | return u'', () | |
518 |
|
505 | |||
519 | def back_latex_name_matches(text): |
|
506 | def back_latex_name_matches(text): | |
520 | u"""Match latex characters back to unicode name |
|
507 | u"""Match latex characters back to unicode name | |
521 |
|
508 | |||
522 | This does ->\\sqrt |
|
509 | This does ->\\sqrt | |
523 |
|
510 | |||
524 | Used on Python 3 only. |
|
511 | Used on Python 3 only. | |
525 | """ |
|
512 | """ | |
526 | if len(text)<2: |
|
513 | if len(text)<2: | |
527 | return u'', () |
|
514 | return u'', () | |
528 | maybe_slash = text[-2] |
|
515 | maybe_slash = text[-2] | |
529 | if maybe_slash != '\\': |
|
516 | if maybe_slash != '\\': | |
530 | return u'', () |
|
517 | return u'', () | |
531 |
|
518 | |||
532 |
|
519 | |||
533 | char = text[-1] |
|
520 | char = text[-1] | |
534 | # no expand on quote for completion in strings. |
|
521 | # no expand on quote for completion in strings. | |
535 | # nor backcomplete standard ascii keys |
|
522 | # nor backcomplete standard ascii keys | |
536 | if char in string.ascii_letters or char in ['"',"'"]: |
|
523 | if char in string.ascii_letters or char in ['"',"'"]: | |
537 | return u'', () |
|
524 | return u'', () | |
538 | try : |
|
525 | try : | |
539 | latex = reverse_latex_symbol[char] |
|
526 | latex = reverse_latex_symbol[char] | |
540 | # '\\' replace the \ as well |
|
527 | # '\\' replace the \ as well | |
541 | return '\\'+char,[latex] |
|
528 | return '\\'+char,[latex] | |
542 | except KeyError as e: |
|
529 | except KeyError as e: | |
543 | pass |
|
530 | pass | |
544 | return u'', () |
|
531 | return u'', () | |
545 |
|
532 | |||
546 |
|
533 | |||
547 | class IPCompleter(Completer): |
|
534 | class IPCompleter(Completer): | |
548 | """Extension of the completer class with IPython-specific features""" |
|
535 | """Extension of the completer class with IPython-specific features""" | |
549 |
|
536 | |||
550 | def _greedy_changed(self, name, old, new): |
|
537 | def _greedy_changed(self, name, old, new): | |
551 | """update the splitter and readline delims when greedy is changed""" |
|
538 | """update the splitter and readline delims when greedy is changed""" | |
552 | if new: |
|
539 | if new: | |
553 | self.splitter.delims = GREEDY_DELIMS |
|
540 | self.splitter.delims = GREEDY_DELIMS | |
554 | else: |
|
541 | else: | |
555 | self.splitter.delims = DELIMS |
|
542 | self.splitter.delims = DELIMS | |
556 |
|
543 | |||
557 | if self.readline: |
|
544 | if self.readline: | |
558 | self.readline.set_completer_delims(self.splitter.delims) |
|
545 | self.readline.set_completer_delims(self.splitter.delims) | |
559 |
|
546 | |||
560 | merge_completions = CBool(True, config=True, |
|
547 | merge_completions = CBool(True, config=True, | |
561 | help="""Whether to merge completion results into a single list |
|
548 | help="""Whether to merge completion results into a single list | |
562 |
|
549 | |||
563 | If False, only the completion results from the first non-empty |
|
550 | If False, only the completion results from the first non-empty | |
564 | completer will be returned. |
|
551 | completer will be returned. | |
565 | """ |
|
552 | """ | |
566 | ) |
|
553 | ) | |
567 | omit__names = Enum((0,1,2), default_value=2, config=True, |
|
554 | omit__names = Enum((0,1,2), default_value=2, config=True, | |
568 | help="""Instruct the completer to omit private method names |
|
555 | help="""Instruct the completer to omit private method names | |
569 |
|
556 | |||
570 | Specifically, when completing on ``object.<tab>``. |
|
557 | Specifically, when completing on ``object.<tab>``. | |
571 |
|
558 | |||
572 | When 2 [default]: all names that start with '_' will be excluded. |
|
559 | When 2 [default]: all names that start with '_' will be excluded. | |
573 |
|
560 | |||
574 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
561 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
575 |
|
562 | |||
576 | When 0: nothing will be excluded. |
|
563 | When 0: nothing will be excluded. | |
577 | """ |
|
564 | """ | |
578 | ) |
|
565 | ) | |
579 | limit_to__all__ = CBool(default_value=False, config=True, |
|
566 | limit_to__all__ = CBool(default_value=False, config=True, | |
580 | help="""Instruct the completer to use __all__ for the completion |
|
567 | help="""Instruct the completer to use __all__ for the completion | |
581 |
|
568 | |||
582 | Specifically, when completing on ``object.<tab>``. |
|
569 | Specifically, when completing on ``object.<tab>``. | |
583 |
|
570 | |||
584 | When True: only those names in obj.__all__ will be included. |
|
571 | When True: only those names in obj.__all__ will be included. | |
585 |
|
572 | |||
586 | When False [default]: the __all__ attribute is ignored |
|
573 | When False [default]: the __all__ attribute is ignored | |
587 | """ |
|
574 | """ | |
588 | ) |
|
575 | ) | |
589 |
|
576 | |||
590 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
577 | def __init__(self, shell=None, namespace=None, global_namespace=None, | |
591 | use_readline=True, config=None, **kwargs): |
|
578 | use_readline=True, config=None, **kwargs): | |
592 | """IPCompleter() -> completer |
|
579 | """IPCompleter() -> completer | |
593 |
|
580 | |||
594 | Return a completer object suitable for use by the readline library |
|
581 | Return a completer object suitable for use by the readline library | |
595 | via readline.set_completer(). |
|
582 | via readline.set_completer(). | |
596 |
|
583 | |||
597 | Inputs: |
|
584 | Inputs: | |
598 |
|
585 | |||
599 | - shell: a pointer to the ipython shell itself. This is needed |
|
586 | - shell: a pointer to the ipython shell itself. This is needed | |
600 | because this completer knows about magic functions, and those can |
|
587 | because this completer knows about magic functions, and those can | |
601 | only be accessed via the ipython instance. |
|
588 | only be accessed via the ipython instance. | |
602 |
|
589 | |||
603 | - namespace: an optional dict where completions are performed. |
|
590 | - namespace: an optional dict where completions are performed. | |
604 |
|
591 | |||
605 | - global_namespace: secondary optional dict for completions, to |
|
592 | - global_namespace: secondary optional dict for completions, to | |
606 | handle cases (such as IPython embedded inside functions) where |
|
593 | handle cases (such as IPython embedded inside functions) where | |
607 | both Python scopes are visible. |
|
594 | both Python scopes are visible. | |
608 |
|
595 | |||
609 | use_readline : bool, optional |
|
596 | use_readline : bool, optional | |
610 | If true, use the readline library. This completer can still function |
|
597 | If true, use the readline library. This completer can still function | |
611 | without readline, though in that case callers must provide some extra |
|
598 | without readline, though in that case callers must provide some extra | |
612 | information on each call about the current line.""" |
|
599 | information on each call about the current line.""" | |
613 |
|
600 | |||
614 | self.magic_escape = ESC_MAGIC |
|
601 | self.magic_escape = ESC_MAGIC | |
615 | self.splitter = CompletionSplitter() |
|
602 | self.splitter = CompletionSplitter() | |
616 |
|
603 | |||
617 | # Readline configuration, only used by the rlcompleter method. |
|
604 | # Readline configuration, only used by the rlcompleter method. | |
618 | if use_readline: |
|
605 | if use_readline: | |
619 | # We store the right version of readline so that later code |
|
606 | # We store the right version of readline so that later code | |
620 | import IPython.utils.rlineimpl as readline |
|
607 | import IPython.utils.rlineimpl as readline | |
621 | self.readline = readline |
|
608 | self.readline = readline | |
622 | else: |
|
609 | else: | |
623 | self.readline = None |
|
610 | self.readline = None | |
624 |
|
611 | |||
625 | # _greedy_changed() depends on splitter and readline being defined: |
|
612 | # _greedy_changed() depends on splitter and readline being defined: | |
626 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
613 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, | |
627 | config=config, **kwargs) |
|
614 | config=config, **kwargs) | |
628 |
|
615 | |||
629 | # List where completion matches will be stored |
|
616 | # List where completion matches will be stored | |
630 | self.matches = [] |
|
617 | self.matches = [] | |
631 | self.shell = shell |
|
618 | self.shell = shell | |
632 | # Regexp to split filenames with spaces in them |
|
619 | # Regexp to split filenames with spaces in them | |
633 | self.space_name_re = re.compile(r'([^\\] )') |
|
620 | self.space_name_re = re.compile(r'([^\\] )') | |
634 | # Hold a local ref. to glob.glob for speed |
|
621 | # Hold a local ref. to glob.glob for speed | |
635 | self.glob = glob.glob |
|
622 | self.glob = glob.glob | |
636 |
|
623 | |||
637 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
624 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
638 | # buffers, to avoid completion problems. |
|
625 | # buffers, to avoid completion problems. | |
639 | term = os.environ.get('TERM','xterm') |
|
626 | term = os.environ.get('TERM','xterm') | |
640 | self.dumb_terminal = term in ['dumb','emacs'] |
|
627 | self.dumb_terminal = term in ['dumb','emacs'] | |
641 |
|
628 | |||
642 | # Special handling of backslashes needed in win32 platforms |
|
629 | # Special handling of backslashes needed in win32 platforms | |
643 | if sys.platform == "win32": |
|
630 | if sys.platform == "win32": | |
644 | self.clean_glob = self._clean_glob_win32 |
|
631 | self.clean_glob = self._clean_glob_win32 | |
645 | else: |
|
632 | else: | |
646 | self.clean_glob = self._clean_glob |
|
633 | self.clean_glob = self._clean_glob | |
647 |
|
634 | |||
648 | #regexp to parse docstring for function signature |
|
635 | #regexp to parse docstring for function signature | |
649 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
636 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
650 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
637 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
651 | #use this if positional argument name is also needed |
|
638 | #use this if positional argument name is also needed | |
652 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
639 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') | |
653 |
|
640 | |||
654 | # All active matcher routines for completion |
|
641 | # All active matcher routines for completion | |
655 | self.matchers = [self.python_matches, |
|
642 | self.matchers = [self.python_matches, | |
656 | self.file_matches, |
|
643 | self.file_matches, | |
657 | self.magic_matches, |
|
644 | self.magic_matches, | |
658 | self.python_func_kw_matches, |
|
645 | self.python_func_kw_matches, | |
659 | self.dict_key_matches, |
|
646 | self.dict_key_matches, | |
660 | ] |
|
647 | ] | |
661 |
|
648 | |||
662 | def all_completions(self, text): |
|
649 | def all_completions(self, text): | |
663 | """ |
|
650 | """ | |
664 | Wrapper around the complete method for the benefit of emacs |
|
651 | Wrapper around the complete method for the benefit of emacs | |
665 | and pydb. |
|
652 | and pydb. | |
666 | """ |
|
653 | """ | |
667 | return self.complete(text)[1] |
|
654 | return self.complete(text)[1] | |
668 |
|
655 | |||
669 | def _clean_glob(self,text): |
|
656 | def _clean_glob(self,text): | |
670 | return self.glob("%s*" % text) |
|
657 | return self.glob("%s*" % text) | |
671 |
|
658 | |||
672 | def _clean_glob_win32(self,text): |
|
659 | def _clean_glob_win32(self,text): | |
673 | return [f.replace("\\","/") |
|
660 | return [f.replace("\\","/") | |
674 | for f in self.glob("%s*" % text)] |
|
661 | for f in self.glob("%s*" % text)] | |
675 |
|
662 | |||
676 | def file_matches(self, text): |
|
663 | def file_matches(self, text): | |
677 | """Match filenames, expanding ~USER type strings. |
|
664 | """Match filenames, expanding ~USER type strings. | |
678 |
|
665 | |||
679 | Most of the seemingly convoluted logic in this completer is an |
|
666 | Most of the seemingly convoluted logic in this completer is an | |
680 | attempt to handle filenames with spaces in them. And yet it's not |
|
667 | attempt to handle filenames with spaces in them. And yet it's not | |
681 | quite perfect, because Python's readline doesn't expose all of the |
|
668 | quite perfect, because Python's readline doesn't expose all of the | |
682 | GNU readline details needed for this to be done correctly. |
|
669 | GNU readline details needed for this to be done correctly. | |
683 |
|
670 | |||
684 | For a filename with a space in it, the printed completions will be |
|
671 | For a filename with a space in it, the printed completions will be | |
685 | only the parts after what's already been typed (instead of the |
|
672 | only the parts after what's already been typed (instead of the | |
686 | full completions, as is normally done). I don't think with the |
|
673 | full completions, as is normally done). I don't think with the | |
687 | current (as of Python 2.3) Python readline it's possible to do |
|
674 | current (as of Python 2.3) Python readline it's possible to do | |
688 | better.""" |
|
675 | better.""" | |
689 |
|
676 | |||
690 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg |
|
677 | #io.rprint('Completer->file_matches: <%r>' % text) # dbg | |
691 |
|
678 | |||
692 | # chars that require escaping with backslash - i.e. chars |
|
679 | # chars that require escaping with backslash - i.e. chars | |
693 | # that readline treats incorrectly as delimiters, but we |
|
680 | # that readline treats incorrectly as delimiters, but we | |
694 | # don't want to treat as delimiters in filename matching |
|
681 | # don't want to treat as delimiters in filename matching | |
695 | # when escaped with backslash |
|
682 | # when escaped with backslash | |
696 | if text.startswith('!'): |
|
683 | if text.startswith('!'): | |
697 | text = text[1:] |
|
684 | text = text[1:] | |
698 | text_prefix = '!' |
|
685 | text_prefix = '!' | |
699 | else: |
|
686 | else: | |
700 | text_prefix = '' |
|
687 | text_prefix = '' | |
701 |
|
688 | |||
702 | text_until_cursor = self.text_until_cursor |
|
689 | text_until_cursor = self.text_until_cursor | |
703 | # track strings with open quotes |
|
690 | # track strings with open quotes | |
704 | open_quotes = has_open_quotes(text_until_cursor) |
|
691 | open_quotes = has_open_quotes(text_until_cursor) | |
705 |
|
692 | |||
706 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
693 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
707 | lsplit = text |
|
694 | lsplit = text | |
708 | else: |
|
695 | else: | |
709 | try: |
|
696 | try: | |
710 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
697 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
711 | lsplit = arg_split(text_until_cursor)[-1] |
|
698 | lsplit = arg_split(text_until_cursor)[-1] | |
712 | except ValueError: |
|
699 | except ValueError: | |
713 | # typically an unmatched ", or backslash without escaped char. |
|
700 | # typically an unmatched ", or backslash without escaped char. | |
714 | if open_quotes: |
|
701 | if open_quotes: | |
715 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
702 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
716 | else: |
|
703 | else: | |
717 | return [] |
|
704 | return [] | |
718 | except IndexError: |
|
705 | except IndexError: | |
719 | # tab pressed on empty line |
|
706 | # tab pressed on empty line | |
720 | lsplit = "" |
|
707 | lsplit = "" | |
721 |
|
708 | |||
722 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
709 | if not open_quotes and lsplit != protect_filename(lsplit): | |
723 | # if protectables are found, do matching on the whole escaped name |
|
710 | # if protectables are found, do matching on the whole escaped name | |
724 | has_protectables = True |
|
711 | has_protectables = True | |
725 | text0,text = text,lsplit |
|
712 | text0,text = text,lsplit | |
726 | else: |
|
713 | else: | |
727 | has_protectables = False |
|
714 | has_protectables = False | |
728 | text = os.path.expanduser(text) |
|
715 | text = os.path.expanduser(text) | |
729 |
|
716 | |||
730 | if text == "": |
|
717 | if text == "": | |
731 | return [text_prefix + protect_filename(f) for f in self.glob("*")] |
|
718 | return [text_prefix + protect_filename(f) for f in self.glob("*")] | |
732 |
|
719 | |||
733 | # Compute the matches from the filesystem |
|
720 | # Compute the matches from the filesystem | |
734 | m0 = self.clean_glob(text.replace('\\','')) |
|
721 | m0 = self.clean_glob(text.replace('\\','')) | |
735 |
|
722 | |||
736 | if has_protectables: |
|
723 | if has_protectables: | |
737 | # If we had protectables, we need to revert our changes to the |
|
724 | # If we had protectables, we need to revert our changes to the | |
738 | # beginning of filename so that we don't double-write the part |
|
725 | # beginning of filename so that we don't double-write the part | |
739 | # of the filename we have so far |
|
726 | # of the filename we have so far | |
740 | len_lsplit = len(lsplit) |
|
727 | len_lsplit = len(lsplit) | |
741 | matches = [text_prefix + text0 + |
|
728 | matches = [text_prefix + text0 + | |
742 | protect_filename(f[len_lsplit:]) for f in m0] |
|
729 | protect_filename(f[len_lsplit:]) for f in m0] | |
743 | else: |
|
730 | else: | |
744 | if open_quotes: |
|
731 | if open_quotes: | |
745 | # if we have a string with an open quote, we don't need to |
|
732 | # if we have a string with an open quote, we don't need to | |
746 | # protect the names at all (and we _shouldn't_, as it |
|
733 | # protect the names at all (and we _shouldn't_, as it | |
747 | # would cause bugs when the filesystem call is made). |
|
734 | # would cause bugs when the filesystem call is made). | |
748 | matches = m0 |
|
735 | matches = m0 | |
749 | else: |
|
736 | else: | |
750 | matches = [text_prefix + |
|
737 | matches = [text_prefix + | |
751 | protect_filename(f) for f in m0] |
|
738 | protect_filename(f) for f in m0] | |
752 |
|
739 | |||
753 | #io.rprint('mm', matches) # dbg |
|
740 | #io.rprint('mm', matches) # dbg | |
754 |
|
741 | |||
755 | # Mark directories in input list by appending '/' to their names. |
|
742 | # Mark directories in input list by appending '/' to their names. | |
756 | matches = [x+'/' if os.path.isdir(x) else x for x in matches] |
|
743 | matches = [x+'/' if os.path.isdir(x) else x for x in matches] | |
757 | return matches |
|
744 | return matches | |
758 |
|
745 | |||
759 | def magic_matches(self, text): |
|
746 | def magic_matches(self, text): | |
760 | """Match magics""" |
|
747 | """Match magics""" | |
761 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg |
|
748 | #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg | |
762 | # Get all shell magics now rather than statically, so magics loaded at |
|
749 | # Get all shell magics now rather than statically, so magics loaded at | |
763 | # runtime show up too. |
|
750 | # runtime show up too. | |
764 | lsm = self.shell.magics_manager.lsmagic() |
|
751 | lsm = self.shell.magics_manager.lsmagic() | |
765 | line_magics = lsm['line'] |
|
752 | line_magics = lsm['line'] | |
766 | cell_magics = lsm['cell'] |
|
753 | cell_magics = lsm['cell'] | |
767 | pre = self.magic_escape |
|
754 | pre = self.magic_escape | |
768 | pre2 = pre+pre |
|
755 | pre2 = pre+pre | |
769 |
|
756 | |||
770 | # Completion logic: |
|
757 | # Completion logic: | |
771 | # - user gives %%: only do cell magics |
|
758 | # - user gives %%: only do cell magics | |
772 | # - user gives %: do both line and cell magics |
|
759 | # - user gives %: do both line and cell magics | |
773 | # - no prefix: do both |
|
760 | # - no prefix: do both | |
774 | # In other words, line magics are skipped if the user gives %% explicitly |
|
761 | # In other words, line magics are skipped if the user gives %% explicitly | |
775 | bare_text = text.lstrip(pre) |
|
762 | bare_text = text.lstrip(pre) | |
776 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
763 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] | |
777 | if not text.startswith(pre2): |
|
764 | if not text.startswith(pre2): | |
778 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
765 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] | |
779 | return comp |
|
766 | return comp | |
780 |
|
767 | |||
781 | def python_matches(self,text): |
|
768 | def python_matches(self,text): | |
782 | """Match attributes or global python names""" |
|
769 | """Match attributes or global python names""" | |
783 |
|
770 | |||
784 | #io.rprint('Completer->python_matches, txt=%r' % text) # dbg |
|
771 | #io.rprint('Completer->python_matches, txt=%r' % text) # dbg | |
785 | if "." in text: |
|
772 | if "." in text: | |
786 | try: |
|
773 | try: | |
787 | matches = self.attr_matches(text) |
|
774 | matches = self.attr_matches(text) | |
788 | if text.endswith('.') and self.omit__names: |
|
775 | if text.endswith('.') and self.omit__names: | |
789 | if self.omit__names == 1: |
|
776 | if self.omit__names == 1: | |
790 | # true if txt is _not_ a __ name, false otherwise: |
|
777 | # true if txt is _not_ a __ name, false otherwise: | |
791 | no__name = (lambda txt: |
|
778 | no__name = (lambda txt: | |
792 | re.match(r'.*\.__.*?__',txt) is None) |
|
779 | re.match(r'.*\.__.*?__',txt) is None) | |
793 | else: |
|
780 | else: | |
794 | # true if txt is _not_ a _ name, false otherwise: |
|
781 | # true if txt is _not_ a _ name, false otherwise: | |
795 | no__name = (lambda txt: |
|
782 | no__name = (lambda txt: | |
796 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
783 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) | |
797 | matches = filter(no__name, matches) |
|
784 | matches = filter(no__name, matches) | |
798 | except NameError: |
|
785 | except NameError: | |
799 | # catches <undefined attributes>.<tab> |
|
786 | # catches <undefined attributes>.<tab> | |
800 | matches = [] |
|
787 | matches = [] | |
801 | else: |
|
788 | else: | |
802 | matches = self.global_matches(text) |
|
789 | matches = self.global_matches(text) | |
803 |
|
790 | |||
804 | return matches |
|
791 | return matches | |
805 |
|
792 | |||
806 | def _default_arguments_from_docstring(self, doc): |
|
793 | def _default_arguments_from_docstring(self, doc): | |
807 | """Parse the first line of docstring for call signature. |
|
794 | """Parse the first line of docstring for call signature. | |
808 |
|
795 | |||
809 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
796 | Docstring should be of the form 'min(iterable[, key=func])\n'. | |
810 | It can also parse cython docstring of the form |
|
797 | It can also parse cython docstring of the form | |
811 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
798 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. | |
812 | """ |
|
799 | """ | |
813 | if doc is None: |
|
800 | if doc is None: | |
814 | return [] |
|
801 | return [] | |
815 |
|
802 | |||
816 | #care only the firstline |
|
803 | #care only the firstline | |
817 | line = doc.lstrip().splitlines()[0] |
|
804 | line = doc.lstrip().splitlines()[0] | |
818 |
|
805 | |||
819 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
806 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
820 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
807 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' | |
821 | sig = self.docstring_sig_re.search(line) |
|
808 | sig = self.docstring_sig_re.search(line) | |
822 | if sig is None: |
|
809 | if sig is None: | |
823 | return [] |
|
810 | return [] | |
824 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
811 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] | |
825 | sig = sig.groups()[0].split(',') |
|
812 | sig = sig.groups()[0].split(',') | |
826 | ret = [] |
|
813 | ret = [] | |
827 | for s in sig: |
|
814 | for s in sig: | |
828 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
815 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
829 | ret += self.docstring_kwd_re.findall(s) |
|
816 | ret += self.docstring_kwd_re.findall(s) | |
830 | return ret |
|
817 | return ret | |
831 |
|
818 | |||
832 | def _default_arguments(self, obj): |
|
819 | def _default_arguments(self, obj): | |
833 | """Return the list of default arguments of obj if it is callable, |
|
820 | """Return the list of default arguments of obj if it is callable, | |
834 | or empty list otherwise.""" |
|
821 | or empty list otherwise.""" | |
835 | call_obj = obj |
|
822 | call_obj = obj | |
836 | ret = [] |
|
823 | ret = [] | |
837 | if inspect.isbuiltin(obj): |
|
824 | if inspect.isbuiltin(obj): | |
838 | pass |
|
825 | pass | |
839 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
826 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
840 | if inspect.isclass(obj): |
|
827 | if inspect.isclass(obj): | |
841 | #for cython embededsignature=True the constructor docstring |
|
828 | #for cython embededsignature=True the constructor docstring | |
842 | #belongs to the object itself not __init__ |
|
829 | #belongs to the object itself not __init__ | |
843 | ret += self._default_arguments_from_docstring( |
|
830 | ret += self._default_arguments_from_docstring( | |
844 | getattr(obj, '__doc__', '')) |
|
831 | getattr(obj, '__doc__', '')) | |
845 | # for classes, check for __init__,__new__ |
|
832 | # for classes, check for __init__,__new__ | |
846 | call_obj = (getattr(obj, '__init__', None) or |
|
833 | call_obj = (getattr(obj, '__init__', None) or | |
847 | getattr(obj, '__new__', None)) |
|
834 | getattr(obj, '__new__', None)) | |
848 | # for all others, check if they are __call__able |
|
835 | # for all others, check if they are __call__able | |
849 | elif hasattr(obj, '__call__'): |
|
836 | elif hasattr(obj, '__call__'): | |
850 | call_obj = obj.__call__ |
|
837 | call_obj = obj.__call__ | |
851 | ret += self._default_arguments_from_docstring( |
|
838 | ret += self._default_arguments_from_docstring( | |
852 | getattr(call_obj, '__doc__', '')) |
|
839 | getattr(call_obj, '__doc__', '')) | |
853 |
|
840 | |||
854 | if PY3: |
|
841 | if PY3: | |
855 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
842 | _keeps = (inspect.Parameter.KEYWORD_ONLY, | |
856 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
843 | inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
857 | signature = inspect.signature |
|
844 | signature = inspect.signature | |
858 | else: |
|
845 | else: | |
859 | import IPython.utils.signatures |
|
846 | import IPython.utils.signatures | |
860 | _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY, |
|
847 | _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY, | |
861 | IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD) |
|
848 | IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD) | |
862 | signature = IPython.utils.signatures.signature |
|
849 | signature = IPython.utils.signatures.signature | |
863 |
|
850 | |||
864 | try: |
|
851 | try: | |
865 | sig = signature(call_obj) |
|
852 | sig = signature(call_obj) | |
866 | ret.extend(k for k, v in sig.parameters.items() if |
|
853 | ret.extend(k for k, v in sig.parameters.items() if | |
867 | v.kind in _keeps) |
|
854 | v.kind in _keeps) | |
868 | except ValueError: |
|
855 | except ValueError: | |
869 | pass |
|
856 | pass | |
870 |
|
857 | |||
871 | return list(set(ret)) |
|
858 | return list(set(ret)) | |
872 |
|
859 | |||
873 | def python_func_kw_matches(self,text): |
|
860 | def python_func_kw_matches(self,text): | |
874 | """Match named parameters (kwargs) of the last open function""" |
|
861 | """Match named parameters (kwargs) of the last open function""" | |
875 |
|
862 | |||
876 | if "." in text: # a parameter cannot be dotted |
|
863 | if "." in text: # a parameter cannot be dotted | |
877 | return [] |
|
864 | return [] | |
878 | try: regexp = self.__funcParamsRegex |
|
865 | try: regexp = self.__funcParamsRegex | |
879 | except AttributeError: |
|
866 | except AttributeError: | |
880 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
867 | regexp = self.__funcParamsRegex = re.compile(r''' | |
881 | '.*?(?<!\\)' | # single quoted strings or |
|
868 | '.*?(?<!\\)' | # single quoted strings or | |
882 | ".*?(?<!\\)" | # double quoted strings or |
|
869 | ".*?(?<!\\)" | # double quoted strings or | |
883 | \w+ | # identifier |
|
870 | \w+ | # identifier | |
884 | \S # other characters |
|
871 | \S # other characters | |
885 | ''', re.VERBOSE | re.DOTALL) |
|
872 | ''', re.VERBOSE | re.DOTALL) | |
886 | # 1. find the nearest identifier that comes before an unclosed |
|
873 | # 1. find the nearest identifier that comes before an unclosed | |
887 | # parenthesis before the cursor |
|
874 | # parenthesis before the cursor | |
888 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
875 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" | |
889 | tokens = regexp.findall(self.text_until_cursor) |
|
876 | tokens = regexp.findall(self.text_until_cursor) | |
890 | tokens.reverse() |
|
877 | tokens.reverse() | |
891 | iterTokens = iter(tokens); openPar = 0 |
|
878 | iterTokens = iter(tokens); openPar = 0 | |
892 |
|
879 | |||
893 | for token in iterTokens: |
|
880 | for token in iterTokens: | |
894 | if token == ')': |
|
881 | if token == ')': | |
895 | openPar -= 1 |
|
882 | openPar -= 1 | |
896 | elif token == '(': |
|
883 | elif token == '(': | |
897 | openPar += 1 |
|
884 | openPar += 1 | |
898 | if openPar > 0: |
|
885 | if openPar > 0: | |
899 | # found the last unclosed parenthesis |
|
886 | # found the last unclosed parenthesis | |
900 | break |
|
887 | break | |
901 | else: |
|
888 | else: | |
902 | return [] |
|
889 | return [] | |
903 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
890 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
904 | ids = [] |
|
891 | ids = [] | |
905 | isId = re.compile(r'\w+$').match |
|
892 | isId = re.compile(r'\w+$').match | |
906 |
|
893 | |||
907 | while True: |
|
894 | while True: | |
908 | try: |
|
895 | try: | |
909 | ids.append(next(iterTokens)) |
|
896 | ids.append(next(iterTokens)) | |
910 | if not isId(ids[-1]): |
|
897 | if not isId(ids[-1]): | |
911 | ids.pop(); break |
|
898 | ids.pop(); break | |
912 | if not next(iterTokens) == '.': |
|
899 | if not next(iterTokens) == '.': | |
913 | break |
|
900 | break | |
914 | except StopIteration: |
|
901 | except StopIteration: | |
915 | break |
|
902 | break | |
916 | # lookup the candidate callable matches either using global_matches |
|
903 | # lookup the candidate callable matches either using global_matches | |
917 | # or attr_matches for dotted names |
|
904 | # or attr_matches for dotted names | |
918 | if len(ids) == 1: |
|
905 | if len(ids) == 1: | |
919 | callableMatches = self.global_matches(ids[0]) |
|
906 | callableMatches = self.global_matches(ids[0]) | |
920 | else: |
|
907 | else: | |
921 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
908 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
922 | argMatches = [] |
|
909 | argMatches = [] | |
923 | for callableMatch in callableMatches: |
|
910 | for callableMatch in callableMatches: | |
924 | try: |
|
911 | try: | |
925 | namedArgs = self._default_arguments(eval(callableMatch, |
|
912 | namedArgs = self._default_arguments(eval(callableMatch, | |
926 | self.namespace)) |
|
913 | self.namespace)) | |
927 | except: |
|
914 | except: | |
928 | continue |
|
915 | continue | |
929 |
|
916 | |||
930 | for namedArg in namedArgs: |
|
917 | for namedArg in namedArgs: | |
931 | if namedArg.startswith(text): |
|
918 | if namedArg.startswith(text): | |
932 | argMatches.append("%s=" %namedArg) |
|
919 | argMatches.append("%s=" %namedArg) | |
933 | return argMatches |
|
920 | return argMatches | |
934 |
|
921 | |||
935 | def dict_key_matches(self, text): |
|
922 | def dict_key_matches(self, text): | |
936 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
923 | "Match string keys in a dictionary, after e.g. 'foo[' " | |
937 | def get_keys(obj): |
|
924 | def get_keys(obj): | |
938 | # Objects can define their own completions by defining an |
|
925 | # Objects can define their own completions by defining an | |
939 | # _ipy_key_completions_() method. |
|
926 | # _ipy_key_completions_() method. | |
940 |
|
|
927 | method = get_real_method(obj, '_ipython_key_completions_') | |
941 | return obj._ipython_key_completions_() |
|
928 | if method is not None: | |
|
929 | return method() | |||
942 |
|
930 | |||
943 | # Special case some common in-memory dict-like types |
|
931 | # Special case some common in-memory dict-like types | |
944 | if isinstance(obj, dict) or\ |
|
932 | if isinstance(obj, dict) or\ | |
945 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
933 | _safe_isinstance(obj, 'pandas', 'DataFrame'): | |
946 | try: |
|
934 | try: | |
947 | return list(obj.keys()) |
|
935 | return list(obj.keys()) | |
948 | except Exception: |
|
936 | except Exception: | |
949 | return [] |
|
937 | return [] | |
950 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
938 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ | |
951 | _safe_isinstance(obj, 'numpy', 'void'): |
|
939 | _safe_isinstance(obj, 'numpy', 'void'): | |
952 | return obj.dtype.names or [] |
|
940 | return obj.dtype.names or [] | |
953 | return [] |
|
941 | return [] | |
954 |
|
942 | |||
955 | try: |
|
943 | try: | |
956 | regexps = self.__dict_key_regexps |
|
944 | regexps = self.__dict_key_regexps | |
957 | except AttributeError: |
|
945 | except AttributeError: | |
958 | dict_key_re_fmt = r'''(?x) |
|
946 | dict_key_re_fmt = r'''(?x) | |
959 | ( # match dict-referring expression wrt greedy setting |
|
947 | ( # match dict-referring expression wrt greedy setting | |
960 | %s |
|
948 | %s | |
961 | ) |
|
949 | ) | |
962 | \[ # open bracket |
|
950 | \[ # open bracket | |
963 | \s* # and optional whitespace |
|
951 | \s* # and optional whitespace | |
964 | ([uUbB]? # string prefix (r not handled) |
|
952 | ([uUbB]? # string prefix (r not handled) | |
965 | (?: # unclosed string |
|
953 | (?: # unclosed string | |
966 | '(?:[^']|(?<!\\)\\')* |
|
954 | '(?:[^']|(?<!\\)\\')* | |
967 | | |
|
955 | | | |
968 | "(?:[^"]|(?<!\\)\\")* |
|
956 | "(?:[^"]|(?<!\\)\\")* | |
969 | ) |
|
957 | ) | |
970 | )? |
|
958 | )? | |
971 | $ |
|
959 | $ | |
972 | ''' |
|
960 | ''' | |
973 | regexps = self.__dict_key_regexps = { |
|
961 | regexps = self.__dict_key_regexps = { | |
974 | False: re.compile(dict_key_re_fmt % ''' |
|
962 | False: re.compile(dict_key_re_fmt % ''' | |
975 | # identifiers separated by . |
|
963 | # identifiers separated by . | |
976 | (?!\d)\w+ |
|
964 | (?!\d)\w+ | |
977 | (?:\.(?!\d)\w+)* |
|
965 | (?:\.(?!\d)\w+)* | |
978 | '''), |
|
966 | '''), | |
979 | True: re.compile(dict_key_re_fmt % ''' |
|
967 | True: re.compile(dict_key_re_fmt % ''' | |
980 | .+ |
|
968 | .+ | |
981 | ''') |
|
969 | ''') | |
982 | } |
|
970 | } | |
983 |
|
971 | |||
984 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
972 | match = regexps[self.greedy].search(self.text_until_cursor) | |
985 | if match is None: |
|
973 | if match is None: | |
986 | return [] |
|
974 | return [] | |
987 |
|
975 | |||
988 | expr, prefix = match.groups() |
|
976 | expr, prefix = match.groups() | |
989 | try: |
|
977 | try: | |
990 | obj = eval(expr, self.namespace) |
|
978 | obj = eval(expr, self.namespace) | |
991 | except Exception: |
|
979 | except Exception: | |
992 | try: |
|
980 | try: | |
993 | obj = eval(expr, self.global_namespace) |
|
981 | obj = eval(expr, self.global_namespace) | |
994 | except Exception: |
|
982 | except Exception: | |
995 | return [] |
|
983 | return [] | |
996 |
|
984 | |||
997 | keys = get_keys(obj) |
|
985 | keys = get_keys(obj) | |
998 | if not keys: |
|
986 | if not keys: | |
999 | return keys |
|
987 | return keys | |
1000 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
988 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) | |
1001 | if not matches: |
|
989 | if not matches: | |
1002 | return matches |
|
990 | return matches | |
1003 |
|
991 | |||
1004 | # get the cursor position of |
|
992 | # get the cursor position of | |
1005 | # - the text being completed |
|
993 | # - the text being completed | |
1006 | # - the start of the key text |
|
994 | # - the start of the key text | |
1007 | # - the start of the completion |
|
995 | # - the start of the completion | |
1008 | text_start = len(self.text_until_cursor) - len(text) |
|
996 | text_start = len(self.text_until_cursor) - len(text) | |
1009 | if prefix: |
|
997 | if prefix: | |
1010 | key_start = match.start(2) |
|
998 | key_start = match.start(2) | |
1011 | completion_start = key_start + token_offset |
|
999 | completion_start = key_start + token_offset | |
1012 | else: |
|
1000 | else: | |
1013 | key_start = completion_start = match.end() |
|
1001 | key_start = completion_start = match.end() | |
1014 |
|
1002 | |||
1015 | # grab the leading prefix, to make sure all completions start with `text` |
|
1003 | # grab the leading prefix, to make sure all completions start with `text` | |
1016 | if text_start > key_start: |
|
1004 | if text_start > key_start: | |
1017 | leading = '' |
|
1005 | leading = '' | |
1018 | else: |
|
1006 | else: | |
1019 | leading = text[text_start:completion_start] |
|
1007 | leading = text[text_start:completion_start] | |
1020 |
|
1008 | |||
1021 | # the index of the `[` character |
|
1009 | # the index of the `[` character | |
1022 | bracket_idx = match.end(1) |
|
1010 | bracket_idx = match.end(1) | |
1023 |
|
1011 | |||
1024 | # append closing quote and bracket as appropriate |
|
1012 | # append closing quote and bracket as appropriate | |
1025 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1013 | # this is *not* appropriate if the opening quote or bracket is outside | |
1026 | # the text given to this method |
|
1014 | # the text given to this method | |
1027 | suf = '' |
|
1015 | suf = '' | |
1028 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1016 | continuation = self.line_buffer[len(self.text_until_cursor):] | |
1029 | if key_start > text_start and closing_quote: |
|
1017 | if key_start > text_start and closing_quote: | |
1030 | # quotes were opened inside text, maybe close them |
|
1018 | # quotes were opened inside text, maybe close them | |
1031 | if continuation.startswith(closing_quote): |
|
1019 | if continuation.startswith(closing_quote): | |
1032 | continuation = continuation[len(closing_quote):] |
|
1020 | continuation = continuation[len(closing_quote):] | |
1033 | else: |
|
1021 | else: | |
1034 | suf += closing_quote |
|
1022 | suf += closing_quote | |
1035 | if bracket_idx > text_start: |
|
1023 | if bracket_idx > text_start: | |
1036 | # brackets were opened inside text, maybe close them |
|
1024 | # brackets were opened inside text, maybe close them | |
1037 | if not continuation.startswith(']'): |
|
1025 | if not continuation.startswith(']'): | |
1038 | suf += ']' |
|
1026 | suf += ']' | |
1039 |
|
1027 | |||
1040 | return [leading + k + suf for k in matches] |
|
1028 | return [leading + k + suf for k in matches] | |
1041 |
|
1029 | |||
1042 | def unicode_name_matches(self, text): |
|
1030 | def unicode_name_matches(self, text): | |
1043 | u"""Match Latex-like syntax for unicode characters base |
|
1031 | u"""Match Latex-like syntax for unicode characters base | |
1044 | on the name of the character. |
|
1032 | on the name of the character. | |
1045 |
|
1033 | |||
1046 | This does \\GREEK SMALL LETTER ETA -> Ξ· |
|
1034 | This does \\GREEK SMALL LETTER ETA -> Ξ· | |
1047 |
|
1035 | |||
1048 | Works only on valid python 3 identifier, or on combining characters that |
|
1036 | Works only on valid python 3 identifier, or on combining characters that | |
1049 | will combine to form a valid identifier. |
|
1037 | will combine to form a valid identifier. | |
1050 |
|
1038 | |||
1051 | Used on Python 3 only. |
|
1039 | Used on Python 3 only. | |
1052 | """ |
|
1040 | """ | |
1053 | slashpos = text.rfind('\\') |
|
1041 | slashpos = text.rfind('\\') | |
1054 | if slashpos > -1: |
|
1042 | if slashpos > -1: | |
1055 | s = text[slashpos+1:] |
|
1043 | s = text[slashpos+1:] | |
1056 | try : |
|
1044 | try : | |
1057 | unic = unicodedata.lookup(s) |
|
1045 | unic = unicodedata.lookup(s) | |
1058 | # allow combining chars |
|
1046 | # allow combining chars | |
1059 | if ('a'+unic).isidentifier(): |
|
1047 | if ('a'+unic).isidentifier(): | |
1060 | return '\\'+s,[unic] |
|
1048 | return '\\'+s,[unic] | |
1061 | except KeyError as e: |
|
1049 | except KeyError as e: | |
1062 | pass |
|
1050 | pass | |
1063 | return u'', [] |
|
1051 | return u'', [] | |
1064 |
|
1052 | |||
1065 |
|
1053 | |||
1066 |
|
1054 | |||
1067 |
|
1055 | |||
1068 | def latex_matches(self, text): |
|
1056 | def latex_matches(self, text): | |
1069 | u"""Match Latex syntax for unicode characters. |
|
1057 | u"""Match Latex syntax for unicode characters. | |
1070 |
|
1058 | |||
1071 | This does both \\alp -> \\alpha and \\alpha -> Ξ± |
|
1059 | This does both \\alp -> \\alpha and \\alpha -> Ξ± | |
1072 |
|
1060 | |||
1073 | Used on Python 3 only. |
|
1061 | Used on Python 3 only. | |
1074 | """ |
|
1062 | """ | |
1075 | slashpos = text.rfind('\\') |
|
1063 | slashpos = text.rfind('\\') | |
1076 | if slashpos > -1: |
|
1064 | if slashpos > -1: | |
1077 | s = text[slashpos:] |
|
1065 | s = text[slashpos:] | |
1078 | if s in latex_symbols: |
|
1066 | if s in latex_symbols: | |
1079 | # Try to complete a full latex symbol to unicode |
|
1067 | # Try to complete a full latex symbol to unicode | |
1080 | # \\alpha -> Ξ± |
|
1068 | # \\alpha -> Ξ± | |
1081 | return s, [latex_symbols[s]] |
|
1069 | return s, [latex_symbols[s]] | |
1082 | else: |
|
1070 | else: | |
1083 | # If a user has partially typed a latex symbol, give them |
|
1071 | # If a user has partially typed a latex symbol, give them | |
1084 | # a full list of options \al -> [\aleph, \alpha] |
|
1072 | # a full list of options \al -> [\aleph, \alpha] | |
1085 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1073 | matches = [k for k in latex_symbols if k.startswith(s)] | |
1086 | return s, matches |
|
1074 | return s, matches | |
1087 | return u'', [] |
|
1075 | return u'', [] | |
1088 |
|
1076 | |||
1089 | def dispatch_custom_completer(self, text): |
|
1077 | def dispatch_custom_completer(self, text): | |
1090 | #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg |
|
1078 | #io.rprint("Custom! '%s' %s" % (text, self.custom_completers)) # dbg | |
1091 | line = self.line_buffer |
|
1079 | line = self.line_buffer | |
1092 | if not line.strip(): |
|
1080 | if not line.strip(): | |
1093 | return None |
|
1081 | return None | |
1094 |
|
1082 | |||
1095 | # Create a little structure to pass all the relevant information about |
|
1083 | # Create a little structure to pass all the relevant information about | |
1096 | # the current completion to any custom completer. |
|
1084 | # the current completion to any custom completer. | |
1097 | event = Bunch() |
|
1085 | event = Bunch() | |
1098 | event.line = line |
|
1086 | event.line = line | |
1099 | event.symbol = text |
|
1087 | event.symbol = text | |
1100 | cmd = line.split(None,1)[0] |
|
1088 | cmd = line.split(None,1)[0] | |
1101 | event.command = cmd |
|
1089 | event.command = cmd | |
1102 | event.text_until_cursor = self.text_until_cursor |
|
1090 | event.text_until_cursor = self.text_until_cursor | |
1103 |
|
1091 | |||
1104 | #print "\ncustom:{%s]\n" % event # dbg |
|
1092 | #print "\ncustom:{%s]\n" % event # dbg | |
1105 |
|
1093 | |||
1106 | # for foo etc, try also to find completer for %foo |
|
1094 | # for foo etc, try also to find completer for %foo | |
1107 | if not cmd.startswith(self.magic_escape): |
|
1095 | if not cmd.startswith(self.magic_escape): | |
1108 | try_magic = self.custom_completers.s_matches( |
|
1096 | try_magic = self.custom_completers.s_matches( | |
1109 | self.magic_escape + cmd) |
|
1097 | self.magic_escape + cmd) | |
1110 | else: |
|
1098 | else: | |
1111 | try_magic = [] |
|
1099 | try_magic = [] | |
1112 |
|
1100 | |||
1113 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1101 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
1114 | try_magic, |
|
1102 | try_magic, | |
1115 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1103 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
1116 | #print "try",c # dbg |
|
1104 | #print "try",c # dbg | |
1117 | try: |
|
1105 | try: | |
1118 | res = c(event) |
|
1106 | res = c(event) | |
1119 | if res: |
|
1107 | if res: | |
1120 | # first, try case sensitive match |
|
1108 | # first, try case sensitive match | |
1121 | withcase = [r for r in res if r.startswith(text)] |
|
1109 | withcase = [r for r in res if r.startswith(text)] | |
1122 | if withcase: |
|
1110 | if withcase: | |
1123 | return withcase |
|
1111 | return withcase | |
1124 | # if none, then case insensitive ones are ok too |
|
1112 | # if none, then case insensitive ones are ok too | |
1125 | text_low = text.lower() |
|
1113 | text_low = text.lower() | |
1126 | return [r for r in res if r.lower().startswith(text_low)] |
|
1114 | return [r for r in res if r.lower().startswith(text_low)] | |
1127 | except TryNext: |
|
1115 | except TryNext: | |
1128 | pass |
|
1116 | pass | |
1129 |
|
1117 | |||
1130 | return None |
|
1118 | return None | |
1131 |
|
1119 | |||
1132 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1120 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
1133 | """Find completions for the given text and line context. |
|
1121 | """Find completions for the given text and line context. | |
1134 |
|
1122 | |||
1135 | Note that both the text and the line_buffer are optional, but at least |
|
1123 | Note that both the text and the line_buffer are optional, but at least | |
1136 | one of them must be given. |
|
1124 | one of them must be given. | |
1137 |
|
1125 | |||
1138 | Parameters |
|
1126 | Parameters | |
1139 | ---------- |
|
1127 | ---------- | |
1140 | text : string, optional |
|
1128 | text : string, optional | |
1141 | Text to perform the completion on. If not given, the line buffer |
|
1129 | Text to perform the completion on. If not given, the line buffer | |
1142 | is split using the instance's CompletionSplitter object. |
|
1130 | is split using the instance's CompletionSplitter object. | |
1143 |
|
1131 | |||
1144 | line_buffer : string, optional |
|
1132 | line_buffer : string, optional | |
1145 | If not given, the completer attempts to obtain the current line |
|
1133 | If not given, the completer attempts to obtain the current line | |
1146 | buffer via readline. This keyword allows clients which are |
|
1134 | buffer via readline. This keyword allows clients which are | |
1147 | requesting for text completions in non-readline contexts to inform |
|
1135 | requesting for text completions in non-readline contexts to inform | |
1148 | the completer of the entire text. |
|
1136 | the completer of the entire text. | |
1149 |
|
1137 | |||
1150 | cursor_pos : int, optional |
|
1138 | cursor_pos : int, optional | |
1151 | Index of the cursor in the full line buffer. Should be provided by |
|
1139 | Index of the cursor in the full line buffer. Should be provided by | |
1152 | remote frontends where kernel has no access to frontend state. |
|
1140 | remote frontends where kernel has no access to frontend state. | |
1153 |
|
1141 | |||
1154 | Returns |
|
1142 | Returns | |
1155 | ------- |
|
1143 | ------- | |
1156 | text : str |
|
1144 | text : str | |
1157 | Text that was actually used in the completion. |
|
1145 | Text that was actually used in the completion. | |
1158 |
|
1146 | |||
1159 | matches : list |
|
1147 | matches : list | |
1160 | A list of completion matches. |
|
1148 | A list of completion matches. | |
1161 | """ |
|
1149 | """ | |
1162 | # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
1150 | # io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
1163 |
|
1151 | |||
1164 | # if the cursor position isn't given, the only sane assumption we can |
|
1152 | # if the cursor position isn't given, the only sane assumption we can | |
1165 | # make is that it's at the end of the line (the common case) |
|
1153 | # make is that it's at the end of the line (the common case) | |
1166 | if cursor_pos is None: |
|
1154 | if cursor_pos is None: | |
1167 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1155 | cursor_pos = len(line_buffer) if text is None else len(text) | |
1168 |
|
1156 | |||
1169 | if PY3: |
|
1157 | if PY3: | |
1170 |
|
1158 | |||
1171 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
1159 | base_text = text if not line_buffer else line_buffer[:cursor_pos] | |
1172 | latex_text, latex_matches = self.latex_matches(base_text) |
|
1160 | latex_text, latex_matches = self.latex_matches(base_text) | |
1173 | if latex_matches: |
|
1161 | if latex_matches: | |
1174 | return latex_text, latex_matches |
|
1162 | return latex_text, latex_matches | |
1175 | name_text = '' |
|
1163 | name_text = '' | |
1176 | name_matches = [] |
|
1164 | name_matches = [] | |
1177 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): |
|
1165 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): | |
1178 | name_text, name_matches = meth(base_text) |
|
1166 | name_text, name_matches = meth(base_text) | |
1179 | if name_text: |
|
1167 | if name_text: | |
1180 | return name_text, name_matches |
|
1168 | return name_text, name_matches | |
1181 |
|
1169 | |||
1182 | # if text is either None or an empty string, rely on the line buffer |
|
1170 | # if text is either None or an empty string, rely on the line buffer | |
1183 | if not text: |
|
1171 | if not text: | |
1184 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1172 | text = self.splitter.split_line(line_buffer, cursor_pos) | |
1185 |
|
1173 | |||
1186 | # If no line buffer is given, assume the input text is all there was |
|
1174 | # If no line buffer is given, assume the input text is all there was | |
1187 | if line_buffer is None: |
|
1175 | if line_buffer is None: | |
1188 | line_buffer = text |
|
1176 | line_buffer = text | |
1189 |
|
1177 | |||
1190 | self.line_buffer = line_buffer |
|
1178 | self.line_buffer = line_buffer | |
1191 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1179 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
1192 | # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg |
|
1180 | # io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg | |
1193 |
|
1181 | |||
1194 | # Start with a clean slate of completions |
|
1182 | # Start with a clean slate of completions | |
1195 | self.matches[:] = [] |
|
1183 | self.matches[:] = [] | |
1196 | custom_res = self.dispatch_custom_completer(text) |
|
1184 | custom_res = self.dispatch_custom_completer(text) | |
1197 | if custom_res is not None: |
|
1185 | if custom_res is not None: | |
1198 | # did custom completers produce something? |
|
1186 | # did custom completers produce something? | |
1199 | self.matches = custom_res |
|
1187 | self.matches = custom_res | |
1200 | else: |
|
1188 | else: | |
1201 | # Extend the list of completions with the results of each |
|
1189 | # Extend the list of completions with the results of each | |
1202 | # matcher, so we return results to the user from all |
|
1190 | # matcher, so we return results to the user from all | |
1203 | # namespaces. |
|
1191 | # namespaces. | |
1204 | if self.merge_completions: |
|
1192 | if self.merge_completions: | |
1205 | self.matches = [] |
|
1193 | self.matches = [] | |
1206 | for matcher in self.matchers: |
|
1194 | for matcher in self.matchers: | |
1207 | try: |
|
1195 | try: | |
1208 | self.matches.extend(matcher(text)) |
|
1196 | self.matches.extend(matcher(text)) | |
1209 | except: |
|
1197 | except: | |
1210 | # Show the ugly traceback if the matcher causes an |
|
1198 | # Show the ugly traceback if the matcher causes an | |
1211 | # exception, but do NOT crash the kernel! |
|
1199 | # exception, but do NOT crash the kernel! | |
1212 | sys.excepthook(*sys.exc_info()) |
|
1200 | sys.excepthook(*sys.exc_info()) | |
1213 | else: |
|
1201 | else: | |
1214 | for matcher in self.matchers: |
|
1202 | for matcher in self.matchers: | |
1215 | self.matches = matcher(text) |
|
1203 | self.matches = matcher(text) | |
1216 | if self.matches: |
|
1204 | if self.matches: | |
1217 | break |
|
1205 | break | |
1218 | # FIXME: we should extend our api to return a dict with completions for |
|
1206 | # FIXME: we should extend our api to return a dict with completions for | |
1219 | # different types of objects. The rlcomplete() method could then |
|
1207 | # different types of objects. The rlcomplete() method could then | |
1220 | # simply collapse the dict into a list for readline, but we'd have |
|
1208 | # simply collapse the dict into a list for readline, but we'd have | |
1221 | # richer completion semantics in other evironments. |
|
1209 | # richer completion semantics in other evironments. | |
1222 |
|
1210 | |||
1223 | self.matches = sorted(set(self.matches), key=completions_sorting_key) |
|
1211 | self.matches = sorted(set(self.matches), key=completions_sorting_key) | |
1224 |
|
1212 | |||
1225 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg |
|
1213 | #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg | |
1226 | return text, self.matches |
|
1214 | return text, self.matches | |
1227 |
|
1215 | |||
1228 | def rlcomplete(self, text, state): |
|
1216 | def rlcomplete(self, text, state): | |
1229 | """Return the state-th possible completion for 'text'. |
|
1217 | """Return the state-th possible completion for 'text'. | |
1230 |
|
1218 | |||
1231 | This is called successively with state == 0, 1, 2, ... until it |
|
1219 | This is called successively with state == 0, 1, 2, ... until it | |
1232 | returns None. The completion should begin with 'text'. |
|
1220 | returns None. The completion should begin with 'text'. | |
1233 |
|
1221 | |||
1234 | Parameters |
|
1222 | Parameters | |
1235 | ---------- |
|
1223 | ---------- | |
1236 | text : string |
|
1224 | text : string | |
1237 | Text to perform the completion on. |
|
1225 | Text to perform the completion on. | |
1238 |
|
1226 | |||
1239 | state : int |
|
1227 | state : int | |
1240 | Counter used by readline. |
|
1228 | Counter used by readline. | |
1241 | """ |
|
1229 | """ | |
1242 | if state==0: |
|
1230 | if state==0: | |
1243 |
|
1231 | |||
1244 | self.line_buffer = line_buffer = self.readline.get_line_buffer() |
|
1232 | self.line_buffer = line_buffer = self.readline.get_line_buffer() | |
1245 | cursor_pos = self.readline.get_endidx() |
|
1233 | cursor_pos = self.readline.get_endidx() | |
1246 |
|
1234 | |||
1247 | #io.rprint("\nRLCOMPLETE: %r %r %r" % |
|
1235 | #io.rprint("\nRLCOMPLETE: %r %r %r" % | |
1248 | # (text, line_buffer, cursor_pos) ) # dbg |
|
1236 | # (text, line_buffer, cursor_pos) ) # dbg | |
1249 |
|
1237 | |||
1250 | # if there is only a tab on a line with only whitespace, instead of |
|
1238 | # if there is only a tab on a line with only whitespace, instead of | |
1251 | # the mostly useless 'do you want to see all million completions' |
|
1239 | # the mostly useless 'do you want to see all million completions' | |
1252 | # message, just do the right thing and give the user his tab! |
|
1240 | # message, just do the right thing and give the user his tab! | |
1253 | # Incidentally, this enables pasting of tabbed text from an editor |
|
1241 | # Incidentally, this enables pasting of tabbed text from an editor | |
1254 | # (as long as autoindent is off). |
|
1242 | # (as long as autoindent is off). | |
1255 |
|
1243 | |||
1256 | # It should be noted that at least pyreadline still shows file |
|
1244 | # It should be noted that at least pyreadline still shows file | |
1257 | # completions - is there a way around it? |
|
1245 | # completions - is there a way around it? | |
1258 |
|
1246 | |||
1259 | # don't apply this on 'dumb' terminals, such as emacs buffers, so |
|
1247 | # don't apply this on 'dumb' terminals, such as emacs buffers, so | |
1260 | # we don't interfere with their own tab-completion mechanism. |
|
1248 | # we don't interfere with their own tab-completion mechanism. | |
1261 | if not (self.dumb_terminal or line_buffer.strip()): |
|
1249 | if not (self.dumb_terminal or line_buffer.strip()): | |
1262 | self.readline.insert_text('\t') |
|
1250 | self.readline.insert_text('\t') | |
1263 | sys.stdout.flush() |
|
1251 | sys.stdout.flush() | |
1264 | return None |
|
1252 | return None | |
1265 |
|
1253 | |||
1266 | # Note: debugging exceptions that may occur in completion is very |
|
1254 | # Note: debugging exceptions that may occur in completion is very | |
1267 | # tricky, because readline unconditionally silences them. So if |
|
1255 | # tricky, because readline unconditionally silences them. So if | |
1268 | # during development you suspect a bug in the completion code, turn |
|
1256 | # during development you suspect a bug in the completion code, turn | |
1269 | # this flag on temporarily by uncommenting the second form (don't |
|
1257 | # this flag on temporarily by uncommenting the second form (don't | |
1270 | # flip the value in the first line, as the '# dbg' marker can be |
|
1258 | # flip the value in the first line, as the '# dbg' marker can be | |
1271 | # automatically detected and is used elsewhere). |
|
1259 | # automatically detected and is used elsewhere). | |
1272 | DEBUG = False |
|
1260 | DEBUG = False | |
1273 | #DEBUG = True # dbg |
|
1261 | #DEBUG = True # dbg | |
1274 | if DEBUG: |
|
1262 | if DEBUG: | |
1275 | try: |
|
1263 | try: | |
1276 | self.complete(text, line_buffer, cursor_pos) |
|
1264 | self.complete(text, line_buffer, cursor_pos) | |
1277 | except: |
|
1265 | except: | |
1278 | import traceback; traceback.print_exc() |
|
1266 | import traceback; traceback.print_exc() | |
1279 | else: |
|
1267 | else: | |
1280 | # The normal production version is here |
|
1268 | # The normal production version is here | |
1281 |
|
1269 | |||
1282 | # This method computes the self.matches array |
|
1270 | # This method computes the self.matches array | |
1283 | self.complete(text, line_buffer, cursor_pos) |
|
1271 | self.complete(text, line_buffer, cursor_pos) | |
1284 |
|
1272 | |||
1285 | try: |
|
1273 | try: | |
1286 | return self.matches[state] |
|
1274 | return self.matches[state] | |
1287 | except IndexError: |
|
1275 | except IndexError: | |
1288 | return None |
|
1276 | return None | |
1289 |
|
1277 |
@@ -1,295 +1,294 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Displayhook for IPython. |
|
2 | """Displayhook for IPython. | |
3 |
|
3 | |||
4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
4 | This defines a callable class that IPython uses for `sys.displayhook`. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | # Copyright (c) IPython Development Team. |
|
7 | # Copyright (c) IPython Development Team. | |
8 | # Distributed under the terms of the Modified BSD License. |
|
8 | # Distributed under the terms of the Modified BSD License. | |
9 |
|
9 | |||
10 | from __future__ import print_function |
|
10 | from __future__ import print_function | |
11 |
|
11 | |||
12 | import sys |
|
12 | import sys | |
13 | import io as _io |
|
13 | import io as _io | |
14 | import tokenize |
|
14 | import tokenize | |
15 |
|
15 | |||
16 | from IPython.core.formatters import _safe_get_formatter_method |
|
|||
17 | from traitlets.config.configurable import Configurable |
|
16 | from traitlets.config.configurable import Configurable | |
18 | from IPython.utils import io |
|
17 | from IPython.utils import io | |
19 | from IPython.utils.py3compat import builtin_mod, cast_unicode_py2 |
|
18 | from IPython.utils.py3compat import builtin_mod, cast_unicode_py2 | |
20 | from traitlets import Instance, Float |
|
19 | from traitlets import Instance, Float | |
21 | from warnings import warn |
|
20 | from warnings import warn | |
22 |
|
21 | |||
23 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
22 | # TODO: Move the various attributes (cache_size, [others now moved]). Some | |
24 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
23 | # of these are also attributes of InteractiveShell. They should be on ONE object | |
25 | # only and the other objects should ask that one object for their values. |
|
24 | # only and the other objects should ask that one object for their values. | |
26 |
|
25 | |||
27 | class DisplayHook(Configurable): |
|
26 | class DisplayHook(Configurable): | |
28 | """The custom IPython displayhook to replace sys.displayhook. |
|
27 | """The custom IPython displayhook to replace sys.displayhook. | |
29 |
|
28 | |||
30 | This class does many things, but the basic idea is that it is a callable |
|
29 | This class does many things, but the basic idea is that it is a callable | |
31 | that gets called anytime user code returns a value. |
|
30 | that gets called anytime user code returns a value. | |
32 | """ |
|
31 | """ | |
33 |
|
32 | |||
34 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
33 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', | |
35 | allow_none=True) |
|
34 | allow_none=True) | |
36 | exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', |
|
35 | exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', | |
37 | allow_none=True) |
|
36 | allow_none=True) | |
38 | cull_fraction = Float(0.2) |
|
37 | cull_fraction = Float(0.2) | |
39 |
|
38 | |||
40 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
39 | def __init__(self, shell=None, cache_size=1000, **kwargs): | |
41 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
40 | super(DisplayHook, self).__init__(shell=shell, **kwargs) | |
42 | cache_size_min = 3 |
|
41 | cache_size_min = 3 | |
43 | if cache_size <= 0: |
|
42 | if cache_size <= 0: | |
44 | self.do_full_cache = 0 |
|
43 | self.do_full_cache = 0 | |
45 | cache_size = 0 |
|
44 | cache_size = 0 | |
46 | elif cache_size < cache_size_min: |
|
45 | elif cache_size < cache_size_min: | |
47 | self.do_full_cache = 0 |
|
46 | self.do_full_cache = 0 | |
48 | cache_size = 0 |
|
47 | cache_size = 0 | |
49 | warn('caching was disabled (min value for cache size is %s).' % |
|
48 | warn('caching was disabled (min value for cache size is %s).' % | |
50 | cache_size_min,level=3) |
|
49 | cache_size_min,level=3) | |
51 | else: |
|
50 | else: | |
52 | self.do_full_cache = 1 |
|
51 | self.do_full_cache = 1 | |
53 |
|
52 | |||
54 | self.cache_size = cache_size |
|
53 | self.cache_size = cache_size | |
55 |
|
54 | |||
56 | # we need a reference to the user-level namespace |
|
55 | # we need a reference to the user-level namespace | |
57 | self.shell = shell |
|
56 | self.shell = shell | |
58 |
|
57 | |||
59 | self._,self.__,self.___ = '','','' |
|
58 | self._,self.__,self.___ = '','','' | |
60 |
|
59 | |||
61 | # these are deliberately global: |
|
60 | # these are deliberately global: | |
62 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
61 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} | |
63 | self.shell.user_ns.update(to_user_ns) |
|
62 | self.shell.user_ns.update(to_user_ns) | |
64 |
|
63 | |||
65 | @property |
|
64 | @property | |
66 | def prompt_count(self): |
|
65 | def prompt_count(self): | |
67 | return self.shell.execution_count |
|
66 | return self.shell.execution_count | |
68 |
|
67 | |||
69 | #------------------------------------------------------------------------- |
|
68 | #------------------------------------------------------------------------- | |
70 | # Methods used in __call__. Override these methods to modify the behavior |
|
69 | # Methods used in __call__. Override these methods to modify the behavior | |
71 | # of the displayhook. |
|
70 | # of the displayhook. | |
72 | #------------------------------------------------------------------------- |
|
71 | #------------------------------------------------------------------------- | |
73 |
|
72 | |||
74 | def check_for_underscore(self): |
|
73 | def check_for_underscore(self): | |
75 | """Check if the user has set the '_' variable by hand.""" |
|
74 | """Check if the user has set the '_' variable by hand.""" | |
76 | # If something injected a '_' variable in __builtin__, delete |
|
75 | # If something injected a '_' variable in __builtin__, delete | |
77 | # ipython's automatic one so we don't clobber that. gettext() in |
|
76 | # ipython's automatic one so we don't clobber that. gettext() in | |
78 | # particular uses _, so we need to stay away from it. |
|
77 | # particular uses _, so we need to stay away from it. | |
79 | if '_' in builtin_mod.__dict__: |
|
78 | if '_' in builtin_mod.__dict__: | |
80 | try: |
|
79 | try: | |
81 | del self.shell.user_ns['_'] |
|
80 | del self.shell.user_ns['_'] | |
82 | except KeyError: |
|
81 | except KeyError: | |
83 | pass |
|
82 | pass | |
84 |
|
83 | |||
85 | def quiet(self): |
|
84 | def quiet(self): | |
86 | """Should we silence the display hook because of ';'?""" |
|
85 | """Should we silence the display hook because of ';'?""" | |
87 | # do not print output if input ends in ';' |
|
86 | # do not print output if input ends in ';' | |
88 |
|
87 | |||
89 | try: |
|
88 | try: | |
90 | cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1]) |
|
89 | cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1]) | |
91 | except IndexError: |
|
90 | except IndexError: | |
92 | # some uses of ipshellembed may fail here |
|
91 | # some uses of ipshellembed may fail here | |
93 | return False |
|
92 | return False | |
94 |
|
93 | |||
95 | sio = _io.StringIO(cell) |
|
94 | sio = _io.StringIO(cell) | |
96 | tokens = list(tokenize.generate_tokens(sio.readline)) |
|
95 | tokens = list(tokenize.generate_tokens(sio.readline)) | |
97 |
|
96 | |||
98 | for token in reversed(tokens): |
|
97 | for token in reversed(tokens): | |
99 | if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): |
|
98 | if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): | |
100 | continue |
|
99 | continue | |
101 | if (token[0] == tokenize.OP) and (token[1] == ';'): |
|
100 | if (token[0] == tokenize.OP) and (token[1] == ';'): | |
102 | return True |
|
101 | return True | |
103 | else: |
|
102 | else: | |
104 | return False |
|
103 | return False | |
105 |
|
104 | |||
106 | def start_displayhook(self): |
|
105 | def start_displayhook(self): | |
107 | """Start the displayhook, initializing resources.""" |
|
106 | """Start the displayhook, initializing resources.""" | |
108 | pass |
|
107 | pass | |
109 |
|
108 | |||
110 | def write_output_prompt(self): |
|
109 | def write_output_prompt(self): | |
111 | """Write the output prompt. |
|
110 | """Write the output prompt. | |
112 |
|
111 | |||
113 | The default implementation simply writes the prompt to |
|
112 | The default implementation simply writes the prompt to | |
114 | ``io.stdout``. |
|
113 | ``io.stdout``. | |
115 | """ |
|
114 | """ | |
116 | # Use write, not print which adds an extra space. |
|
115 | # Use write, not print which adds an extra space. | |
117 | io.stdout.write(self.shell.separate_out) |
|
116 | io.stdout.write(self.shell.separate_out) | |
118 | outprompt = self.shell.prompt_manager.render('out') |
|
117 | outprompt = self.shell.prompt_manager.render('out') | |
119 | if self.do_full_cache: |
|
118 | if self.do_full_cache: | |
120 | io.stdout.write(outprompt) |
|
119 | io.stdout.write(outprompt) | |
121 |
|
120 | |||
122 | def compute_format_data(self, result): |
|
121 | def compute_format_data(self, result): | |
123 | """Compute format data of the object to be displayed. |
|
122 | """Compute format data of the object to be displayed. | |
124 |
|
123 | |||
125 | The format data is a generalization of the :func:`repr` of an object. |
|
124 | The format data is a generalization of the :func:`repr` of an object. | |
126 | In the default implementation the format data is a :class:`dict` of |
|
125 | In the default implementation the format data is a :class:`dict` of | |
127 | key value pair where the keys are valid MIME types and the values |
|
126 | key value pair where the keys are valid MIME types and the values | |
128 | are JSON'able data structure containing the raw data for that MIME |
|
127 | are JSON'able data structure containing the raw data for that MIME | |
129 | type. It is up to frontends to determine pick a MIME to to use and |
|
128 | type. It is up to frontends to determine pick a MIME to to use and | |
130 | display that data in an appropriate manner. |
|
129 | display that data in an appropriate manner. | |
131 |
|
130 | |||
132 | This method only computes the format data for the object and should |
|
131 | This method only computes the format data for the object and should | |
133 | NOT actually print or write that to a stream. |
|
132 | NOT actually print or write that to a stream. | |
134 |
|
133 | |||
135 | Parameters |
|
134 | Parameters | |
136 | ---------- |
|
135 | ---------- | |
137 | result : object |
|
136 | result : object | |
138 | The Python object passed to the display hook, whose format will be |
|
137 | The Python object passed to the display hook, whose format will be | |
139 | computed. |
|
138 | computed. | |
140 |
|
139 | |||
141 | Returns |
|
140 | Returns | |
142 | ------- |
|
141 | ------- | |
143 | (format_dict, md_dict) : dict |
|
142 | (format_dict, md_dict) : dict | |
144 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
143 | format_dict is a :class:`dict` whose keys are valid MIME types and values are | |
145 | JSON'able raw data for that MIME type. It is recommended that |
|
144 | JSON'able raw data for that MIME type. It is recommended that | |
146 | all return values of this should always include the "text/plain" |
|
145 | all return values of this should always include the "text/plain" | |
147 | MIME type representation of the object. |
|
146 | MIME type representation of the object. | |
148 | md_dict is a :class:`dict` with the same MIME type keys |
|
147 | md_dict is a :class:`dict` with the same MIME type keys | |
149 | of metadata associated with each output. |
|
148 | of metadata associated with each output. | |
150 |
|
149 | |||
151 | """ |
|
150 | """ | |
152 | return self.shell.display_formatter.format(result) |
|
151 | return self.shell.display_formatter.format(result) | |
153 |
|
152 | |||
154 | def write_format_data(self, format_dict, md_dict=None): |
|
153 | def write_format_data(self, format_dict, md_dict=None): | |
155 | """Write the format data dict to the frontend. |
|
154 | """Write the format data dict to the frontend. | |
156 |
|
155 | |||
157 | This default version of this method simply writes the plain text |
|
156 | This default version of this method simply writes the plain text | |
158 | representation of the object to ``io.stdout``. Subclasses should |
|
157 | representation of the object to ``io.stdout``. Subclasses should | |
159 | override this method to send the entire `format_dict` to the |
|
158 | override this method to send the entire `format_dict` to the | |
160 | frontends. |
|
159 | frontends. | |
161 |
|
160 | |||
162 | Parameters |
|
161 | Parameters | |
163 | ---------- |
|
162 | ---------- | |
164 | format_dict : dict |
|
163 | format_dict : dict | |
165 | The format dict for the object passed to `sys.displayhook`. |
|
164 | The format dict for the object passed to `sys.displayhook`. | |
166 | md_dict : dict (optional) |
|
165 | md_dict : dict (optional) | |
167 | The metadata dict to be associated with the display data. |
|
166 | The metadata dict to be associated with the display data. | |
168 | """ |
|
167 | """ | |
169 | if 'text/plain' not in format_dict: |
|
168 | if 'text/plain' not in format_dict: | |
170 | # nothing to do |
|
169 | # nothing to do | |
171 | return |
|
170 | return | |
172 | # We want to print because we want to always make sure we have a |
|
171 | # We want to print because we want to always make sure we have a | |
173 | # newline, even if all the prompt separators are ''. This is the |
|
172 | # newline, even if all the prompt separators are ''. This is the | |
174 | # standard IPython behavior. |
|
173 | # standard IPython behavior. | |
175 | result_repr = format_dict['text/plain'] |
|
174 | result_repr = format_dict['text/plain'] | |
176 | if '\n' in result_repr: |
|
175 | if '\n' in result_repr: | |
177 | # So that multi-line strings line up with the left column of |
|
176 | # So that multi-line strings line up with the left column of | |
178 | # the screen, instead of having the output prompt mess up |
|
177 | # the screen, instead of having the output prompt mess up | |
179 | # their first line. |
|
178 | # their first line. | |
180 | # We use the prompt template instead of the expanded prompt |
|
179 | # We use the prompt template instead of the expanded prompt | |
181 | # because the expansion may add ANSI escapes that will interfere |
|
180 | # because the expansion may add ANSI escapes that will interfere | |
182 | # with our ability to determine whether or not we should add |
|
181 | # with our ability to determine whether or not we should add | |
183 | # a newline. |
|
182 | # a newline. | |
184 | prompt_template = self.shell.prompt_manager.out_template |
|
183 | prompt_template = self.shell.prompt_manager.out_template | |
185 | if prompt_template and not prompt_template.endswith('\n'): |
|
184 | if prompt_template and not prompt_template.endswith('\n'): | |
186 | # But avoid extraneous empty lines. |
|
185 | # But avoid extraneous empty lines. | |
187 | result_repr = '\n' + result_repr |
|
186 | result_repr = '\n' + result_repr | |
188 |
|
187 | |||
189 | print(result_repr, file=io.stdout) |
|
188 | print(result_repr, file=io.stdout) | |
190 |
|
189 | |||
191 | def update_user_ns(self, result): |
|
190 | def update_user_ns(self, result): | |
192 | """Update user_ns with various things like _, __, _1, etc.""" |
|
191 | """Update user_ns with various things like _, __, _1, etc.""" | |
193 |
|
192 | |||
194 | # Avoid recursive reference when displaying _oh/Out |
|
193 | # Avoid recursive reference when displaying _oh/Out | |
195 | if result is not self.shell.user_ns['_oh']: |
|
194 | if result is not self.shell.user_ns['_oh']: | |
196 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
195 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: | |
197 | self.cull_cache() |
|
196 | self.cull_cache() | |
198 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
197 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise | |
199 | # we cause buggy behavior for things like gettext). |
|
198 | # we cause buggy behavior for things like gettext). | |
200 |
|
199 | |||
201 | if '_' not in builtin_mod.__dict__: |
|
200 | if '_' not in builtin_mod.__dict__: | |
202 | self.___ = self.__ |
|
201 | self.___ = self.__ | |
203 | self.__ = self._ |
|
202 | self.__ = self._ | |
204 | self._ = result |
|
203 | self._ = result | |
205 | self.shell.push({'_':self._, |
|
204 | self.shell.push({'_':self._, | |
206 | '__':self.__, |
|
205 | '__':self.__, | |
207 | '___':self.___}, interactive=False) |
|
206 | '___':self.___}, interactive=False) | |
208 |
|
207 | |||
209 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
208 | # hackish access to top-level namespace to create _1,_2... dynamically | |
210 | to_main = {} |
|
209 | to_main = {} | |
211 | if self.do_full_cache: |
|
210 | if self.do_full_cache: | |
212 | new_result = '_'+repr(self.prompt_count) |
|
211 | new_result = '_'+repr(self.prompt_count) | |
213 | to_main[new_result] = result |
|
212 | to_main[new_result] = result | |
214 | self.shell.push(to_main, interactive=False) |
|
213 | self.shell.push(to_main, interactive=False) | |
215 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
214 | self.shell.user_ns['_oh'][self.prompt_count] = result | |
216 |
|
215 | |||
217 | def fill_exec_result(self, result): |
|
216 | def fill_exec_result(self, result): | |
218 | if self.exec_result is not None: |
|
217 | if self.exec_result is not None: | |
219 | self.exec_result.result = result |
|
218 | self.exec_result.result = result | |
220 |
|
219 | |||
221 | def log_output(self, format_dict): |
|
220 | def log_output(self, format_dict): | |
222 | """Log the output.""" |
|
221 | """Log the output.""" | |
223 | if 'text/plain' not in format_dict: |
|
222 | if 'text/plain' not in format_dict: | |
224 | # nothing to do |
|
223 | # nothing to do | |
225 | return |
|
224 | return | |
226 | if self.shell.logger.log_output: |
|
225 | if self.shell.logger.log_output: | |
227 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
226 | self.shell.logger.log_write(format_dict['text/plain'], 'output') | |
228 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
227 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ | |
229 | format_dict['text/plain'] |
|
228 | format_dict['text/plain'] | |
230 |
|
229 | |||
231 | def finish_displayhook(self): |
|
230 | def finish_displayhook(self): | |
232 | """Finish up all displayhook activities.""" |
|
231 | """Finish up all displayhook activities.""" | |
233 | io.stdout.write(self.shell.separate_out2) |
|
232 | io.stdout.write(self.shell.separate_out2) | |
234 | io.stdout.flush() |
|
233 | io.stdout.flush() | |
235 |
|
234 | |||
236 | def __call__(self, result=None): |
|
235 | def __call__(self, result=None): | |
237 | """Printing with history cache management. |
|
236 | """Printing with history cache management. | |
238 |
|
237 | |||
239 | This is invoked everytime the interpreter needs to print, and is |
|
238 | This is invoked everytime the interpreter needs to print, and is | |
240 | activated by setting the variable sys.displayhook to it. |
|
239 | activated by setting the variable sys.displayhook to it. | |
241 | """ |
|
240 | """ | |
242 | self.check_for_underscore() |
|
241 | self.check_for_underscore() | |
243 | if result is not None and not self.quiet(): |
|
242 | if result is not None and not self.quiet(): | |
244 | self.start_displayhook() |
|
243 | self.start_displayhook() | |
245 | self.write_output_prompt() |
|
244 | self.write_output_prompt() | |
246 | format_dict, md_dict = self.compute_format_data(result) |
|
245 | format_dict, md_dict = self.compute_format_data(result) | |
247 | self.update_user_ns(result) |
|
246 | self.update_user_ns(result) | |
248 | self.fill_exec_result(result) |
|
247 | self.fill_exec_result(result) | |
249 | if format_dict: |
|
248 | if format_dict: | |
250 | self.write_format_data(format_dict, md_dict) |
|
249 | self.write_format_data(format_dict, md_dict) | |
251 | self.log_output(format_dict) |
|
250 | self.log_output(format_dict) | |
252 | self.finish_displayhook() |
|
251 | self.finish_displayhook() | |
253 |
|
252 | |||
254 | def cull_cache(self): |
|
253 | def cull_cache(self): | |
255 | """Output cache is full, cull the oldest entries""" |
|
254 | """Output cache is full, cull the oldest entries""" | |
256 | oh = self.shell.user_ns.get('_oh', {}) |
|
255 | oh = self.shell.user_ns.get('_oh', {}) | |
257 | sz = len(oh) |
|
256 | sz = len(oh) | |
258 | cull_count = max(int(sz * self.cull_fraction), 2) |
|
257 | cull_count = max(int(sz * self.cull_fraction), 2) | |
259 | warn('Output cache limit (currently {sz} entries) hit.\n' |
|
258 | warn('Output cache limit (currently {sz} entries) hit.\n' | |
260 | 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) |
|
259 | 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) | |
261 |
|
260 | |||
262 | for i, n in enumerate(sorted(oh)): |
|
261 | for i, n in enumerate(sorted(oh)): | |
263 | if i >= cull_count: |
|
262 | if i >= cull_count: | |
264 | break |
|
263 | break | |
265 | self.shell.user_ns.pop('_%i' % n, None) |
|
264 | self.shell.user_ns.pop('_%i' % n, None) | |
266 | oh.pop(n, None) |
|
265 | oh.pop(n, None) | |
267 |
|
266 | |||
268 |
|
267 | |||
269 | def flush(self): |
|
268 | def flush(self): | |
270 | if not self.do_full_cache: |
|
269 | if not self.do_full_cache: | |
271 | raise ValueError("You shouldn't have reached the cache flush " |
|
270 | raise ValueError("You shouldn't have reached the cache flush " | |
272 | "if full caching is not enabled!") |
|
271 | "if full caching is not enabled!") | |
273 | # delete auto-generated vars from global namespace |
|
272 | # delete auto-generated vars from global namespace | |
274 |
|
273 | |||
275 | for n in range(1,self.prompt_count + 1): |
|
274 | for n in range(1,self.prompt_count + 1): | |
276 | key = '_'+repr(n) |
|
275 | key = '_'+repr(n) | |
277 | try: |
|
276 | try: | |
278 | del self.shell.user_ns[key] |
|
277 | del self.shell.user_ns[key] | |
279 | except: pass |
|
278 | except: pass | |
280 | # In some embedded circumstances, the user_ns doesn't have the |
|
279 | # In some embedded circumstances, the user_ns doesn't have the | |
281 | # '_oh' key set up. |
|
280 | # '_oh' key set up. | |
282 | oh = self.shell.user_ns.get('_oh', None) |
|
281 | oh = self.shell.user_ns.get('_oh', None) | |
283 | if oh is not None: |
|
282 | if oh is not None: | |
284 | oh.clear() |
|
283 | oh.clear() | |
285 |
|
284 | |||
286 | # Release our own references to objects: |
|
285 | # Release our own references to objects: | |
287 | self._, self.__, self.___ = '', '', '' |
|
286 | self._, self.__, self.___ = '', '', '' | |
288 |
|
287 | |||
289 | if '_' not in builtin_mod.__dict__: |
|
288 | if '_' not in builtin_mod.__dict__: | |
290 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
289 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) | |
291 | import gc |
|
290 | import gc | |
292 | # TODO: Is this really needed? |
|
291 | # TODO: Is this really needed? | |
293 | # IronPython blocks here forever |
|
292 | # IronPython blocks here forever | |
294 | if sys.platform != "cli": |
|
293 | if sys.platform != "cli": | |
295 | gc.collect() |
|
294 | gc.collect() |
@@ -1,974 +1,952 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Display formatters. |
|
2 | """Display formatters. | |
3 |
|
3 | |||
4 | Inheritance diagram: |
|
4 | Inheritance diagram: | |
5 |
|
5 | |||
6 | .. inheritance-diagram:: IPython.core.formatters |
|
6 | .. inheritance-diagram:: IPython.core.formatters | |
7 | :parts: 3 |
|
7 | :parts: 3 | |
8 | """ |
|
8 | """ | |
9 |
|
9 | |||
10 | # Copyright (c) IPython Development Team. |
|
10 | # Copyright (c) IPython Development Team. | |
11 | # Distributed under the terms of the Modified BSD License. |
|
11 | # Distributed under the terms of the Modified BSD License. | |
12 |
|
12 | |||
13 | import abc |
|
13 | import abc | |
14 | import inspect |
|
14 | import inspect | |
15 | import json |
|
15 | import json | |
16 | import sys |
|
16 | import sys | |
17 | import traceback |
|
17 | import traceback | |
18 | import warnings |
|
18 | import warnings | |
19 |
|
19 | |||
20 | from decorator import decorator |
|
20 | from decorator import decorator | |
21 |
|
21 | |||
22 | from traitlets.config.configurable import Configurable |
|
22 | from traitlets.config.configurable import Configurable | |
23 | from IPython.core.getipython import get_ipython |
|
23 | from IPython.core.getipython import get_ipython | |
24 | from IPython.utils.sentinel import Sentinel |
|
24 | from IPython.utils.sentinel import Sentinel | |
|
25 | from IPython.utils.dir2 import get_real_method | |||
25 | from IPython.lib import pretty |
|
26 | from IPython.lib import pretty | |
26 | from traitlets import ( |
|
27 | from traitlets import ( | |
27 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
28 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, | |
28 | ForwardDeclaredInstance, |
|
29 | ForwardDeclaredInstance, | |
29 | ) |
|
30 | ) | |
30 | from IPython.utils.py3compat import ( |
|
31 | from IPython.utils.py3compat import ( | |
31 | with_metaclass, string_types, unicode_type, |
|
32 | with_metaclass, string_types, unicode_type, | |
32 | ) |
|
33 | ) | |
33 |
|
34 | |||
34 |
|
35 | |||
35 | #----------------------------------------------------------------------------- |
|
|||
36 | # The main DisplayFormatter class |
|
|||
37 | #----------------------------------------------------------------------------- |
|
|||
38 |
|
||||
39 |
|
||||
40 | def _safe_get_formatter_method(obj, name): |
|
|||
41 | """Safely get a formatter method |
|
|||
42 |
|
||||
43 | - Classes cannot have formatter methods, only instance |
|
|||
44 | - protect against proxy objects that claim to have everything |
|
|||
45 | """ |
|
|||
46 | if inspect.isclass(obj): |
|
|||
47 | # repr methods only make sense on instances, not classes |
|
|||
48 | return None |
|
|||
49 | method = pretty._safe_getattr(obj, name, None) |
|
|||
50 | if callable(method): |
|
|||
51 | # obj claims to have repr method... |
|
|||
52 | if callable(pretty._safe_getattr(obj, '_ipython_canary_method_should_not_exist_', None)): |
|
|||
53 | # ...but don't trust proxy objects that claim to have everything |
|
|||
54 | return None |
|
|||
55 | return method |
|
|||
56 |
|
||||
57 |
|
||||
58 | class DisplayFormatter(Configurable): |
|
36 | class DisplayFormatter(Configurable): | |
59 |
|
37 | |||
60 | # When set to true only the default plain text formatter will be used. |
|
38 | # When set to true only the default plain text formatter will be used. | |
61 | plain_text_only = Bool(False, config=True) |
|
39 | plain_text_only = Bool(False, config=True) | |
62 | def _plain_text_only_changed(self, name, old, new): |
|
40 | def _plain_text_only_changed(self, name, old, new): | |
63 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
41 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. | |
64 |
|
42 | |||
65 | It will be removed in IPython 5.0 |
|
43 | It will be removed in IPython 5.0 | |
66 |
|
44 | |||
67 | Use DisplayFormatter.active_types = ['text/plain'] |
|
45 | Use DisplayFormatter.active_types = ['text/plain'] | |
68 | for the same effect. |
|
46 | for the same effect. | |
69 | """, DeprecationWarning) |
|
47 | """, DeprecationWarning) | |
70 | if new: |
|
48 | if new: | |
71 | self.active_types = ['text/plain'] |
|
49 | self.active_types = ['text/plain'] | |
72 | else: |
|
50 | else: | |
73 | self.active_types = self.format_types |
|
51 | self.active_types = self.format_types | |
74 |
|
52 | |||
75 | active_types = List(Unicode(), config=True, |
|
53 | active_types = List(Unicode(), config=True, | |
76 | help="""List of currently active mime-types to display. |
|
54 | help="""List of currently active mime-types to display. | |
77 | You can use this to set a white-list for formats to display. |
|
55 | You can use this to set a white-list for formats to display. | |
78 |
|
56 | |||
79 | Most users will not need to change this value. |
|
57 | Most users will not need to change this value. | |
80 | """) |
|
58 | """) | |
81 | def _active_types_default(self): |
|
59 | def _active_types_default(self): | |
82 | return self.format_types |
|
60 | return self.format_types | |
83 |
|
61 | |||
84 | def _active_types_changed(self, name, old, new): |
|
62 | def _active_types_changed(self, name, old, new): | |
85 | for key, formatter in self.formatters.items(): |
|
63 | for key, formatter in self.formatters.items(): | |
86 | if key in new: |
|
64 | if key in new: | |
87 | formatter.enabled = True |
|
65 | formatter.enabled = True | |
88 | else: |
|
66 | else: | |
89 | formatter.enabled = False |
|
67 | formatter.enabled = False | |
90 |
|
68 | |||
91 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') |
|
69 | ipython_display_formatter = ForwardDeclaredInstance('FormatterABC') | |
92 | def _ipython_display_formatter_default(self): |
|
70 | def _ipython_display_formatter_default(self): | |
93 | return IPythonDisplayFormatter(parent=self) |
|
71 | return IPythonDisplayFormatter(parent=self) | |
94 |
|
72 | |||
95 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
73 | # A dict of formatter whose keys are format types (MIME types) and whose | |
96 | # values are subclasses of BaseFormatter. |
|
74 | # values are subclasses of BaseFormatter. | |
97 | formatters = Dict() |
|
75 | formatters = Dict() | |
98 | def _formatters_default(self): |
|
76 | def _formatters_default(self): | |
99 | """Activate the default formatters.""" |
|
77 | """Activate the default formatters.""" | |
100 | formatter_classes = [ |
|
78 | formatter_classes = [ | |
101 | PlainTextFormatter, |
|
79 | PlainTextFormatter, | |
102 | HTMLFormatter, |
|
80 | HTMLFormatter, | |
103 | MarkdownFormatter, |
|
81 | MarkdownFormatter, | |
104 | SVGFormatter, |
|
82 | SVGFormatter, | |
105 | PNGFormatter, |
|
83 | PNGFormatter, | |
106 | PDFFormatter, |
|
84 | PDFFormatter, | |
107 | JPEGFormatter, |
|
85 | JPEGFormatter, | |
108 | LatexFormatter, |
|
86 | LatexFormatter, | |
109 | JSONFormatter, |
|
87 | JSONFormatter, | |
110 | JavascriptFormatter |
|
88 | JavascriptFormatter | |
111 | ] |
|
89 | ] | |
112 | d = {} |
|
90 | d = {} | |
113 | for cls in formatter_classes: |
|
91 | for cls in formatter_classes: | |
114 | f = cls(parent=self) |
|
92 | f = cls(parent=self) | |
115 | d[f.format_type] = f |
|
93 | d[f.format_type] = f | |
116 | return d |
|
94 | return d | |
117 |
|
95 | |||
118 | def format(self, obj, include=None, exclude=None): |
|
96 | def format(self, obj, include=None, exclude=None): | |
119 | """Return a format data dict for an object. |
|
97 | """Return a format data dict for an object. | |
120 |
|
98 | |||
121 | By default all format types will be computed. |
|
99 | By default all format types will be computed. | |
122 |
|
100 | |||
123 | The following MIME types are currently implemented: |
|
101 | The following MIME types are currently implemented: | |
124 |
|
102 | |||
125 | * text/plain |
|
103 | * text/plain | |
126 | * text/html |
|
104 | * text/html | |
127 | * text/markdown |
|
105 | * text/markdown | |
128 | * text/latex |
|
106 | * text/latex | |
129 | * application/json |
|
107 | * application/json | |
130 | * application/javascript |
|
108 | * application/javascript | |
131 | * application/pdf |
|
109 | * application/pdf | |
132 | * image/png |
|
110 | * image/png | |
133 | * image/jpeg |
|
111 | * image/jpeg | |
134 | * image/svg+xml |
|
112 | * image/svg+xml | |
135 |
|
113 | |||
136 | Parameters |
|
114 | Parameters | |
137 | ---------- |
|
115 | ---------- | |
138 | obj : object |
|
116 | obj : object | |
139 | The Python object whose format data will be computed. |
|
117 | The Python object whose format data will be computed. | |
140 | include : list or tuple, optional |
|
118 | include : list or tuple, optional | |
141 | A list of format type strings (MIME types) to include in the |
|
119 | A list of format type strings (MIME types) to include in the | |
142 | format data dict. If this is set *only* the format types included |
|
120 | format data dict. If this is set *only* the format types included | |
143 | in this list will be computed. |
|
121 | in this list will be computed. | |
144 | exclude : list or tuple, optional |
|
122 | exclude : list or tuple, optional | |
145 | A list of format type string (MIME types) to exclude in the format |
|
123 | A list of format type string (MIME types) to exclude in the format | |
146 | data dict. If this is set all format types will be computed, |
|
124 | data dict. If this is set all format types will be computed, | |
147 | except for those included in this argument. |
|
125 | except for those included in this argument. | |
148 |
|
126 | |||
149 | Returns |
|
127 | Returns | |
150 | ------- |
|
128 | ------- | |
151 | (format_dict, metadata_dict) : tuple of two dicts |
|
129 | (format_dict, metadata_dict) : tuple of two dicts | |
152 |
|
130 | |||
153 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
131 | format_dict is a dictionary of key/value pairs, one of each format that was | |
154 | generated for the object. The keys are the format types, which |
|
132 | generated for the object. The keys are the format types, which | |
155 | will usually be MIME type strings and the values and JSON'able |
|
133 | will usually be MIME type strings and the values and JSON'able | |
156 | data structure containing the raw data for the representation in |
|
134 | data structure containing the raw data for the representation in | |
157 | that format. |
|
135 | that format. | |
158 |
|
136 | |||
159 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
137 | metadata_dict is a dictionary of metadata about each mime-type output. | |
160 | Its keys will be a strict subset of the keys in format_dict. |
|
138 | Its keys will be a strict subset of the keys in format_dict. | |
161 | """ |
|
139 | """ | |
162 | format_dict = {} |
|
140 | format_dict = {} | |
163 | md_dict = {} |
|
141 | md_dict = {} | |
164 |
|
142 | |||
165 | if self.ipython_display_formatter(obj): |
|
143 | if self.ipython_display_formatter(obj): | |
166 | # object handled itself, don't proceed |
|
144 | # object handled itself, don't proceed | |
167 | return {}, {} |
|
145 | return {}, {} | |
168 |
|
146 | |||
169 | for format_type, formatter in self.formatters.items(): |
|
147 | for format_type, formatter in self.formatters.items(): | |
170 | if include and format_type not in include: |
|
148 | if include and format_type not in include: | |
171 | continue |
|
149 | continue | |
172 | if exclude and format_type in exclude: |
|
150 | if exclude and format_type in exclude: | |
173 | continue |
|
151 | continue | |
174 |
|
152 | |||
175 | md = None |
|
153 | md = None | |
176 | try: |
|
154 | try: | |
177 | data = formatter(obj) |
|
155 | data = formatter(obj) | |
178 | except: |
|
156 | except: | |
179 | # FIXME: log the exception |
|
157 | # FIXME: log the exception | |
180 | raise |
|
158 | raise | |
181 |
|
159 | |||
182 | # formatters can return raw data or (data, metadata) |
|
160 | # formatters can return raw data or (data, metadata) | |
183 | if isinstance(data, tuple) and len(data) == 2: |
|
161 | if isinstance(data, tuple) and len(data) == 2: | |
184 | data, md = data |
|
162 | data, md = data | |
185 |
|
163 | |||
186 | if data is not None: |
|
164 | if data is not None: | |
187 | format_dict[format_type] = data |
|
165 | format_dict[format_type] = data | |
188 | if md is not None: |
|
166 | if md is not None: | |
189 | md_dict[format_type] = md |
|
167 | md_dict[format_type] = md | |
190 |
|
168 | |||
191 | return format_dict, md_dict |
|
169 | return format_dict, md_dict | |
192 |
|
170 | |||
193 | @property |
|
171 | @property | |
194 | def format_types(self): |
|
172 | def format_types(self): | |
195 | """Return the format types (MIME types) of the active formatters.""" |
|
173 | """Return the format types (MIME types) of the active formatters.""" | |
196 | return list(self.formatters.keys()) |
|
174 | return list(self.formatters.keys()) | |
197 |
|
175 | |||
198 |
|
176 | |||
199 | #----------------------------------------------------------------------------- |
|
177 | #----------------------------------------------------------------------------- | |
200 | # Formatters for specific format types (text, html, svg, etc.) |
|
178 | # Formatters for specific format types (text, html, svg, etc.) | |
201 | #----------------------------------------------------------------------------- |
|
179 | #----------------------------------------------------------------------------- | |
202 |
|
180 | |||
203 |
|
181 | |||
204 | def _safe_repr(obj): |
|
182 | def _safe_repr(obj): | |
205 | """Try to return a repr of an object |
|
183 | """Try to return a repr of an object | |
206 |
|
184 | |||
207 | always returns a string, at least. |
|
185 | always returns a string, at least. | |
208 | """ |
|
186 | """ | |
209 | try: |
|
187 | try: | |
210 | return repr(obj) |
|
188 | return repr(obj) | |
211 | except Exception as e: |
|
189 | except Exception as e: | |
212 | return "un-repr-able object (%r)" % e |
|
190 | return "un-repr-able object (%r)" % e | |
213 |
|
191 | |||
214 |
|
192 | |||
215 | class FormatterWarning(UserWarning): |
|
193 | class FormatterWarning(UserWarning): | |
216 | """Warning class for errors in formatters""" |
|
194 | """Warning class for errors in formatters""" | |
217 |
|
195 | |||
218 | @decorator |
|
196 | @decorator | |
219 | def catch_format_error(method, self, *args, **kwargs): |
|
197 | def catch_format_error(method, self, *args, **kwargs): | |
220 | """show traceback on failed format call""" |
|
198 | """show traceback on failed format call""" | |
221 | try: |
|
199 | try: | |
222 | r = method(self, *args, **kwargs) |
|
200 | r = method(self, *args, **kwargs) | |
223 | except NotImplementedError: |
|
201 | except NotImplementedError: | |
224 | # don't warn on NotImplementedErrors |
|
202 | # don't warn on NotImplementedErrors | |
225 | return None |
|
203 | return None | |
226 | except Exception: |
|
204 | except Exception: | |
227 | exc_info = sys.exc_info() |
|
205 | exc_info = sys.exc_info() | |
228 | ip = get_ipython() |
|
206 | ip = get_ipython() | |
229 | if ip is not None: |
|
207 | if ip is not None: | |
230 | ip.showtraceback(exc_info) |
|
208 | ip.showtraceback(exc_info) | |
231 | else: |
|
209 | else: | |
232 | traceback.print_exception(*exc_info) |
|
210 | traceback.print_exception(*exc_info) | |
233 | return None |
|
211 | return None | |
234 | return self._check_return(r, args[0]) |
|
212 | return self._check_return(r, args[0]) | |
235 |
|
213 | |||
236 |
|
214 | |||
237 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): |
|
215 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): | |
238 | """ Abstract base class for Formatters. |
|
216 | """ Abstract base class for Formatters. | |
239 |
|
217 | |||
240 | A formatter is a callable class that is responsible for computing the |
|
218 | A formatter is a callable class that is responsible for computing the | |
241 | raw format data for a particular format type (MIME type). For example, |
|
219 | raw format data for a particular format type (MIME type). For example, | |
242 | an HTML formatter would have a format type of `text/html` and would return |
|
220 | an HTML formatter would have a format type of `text/html` and would return | |
243 | the HTML representation of the object when called. |
|
221 | the HTML representation of the object when called. | |
244 | """ |
|
222 | """ | |
245 |
|
223 | |||
246 | # The format type of the data returned, usually a MIME type. |
|
224 | # The format type of the data returned, usually a MIME type. | |
247 | format_type = 'text/plain' |
|
225 | format_type = 'text/plain' | |
248 |
|
226 | |||
249 | # Is the formatter enabled... |
|
227 | # Is the formatter enabled... | |
250 | enabled = True |
|
228 | enabled = True | |
251 |
|
229 | |||
252 | @abc.abstractmethod |
|
230 | @abc.abstractmethod | |
253 | def __call__(self, obj): |
|
231 | def __call__(self, obj): | |
254 | """Return a JSON'able representation of the object. |
|
232 | """Return a JSON'able representation of the object. | |
255 |
|
233 | |||
256 | If the object cannot be formatted by this formatter, |
|
234 | If the object cannot be formatted by this formatter, | |
257 | warn and return None. |
|
235 | warn and return None. | |
258 | """ |
|
236 | """ | |
259 | return repr(obj) |
|
237 | return repr(obj) | |
260 |
|
238 | |||
261 |
|
239 | |||
262 | def _mod_name_key(typ): |
|
240 | def _mod_name_key(typ): | |
263 | """Return a (__module__, __name__) tuple for a type. |
|
241 | """Return a (__module__, __name__) tuple for a type. | |
264 |
|
242 | |||
265 | Used as key in Formatter.deferred_printers. |
|
243 | Used as key in Formatter.deferred_printers. | |
266 | """ |
|
244 | """ | |
267 | module = getattr(typ, '__module__', None) |
|
245 | module = getattr(typ, '__module__', None) | |
268 | name = getattr(typ, '__name__', None) |
|
246 | name = getattr(typ, '__name__', None) | |
269 | return (module, name) |
|
247 | return (module, name) | |
270 |
|
248 | |||
271 |
|
249 | |||
272 | def _get_type(obj): |
|
250 | def _get_type(obj): | |
273 | """Return the type of an instance (old and new-style)""" |
|
251 | """Return the type of an instance (old and new-style)""" | |
274 | return getattr(obj, '__class__', None) or type(obj) |
|
252 | return getattr(obj, '__class__', None) or type(obj) | |
275 |
|
253 | |||
276 |
|
254 | |||
277 | _raise_key_error = Sentinel('_raise_key_error', __name__, |
|
255 | _raise_key_error = Sentinel('_raise_key_error', __name__, | |
278 | """ |
|
256 | """ | |
279 | Special value to raise a KeyError |
|
257 | Special value to raise a KeyError | |
280 |
|
258 | |||
281 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` |
|
259 | Raise KeyError in `BaseFormatter.pop` if passed as the default value to `pop` | |
282 | """) |
|
260 | """) | |
283 |
|
261 | |||
284 |
|
262 | |||
285 | class BaseFormatter(Configurable): |
|
263 | class BaseFormatter(Configurable): | |
286 | """A base formatter class that is configurable. |
|
264 | """A base formatter class that is configurable. | |
287 |
|
265 | |||
288 | This formatter should usually be used as the base class of all formatters. |
|
266 | This formatter should usually be used as the base class of all formatters. | |
289 | It is a traited :class:`Configurable` class and includes an extensible |
|
267 | It is a traited :class:`Configurable` class and includes an extensible | |
290 | API for users to determine how their objects are formatted. The following |
|
268 | API for users to determine how their objects are formatted. The following | |
291 | logic is used to find a function to format an given object. |
|
269 | logic is used to find a function to format an given object. | |
292 |
|
270 | |||
293 | 1. The object is introspected to see if it has a method with the name |
|
271 | 1. The object is introspected to see if it has a method with the name | |
294 | :attr:`print_method`. If is does, that object is passed to that method |
|
272 | :attr:`print_method`. If is does, that object is passed to that method | |
295 | for formatting. |
|
273 | for formatting. | |
296 | 2. If no print method is found, three internal dictionaries are consulted |
|
274 | 2. If no print method is found, three internal dictionaries are consulted | |
297 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
275 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
298 | and :attr:`deferred_printers`. |
|
276 | and :attr:`deferred_printers`. | |
299 |
|
277 | |||
300 | Users should use these dictionaries to register functions that will be |
|
278 | Users should use these dictionaries to register functions that will be | |
301 | used to compute the format data for their objects (if those objects don't |
|
279 | used to compute the format data for their objects (if those objects don't | |
302 | have the special print methods). The easiest way of using these |
|
280 | have the special print methods). The easiest way of using these | |
303 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
281 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
304 | methods. |
|
282 | methods. | |
305 |
|
283 | |||
306 | If no function/callable is found to compute the format data, ``None`` is |
|
284 | If no function/callable is found to compute the format data, ``None`` is | |
307 | returned and this format type is not used. |
|
285 | returned and this format type is not used. | |
308 | """ |
|
286 | """ | |
309 |
|
287 | |||
310 | format_type = Unicode('text/plain') |
|
288 | format_type = Unicode('text/plain') | |
311 | _return_type = string_types |
|
289 | _return_type = string_types | |
312 |
|
290 | |||
313 | enabled = Bool(True, config=True) |
|
291 | enabled = Bool(True, config=True) | |
314 |
|
292 | |||
315 | print_method = ObjectName('__repr__') |
|
293 | print_method = ObjectName('__repr__') | |
316 |
|
294 | |||
317 | # The singleton printers. |
|
295 | # The singleton printers. | |
318 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
296 | # Maps the IDs of the builtin singleton objects to the format functions. | |
319 | singleton_printers = Dict(config=True) |
|
297 | singleton_printers = Dict(config=True) | |
320 |
|
298 | |||
321 | # The type-specific printers. |
|
299 | # The type-specific printers. | |
322 | # Map type objects to the format functions. |
|
300 | # Map type objects to the format functions. | |
323 | type_printers = Dict(config=True) |
|
301 | type_printers = Dict(config=True) | |
324 |
|
302 | |||
325 | # The deferred-import type-specific printers. |
|
303 | # The deferred-import type-specific printers. | |
326 | # Map (modulename, classname) pairs to the format functions. |
|
304 | # Map (modulename, classname) pairs to the format functions. | |
327 | deferred_printers = Dict(config=True) |
|
305 | deferred_printers = Dict(config=True) | |
328 |
|
306 | |||
329 | @catch_format_error |
|
307 | @catch_format_error | |
330 | def __call__(self, obj): |
|
308 | def __call__(self, obj): | |
331 | """Compute the format for an object.""" |
|
309 | """Compute the format for an object.""" | |
332 | if self.enabled: |
|
310 | if self.enabled: | |
333 | # lookup registered printer |
|
311 | # lookup registered printer | |
334 | try: |
|
312 | try: | |
335 | printer = self.lookup(obj) |
|
313 | printer = self.lookup(obj) | |
336 | except KeyError: |
|
314 | except KeyError: | |
337 | pass |
|
315 | pass | |
338 | else: |
|
316 | else: | |
339 | return printer(obj) |
|
317 | return printer(obj) | |
340 | # Finally look for special method names |
|
318 | # Finally look for special method names | |
341 |
method = |
|
319 | method = get_real_method(obj, self.print_method) | |
342 | if method is not None: |
|
320 | if method is not None: | |
343 | return method() |
|
321 | return method() | |
344 | return None |
|
322 | return None | |
345 | else: |
|
323 | else: | |
346 | return None |
|
324 | return None | |
347 |
|
325 | |||
348 | def __contains__(self, typ): |
|
326 | def __contains__(self, typ): | |
349 | """map in to lookup_by_type""" |
|
327 | """map in to lookup_by_type""" | |
350 | try: |
|
328 | try: | |
351 | self.lookup_by_type(typ) |
|
329 | self.lookup_by_type(typ) | |
352 | except KeyError: |
|
330 | except KeyError: | |
353 | return False |
|
331 | return False | |
354 | else: |
|
332 | else: | |
355 | return True |
|
333 | return True | |
356 |
|
334 | |||
357 | def _check_return(self, r, obj): |
|
335 | def _check_return(self, r, obj): | |
358 | """Check that a return value is appropriate |
|
336 | """Check that a return value is appropriate | |
359 |
|
337 | |||
360 | Return the value if so, None otherwise, warning if invalid. |
|
338 | Return the value if so, None otherwise, warning if invalid. | |
361 | """ |
|
339 | """ | |
362 | if r is None or isinstance(r, self._return_type) or \ |
|
340 | if r is None or isinstance(r, self._return_type) or \ | |
363 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): |
|
341 | (isinstance(r, tuple) and r and isinstance(r[0], self._return_type)): | |
364 | return r |
|
342 | return r | |
365 | else: |
|
343 | else: | |
366 | warnings.warn( |
|
344 | warnings.warn( | |
367 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ |
|
345 | "%s formatter returned invalid type %s (expected %s) for object: %s" % \ | |
368 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), |
|
346 | (self.format_type, type(r), self._return_type, _safe_repr(obj)), | |
369 | FormatterWarning |
|
347 | FormatterWarning | |
370 | ) |
|
348 | ) | |
371 |
|
349 | |||
372 | def lookup(self, obj): |
|
350 | def lookup(self, obj): | |
373 | """Look up the formatter for a given instance. |
|
351 | """Look up the formatter for a given instance. | |
374 |
|
352 | |||
375 | Parameters |
|
353 | Parameters | |
376 | ---------- |
|
354 | ---------- | |
377 | obj : object instance |
|
355 | obj : object instance | |
378 |
|
356 | |||
379 | Returns |
|
357 | Returns | |
380 | ------- |
|
358 | ------- | |
381 | f : callable |
|
359 | f : callable | |
382 | The registered formatting callable for the type. |
|
360 | The registered formatting callable for the type. | |
383 |
|
361 | |||
384 | Raises |
|
362 | Raises | |
385 | ------ |
|
363 | ------ | |
386 | KeyError if the type has not been registered. |
|
364 | KeyError if the type has not been registered. | |
387 | """ |
|
365 | """ | |
388 | # look for singleton first |
|
366 | # look for singleton first | |
389 | obj_id = id(obj) |
|
367 | obj_id = id(obj) | |
390 | if obj_id in self.singleton_printers: |
|
368 | if obj_id in self.singleton_printers: | |
391 | return self.singleton_printers[obj_id] |
|
369 | return self.singleton_printers[obj_id] | |
392 | # then lookup by type |
|
370 | # then lookup by type | |
393 | return self.lookup_by_type(_get_type(obj)) |
|
371 | return self.lookup_by_type(_get_type(obj)) | |
394 |
|
372 | |||
395 | def lookup_by_type(self, typ): |
|
373 | def lookup_by_type(self, typ): | |
396 | """Look up the registered formatter for a type. |
|
374 | """Look up the registered formatter for a type. | |
397 |
|
375 | |||
398 | Parameters |
|
376 | Parameters | |
399 | ---------- |
|
377 | ---------- | |
400 | typ : type or '__module__.__name__' string for a type |
|
378 | typ : type or '__module__.__name__' string for a type | |
401 |
|
379 | |||
402 | Returns |
|
380 | Returns | |
403 | ------- |
|
381 | ------- | |
404 | f : callable |
|
382 | f : callable | |
405 | The registered formatting callable for the type. |
|
383 | The registered formatting callable for the type. | |
406 |
|
384 | |||
407 | Raises |
|
385 | Raises | |
408 | ------ |
|
386 | ------ | |
409 | KeyError if the type has not been registered. |
|
387 | KeyError if the type has not been registered. | |
410 | """ |
|
388 | """ | |
411 | if isinstance(typ, string_types): |
|
389 | if isinstance(typ, string_types): | |
412 | typ_key = tuple(typ.rsplit('.',1)) |
|
390 | typ_key = tuple(typ.rsplit('.',1)) | |
413 | if typ_key not in self.deferred_printers: |
|
391 | if typ_key not in self.deferred_printers: | |
414 | # We may have it cached in the type map. We will have to |
|
392 | # We may have it cached in the type map. We will have to | |
415 | # iterate over all of the types to check. |
|
393 | # iterate over all of the types to check. | |
416 | for cls in self.type_printers: |
|
394 | for cls in self.type_printers: | |
417 | if _mod_name_key(cls) == typ_key: |
|
395 | if _mod_name_key(cls) == typ_key: | |
418 | return self.type_printers[cls] |
|
396 | return self.type_printers[cls] | |
419 | else: |
|
397 | else: | |
420 | return self.deferred_printers[typ_key] |
|
398 | return self.deferred_printers[typ_key] | |
421 | else: |
|
399 | else: | |
422 | for cls in pretty._get_mro(typ): |
|
400 | for cls in pretty._get_mro(typ): | |
423 | if cls in self.type_printers or self._in_deferred_types(cls): |
|
401 | if cls in self.type_printers or self._in_deferred_types(cls): | |
424 | return self.type_printers[cls] |
|
402 | return self.type_printers[cls] | |
425 |
|
403 | |||
426 | # If we have reached here, the lookup failed. |
|
404 | # If we have reached here, the lookup failed. | |
427 | raise KeyError("No registered printer for {0!r}".format(typ)) |
|
405 | raise KeyError("No registered printer for {0!r}".format(typ)) | |
428 |
|
406 | |||
429 | def for_type(self, typ, func=None): |
|
407 | def for_type(self, typ, func=None): | |
430 | """Add a format function for a given type. |
|
408 | """Add a format function for a given type. | |
431 |
|
409 | |||
432 | Parameters |
|
410 | Parameters | |
433 | ----------- |
|
411 | ----------- | |
434 | typ : type or '__module__.__name__' string for a type |
|
412 | typ : type or '__module__.__name__' string for a type | |
435 | The class of the object that will be formatted using `func`. |
|
413 | The class of the object that will be formatted using `func`. | |
436 | func : callable |
|
414 | func : callable | |
437 | A callable for computing the format data. |
|
415 | A callable for computing the format data. | |
438 | `func` will be called with the object to be formatted, |
|
416 | `func` will be called with the object to be formatted, | |
439 | and will return the raw data in this formatter's format. |
|
417 | and will return the raw data in this formatter's format. | |
440 | Subclasses may use a different call signature for the |
|
418 | Subclasses may use a different call signature for the | |
441 | `func` argument. |
|
419 | `func` argument. | |
442 |
|
420 | |||
443 | If `func` is None or not specified, there will be no change, |
|
421 | If `func` is None or not specified, there will be no change, | |
444 | only returning the current value. |
|
422 | only returning the current value. | |
445 |
|
423 | |||
446 | Returns |
|
424 | Returns | |
447 | ------- |
|
425 | ------- | |
448 | oldfunc : callable |
|
426 | oldfunc : callable | |
449 | The currently registered callable. |
|
427 | The currently registered callable. | |
450 | If you are registering a new formatter, |
|
428 | If you are registering a new formatter, | |
451 | this will be the previous value (to enable restoring later). |
|
429 | this will be the previous value (to enable restoring later). | |
452 | """ |
|
430 | """ | |
453 | # if string given, interpret as 'pkg.module.class_name' |
|
431 | # if string given, interpret as 'pkg.module.class_name' | |
454 | if isinstance(typ, string_types): |
|
432 | if isinstance(typ, string_types): | |
455 | type_module, type_name = typ.rsplit('.', 1) |
|
433 | type_module, type_name = typ.rsplit('.', 1) | |
456 | return self.for_type_by_name(type_module, type_name, func) |
|
434 | return self.for_type_by_name(type_module, type_name, func) | |
457 |
|
435 | |||
458 | try: |
|
436 | try: | |
459 | oldfunc = self.lookup_by_type(typ) |
|
437 | oldfunc = self.lookup_by_type(typ) | |
460 | except KeyError: |
|
438 | except KeyError: | |
461 | oldfunc = None |
|
439 | oldfunc = None | |
462 |
|
440 | |||
463 | if func is not None: |
|
441 | if func is not None: | |
464 | self.type_printers[typ] = func |
|
442 | self.type_printers[typ] = func | |
465 |
|
443 | |||
466 | return oldfunc |
|
444 | return oldfunc | |
467 |
|
445 | |||
468 | def for_type_by_name(self, type_module, type_name, func=None): |
|
446 | def for_type_by_name(self, type_module, type_name, func=None): | |
469 | """Add a format function for a type specified by the full dotted |
|
447 | """Add a format function for a type specified by the full dotted | |
470 | module and name of the type, rather than the type of the object. |
|
448 | module and name of the type, rather than the type of the object. | |
471 |
|
449 | |||
472 | Parameters |
|
450 | Parameters | |
473 | ---------- |
|
451 | ---------- | |
474 | type_module : str |
|
452 | type_module : str | |
475 | The full dotted name of the module the type is defined in, like |
|
453 | The full dotted name of the module the type is defined in, like | |
476 | ``numpy``. |
|
454 | ``numpy``. | |
477 | type_name : str |
|
455 | type_name : str | |
478 | The name of the type (the class name), like ``dtype`` |
|
456 | The name of the type (the class name), like ``dtype`` | |
479 | func : callable |
|
457 | func : callable | |
480 | A callable for computing the format data. |
|
458 | A callable for computing the format data. | |
481 | `func` will be called with the object to be formatted, |
|
459 | `func` will be called with the object to be formatted, | |
482 | and will return the raw data in this formatter's format. |
|
460 | and will return the raw data in this formatter's format. | |
483 | Subclasses may use a different call signature for the |
|
461 | Subclasses may use a different call signature for the | |
484 | `func` argument. |
|
462 | `func` argument. | |
485 |
|
463 | |||
486 | If `func` is None or unspecified, there will be no change, |
|
464 | If `func` is None or unspecified, there will be no change, | |
487 | only returning the current value. |
|
465 | only returning the current value. | |
488 |
|
466 | |||
489 | Returns |
|
467 | Returns | |
490 | ------- |
|
468 | ------- | |
491 | oldfunc : callable |
|
469 | oldfunc : callable | |
492 | The currently registered callable. |
|
470 | The currently registered callable. | |
493 | If you are registering a new formatter, |
|
471 | If you are registering a new formatter, | |
494 | this will be the previous value (to enable restoring later). |
|
472 | this will be the previous value (to enable restoring later). | |
495 | """ |
|
473 | """ | |
496 | key = (type_module, type_name) |
|
474 | key = (type_module, type_name) | |
497 |
|
475 | |||
498 | try: |
|
476 | try: | |
499 | oldfunc = self.lookup_by_type("%s.%s" % key) |
|
477 | oldfunc = self.lookup_by_type("%s.%s" % key) | |
500 | except KeyError: |
|
478 | except KeyError: | |
501 | oldfunc = None |
|
479 | oldfunc = None | |
502 |
|
480 | |||
503 | if func is not None: |
|
481 | if func is not None: | |
504 | self.deferred_printers[key] = func |
|
482 | self.deferred_printers[key] = func | |
505 | return oldfunc |
|
483 | return oldfunc | |
506 |
|
484 | |||
507 | def pop(self, typ, default=_raise_key_error): |
|
485 | def pop(self, typ, default=_raise_key_error): | |
508 | """Pop a formatter for the given type. |
|
486 | """Pop a formatter for the given type. | |
509 |
|
487 | |||
510 | Parameters |
|
488 | Parameters | |
511 | ---------- |
|
489 | ---------- | |
512 | typ : type or '__module__.__name__' string for a type |
|
490 | typ : type or '__module__.__name__' string for a type | |
513 | default : object |
|
491 | default : object | |
514 | value to be returned if no formatter is registered for typ. |
|
492 | value to be returned if no formatter is registered for typ. | |
515 |
|
493 | |||
516 | Returns |
|
494 | Returns | |
517 | ------- |
|
495 | ------- | |
518 | obj : object |
|
496 | obj : object | |
519 | The last registered object for the type. |
|
497 | The last registered object for the type. | |
520 |
|
498 | |||
521 | Raises |
|
499 | Raises | |
522 | ------ |
|
500 | ------ | |
523 | KeyError if the type is not registered and default is not specified. |
|
501 | KeyError if the type is not registered and default is not specified. | |
524 | """ |
|
502 | """ | |
525 |
|
503 | |||
526 | if isinstance(typ, string_types): |
|
504 | if isinstance(typ, string_types): | |
527 | typ_key = tuple(typ.rsplit('.',1)) |
|
505 | typ_key = tuple(typ.rsplit('.',1)) | |
528 | if typ_key not in self.deferred_printers: |
|
506 | if typ_key not in self.deferred_printers: | |
529 | # We may have it cached in the type map. We will have to |
|
507 | # We may have it cached in the type map. We will have to | |
530 | # iterate over all of the types to check. |
|
508 | # iterate over all of the types to check. | |
531 | for cls in self.type_printers: |
|
509 | for cls in self.type_printers: | |
532 | if _mod_name_key(cls) == typ_key: |
|
510 | if _mod_name_key(cls) == typ_key: | |
533 | old = self.type_printers.pop(cls) |
|
511 | old = self.type_printers.pop(cls) | |
534 | break |
|
512 | break | |
535 | else: |
|
513 | else: | |
536 | old = default |
|
514 | old = default | |
537 | else: |
|
515 | else: | |
538 | old = self.deferred_printers.pop(typ_key) |
|
516 | old = self.deferred_printers.pop(typ_key) | |
539 | else: |
|
517 | else: | |
540 | if typ in self.type_printers: |
|
518 | if typ in self.type_printers: | |
541 | old = self.type_printers.pop(typ) |
|
519 | old = self.type_printers.pop(typ) | |
542 | else: |
|
520 | else: | |
543 | old = self.deferred_printers.pop(_mod_name_key(typ), default) |
|
521 | old = self.deferred_printers.pop(_mod_name_key(typ), default) | |
544 | if old is _raise_key_error: |
|
522 | if old is _raise_key_error: | |
545 | raise KeyError("No registered value for {0!r}".format(typ)) |
|
523 | raise KeyError("No registered value for {0!r}".format(typ)) | |
546 | return old |
|
524 | return old | |
547 |
|
525 | |||
548 | def _in_deferred_types(self, cls): |
|
526 | def _in_deferred_types(self, cls): | |
549 | """ |
|
527 | """ | |
550 | Check if the given class is specified in the deferred type registry. |
|
528 | Check if the given class is specified in the deferred type registry. | |
551 |
|
529 | |||
552 | Successful matches will be moved to the regular type registry for future use. |
|
530 | Successful matches will be moved to the regular type registry for future use. | |
553 | """ |
|
531 | """ | |
554 | mod = getattr(cls, '__module__', None) |
|
532 | mod = getattr(cls, '__module__', None) | |
555 | name = getattr(cls, '__name__', None) |
|
533 | name = getattr(cls, '__name__', None) | |
556 | key = (mod, name) |
|
534 | key = (mod, name) | |
557 | if key in self.deferred_printers: |
|
535 | if key in self.deferred_printers: | |
558 | # Move the printer over to the regular registry. |
|
536 | # Move the printer over to the regular registry. | |
559 | printer = self.deferred_printers.pop(key) |
|
537 | printer = self.deferred_printers.pop(key) | |
560 | self.type_printers[cls] = printer |
|
538 | self.type_printers[cls] = printer | |
561 | return True |
|
539 | return True | |
562 | return False |
|
540 | return False | |
563 |
|
541 | |||
564 |
|
542 | |||
565 | class PlainTextFormatter(BaseFormatter): |
|
543 | class PlainTextFormatter(BaseFormatter): | |
566 | """The default pretty-printer. |
|
544 | """The default pretty-printer. | |
567 |
|
545 | |||
568 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
546 | This uses :mod:`IPython.lib.pretty` to compute the format data of | |
569 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
547 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
570 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
548 | See the documentation of :mod:`IPython.lib.pretty` for details on | |
571 | how to write pretty printers. Here is a simple example:: |
|
549 | how to write pretty printers. Here is a simple example:: | |
572 |
|
550 | |||
573 | def dtype_pprinter(obj, p, cycle): |
|
551 | def dtype_pprinter(obj, p, cycle): | |
574 | if cycle: |
|
552 | if cycle: | |
575 | return p.text('dtype(...)') |
|
553 | return p.text('dtype(...)') | |
576 | if hasattr(obj, 'fields'): |
|
554 | if hasattr(obj, 'fields'): | |
577 | if obj.fields is None: |
|
555 | if obj.fields is None: | |
578 | p.text(repr(obj)) |
|
556 | p.text(repr(obj)) | |
579 | else: |
|
557 | else: | |
580 | p.begin_group(7, 'dtype([') |
|
558 | p.begin_group(7, 'dtype([') | |
581 | for i, field in enumerate(obj.descr): |
|
559 | for i, field in enumerate(obj.descr): | |
582 | if i > 0: |
|
560 | if i > 0: | |
583 | p.text(',') |
|
561 | p.text(',') | |
584 | p.breakable() |
|
562 | p.breakable() | |
585 | p.pretty(field) |
|
563 | p.pretty(field) | |
586 | p.end_group(7, '])') |
|
564 | p.end_group(7, '])') | |
587 | """ |
|
565 | """ | |
588 |
|
566 | |||
589 | # The format type of data returned. |
|
567 | # The format type of data returned. | |
590 | format_type = Unicode('text/plain') |
|
568 | format_type = Unicode('text/plain') | |
591 |
|
569 | |||
592 | # This subclass ignores this attribute as it always need to return |
|
570 | # This subclass ignores this attribute as it always need to return | |
593 | # something. |
|
571 | # something. | |
594 | enabled = Bool(True, config=False) |
|
572 | enabled = Bool(True, config=False) | |
595 |
|
573 | |||
596 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True, |
|
574 | max_seq_length = Integer(pretty.MAX_SEQ_LENGTH, config=True, | |
597 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. |
|
575 | help="""Truncate large collections (lists, dicts, tuples, sets) to this size. | |
598 |
|
576 | |||
599 | Set to 0 to disable truncation. |
|
577 | Set to 0 to disable truncation. | |
600 | """ |
|
578 | """ | |
601 | ) |
|
579 | ) | |
602 |
|
580 | |||
603 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
581 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
604 | print_method = ObjectName('_repr_pretty_') |
|
582 | print_method = ObjectName('_repr_pretty_') | |
605 |
|
583 | |||
606 | # Whether to pretty-print or not. |
|
584 | # Whether to pretty-print or not. | |
607 | pprint = Bool(True, config=True) |
|
585 | pprint = Bool(True, config=True) | |
608 |
|
586 | |||
609 | # Whether to be verbose or not. |
|
587 | # Whether to be verbose or not. | |
610 | verbose = Bool(False, config=True) |
|
588 | verbose = Bool(False, config=True) | |
611 |
|
589 | |||
612 | # The maximum width. |
|
590 | # The maximum width. | |
613 | max_width = Integer(79, config=True) |
|
591 | max_width = Integer(79, config=True) | |
614 |
|
592 | |||
615 | # The newline character. |
|
593 | # The newline character. | |
616 | newline = Unicode('\n', config=True) |
|
594 | newline = Unicode('\n', config=True) | |
617 |
|
595 | |||
618 | # format-string for pprinting floats |
|
596 | # format-string for pprinting floats | |
619 | float_format = Unicode('%r') |
|
597 | float_format = Unicode('%r') | |
620 | # setter for float precision, either int or direct format-string |
|
598 | # setter for float precision, either int or direct format-string | |
621 | float_precision = CUnicode('', config=True) |
|
599 | float_precision = CUnicode('', config=True) | |
622 |
|
600 | |||
623 | def _float_precision_changed(self, name, old, new): |
|
601 | def _float_precision_changed(self, name, old, new): | |
624 | """float_precision changed, set float_format accordingly. |
|
602 | """float_precision changed, set float_format accordingly. | |
625 |
|
603 | |||
626 | float_precision can be set by int or str. |
|
604 | float_precision can be set by int or str. | |
627 | This will set float_format, after interpreting input. |
|
605 | This will set float_format, after interpreting input. | |
628 | If numpy has been imported, numpy print precision will also be set. |
|
606 | If numpy has been imported, numpy print precision will also be set. | |
629 |
|
607 | |||
630 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
608 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
631 |
|
609 | |||
632 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
610 | An empty string returns to defaults (repr for float, 8 for numpy). | |
633 |
|
611 | |||
634 | This parameter can be set via the '%precision' magic. |
|
612 | This parameter can be set via the '%precision' magic. | |
635 | """ |
|
613 | """ | |
636 |
|
614 | |||
637 | if '%' in new: |
|
615 | if '%' in new: | |
638 | # got explicit format string |
|
616 | # got explicit format string | |
639 | fmt = new |
|
617 | fmt = new | |
640 | try: |
|
618 | try: | |
641 | fmt%3.14159 |
|
619 | fmt%3.14159 | |
642 | except Exception: |
|
620 | except Exception: | |
643 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
621 | raise ValueError("Precision must be int or format string, not %r"%new) | |
644 | elif new: |
|
622 | elif new: | |
645 | # otherwise, should be an int |
|
623 | # otherwise, should be an int | |
646 | try: |
|
624 | try: | |
647 | i = int(new) |
|
625 | i = int(new) | |
648 | assert i >= 0 |
|
626 | assert i >= 0 | |
649 | except ValueError: |
|
627 | except ValueError: | |
650 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
628 | raise ValueError("Precision must be int or format string, not %r"%new) | |
651 | except AssertionError: |
|
629 | except AssertionError: | |
652 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
630 | raise ValueError("int precision must be non-negative, not %r"%i) | |
653 |
|
631 | |||
654 | fmt = '%%.%if'%i |
|
632 | fmt = '%%.%if'%i | |
655 | if 'numpy' in sys.modules: |
|
633 | if 'numpy' in sys.modules: | |
656 | # set numpy precision if it has been imported |
|
634 | # set numpy precision if it has been imported | |
657 | import numpy |
|
635 | import numpy | |
658 | numpy.set_printoptions(precision=i) |
|
636 | numpy.set_printoptions(precision=i) | |
659 | else: |
|
637 | else: | |
660 | # default back to repr |
|
638 | # default back to repr | |
661 | fmt = '%r' |
|
639 | fmt = '%r' | |
662 | if 'numpy' in sys.modules: |
|
640 | if 'numpy' in sys.modules: | |
663 | import numpy |
|
641 | import numpy | |
664 | # numpy default is 8 |
|
642 | # numpy default is 8 | |
665 | numpy.set_printoptions(precision=8) |
|
643 | numpy.set_printoptions(precision=8) | |
666 | self.float_format = fmt |
|
644 | self.float_format = fmt | |
667 |
|
645 | |||
668 | # Use the default pretty printers from IPython.lib.pretty. |
|
646 | # Use the default pretty printers from IPython.lib.pretty. | |
669 | def _singleton_printers_default(self): |
|
647 | def _singleton_printers_default(self): | |
670 | return pretty._singleton_pprinters.copy() |
|
648 | return pretty._singleton_pprinters.copy() | |
671 |
|
649 | |||
672 | def _type_printers_default(self): |
|
650 | def _type_printers_default(self): | |
673 | d = pretty._type_pprinters.copy() |
|
651 | d = pretty._type_pprinters.copy() | |
674 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
652 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
675 | return d |
|
653 | return d | |
676 |
|
654 | |||
677 | def _deferred_printers_default(self): |
|
655 | def _deferred_printers_default(self): | |
678 | return pretty._deferred_type_pprinters.copy() |
|
656 | return pretty._deferred_type_pprinters.copy() | |
679 |
|
657 | |||
680 | #### FormatterABC interface #### |
|
658 | #### FormatterABC interface #### | |
681 |
|
659 | |||
682 | @catch_format_error |
|
660 | @catch_format_error | |
683 | def __call__(self, obj): |
|
661 | def __call__(self, obj): | |
684 | """Compute the pretty representation of the object.""" |
|
662 | """Compute the pretty representation of the object.""" | |
685 | if not self.pprint: |
|
663 | if not self.pprint: | |
686 | return repr(obj) |
|
664 | return repr(obj) | |
687 | else: |
|
665 | else: | |
688 | # handle str and unicode on Python 2 |
|
666 | # handle str and unicode on Python 2 | |
689 | # io.StringIO only accepts unicode, |
|
667 | # io.StringIO only accepts unicode, | |
690 | # cStringIO doesn't handle unicode on py2, |
|
668 | # cStringIO doesn't handle unicode on py2, | |
691 | # StringIO allows str, unicode but only ascii str |
|
669 | # StringIO allows str, unicode but only ascii str | |
692 | stream = pretty.CUnicodeIO() |
|
670 | stream = pretty.CUnicodeIO() | |
693 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
671 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
694 | self.max_width, self.newline, |
|
672 | self.max_width, self.newline, | |
695 | max_seq_length=self.max_seq_length, |
|
673 | max_seq_length=self.max_seq_length, | |
696 | singleton_pprinters=self.singleton_printers, |
|
674 | singleton_pprinters=self.singleton_printers, | |
697 | type_pprinters=self.type_printers, |
|
675 | type_pprinters=self.type_printers, | |
698 | deferred_pprinters=self.deferred_printers) |
|
676 | deferred_pprinters=self.deferred_printers) | |
699 | printer.pretty(obj) |
|
677 | printer.pretty(obj) | |
700 | printer.flush() |
|
678 | printer.flush() | |
701 | return stream.getvalue() |
|
679 | return stream.getvalue() | |
702 |
|
680 | |||
703 |
|
681 | |||
704 | class HTMLFormatter(BaseFormatter): |
|
682 | class HTMLFormatter(BaseFormatter): | |
705 | """An HTML formatter. |
|
683 | """An HTML formatter. | |
706 |
|
684 | |||
707 | To define the callables that compute the HTML representation of your |
|
685 | To define the callables that compute the HTML representation of your | |
708 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
686 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
709 | or :meth:`for_type_by_name` methods to register functions that handle |
|
687 | or :meth:`for_type_by_name` methods to register functions that handle | |
710 | this. |
|
688 | this. | |
711 |
|
689 | |||
712 | The return value of this formatter should be a valid HTML snippet that |
|
690 | The return value of this formatter should be a valid HTML snippet that | |
713 | could be injected into an existing DOM. It should *not* include the |
|
691 | could be injected into an existing DOM. It should *not* include the | |
714 | ```<html>`` or ```<body>`` tags. |
|
692 | ```<html>`` or ```<body>`` tags. | |
715 | """ |
|
693 | """ | |
716 | format_type = Unicode('text/html') |
|
694 | format_type = Unicode('text/html') | |
717 |
|
695 | |||
718 | print_method = ObjectName('_repr_html_') |
|
696 | print_method = ObjectName('_repr_html_') | |
719 |
|
697 | |||
720 |
|
698 | |||
721 | class MarkdownFormatter(BaseFormatter): |
|
699 | class MarkdownFormatter(BaseFormatter): | |
722 | """A Markdown formatter. |
|
700 | """A Markdown formatter. | |
723 |
|
701 | |||
724 | To define the callables that compute the Markdown representation of your |
|
702 | To define the callables that compute the Markdown representation of your | |
725 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` |
|
703 | objects, define a :meth:`_repr_markdown_` method or use the :meth:`for_type` | |
726 | or :meth:`for_type_by_name` methods to register functions that handle |
|
704 | or :meth:`for_type_by_name` methods to register functions that handle | |
727 | this. |
|
705 | this. | |
728 |
|
706 | |||
729 | The return value of this formatter should be a valid Markdown. |
|
707 | The return value of this formatter should be a valid Markdown. | |
730 | """ |
|
708 | """ | |
731 | format_type = Unicode('text/markdown') |
|
709 | format_type = Unicode('text/markdown') | |
732 |
|
710 | |||
733 | print_method = ObjectName('_repr_markdown_') |
|
711 | print_method = ObjectName('_repr_markdown_') | |
734 |
|
712 | |||
735 | class SVGFormatter(BaseFormatter): |
|
713 | class SVGFormatter(BaseFormatter): | |
736 | """An SVG formatter. |
|
714 | """An SVG formatter. | |
737 |
|
715 | |||
738 | To define the callables that compute the SVG representation of your |
|
716 | To define the callables that compute the SVG representation of your | |
739 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
717 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
740 | or :meth:`for_type_by_name` methods to register functions that handle |
|
718 | or :meth:`for_type_by_name` methods to register functions that handle | |
741 | this. |
|
719 | this. | |
742 |
|
720 | |||
743 | The return value of this formatter should be valid SVG enclosed in |
|
721 | The return value of this formatter should be valid SVG enclosed in | |
744 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
722 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
745 | *not* include the ```<html>`` or ```<body>`` tags. |
|
723 | *not* include the ```<html>`` or ```<body>`` tags. | |
746 | """ |
|
724 | """ | |
747 | format_type = Unicode('image/svg+xml') |
|
725 | format_type = Unicode('image/svg+xml') | |
748 |
|
726 | |||
749 | print_method = ObjectName('_repr_svg_') |
|
727 | print_method = ObjectName('_repr_svg_') | |
750 |
|
728 | |||
751 |
|
729 | |||
752 | class PNGFormatter(BaseFormatter): |
|
730 | class PNGFormatter(BaseFormatter): | |
753 | """A PNG formatter. |
|
731 | """A PNG formatter. | |
754 |
|
732 | |||
755 | To define the callables that compute the PNG representation of your |
|
733 | To define the callables that compute the PNG representation of your | |
756 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
734 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
757 | or :meth:`for_type_by_name` methods to register functions that handle |
|
735 | or :meth:`for_type_by_name` methods to register functions that handle | |
758 | this. |
|
736 | this. | |
759 |
|
737 | |||
760 | The return value of this formatter should be raw PNG data, *not* |
|
738 | The return value of this formatter should be raw PNG data, *not* | |
761 | base64 encoded. |
|
739 | base64 encoded. | |
762 | """ |
|
740 | """ | |
763 | format_type = Unicode('image/png') |
|
741 | format_type = Unicode('image/png') | |
764 |
|
742 | |||
765 | print_method = ObjectName('_repr_png_') |
|
743 | print_method = ObjectName('_repr_png_') | |
766 |
|
744 | |||
767 | _return_type = (bytes, unicode_type) |
|
745 | _return_type = (bytes, unicode_type) | |
768 |
|
746 | |||
769 |
|
747 | |||
770 | class JPEGFormatter(BaseFormatter): |
|
748 | class JPEGFormatter(BaseFormatter): | |
771 | """A JPEG formatter. |
|
749 | """A JPEG formatter. | |
772 |
|
750 | |||
773 | To define the callables that compute the JPEG representation of your |
|
751 | To define the callables that compute the JPEG representation of your | |
774 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
752 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |
775 | or :meth:`for_type_by_name` methods to register functions that handle |
|
753 | or :meth:`for_type_by_name` methods to register functions that handle | |
776 | this. |
|
754 | this. | |
777 |
|
755 | |||
778 | The return value of this formatter should be raw JPEG data, *not* |
|
756 | The return value of this formatter should be raw JPEG data, *not* | |
779 | base64 encoded. |
|
757 | base64 encoded. | |
780 | """ |
|
758 | """ | |
781 | format_type = Unicode('image/jpeg') |
|
759 | format_type = Unicode('image/jpeg') | |
782 |
|
760 | |||
783 | print_method = ObjectName('_repr_jpeg_') |
|
761 | print_method = ObjectName('_repr_jpeg_') | |
784 |
|
762 | |||
785 | _return_type = (bytes, unicode_type) |
|
763 | _return_type = (bytes, unicode_type) | |
786 |
|
764 | |||
787 |
|
765 | |||
788 | class LatexFormatter(BaseFormatter): |
|
766 | class LatexFormatter(BaseFormatter): | |
789 | """A LaTeX formatter. |
|
767 | """A LaTeX formatter. | |
790 |
|
768 | |||
791 | To define the callables that compute the LaTeX representation of your |
|
769 | To define the callables that compute the LaTeX representation of your | |
792 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
770 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
793 | or :meth:`for_type_by_name` methods to register functions that handle |
|
771 | or :meth:`for_type_by_name` methods to register functions that handle | |
794 | this. |
|
772 | this. | |
795 |
|
773 | |||
796 | The return value of this formatter should be a valid LaTeX equation, |
|
774 | The return value of this formatter should be a valid LaTeX equation, | |
797 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
775 | enclosed in either ```$```, ```$$``` or another LaTeX equation | |
798 | environment. |
|
776 | environment. | |
799 | """ |
|
777 | """ | |
800 | format_type = Unicode('text/latex') |
|
778 | format_type = Unicode('text/latex') | |
801 |
|
779 | |||
802 | print_method = ObjectName('_repr_latex_') |
|
780 | print_method = ObjectName('_repr_latex_') | |
803 |
|
781 | |||
804 |
|
782 | |||
805 | class JSONFormatter(BaseFormatter): |
|
783 | class JSONFormatter(BaseFormatter): | |
806 | """A JSON string formatter. |
|
784 | """A JSON string formatter. | |
807 |
|
785 | |||
808 | To define the callables that compute the JSONable representation of |
|
786 | To define the callables that compute the JSONable representation of | |
809 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
787 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
810 | or :meth:`for_type_by_name` methods to register functions that handle |
|
788 | or :meth:`for_type_by_name` methods to register functions that handle | |
811 | this. |
|
789 | this. | |
812 |
|
790 | |||
813 | The return value of this formatter should be a JSONable list or dict. |
|
791 | The return value of this formatter should be a JSONable list or dict. | |
814 | JSON scalars (None, number, string) are not allowed, only dict or list containers. |
|
792 | JSON scalars (None, number, string) are not allowed, only dict or list containers. | |
815 | """ |
|
793 | """ | |
816 | format_type = Unicode('application/json') |
|
794 | format_type = Unicode('application/json') | |
817 | _return_type = (list, dict) |
|
795 | _return_type = (list, dict) | |
818 |
|
796 | |||
819 | print_method = ObjectName('_repr_json_') |
|
797 | print_method = ObjectName('_repr_json_') | |
820 |
|
798 | |||
821 | def _check_return(self, r, obj): |
|
799 | def _check_return(self, r, obj): | |
822 | """Check that a return value is appropriate |
|
800 | """Check that a return value is appropriate | |
823 |
|
801 | |||
824 | Return the value if so, None otherwise, warning if invalid. |
|
802 | Return the value if so, None otherwise, warning if invalid. | |
825 | """ |
|
803 | """ | |
826 | if r is None: |
|
804 | if r is None: | |
827 | return |
|
805 | return | |
828 | md = None |
|
806 | md = None | |
829 | if isinstance(r, tuple): |
|
807 | if isinstance(r, tuple): | |
830 | # unpack data, metadata tuple for type checking on first element |
|
808 | # unpack data, metadata tuple for type checking on first element | |
831 | r, md = r |
|
809 | r, md = r | |
832 |
|
810 | |||
833 | # handle deprecated JSON-as-string form from IPython < 3 |
|
811 | # handle deprecated JSON-as-string form from IPython < 3 | |
834 | if isinstance(r, string_types): |
|
812 | if isinstance(r, string_types): | |
835 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", |
|
813 | warnings.warn("JSON expects JSONable list/dict containers, not JSON strings", | |
836 | FormatterWarning) |
|
814 | FormatterWarning) | |
837 | r = json.loads(r) |
|
815 | r = json.loads(r) | |
838 |
|
816 | |||
839 | if md is not None: |
|
817 | if md is not None: | |
840 | # put the tuple back together |
|
818 | # put the tuple back together | |
841 | r = (r, md) |
|
819 | r = (r, md) | |
842 | return super(JSONFormatter, self)._check_return(r, obj) |
|
820 | return super(JSONFormatter, self)._check_return(r, obj) | |
843 |
|
821 | |||
844 |
|
822 | |||
845 | class JavascriptFormatter(BaseFormatter): |
|
823 | class JavascriptFormatter(BaseFormatter): | |
846 | """A Javascript formatter. |
|
824 | """A Javascript formatter. | |
847 |
|
825 | |||
848 | To define the callables that compute the Javascript representation of |
|
826 | To define the callables that compute the Javascript representation of | |
849 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
827 | your objects, define a :meth:`_repr_javascript_` method or use the | |
850 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
828 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
851 | that handle this. |
|
829 | that handle this. | |
852 |
|
830 | |||
853 | The return value of this formatter should be valid Javascript code and |
|
831 | The return value of this formatter should be valid Javascript code and | |
854 | should *not* be enclosed in ```<script>``` tags. |
|
832 | should *not* be enclosed in ```<script>``` tags. | |
855 | """ |
|
833 | """ | |
856 | format_type = Unicode('application/javascript') |
|
834 | format_type = Unicode('application/javascript') | |
857 |
|
835 | |||
858 | print_method = ObjectName('_repr_javascript_') |
|
836 | print_method = ObjectName('_repr_javascript_') | |
859 |
|
837 | |||
860 |
|
838 | |||
861 | class PDFFormatter(BaseFormatter): |
|
839 | class PDFFormatter(BaseFormatter): | |
862 | """A PDF formatter. |
|
840 | """A PDF formatter. | |
863 |
|
841 | |||
864 | To define the callables that compute the PDF representation of your |
|
842 | To define the callables that compute the PDF representation of your | |
865 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` |
|
843 | objects, define a :meth:`_repr_pdf_` method or use the :meth:`for_type` | |
866 | or :meth:`for_type_by_name` methods to register functions that handle |
|
844 | or :meth:`for_type_by_name` methods to register functions that handle | |
867 | this. |
|
845 | this. | |
868 |
|
846 | |||
869 | The return value of this formatter should be raw PDF data, *not* |
|
847 | The return value of this formatter should be raw PDF data, *not* | |
870 | base64 encoded. |
|
848 | base64 encoded. | |
871 | """ |
|
849 | """ | |
872 | format_type = Unicode('application/pdf') |
|
850 | format_type = Unicode('application/pdf') | |
873 |
|
851 | |||
874 | print_method = ObjectName('_repr_pdf_') |
|
852 | print_method = ObjectName('_repr_pdf_') | |
875 |
|
853 | |||
876 | _return_type = (bytes, unicode_type) |
|
854 | _return_type = (bytes, unicode_type) | |
877 |
|
855 | |||
878 | class IPythonDisplayFormatter(BaseFormatter): |
|
856 | class IPythonDisplayFormatter(BaseFormatter): | |
879 | """A Formatter for objects that know how to display themselves. |
|
857 | """A Formatter for objects that know how to display themselves. | |
880 |
|
858 | |||
881 | To define the callables that compute the representation of your |
|
859 | To define the callables that compute the representation of your | |
882 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` |
|
860 | objects, define a :meth:`_ipython_display_` method or use the :meth:`for_type` | |
883 | or :meth:`for_type_by_name` methods to register functions that handle |
|
861 | or :meth:`for_type_by_name` methods to register functions that handle | |
884 | this. Unlike mime-type displays, this method should not return anything, |
|
862 | this. Unlike mime-type displays, this method should not return anything, | |
885 | instead calling any appropriate display methods itself. |
|
863 | instead calling any appropriate display methods itself. | |
886 |
|
864 | |||
887 | This display formatter has highest priority. |
|
865 | This display formatter has highest priority. | |
888 | If it fires, no other display formatter will be called. |
|
866 | If it fires, no other display formatter will be called. | |
889 | """ |
|
867 | """ | |
890 | print_method = ObjectName('_ipython_display_') |
|
868 | print_method = ObjectName('_ipython_display_') | |
891 | _return_type = (type(None), bool) |
|
869 | _return_type = (type(None), bool) | |
892 |
|
870 | |||
893 |
|
871 | |||
894 | @catch_format_error |
|
872 | @catch_format_error | |
895 | def __call__(self, obj): |
|
873 | def __call__(self, obj): | |
896 | """Compute the format for an object.""" |
|
874 | """Compute the format for an object.""" | |
897 | if self.enabled: |
|
875 | if self.enabled: | |
898 | # lookup registered printer |
|
876 | # lookup registered printer | |
899 | try: |
|
877 | try: | |
900 | printer = self.lookup(obj) |
|
878 | printer = self.lookup(obj) | |
901 | except KeyError: |
|
879 | except KeyError: | |
902 | pass |
|
880 | pass | |
903 | else: |
|
881 | else: | |
904 | printer(obj) |
|
882 | printer(obj) | |
905 | return True |
|
883 | return True | |
906 | # Finally look for special method names |
|
884 | # Finally look for special method names | |
907 |
method = |
|
885 | method = get_real_method(obj, self.print_method) | |
908 | if method is not None: |
|
886 | if method is not None: | |
909 | method() |
|
887 | method() | |
910 | return True |
|
888 | return True | |
911 |
|
889 | |||
912 |
|
890 | |||
913 | FormatterABC.register(BaseFormatter) |
|
891 | FormatterABC.register(BaseFormatter) | |
914 | FormatterABC.register(PlainTextFormatter) |
|
892 | FormatterABC.register(PlainTextFormatter) | |
915 | FormatterABC.register(HTMLFormatter) |
|
893 | FormatterABC.register(HTMLFormatter) | |
916 | FormatterABC.register(MarkdownFormatter) |
|
894 | FormatterABC.register(MarkdownFormatter) | |
917 | FormatterABC.register(SVGFormatter) |
|
895 | FormatterABC.register(SVGFormatter) | |
918 | FormatterABC.register(PNGFormatter) |
|
896 | FormatterABC.register(PNGFormatter) | |
919 | FormatterABC.register(PDFFormatter) |
|
897 | FormatterABC.register(PDFFormatter) | |
920 | FormatterABC.register(JPEGFormatter) |
|
898 | FormatterABC.register(JPEGFormatter) | |
921 | FormatterABC.register(LatexFormatter) |
|
899 | FormatterABC.register(LatexFormatter) | |
922 | FormatterABC.register(JSONFormatter) |
|
900 | FormatterABC.register(JSONFormatter) | |
923 | FormatterABC.register(JavascriptFormatter) |
|
901 | FormatterABC.register(JavascriptFormatter) | |
924 | FormatterABC.register(IPythonDisplayFormatter) |
|
902 | FormatterABC.register(IPythonDisplayFormatter) | |
925 |
|
903 | |||
926 |
|
904 | |||
927 | def format_display_data(obj, include=None, exclude=None): |
|
905 | def format_display_data(obj, include=None, exclude=None): | |
928 | """Return a format data dict for an object. |
|
906 | """Return a format data dict for an object. | |
929 |
|
907 | |||
930 | By default all format types will be computed. |
|
908 | By default all format types will be computed. | |
931 |
|
909 | |||
932 | The following MIME types are currently implemented: |
|
910 | The following MIME types are currently implemented: | |
933 |
|
911 | |||
934 | * text/plain |
|
912 | * text/plain | |
935 | * text/html |
|
913 | * text/html | |
936 | * text/markdown |
|
914 | * text/markdown | |
937 | * text/latex |
|
915 | * text/latex | |
938 | * application/json |
|
916 | * application/json | |
939 | * application/javascript |
|
917 | * application/javascript | |
940 | * application/pdf |
|
918 | * application/pdf | |
941 | * image/png |
|
919 | * image/png | |
942 | * image/jpeg |
|
920 | * image/jpeg | |
943 | * image/svg+xml |
|
921 | * image/svg+xml | |
944 |
|
922 | |||
945 | Parameters |
|
923 | Parameters | |
946 | ---------- |
|
924 | ---------- | |
947 | obj : object |
|
925 | obj : object | |
948 | The Python object whose format data will be computed. |
|
926 | The Python object whose format data will be computed. | |
949 |
|
927 | |||
950 | Returns |
|
928 | Returns | |
951 | ------- |
|
929 | ------- | |
952 | format_dict : dict |
|
930 | format_dict : dict | |
953 | A dictionary of key/value pairs, one or each format that was |
|
931 | A dictionary of key/value pairs, one or each format that was | |
954 | generated for the object. The keys are the format types, which |
|
932 | generated for the object. The keys are the format types, which | |
955 | will usually be MIME type strings and the values and JSON'able |
|
933 | will usually be MIME type strings and the values and JSON'able | |
956 | data structure containing the raw data for the representation in |
|
934 | data structure containing the raw data for the representation in | |
957 | that format. |
|
935 | that format. | |
958 | include : list or tuple, optional |
|
936 | include : list or tuple, optional | |
959 | A list of format type strings (MIME types) to include in the |
|
937 | A list of format type strings (MIME types) to include in the | |
960 | format data dict. If this is set *only* the format types included |
|
938 | format data dict. If this is set *only* the format types included | |
961 | in this list will be computed. |
|
939 | in this list will be computed. | |
962 | exclude : list or tuple, optional |
|
940 | exclude : list or tuple, optional | |
963 | A list of format type string (MIME types) to exclue in the format |
|
941 | A list of format type string (MIME types) to exclue in the format | |
964 | data dict. If this is set all format types will be computed, |
|
942 | data dict. If this is set all format types will be computed, | |
965 | except for those included in this argument. |
|
943 | except for those included in this argument. | |
966 | """ |
|
944 | """ | |
967 | from IPython.core.interactiveshell import InteractiveShell |
|
945 | from IPython.core.interactiveshell import InteractiveShell | |
968 |
|
946 | |||
969 | InteractiveShell.instance().display_formatter.format( |
|
947 | InteractiveShell.instance().display_formatter.format( | |
970 | obj, |
|
948 | obj, | |
971 | include, |
|
949 | include, | |
972 | exclude |
|
950 | exclude | |
973 | ) |
|
951 | ) | |
974 |
|
952 |
@@ -1,58 +1,81 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """A fancy version of Python's builtin :func:`dir` function. |
|
2 | """A fancy version of Python's builtin :func:`dir` function. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | # Copyright (c) IPython Development Team. | |
6 | # Copyright (C) 2008-2011 The IPython Development Team |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
|||
8 | # Distributed under the terms of the BSD License. The full license is in |
|
|||
9 | # the file COPYING, distributed as part of this software. |
|
|||
10 | #----------------------------------------------------------------------------- |
|
|||
11 |
|
||||
12 | #----------------------------------------------------------------------------- |
|
|||
13 | # Imports |
|
|||
14 | #----------------------------------------------------------------------------- |
|
|||
15 | from .py3compat import string_types |
|
|||
16 |
|
7 | |||
17 | #----------------------------------------------------------------------------- |
|
8 | import inspect | |
18 | # Code |
|
9 | from .py3compat import string_types | |
19 | #----------------------------------------------------------------------------- |
|
|||
20 |
|
10 | |||
21 |
|
11 | |||
22 | def safe_hasattr(obj, attr): |
|
12 | def safe_hasattr(obj, attr): | |
23 | """In recent versions of Python, hasattr() only catches AttributeError. |
|
13 | """In recent versions of Python, hasattr() only catches AttributeError. | |
24 | This catches all errors. |
|
14 | This catches all errors. | |
25 | """ |
|
15 | """ | |
26 | try: |
|
16 | try: | |
27 | getattr(obj, attr) |
|
17 | getattr(obj, attr) | |
28 | return True |
|
18 | return True | |
29 | except: |
|
19 | except: | |
30 | return False |
|
20 | return False | |
31 |
|
21 | |||
32 |
|
22 | |||
33 | def dir2(obj): |
|
23 | def dir2(obj): | |
34 | """dir2(obj) -> list of strings |
|
24 | """dir2(obj) -> list of strings | |
35 |
|
25 | |||
36 | Extended version of the Python builtin dir(), which does a few extra |
|
26 | Extended version of the Python builtin dir(), which does a few extra | |
37 | checks. |
|
27 | checks. | |
38 |
|
28 | |||
39 | This version is guaranteed to return only a list of true strings, whereas |
|
29 | This version is guaranteed to return only a list of true strings, whereas | |
40 | dir() returns anything that objects inject into themselves, even if they |
|
30 | dir() returns anything that objects inject into themselves, even if they | |
41 | are later not really valid for attribute access (many extension libraries |
|
31 | are later not really valid for attribute access (many extension libraries | |
42 | have such bugs). |
|
32 | have such bugs). | |
43 | """ |
|
33 | """ | |
44 |
|
34 | |||
45 | # Start building the attribute list via dir(), and then complete it |
|
35 | # Start building the attribute list via dir(), and then complete it | |
46 | # with a few extra special-purpose calls. |
|
36 | # with a few extra special-purpose calls. | |
47 |
|
37 | |||
48 | try: |
|
38 | try: | |
49 | words = set(dir(obj)) |
|
39 | words = set(dir(obj)) | |
50 | except Exception: |
|
40 | except Exception: | |
51 | # TypeError: dir(obj) does not return a list |
|
41 | # TypeError: dir(obj) does not return a list | |
52 | words = set() |
|
42 | words = set() | |
53 |
|
43 | |||
54 | # filter out non-string attributes which may be stuffed by dir() calls |
|
44 | # filter out non-string attributes which may be stuffed by dir() calls | |
55 | # and poor coding in third-party modules |
|
45 | # and poor coding in third-party modules | |
56 |
|
46 | |||
57 | words = [w for w in words if isinstance(w, string_types)] |
|
47 | words = [w for w in words if isinstance(w, string_types)] | |
58 | return sorted(words) |
|
48 | return sorted(words) | |
|
49 | ||||
|
50 | ||||
|
51 | def get_real_method(obj, name): | |||
|
52 | """Like getattr, but with a few extra sanity checks: | |||
|
53 | ||||
|
54 | - If obj is a class, ignore its methods | |||
|
55 | - Check if obj is a proxy that claims to have all attributes | |||
|
56 | - Catch attribute access failing with any exception | |||
|
57 | - Check that the attribute is a callable object | |||
|
58 | ||||
|
59 | Returns the method or None. | |||
|
60 | """ | |||
|
61 | if inspect.isclass(obj): | |||
|
62 | return None | |||
|
63 | ||||
|
64 | try: | |||
|
65 | canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None) | |||
|
66 | except Exception: | |||
|
67 | return None | |||
|
68 | ||||
|
69 | if canary is not None: | |||
|
70 | # It claimed to have an attribute it should never have | |||
|
71 | return None | |||
|
72 | ||||
|
73 | try: | |||
|
74 | m = getattr(obj, name, None) | |||
|
75 | except Exception: | |||
|
76 | return None | |||
|
77 | ||||
|
78 | if callable(m): | |||
|
79 | return m | |||
|
80 | ||||
|
81 | return None |
General Comments 0
You need to be logged in to leave comments.
Login now