Show More
@@ -1,655 +1,654 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 | Authors: |
|
9 | Authors: | |
10 |
|
10 | |||
11 | * Robert Kern |
|
11 | * Robert Kern | |
12 | * Brian Granger |
|
12 | * Brian Granger | |
13 | """ |
|
13 | """ | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Copyright (C) 2010-2011, IPython Development Team. |
|
15 | # Copyright (C) 2010-2011, IPython Development Team. | |
16 | # |
|
16 | # | |
17 | # Distributed under the terms of the Modified BSD License. |
|
17 | # Distributed under the terms of the Modified BSD License. | |
18 | # |
|
18 | # | |
19 | # The full license is in the file COPYING.txt, distributed with this software. |
|
19 | # The full license is in the file COPYING.txt, distributed with this software. | |
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 |
|
21 | |||
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | # Imports |
|
23 | # Imports | |
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 |
|
25 | |||
26 | # Stdlib imports |
|
26 | # Stdlib imports | |
27 | import abc |
|
27 | import abc | |
28 | import sys |
|
28 | import sys | |
29 | import warnings |
|
29 | import warnings | |
30 | # We must use StringIO, as cStringIO doesn't handle unicode properly. |
|
30 | # We must use StringIO, as cStringIO doesn't handle unicode properly. | |
31 | from io import StringIO |
|
31 | from io import StringIO | |
32 |
|
32 | |||
33 | # Our own imports |
|
33 | # Our own imports | |
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.lib import pretty |
|
35 | from IPython.lib import pretty | |
36 | from IPython.utils.traitlets import ( |
|
36 | from IPython.utils.traitlets import ( | |
37 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, |
|
37 | Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List, | |
38 | ) |
|
38 | ) | |
39 | from IPython.utils.py3compat import unicode_to_str |
|
39 | from IPython.utils.py3compat import unicode_to_str, with_metaclass | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 | # The main DisplayFormatter class |
|
43 | # The main DisplayFormatter class | |
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 |
|
45 | |||
46 |
|
46 | |||
47 | class DisplayFormatter(Configurable): |
|
47 | class DisplayFormatter(Configurable): | |
48 |
|
48 | |||
49 | # When set to true only the default plain text formatter will be used. |
|
49 | # When set to true only the default plain text formatter will be used. | |
50 | plain_text_only = Bool(False, config=True) |
|
50 | plain_text_only = Bool(False, config=True) | |
51 | def _plain_text_only_changed(self, name, old, new): |
|
51 | def _plain_text_only_changed(self, name, old, new): | |
52 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. |
|
52 | warnings.warn("""DisplayFormatter.plain_text_only is deprecated. | |
53 |
|
53 | |||
54 | Use DisplayFormatter.active_types = ['text/plain'] |
|
54 | Use DisplayFormatter.active_types = ['text/plain'] | |
55 | for the same effect. |
|
55 | for the same effect. | |
56 | """, DeprecationWarning) |
|
56 | """, DeprecationWarning) | |
57 | if new: |
|
57 | if new: | |
58 | self.active_types = ['text/plain'] |
|
58 | self.active_types = ['text/plain'] | |
59 | else: |
|
59 | else: | |
60 | self.active_types = self.format_types |
|
60 | self.active_types = self.format_types | |
61 |
|
61 | |||
62 | active_types = List(Unicode, config=True, |
|
62 | active_types = List(Unicode, config=True, | |
63 | help="""List of currently active mime-types to display. |
|
63 | help="""List of currently active mime-types to display. | |
64 | You can use this to set a white-list for formats to display. |
|
64 | You can use this to set a white-list for formats to display. | |
65 |
|
65 | |||
66 | Most users will not need to change this value. |
|
66 | Most users will not need to change this value. | |
67 | """) |
|
67 | """) | |
68 | def _active_types_default(self): |
|
68 | def _active_types_default(self): | |
69 | return self.format_types |
|
69 | return self.format_types | |
70 |
|
70 | |||
71 | def _active_types_changed(self, name, old, new): |
|
71 | def _active_types_changed(self, name, old, new): | |
72 | for key, formatter in self.formatters.items(): |
|
72 | for key, formatter in self.formatters.items(): | |
73 | if key in new: |
|
73 | if key in new: | |
74 | formatter.enabled = True |
|
74 | formatter.enabled = True | |
75 | else: |
|
75 | else: | |
76 | formatter.enabled = False |
|
76 | formatter.enabled = False | |
77 |
|
77 | |||
78 | # A dict of formatter whose keys are format types (MIME types) and whose |
|
78 | # A dict of formatter whose keys are format types (MIME types) and whose | |
79 | # values are subclasses of BaseFormatter. |
|
79 | # values are subclasses of BaseFormatter. | |
80 | formatters = Dict() |
|
80 | formatters = Dict() | |
81 | def _formatters_default(self): |
|
81 | def _formatters_default(self): | |
82 | """Activate the default formatters.""" |
|
82 | """Activate the default formatters.""" | |
83 | formatter_classes = [ |
|
83 | formatter_classes = [ | |
84 | PlainTextFormatter, |
|
84 | PlainTextFormatter, | |
85 | HTMLFormatter, |
|
85 | HTMLFormatter, | |
86 | SVGFormatter, |
|
86 | SVGFormatter, | |
87 | PNGFormatter, |
|
87 | PNGFormatter, | |
88 | JPEGFormatter, |
|
88 | JPEGFormatter, | |
89 | LatexFormatter, |
|
89 | LatexFormatter, | |
90 | JSONFormatter, |
|
90 | JSONFormatter, | |
91 | JavascriptFormatter |
|
91 | JavascriptFormatter | |
92 | ] |
|
92 | ] | |
93 | d = {} |
|
93 | d = {} | |
94 | for cls in formatter_classes: |
|
94 | for cls in formatter_classes: | |
95 | f = cls(parent=self) |
|
95 | f = cls(parent=self) | |
96 | d[f.format_type] = f |
|
96 | d[f.format_type] = f | |
97 | return d |
|
97 | return d | |
98 |
|
98 | |||
99 | def format(self, obj, include=None, exclude=None): |
|
99 | def format(self, obj, include=None, exclude=None): | |
100 | """Return a format data dict for an object. |
|
100 | """Return a format data dict for an object. | |
101 |
|
101 | |||
102 | By default all format types will be computed. |
|
102 | By default all format types will be computed. | |
103 |
|
103 | |||
104 | The following MIME types are currently implemented: |
|
104 | The following MIME types are currently implemented: | |
105 |
|
105 | |||
106 | * text/plain |
|
106 | * text/plain | |
107 | * text/html |
|
107 | * text/html | |
108 | * text/latex |
|
108 | * text/latex | |
109 | * application/json |
|
109 | * application/json | |
110 | * application/javascript |
|
110 | * application/javascript | |
111 | * image/png |
|
111 | * image/png | |
112 | * image/jpeg |
|
112 | * image/jpeg | |
113 | * image/svg+xml |
|
113 | * image/svg+xml | |
114 |
|
114 | |||
115 | Parameters |
|
115 | Parameters | |
116 | ---------- |
|
116 | ---------- | |
117 | obj : object |
|
117 | obj : object | |
118 | The Python object whose format data will be computed. |
|
118 | The Python object whose format data will be computed. | |
119 | include : list or tuple, optional |
|
119 | include : list or tuple, optional | |
120 | A list of format type strings (MIME types) to include in the |
|
120 | A list of format type strings (MIME types) to include in the | |
121 | format data dict. If this is set *only* the format types included |
|
121 | format data dict. If this is set *only* the format types included | |
122 | in this list will be computed. |
|
122 | in this list will be computed. | |
123 | exclude : list or tuple, optional |
|
123 | exclude : list or tuple, optional | |
124 | A list of format type string (MIME types) to exclude in the format |
|
124 | A list of format type string (MIME types) to exclude in the format | |
125 | data dict. If this is set all format types will be computed, |
|
125 | data dict. If this is set all format types will be computed, | |
126 | except for those included in this argument. |
|
126 | except for those included in this argument. | |
127 |
|
127 | |||
128 | Returns |
|
128 | Returns | |
129 | ------- |
|
129 | ------- | |
130 | (format_dict, metadata_dict) : tuple of two dicts |
|
130 | (format_dict, metadata_dict) : tuple of two dicts | |
131 |
|
131 | |||
132 | format_dict is a dictionary of key/value pairs, one of each format that was |
|
132 | format_dict is a dictionary of key/value pairs, one of each format that was | |
133 | generated for the object. The keys are the format types, which |
|
133 | generated for the object. The keys are the format types, which | |
134 | will usually be MIME type strings and the values and JSON'able |
|
134 | will usually be MIME type strings and the values and JSON'able | |
135 | data structure containing the raw data for the representation in |
|
135 | data structure containing the raw data for the representation in | |
136 | that format. |
|
136 | that format. | |
137 |
|
137 | |||
138 | metadata_dict is a dictionary of metadata about each mime-type output. |
|
138 | metadata_dict is a dictionary of metadata about each mime-type output. | |
139 | Its keys will be a strict subset of the keys in format_dict. |
|
139 | Its keys will be a strict subset of the keys in format_dict. | |
140 | """ |
|
140 | """ | |
141 | format_dict = {} |
|
141 | format_dict = {} | |
142 | md_dict = {} |
|
142 | md_dict = {} | |
143 |
|
143 | |||
144 | for format_type, formatter in self.formatters.items(): |
|
144 | for format_type, formatter in self.formatters.items(): | |
145 | if include and format_type not in include: |
|
145 | if include and format_type not in include: | |
146 | continue |
|
146 | continue | |
147 | if exclude and format_type in exclude: |
|
147 | if exclude and format_type in exclude: | |
148 | continue |
|
148 | continue | |
149 |
|
149 | |||
150 | md = None |
|
150 | md = None | |
151 | try: |
|
151 | try: | |
152 | data = formatter(obj) |
|
152 | data = formatter(obj) | |
153 | except: |
|
153 | except: | |
154 | # FIXME: log the exception |
|
154 | # FIXME: log the exception | |
155 | raise |
|
155 | raise | |
156 |
|
156 | |||
157 | # formatters can return raw data or (data, metadata) |
|
157 | # formatters can return raw data or (data, metadata) | |
158 | if isinstance(data, tuple) and len(data) == 2: |
|
158 | if isinstance(data, tuple) and len(data) == 2: | |
159 | data, md = data |
|
159 | data, md = data | |
160 |
|
160 | |||
161 | if data is not None: |
|
161 | if data is not None: | |
162 | format_dict[format_type] = data |
|
162 | format_dict[format_type] = data | |
163 | if md is not None: |
|
163 | if md is not None: | |
164 | md_dict[format_type] = md |
|
164 | md_dict[format_type] = md | |
165 |
|
165 | |||
166 | return format_dict, md_dict |
|
166 | return format_dict, md_dict | |
167 |
|
167 | |||
168 | @property |
|
168 | @property | |
169 | def format_types(self): |
|
169 | def format_types(self): | |
170 | """Return the format types (MIME types) of the active formatters.""" |
|
170 | """Return the format types (MIME types) of the active formatters.""" | |
171 | return self.formatters.keys() |
|
171 | return self.formatters.keys() | |
172 |
|
172 | |||
173 |
|
173 | |||
174 | #----------------------------------------------------------------------------- |
|
174 | #----------------------------------------------------------------------------- | |
175 | # Formatters for specific format types (text, html, svg, etc.) |
|
175 | # Formatters for specific format types (text, html, svg, etc.) | |
176 | #----------------------------------------------------------------------------- |
|
176 | #----------------------------------------------------------------------------- | |
177 |
|
177 | |||
178 |
|
178 | |||
179 | class FormatterABC(object): |
|
179 | class FormatterABC(with_metaclass(abc.ABCMeta, object)): | |
180 | """ Abstract base class for Formatters. |
|
180 | """ Abstract base class for Formatters. | |
181 |
|
181 | |||
182 | A formatter is a callable class that is responsible for computing the |
|
182 | A formatter is a callable class that is responsible for computing the | |
183 | raw format data for a particular format type (MIME type). For example, |
|
183 | raw format data for a particular format type (MIME type). For example, | |
184 | an HTML formatter would have a format type of `text/html` and would return |
|
184 | an HTML formatter would have a format type of `text/html` and would return | |
185 | the HTML representation of the object when called. |
|
185 | the HTML representation of the object when called. | |
186 | """ |
|
186 | """ | |
187 | __metaclass__ = abc.ABCMeta |
|
|||
188 |
|
187 | |||
189 | # The format type of the data returned, usually a MIME type. |
|
188 | # The format type of the data returned, usually a MIME type. | |
190 | format_type = 'text/plain' |
|
189 | format_type = 'text/plain' | |
191 |
|
190 | |||
192 | # Is the formatter enabled... |
|
191 | # Is the formatter enabled... | |
193 | enabled = True |
|
192 | enabled = True | |
194 |
|
193 | |||
195 | @abc.abstractmethod |
|
194 | @abc.abstractmethod | |
196 | def __call__(self, obj): |
|
195 | def __call__(self, obj): | |
197 | """Return a JSON'able representation of the object. |
|
196 | """Return a JSON'able representation of the object. | |
198 |
|
197 | |||
199 | If the object cannot be formatted by this formatter, then return None |
|
198 | If the object cannot be formatted by this formatter, then return None | |
200 | """ |
|
199 | """ | |
201 | try: |
|
200 | try: | |
202 | return repr(obj) |
|
201 | return repr(obj) | |
203 | except TypeError: |
|
202 | except TypeError: | |
204 | return None |
|
203 | return None | |
205 |
|
204 | |||
206 |
|
205 | |||
207 | class BaseFormatter(Configurable): |
|
206 | class BaseFormatter(Configurable): | |
208 | """A base formatter class that is configurable. |
|
207 | """A base formatter class that is configurable. | |
209 |
|
208 | |||
210 | This formatter should usually be used as the base class of all formatters. |
|
209 | This formatter should usually be used as the base class of all formatters. | |
211 | It is a traited :class:`Configurable` class and includes an extensible |
|
210 | It is a traited :class:`Configurable` class and includes an extensible | |
212 | API for users to determine how their objects are formatted. The following |
|
211 | API for users to determine how their objects are formatted. The following | |
213 | logic is used to find a function to format an given object. |
|
212 | logic is used to find a function to format an given object. | |
214 |
|
213 | |||
215 | 1. The object is introspected to see if it has a method with the name |
|
214 | 1. The object is introspected to see if it has a method with the name | |
216 | :attr:`print_method`. If is does, that object is passed to that method |
|
215 | :attr:`print_method`. If is does, that object is passed to that method | |
217 | for formatting. |
|
216 | for formatting. | |
218 | 2. If no print method is found, three internal dictionaries are consulted |
|
217 | 2. If no print method is found, three internal dictionaries are consulted | |
219 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` |
|
218 | to find print method: :attr:`singleton_printers`, :attr:`type_printers` | |
220 | and :attr:`deferred_printers`. |
|
219 | and :attr:`deferred_printers`. | |
221 |
|
220 | |||
222 | Users should use these dictionaries to register functions that will be |
|
221 | Users should use these dictionaries to register functions that will be | |
223 | used to compute the format data for their objects (if those objects don't |
|
222 | used to compute the format data for their objects (if those objects don't | |
224 | have the special print methods). The easiest way of using these |
|
223 | have the special print methods). The easiest way of using these | |
225 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` |
|
224 | dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name` | |
226 | methods. |
|
225 | methods. | |
227 |
|
226 | |||
228 | If no function/callable is found to compute the format data, ``None`` is |
|
227 | If no function/callable is found to compute the format data, ``None`` is | |
229 | returned and this format type is not used. |
|
228 | returned and this format type is not used. | |
230 | """ |
|
229 | """ | |
231 |
|
230 | |||
232 | format_type = Unicode('text/plain') |
|
231 | format_type = Unicode('text/plain') | |
233 |
|
232 | |||
234 | enabled = Bool(True, config=True) |
|
233 | enabled = Bool(True, config=True) | |
235 |
|
234 | |||
236 | print_method = ObjectName('__repr__') |
|
235 | print_method = ObjectName('__repr__') | |
237 |
|
236 | |||
238 | # The singleton printers. |
|
237 | # The singleton printers. | |
239 | # Maps the IDs of the builtin singleton objects to the format functions. |
|
238 | # Maps the IDs of the builtin singleton objects to the format functions. | |
240 | singleton_printers = Dict(config=True) |
|
239 | singleton_printers = Dict(config=True) | |
241 | def _singleton_printers_default(self): |
|
240 | def _singleton_printers_default(self): | |
242 | return {} |
|
241 | return {} | |
243 |
|
242 | |||
244 | # The type-specific printers. |
|
243 | # The type-specific printers. | |
245 | # Map type objects to the format functions. |
|
244 | # Map type objects to the format functions. | |
246 | type_printers = Dict(config=True) |
|
245 | type_printers = Dict(config=True) | |
247 | def _type_printers_default(self): |
|
246 | def _type_printers_default(self): | |
248 | return {} |
|
247 | return {} | |
249 |
|
248 | |||
250 | # The deferred-import type-specific printers. |
|
249 | # The deferred-import type-specific printers. | |
251 | # Map (modulename, classname) pairs to the format functions. |
|
250 | # Map (modulename, classname) pairs to the format functions. | |
252 | deferred_printers = Dict(config=True) |
|
251 | deferred_printers = Dict(config=True) | |
253 | def _deferred_printers_default(self): |
|
252 | def _deferred_printers_default(self): | |
254 | return {} |
|
253 | return {} | |
255 |
|
254 | |||
256 | def __call__(self, obj): |
|
255 | def __call__(self, obj): | |
257 | """Compute the format for an object.""" |
|
256 | """Compute the format for an object.""" | |
258 | if self.enabled: |
|
257 | if self.enabled: | |
259 | obj_id = id(obj) |
|
258 | obj_id = id(obj) | |
260 | try: |
|
259 | try: | |
261 | obj_class = getattr(obj, '__class__', None) or type(obj) |
|
260 | obj_class = getattr(obj, '__class__', None) or type(obj) | |
262 | # First try to find registered singleton printers for the type. |
|
261 | # First try to find registered singleton printers for the type. | |
263 | try: |
|
262 | try: | |
264 | printer = self.singleton_printers[obj_id] |
|
263 | printer = self.singleton_printers[obj_id] | |
265 | except (TypeError, KeyError): |
|
264 | except (TypeError, KeyError): | |
266 | pass |
|
265 | pass | |
267 | else: |
|
266 | else: | |
268 | return printer(obj) |
|
267 | return printer(obj) | |
269 | # Next look for type_printers. |
|
268 | # Next look for type_printers. | |
270 | for cls in pretty._get_mro(obj_class): |
|
269 | for cls in pretty._get_mro(obj_class): | |
271 | if cls in self.type_printers: |
|
270 | if cls in self.type_printers: | |
272 | return self.type_printers[cls](obj) |
|
271 | return self.type_printers[cls](obj) | |
273 | else: |
|
272 | else: | |
274 | printer = self._in_deferred_types(cls) |
|
273 | printer = self._in_deferred_types(cls) | |
275 | if printer is not None: |
|
274 | if printer is not None: | |
276 | return printer(obj) |
|
275 | return printer(obj) | |
277 | # Finally look for special method names. |
|
276 | # Finally look for special method names. | |
278 | if hasattr(obj_class, self.print_method): |
|
277 | if hasattr(obj_class, self.print_method): | |
279 | printer = getattr(obj_class, self.print_method) |
|
278 | printer = getattr(obj_class, self.print_method) | |
280 | return printer(obj) |
|
279 | return printer(obj) | |
281 | return None |
|
280 | return None | |
282 | except Exception: |
|
281 | except Exception: | |
283 | pass |
|
282 | pass | |
284 | else: |
|
283 | else: | |
285 | return None |
|
284 | return None | |
286 |
|
285 | |||
287 | def for_type(self, typ, func): |
|
286 | def for_type(self, typ, func): | |
288 | """Add a format function for a given type. |
|
287 | """Add a format function for a given type. | |
289 |
|
288 | |||
290 | Parameters |
|
289 | Parameters | |
291 | ----------- |
|
290 | ----------- | |
292 | typ : class |
|
291 | typ : class | |
293 | The class of the object that will be formatted using `func`. |
|
292 | The class of the object that will be formatted using `func`. | |
294 | func : callable |
|
293 | func : callable | |
295 | The callable that will be called to compute the format data. The |
|
294 | The callable that will be called to compute the format data. The | |
296 | call signature of this function is simple, it must take the |
|
295 | call signature of this function is simple, it must take the | |
297 | object to be formatted and return the raw data for the given |
|
296 | object to be formatted and return the raw data for the given | |
298 | format. Subclasses may use a different call signature for the |
|
297 | format. Subclasses may use a different call signature for the | |
299 | `func` argument. |
|
298 | `func` argument. | |
300 | """ |
|
299 | """ | |
301 | oldfunc = self.type_printers.get(typ, None) |
|
300 | oldfunc = self.type_printers.get(typ, None) | |
302 | if func is not None: |
|
301 | if func is not None: | |
303 | # To support easy restoration of old printers, we need to ignore |
|
302 | # To support easy restoration of old printers, we need to ignore | |
304 | # Nones. |
|
303 | # Nones. | |
305 | self.type_printers[typ] = func |
|
304 | self.type_printers[typ] = func | |
306 | return oldfunc |
|
305 | return oldfunc | |
307 |
|
306 | |||
308 | def for_type_by_name(self, type_module, type_name, func): |
|
307 | def for_type_by_name(self, type_module, type_name, func): | |
309 | """Add a format function for a type specified by the full dotted |
|
308 | """Add a format function for a type specified by the full dotted | |
310 | module and name of the type, rather than the type of the object. |
|
309 | module and name of the type, rather than the type of the object. | |
311 |
|
310 | |||
312 | Parameters |
|
311 | Parameters | |
313 | ---------- |
|
312 | ---------- | |
314 | type_module : str |
|
313 | type_module : str | |
315 | The full dotted name of the module the type is defined in, like |
|
314 | The full dotted name of the module the type is defined in, like | |
316 | ``numpy``. |
|
315 | ``numpy``. | |
317 | type_name : str |
|
316 | type_name : str | |
318 | The name of the type (the class name), like ``dtype`` |
|
317 | The name of the type (the class name), like ``dtype`` | |
319 | func : callable |
|
318 | func : callable | |
320 | The callable that will be called to compute the format data. The |
|
319 | The callable that will be called to compute the format data. The | |
321 | call signature of this function is simple, it must take the |
|
320 | call signature of this function is simple, it must take the | |
322 | object to be formatted and return the raw data for the given |
|
321 | object to be formatted and return the raw data for the given | |
323 | format. Subclasses may use a different call signature for the |
|
322 | format. Subclasses may use a different call signature for the | |
324 | `func` argument. |
|
323 | `func` argument. | |
325 | """ |
|
324 | """ | |
326 | key = (type_module, type_name) |
|
325 | key = (type_module, type_name) | |
327 | oldfunc = self.deferred_printers.get(key, None) |
|
326 | oldfunc = self.deferred_printers.get(key, None) | |
328 | if func is not None: |
|
327 | if func is not None: | |
329 | # To support easy restoration of old printers, we need to ignore |
|
328 | # To support easy restoration of old printers, we need to ignore | |
330 | # Nones. |
|
329 | # Nones. | |
331 | self.deferred_printers[key] = func |
|
330 | self.deferred_printers[key] = func | |
332 | return oldfunc |
|
331 | return oldfunc | |
333 |
|
332 | |||
334 | def _in_deferred_types(self, cls): |
|
333 | def _in_deferred_types(self, cls): | |
335 | """ |
|
334 | """ | |
336 | Check if the given class is specified in the deferred type registry. |
|
335 | Check if the given class is specified in the deferred type registry. | |
337 |
|
336 | |||
338 | Returns the printer from the registry if it exists, and None if the |
|
337 | Returns the printer from the registry if it exists, and None if the | |
339 | class is not in the registry. Successful matches will be moved to the |
|
338 | class is not in the registry. Successful matches will be moved to the | |
340 | regular type registry for future use. |
|
339 | regular type registry for future use. | |
341 | """ |
|
340 | """ | |
342 | mod = getattr(cls, '__module__', None) |
|
341 | mod = getattr(cls, '__module__', None) | |
343 | name = getattr(cls, '__name__', None) |
|
342 | name = getattr(cls, '__name__', None) | |
344 | key = (mod, name) |
|
343 | key = (mod, name) | |
345 | printer = None |
|
344 | printer = None | |
346 | if key in self.deferred_printers: |
|
345 | if key in self.deferred_printers: | |
347 | # Move the printer over to the regular registry. |
|
346 | # Move the printer over to the regular registry. | |
348 | printer = self.deferred_printers.pop(key) |
|
347 | printer = self.deferred_printers.pop(key) | |
349 | self.type_printers[cls] = printer |
|
348 | self.type_printers[cls] = printer | |
350 | return printer |
|
349 | return printer | |
351 |
|
350 | |||
352 |
|
351 | |||
353 | class PlainTextFormatter(BaseFormatter): |
|
352 | class PlainTextFormatter(BaseFormatter): | |
354 | """The default pretty-printer. |
|
353 | """The default pretty-printer. | |
355 |
|
354 | |||
356 | This uses :mod:`IPython.lib.pretty` to compute the format data of |
|
355 | This uses :mod:`IPython.lib.pretty` to compute the format data of | |
357 | the object. If the object cannot be pretty printed, :func:`repr` is used. |
|
356 | the object. If the object cannot be pretty printed, :func:`repr` is used. | |
358 | See the documentation of :mod:`IPython.lib.pretty` for details on |
|
357 | See the documentation of :mod:`IPython.lib.pretty` for details on | |
359 | how to write pretty printers. Here is a simple example:: |
|
358 | how to write pretty printers. Here is a simple example:: | |
360 |
|
359 | |||
361 | def dtype_pprinter(obj, p, cycle): |
|
360 | def dtype_pprinter(obj, p, cycle): | |
362 | if cycle: |
|
361 | if cycle: | |
363 | return p.text('dtype(...)') |
|
362 | return p.text('dtype(...)') | |
364 | if hasattr(obj, 'fields'): |
|
363 | if hasattr(obj, 'fields'): | |
365 | if obj.fields is None: |
|
364 | if obj.fields is None: | |
366 | p.text(repr(obj)) |
|
365 | p.text(repr(obj)) | |
367 | else: |
|
366 | else: | |
368 | p.begin_group(7, 'dtype([') |
|
367 | p.begin_group(7, 'dtype([') | |
369 | for i, field in enumerate(obj.descr): |
|
368 | for i, field in enumerate(obj.descr): | |
370 | if i > 0: |
|
369 | if i > 0: | |
371 | p.text(',') |
|
370 | p.text(',') | |
372 | p.breakable() |
|
371 | p.breakable() | |
373 | p.pretty(field) |
|
372 | p.pretty(field) | |
374 | p.end_group(7, '])') |
|
373 | p.end_group(7, '])') | |
375 | """ |
|
374 | """ | |
376 |
|
375 | |||
377 | # The format type of data returned. |
|
376 | # The format type of data returned. | |
378 | format_type = Unicode('text/plain') |
|
377 | format_type = Unicode('text/plain') | |
379 |
|
378 | |||
380 | # This subclass ignores this attribute as it always need to return |
|
379 | # This subclass ignores this attribute as it always need to return | |
381 | # something. |
|
380 | # something. | |
382 | enabled = Bool(True, config=False) |
|
381 | enabled = Bool(True, config=False) | |
383 |
|
382 | |||
384 | # Look for a _repr_pretty_ methods to use for pretty printing. |
|
383 | # Look for a _repr_pretty_ methods to use for pretty printing. | |
385 | print_method = ObjectName('_repr_pretty_') |
|
384 | print_method = ObjectName('_repr_pretty_') | |
386 |
|
385 | |||
387 | # Whether to pretty-print or not. |
|
386 | # Whether to pretty-print or not. | |
388 | pprint = Bool(True, config=True) |
|
387 | pprint = Bool(True, config=True) | |
389 |
|
388 | |||
390 | # Whether to be verbose or not. |
|
389 | # Whether to be verbose or not. | |
391 | verbose = Bool(False, config=True) |
|
390 | verbose = Bool(False, config=True) | |
392 |
|
391 | |||
393 | # The maximum width. |
|
392 | # The maximum width. | |
394 | max_width = Integer(79, config=True) |
|
393 | max_width = Integer(79, config=True) | |
395 |
|
394 | |||
396 | # The newline character. |
|
395 | # The newline character. | |
397 | newline = Unicode('\n', config=True) |
|
396 | newline = Unicode('\n', config=True) | |
398 |
|
397 | |||
399 | # format-string for pprinting floats |
|
398 | # format-string for pprinting floats | |
400 | float_format = Unicode('%r') |
|
399 | float_format = Unicode('%r') | |
401 | # setter for float precision, either int or direct format-string |
|
400 | # setter for float precision, either int or direct format-string | |
402 | float_precision = CUnicode('', config=True) |
|
401 | float_precision = CUnicode('', config=True) | |
403 |
|
402 | |||
404 | def _float_precision_changed(self, name, old, new): |
|
403 | def _float_precision_changed(self, name, old, new): | |
405 | """float_precision changed, set float_format accordingly. |
|
404 | """float_precision changed, set float_format accordingly. | |
406 |
|
405 | |||
407 | float_precision can be set by int or str. |
|
406 | float_precision can be set by int or str. | |
408 | This will set float_format, after interpreting input. |
|
407 | This will set float_format, after interpreting input. | |
409 | If numpy has been imported, numpy print precision will also be set. |
|
408 | If numpy has been imported, numpy print precision will also be set. | |
410 |
|
409 | |||
411 | integer `n` sets format to '%.nf', otherwise, format set directly. |
|
410 | integer `n` sets format to '%.nf', otherwise, format set directly. | |
412 |
|
411 | |||
413 | An empty string returns to defaults (repr for float, 8 for numpy). |
|
412 | An empty string returns to defaults (repr for float, 8 for numpy). | |
414 |
|
413 | |||
415 | This parameter can be set via the '%precision' magic. |
|
414 | This parameter can be set via the '%precision' magic. | |
416 | """ |
|
415 | """ | |
417 |
|
416 | |||
418 | if '%' in new: |
|
417 | if '%' in new: | |
419 | # got explicit format string |
|
418 | # got explicit format string | |
420 | fmt = new |
|
419 | fmt = new | |
421 | try: |
|
420 | try: | |
422 | fmt%3.14159 |
|
421 | fmt%3.14159 | |
423 | except Exception: |
|
422 | except Exception: | |
424 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
423 | raise ValueError("Precision must be int or format string, not %r"%new) | |
425 | elif new: |
|
424 | elif new: | |
426 | # otherwise, should be an int |
|
425 | # otherwise, should be an int | |
427 | try: |
|
426 | try: | |
428 | i = int(new) |
|
427 | i = int(new) | |
429 | assert i >= 0 |
|
428 | assert i >= 0 | |
430 | except ValueError: |
|
429 | except ValueError: | |
431 | raise ValueError("Precision must be int or format string, not %r"%new) |
|
430 | raise ValueError("Precision must be int or format string, not %r"%new) | |
432 | except AssertionError: |
|
431 | except AssertionError: | |
433 | raise ValueError("int precision must be non-negative, not %r"%i) |
|
432 | raise ValueError("int precision must be non-negative, not %r"%i) | |
434 |
|
433 | |||
435 | fmt = '%%.%if'%i |
|
434 | fmt = '%%.%if'%i | |
436 | if 'numpy' in sys.modules: |
|
435 | if 'numpy' in sys.modules: | |
437 | # set numpy precision if it has been imported |
|
436 | # set numpy precision if it has been imported | |
438 | import numpy |
|
437 | import numpy | |
439 | numpy.set_printoptions(precision=i) |
|
438 | numpy.set_printoptions(precision=i) | |
440 | else: |
|
439 | else: | |
441 | # default back to repr |
|
440 | # default back to repr | |
442 | fmt = '%r' |
|
441 | fmt = '%r' | |
443 | if 'numpy' in sys.modules: |
|
442 | if 'numpy' in sys.modules: | |
444 | import numpy |
|
443 | import numpy | |
445 | # numpy default is 8 |
|
444 | # numpy default is 8 | |
446 | numpy.set_printoptions(precision=8) |
|
445 | numpy.set_printoptions(precision=8) | |
447 | self.float_format = fmt |
|
446 | self.float_format = fmt | |
448 |
|
447 | |||
449 | # Use the default pretty printers from IPython.lib.pretty. |
|
448 | # Use the default pretty printers from IPython.lib.pretty. | |
450 | def _singleton_printers_default(self): |
|
449 | def _singleton_printers_default(self): | |
451 | return pretty._singleton_pprinters.copy() |
|
450 | return pretty._singleton_pprinters.copy() | |
452 |
|
451 | |||
453 | def _type_printers_default(self): |
|
452 | def _type_printers_default(self): | |
454 | d = pretty._type_pprinters.copy() |
|
453 | d = pretty._type_pprinters.copy() | |
455 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) |
|
454 | d[float] = lambda obj,p,cycle: p.text(self.float_format%obj) | |
456 | return d |
|
455 | return d | |
457 |
|
456 | |||
458 | def _deferred_printers_default(self): |
|
457 | def _deferred_printers_default(self): | |
459 | return pretty._deferred_type_pprinters.copy() |
|
458 | return pretty._deferred_type_pprinters.copy() | |
460 |
|
459 | |||
461 | #### FormatterABC interface #### |
|
460 | #### FormatterABC interface #### | |
462 |
|
461 | |||
463 | def __call__(self, obj): |
|
462 | def __call__(self, obj): | |
464 | """Compute the pretty representation of the object.""" |
|
463 | """Compute the pretty representation of the object.""" | |
465 | if not self.pprint: |
|
464 | if not self.pprint: | |
466 | try: |
|
465 | try: | |
467 | return repr(obj) |
|
466 | return repr(obj) | |
468 | except TypeError: |
|
467 | except TypeError: | |
469 | return '' |
|
468 | return '' | |
470 | else: |
|
469 | else: | |
471 | # This uses use StringIO, as cStringIO doesn't handle unicode. |
|
470 | # This uses use StringIO, as cStringIO doesn't handle unicode. | |
472 | stream = StringIO() |
|
471 | stream = StringIO() | |
473 | # self.newline.encode() is a quick fix for issue gh-597. We need to |
|
472 | # self.newline.encode() is a quick fix for issue gh-597. We need to | |
474 | # ensure that stream does not get a mix of unicode and bytestrings, |
|
473 | # ensure that stream does not get a mix of unicode and bytestrings, | |
475 | # or it will cause trouble. |
|
474 | # or it will cause trouble. | |
476 | printer = pretty.RepresentationPrinter(stream, self.verbose, |
|
475 | printer = pretty.RepresentationPrinter(stream, self.verbose, | |
477 | self.max_width, unicode_to_str(self.newline), |
|
476 | self.max_width, unicode_to_str(self.newline), | |
478 | singleton_pprinters=self.singleton_printers, |
|
477 | singleton_pprinters=self.singleton_printers, | |
479 | type_pprinters=self.type_printers, |
|
478 | type_pprinters=self.type_printers, | |
480 | deferred_pprinters=self.deferred_printers) |
|
479 | deferred_pprinters=self.deferred_printers) | |
481 | printer.pretty(obj) |
|
480 | printer.pretty(obj) | |
482 | printer.flush() |
|
481 | printer.flush() | |
483 | return stream.getvalue() |
|
482 | return stream.getvalue() | |
484 |
|
483 | |||
485 |
|
484 | |||
486 | class HTMLFormatter(BaseFormatter): |
|
485 | class HTMLFormatter(BaseFormatter): | |
487 | """An HTML formatter. |
|
486 | """An HTML formatter. | |
488 |
|
487 | |||
489 | To define the callables that compute the HTML representation of your |
|
488 | To define the callables that compute the HTML representation of your | |
490 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` |
|
489 | objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` | |
491 | or :meth:`for_type_by_name` methods to register functions that handle |
|
490 | or :meth:`for_type_by_name` methods to register functions that handle | |
492 | this. |
|
491 | this. | |
493 |
|
492 | |||
494 | The return value of this formatter should be a valid HTML snippet that |
|
493 | The return value of this formatter should be a valid HTML snippet that | |
495 | could be injected into an existing DOM. It should *not* include the |
|
494 | could be injected into an existing DOM. It should *not* include the | |
496 | ```<html>`` or ```<body>`` tags. |
|
495 | ```<html>`` or ```<body>`` tags. | |
497 | """ |
|
496 | """ | |
498 | format_type = Unicode('text/html') |
|
497 | format_type = Unicode('text/html') | |
499 |
|
498 | |||
500 | print_method = ObjectName('_repr_html_') |
|
499 | print_method = ObjectName('_repr_html_') | |
501 |
|
500 | |||
502 |
|
501 | |||
503 | class SVGFormatter(BaseFormatter): |
|
502 | class SVGFormatter(BaseFormatter): | |
504 | """An SVG formatter. |
|
503 | """An SVG formatter. | |
505 |
|
504 | |||
506 | To define the callables that compute the SVG representation of your |
|
505 | To define the callables that compute the SVG representation of your | |
507 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` |
|
506 | objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type` | |
508 | or :meth:`for_type_by_name` methods to register functions that handle |
|
507 | or :meth:`for_type_by_name` methods to register functions that handle | |
509 | this. |
|
508 | this. | |
510 |
|
509 | |||
511 | The return value of this formatter should be valid SVG enclosed in |
|
510 | The return value of this formatter should be valid SVG enclosed in | |
512 | ```<svg>``` tags, that could be injected into an existing DOM. It should |
|
511 | ```<svg>``` tags, that could be injected into an existing DOM. It should | |
513 | *not* include the ```<html>`` or ```<body>`` tags. |
|
512 | *not* include the ```<html>`` or ```<body>`` tags. | |
514 | """ |
|
513 | """ | |
515 | format_type = Unicode('image/svg+xml') |
|
514 | format_type = Unicode('image/svg+xml') | |
516 |
|
515 | |||
517 | print_method = ObjectName('_repr_svg_') |
|
516 | print_method = ObjectName('_repr_svg_') | |
518 |
|
517 | |||
519 |
|
518 | |||
520 | class PNGFormatter(BaseFormatter): |
|
519 | class PNGFormatter(BaseFormatter): | |
521 | """A PNG formatter. |
|
520 | """A PNG formatter. | |
522 |
|
521 | |||
523 | To define the callables that compute the PNG representation of your |
|
522 | To define the callables that compute the PNG representation of your | |
524 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` |
|
523 | objects, define a :meth:`_repr_png_` method or use the :meth:`for_type` | |
525 | or :meth:`for_type_by_name` methods to register functions that handle |
|
524 | or :meth:`for_type_by_name` methods to register functions that handle | |
526 | this. |
|
525 | this. | |
527 |
|
526 | |||
528 | The return value of this formatter should be raw PNG data, *not* |
|
527 | The return value of this formatter should be raw PNG data, *not* | |
529 | base64 encoded. |
|
528 | base64 encoded. | |
530 | """ |
|
529 | """ | |
531 | format_type = Unicode('image/png') |
|
530 | format_type = Unicode('image/png') | |
532 |
|
531 | |||
533 | print_method = ObjectName('_repr_png_') |
|
532 | print_method = ObjectName('_repr_png_') | |
534 |
|
533 | |||
535 |
|
534 | |||
536 | class JPEGFormatter(BaseFormatter): |
|
535 | class JPEGFormatter(BaseFormatter): | |
537 | """A JPEG formatter. |
|
536 | """A JPEG formatter. | |
538 |
|
537 | |||
539 | To define the callables that compute the JPEG representation of your |
|
538 | To define the callables that compute the JPEG representation of your | |
540 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` |
|
539 | objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type` | |
541 | or :meth:`for_type_by_name` methods to register functions that handle |
|
540 | or :meth:`for_type_by_name` methods to register functions that handle | |
542 | this. |
|
541 | this. | |
543 |
|
542 | |||
544 | The return value of this formatter should be raw JPEG data, *not* |
|
543 | The return value of this formatter should be raw JPEG data, *not* | |
545 | base64 encoded. |
|
544 | base64 encoded. | |
546 | """ |
|
545 | """ | |
547 | format_type = Unicode('image/jpeg') |
|
546 | format_type = Unicode('image/jpeg') | |
548 |
|
547 | |||
549 | print_method = ObjectName('_repr_jpeg_') |
|
548 | print_method = ObjectName('_repr_jpeg_') | |
550 |
|
549 | |||
551 |
|
550 | |||
552 | class LatexFormatter(BaseFormatter): |
|
551 | class LatexFormatter(BaseFormatter): | |
553 | """A LaTeX formatter. |
|
552 | """A LaTeX formatter. | |
554 |
|
553 | |||
555 | To define the callables that compute the LaTeX representation of your |
|
554 | To define the callables that compute the LaTeX representation of your | |
556 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` |
|
555 | objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type` | |
557 | or :meth:`for_type_by_name` methods to register functions that handle |
|
556 | or :meth:`for_type_by_name` methods to register functions that handle | |
558 | this. |
|
557 | this. | |
559 |
|
558 | |||
560 | The return value of this formatter should be a valid LaTeX equation, |
|
559 | The return value of this formatter should be a valid LaTeX equation, | |
561 | enclosed in either ```$```, ```$$``` or another LaTeX equation |
|
560 | enclosed in either ```$```, ```$$``` or another LaTeX equation | |
562 | environment. |
|
561 | environment. | |
563 | """ |
|
562 | """ | |
564 | format_type = Unicode('text/latex') |
|
563 | format_type = Unicode('text/latex') | |
565 |
|
564 | |||
566 | print_method = ObjectName('_repr_latex_') |
|
565 | print_method = ObjectName('_repr_latex_') | |
567 |
|
566 | |||
568 |
|
567 | |||
569 | class JSONFormatter(BaseFormatter): |
|
568 | class JSONFormatter(BaseFormatter): | |
570 | """A JSON string formatter. |
|
569 | """A JSON string formatter. | |
571 |
|
570 | |||
572 | To define the callables that compute the JSON string representation of |
|
571 | To define the callables that compute the JSON string representation of | |
573 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` |
|
572 | your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type` | |
574 | or :meth:`for_type_by_name` methods to register functions that handle |
|
573 | or :meth:`for_type_by_name` methods to register functions that handle | |
575 | this. |
|
574 | this. | |
576 |
|
575 | |||
577 | The return value of this formatter should be a valid JSON string. |
|
576 | The return value of this formatter should be a valid JSON string. | |
578 | """ |
|
577 | """ | |
579 | format_type = Unicode('application/json') |
|
578 | format_type = Unicode('application/json') | |
580 |
|
579 | |||
581 | print_method = ObjectName('_repr_json_') |
|
580 | print_method = ObjectName('_repr_json_') | |
582 |
|
581 | |||
583 |
|
582 | |||
584 | class JavascriptFormatter(BaseFormatter): |
|
583 | class JavascriptFormatter(BaseFormatter): | |
585 | """A Javascript formatter. |
|
584 | """A Javascript formatter. | |
586 |
|
585 | |||
587 | To define the callables that compute the Javascript representation of |
|
586 | To define the callables that compute the Javascript representation of | |
588 | your objects, define a :meth:`_repr_javascript_` method or use the |
|
587 | your objects, define a :meth:`_repr_javascript_` method or use the | |
589 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions |
|
588 | :meth:`for_type` or :meth:`for_type_by_name` methods to register functions | |
590 | that handle this. |
|
589 | that handle this. | |
591 |
|
590 | |||
592 | The return value of this formatter should be valid Javascript code and |
|
591 | The return value of this formatter should be valid Javascript code and | |
593 | should *not* be enclosed in ```<script>``` tags. |
|
592 | should *not* be enclosed in ```<script>``` tags. | |
594 | """ |
|
593 | """ | |
595 | format_type = Unicode('application/javascript') |
|
594 | format_type = Unicode('application/javascript') | |
596 |
|
595 | |||
597 | print_method = ObjectName('_repr_javascript_') |
|
596 | print_method = ObjectName('_repr_javascript_') | |
598 |
|
597 | |||
599 | FormatterABC.register(BaseFormatter) |
|
598 | FormatterABC.register(BaseFormatter) | |
600 | FormatterABC.register(PlainTextFormatter) |
|
599 | FormatterABC.register(PlainTextFormatter) | |
601 | FormatterABC.register(HTMLFormatter) |
|
600 | FormatterABC.register(HTMLFormatter) | |
602 | FormatterABC.register(SVGFormatter) |
|
601 | FormatterABC.register(SVGFormatter) | |
603 | FormatterABC.register(PNGFormatter) |
|
602 | FormatterABC.register(PNGFormatter) | |
604 | FormatterABC.register(JPEGFormatter) |
|
603 | FormatterABC.register(JPEGFormatter) | |
605 | FormatterABC.register(LatexFormatter) |
|
604 | FormatterABC.register(LatexFormatter) | |
606 | FormatterABC.register(JSONFormatter) |
|
605 | FormatterABC.register(JSONFormatter) | |
607 | FormatterABC.register(JavascriptFormatter) |
|
606 | FormatterABC.register(JavascriptFormatter) | |
608 |
|
607 | |||
609 |
|
608 | |||
610 | def format_display_data(obj, include=None, exclude=None): |
|
609 | def format_display_data(obj, include=None, exclude=None): | |
611 | """Return a format data dict for an object. |
|
610 | """Return a format data dict for an object. | |
612 |
|
611 | |||
613 | By default all format types will be computed. |
|
612 | By default all format types will be computed. | |
614 |
|
613 | |||
615 | The following MIME types are currently implemented: |
|
614 | The following MIME types are currently implemented: | |
616 |
|
615 | |||
617 | * text/plain |
|
616 | * text/plain | |
618 | * text/html |
|
617 | * text/html | |
619 | * text/latex |
|
618 | * text/latex | |
620 | * application/json |
|
619 | * application/json | |
621 | * application/javascript |
|
620 | * application/javascript | |
622 | * image/png |
|
621 | * image/png | |
623 | * image/jpeg |
|
622 | * image/jpeg | |
624 | * image/svg+xml |
|
623 | * image/svg+xml | |
625 |
|
624 | |||
626 | Parameters |
|
625 | Parameters | |
627 | ---------- |
|
626 | ---------- | |
628 | obj : object |
|
627 | obj : object | |
629 | The Python object whose format data will be computed. |
|
628 | The Python object whose format data will be computed. | |
630 |
|
629 | |||
631 | Returns |
|
630 | Returns | |
632 | ------- |
|
631 | ------- | |
633 | format_dict : dict |
|
632 | format_dict : dict | |
634 | A dictionary of key/value pairs, one or each format that was |
|
633 | A dictionary of key/value pairs, one or each format that was | |
635 | generated for the object. The keys are the format types, which |
|
634 | generated for the object. The keys are the format types, which | |
636 | will usually be MIME type strings and the values and JSON'able |
|
635 | will usually be MIME type strings and the values and JSON'able | |
637 | data structure containing the raw data for the representation in |
|
636 | data structure containing the raw data for the representation in | |
638 | that format. |
|
637 | that format. | |
639 | include : list or tuple, optional |
|
638 | include : list or tuple, optional | |
640 | A list of format type strings (MIME types) to include in the |
|
639 | A list of format type strings (MIME types) to include in the | |
641 | format data dict. If this is set *only* the format types included |
|
640 | format data dict. If this is set *only* the format types included | |
642 | in this list will be computed. |
|
641 | in this list will be computed. | |
643 | exclude : list or tuple, optional |
|
642 | exclude : list or tuple, optional | |
644 | A list of format type string (MIME types) to exclue in the format |
|
643 | A list of format type string (MIME types) to exclue in the format | |
645 | data dict. If this is set all format types will be computed, |
|
644 | data dict. If this is set all format types will be computed, | |
646 | except for those included in this argument. |
|
645 | except for those included in this argument. | |
647 | """ |
|
646 | """ | |
648 | from IPython.core.interactiveshell import InteractiveShell |
|
647 | from IPython.core.interactiveshell import InteractiveShell | |
649 |
|
648 | |||
650 | InteractiveShell.instance().display_formatter.format( |
|
649 | InteractiveShell.instance().display_formatter.format( | |
651 | obj, |
|
650 | obj, | |
652 | include, |
|
651 | include, | |
653 | exclude |
|
652 | exclude | |
654 | ) |
|
653 | ) | |
655 |
|
654 |
@@ -1,531 +1,531 b'' | |||||
1 | import abc |
|
1 | import abc | |
2 | import functools |
|
2 | import functools | |
3 | import re |
|
3 | import re | |
4 | from io import StringIO |
|
4 | from io import StringIO | |
5 |
|
5 | |||
6 | from IPython.core.splitinput import LineInfo |
|
6 | from IPython.core.splitinput import LineInfo | |
7 | from IPython.utils import tokenize2 |
|
7 | from IPython.utils import tokenize2 | |
8 | from IPython.utils.openpy import cookie_comment_re |
|
8 | from IPython.utils.openpy import cookie_comment_re | |
|
9 | from IPython.utils.py3compat import with_metaclass | |||
9 | from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError |
|
10 | from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError | |
10 |
|
11 | |||
11 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
12 | # Globals |
|
13 | # Globals | |
13 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
14 |
|
15 | |||
15 | # The escape sequences that define the syntax transformations IPython will |
|
16 | # The escape sequences that define the syntax transformations IPython will | |
16 | # apply to user input. These can NOT be just changed here: many regular |
|
17 | # apply to user input. These can NOT be just changed here: many regular | |
17 | # expressions and other parts of the code may use their hardcoded values, and |
|
18 | # expressions and other parts of the code may use their hardcoded values, and | |
18 | # for all intents and purposes they constitute the 'IPython syntax', so they |
|
19 | # for all intents and purposes they constitute the 'IPython syntax', so they | |
19 | # should be considered fixed. |
|
20 | # should be considered fixed. | |
20 |
|
21 | |||
21 | ESC_SHELL = '!' # Send line to underlying system shell |
|
22 | ESC_SHELL = '!' # Send line to underlying system shell | |
22 | ESC_SH_CAP = '!!' # Send line to system shell and capture output |
|
23 | ESC_SH_CAP = '!!' # Send line to system shell and capture output | |
23 | ESC_HELP = '?' # Find information about object |
|
24 | ESC_HELP = '?' # Find information about object | |
24 | ESC_HELP2 = '??' # Find extra-detailed information about object |
|
25 | ESC_HELP2 = '??' # Find extra-detailed information about object | |
25 | ESC_MAGIC = '%' # Call magic function |
|
26 | ESC_MAGIC = '%' # Call magic function | |
26 | ESC_MAGIC2 = '%%' # Call cell-magic function |
|
27 | ESC_MAGIC2 = '%%' # Call cell-magic function | |
27 | ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call |
|
28 | ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call | |
28 | ESC_QUOTE2 = ';' # Quote all args as a single string, call |
|
29 | ESC_QUOTE2 = ';' # Quote all args as a single string, call | |
29 | ESC_PAREN = '/' # Call first argument with rest of line as arguments |
|
30 | ESC_PAREN = '/' # Call first argument with rest of line as arguments | |
30 |
|
31 | |||
31 | ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\ |
|
32 | ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\ | |
32 | ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\ |
|
33 | ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\ | |
33 | ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ] |
|
34 | ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ] | |
34 |
|
35 | |||
35 |
|
36 | |||
36 | class InputTransformer(object): |
|
37 | class InputTransformer(with_metaclass(abc.ABCMeta, object)): | |
37 | """Abstract base class for line-based input transformers.""" |
|
38 | """Abstract base class for line-based input transformers.""" | |
38 | __metaclass__ = abc.ABCMeta |
|
|||
39 |
|
39 | |||
40 | @abc.abstractmethod |
|
40 | @abc.abstractmethod | |
41 | def push(self, line): |
|
41 | def push(self, line): | |
42 | """Send a line of input to the transformer, returning the transformed |
|
42 | """Send a line of input to the transformer, returning the transformed | |
43 | input or None if the transformer is waiting for more input. |
|
43 | input or None if the transformer is waiting for more input. | |
44 |
|
44 | |||
45 | Must be overridden by subclasses. |
|
45 | Must be overridden by subclasses. | |
46 | """ |
|
46 | """ | |
47 | pass |
|
47 | pass | |
48 |
|
48 | |||
49 | @abc.abstractmethod |
|
49 | @abc.abstractmethod | |
50 | def reset(self): |
|
50 | def reset(self): | |
51 | """Return, transformed any lines that the transformer has accumulated, |
|
51 | """Return, transformed any lines that the transformer has accumulated, | |
52 | and reset its internal state. |
|
52 | and reset its internal state. | |
53 |
|
53 | |||
54 | Must be overridden by subclasses. |
|
54 | Must be overridden by subclasses. | |
55 | """ |
|
55 | """ | |
56 | pass |
|
56 | pass | |
57 |
|
57 | |||
58 | @classmethod |
|
58 | @classmethod | |
59 | def wrap(cls, func): |
|
59 | def wrap(cls, func): | |
60 | """Can be used by subclasses as a decorator, to return a factory that |
|
60 | """Can be used by subclasses as a decorator, to return a factory that | |
61 | will allow instantiation with the decorated object. |
|
61 | will allow instantiation with the decorated object. | |
62 | """ |
|
62 | """ | |
63 | @functools.wraps(func) |
|
63 | @functools.wraps(func) | |
64 | def transformer_factory(**kwargs): |
|
64 | def transformer_factory(**kwargs): | |
65 | return cls(func, **kwargs) |
|
65 | return cls(func, **kwargs) | |
66 |
|
66 | |||
67 | return transformer_factory |
|
67 | return transformer_factory | |
68 |
|
68 | |||
69 | class StatelessInputTransformer(InputTransformer): |
|
69 | class StatelessInputTransformer(InputTransformer): | |
70 | """Wrapper for a stateless input transformer implemented as a function.""" |
|
70 | """Wrapper for a stateless input transformer implemented as a function.""" | |
71 | def __init__(self, func): |
|
71 | def __init__(self, func): | |
72 | self.func = func |
|
72 | self.func = func | |
73 |
|
73 | |||
74 | def __repr__(self): |
|
74 | def __repr__(self): | |
75 | return "StatelessInputTransformer(func={0!r})".format(self.func) |
|
75 | return "StatelessInputTransformer(func={0!r})".format(self.func) | |
76 |
|
76 | |||
77 | def push(self, line): |
|
77 | def push(self, line): | |
78 | """Send a line of input to the transformer, returning the |
|
78 | """Send a line of input to the transformer, returning the | |
79 | transformed input.""" |
|
79 | transformed input.""" | |
80 | return self.func(line) |
|
80 | return self.func(line) | |
81 |
|
81 | |||
82 | def reset(self): |
|
82 | def reset(self): | |
83 | """No-op - exists for compatibility.""" |
|
83 | """No-op - exists for compatibility.""" | |
84 | pass |
|
84 | pass | |
85 |
|
85 | |||
86 | class CoroutineInputTransformer(InputTransformer): |
|
86 | class CoroutineInputTransformer(InputTransformer): | |
87 | """Wrapper for an input transformer implemented as a coroutine.""" |
|
87 | """Wrapper for an input transformer implemented as a coroutine.""" | |
88 | def __init__(self, coro, **kwargs): |
|
88 | def __init__(self, coro, **kwargs): | |
89 | # Prime it |
|
89 | # Prime it | |
90 | self.coro = coro(**kwargs) |
|
90 | self.coro = coro(**kwargs) | |
91 | next(self.coro) |
|
91 | next(self.coro) | |
92 |
|
92 | |||
93 | def __repr__(self): |
|
93 | def __repr__(self): | |
94 | return "CoroutineInputTransformer(coro={0!r})".format(self.coro) |
|
94 | return "CoroutineInputTransformer(coro={0!r})".format(self.coro) | |
95 |
|
95 | |||
96 | def push(self, line): |
|
96 | def push(self, line): | |
97 | """Send a line of input to the transformer, returning the |
|
97 | """Send a line of input to the transformer, returning the | |
98 | transformed input or None if the transformer is waiting for more |
|
98 | transformed input or None if the transformer is waiting for more | |
99 | input. |
|
99 | input. | |
100 | """ |
|
100 | """ | |
101 | return self.coro.send(line) |
|
101 | return self.coro.send(line) | |
102 |
|
102 | |||
103 | def reset(self): |
|
103 | def reset(self): | |
104 | """Return, transformed any lines that the transformer has |
|
104 | """Return, transformed any lines that the transformer has | |
105 | accumulated, and reset its internal state. |
|
105 | accumulated, and reset its internal state. | |
106 | """ |
|
106 | """ | |
107 | return self.coro.send(None) |
|
107 | return self.coro.send(None) | |
108 |
|
108 | |||
109 | class TokenInputTransformer(InputTransformer): |
|
109 | class TokenInputTransformer(InputTransformer): | |
110 | """Wrapper for a token-based input transformer. |
|
110 | """Wrapper for a token-based input transformer. | |
111 |
|
111 | |||
112 | func should accept a list of tokens (5-tuples, see tokenize docs), and |
|
112 | func should accept a list of tokens (5-tuples, see tokenize docs), and | |
113 | return an iterable which can be passed to tokenize.untokenize(). |
|
113 | return an iterable which can be passed to tokenize.untokenize(). | |
114 | """ |
|
114 | """ | |
115 | def __init__(self, func): |
|
115 | def __init__(self, func): | |
116 | self.func = func |
|
116 | self.func = func | |
117 | self.current_line = "" |
|
117 | self.current_line = "" | |
118 | self.line_used = False |
|
118 | self.line_used = False | |
119 | self.reset_tokenizer() |
|
119 | self.reset_tokenizer() | |
120 |
|
120 | |||
121 | def reset_tokenizer(self): |
|
121 | def reset_tokenizer(self): | |
122 | self.tokenizer = generate_tokens(self.get_line) |
|
122 | self.tokenizer = generate_tokens(self.get_line) | |
123 |
|
123 | |||
124 | def get_line(self): |
|
124 | def get_line(self): | |
125 | if self.line_used: |
|
125 | if self.line_used: | |
126 | raise TokenError |
|
126 | raise TokenError | |
127 | self.line_used = True |
|
127 | self.line_used = True | |
128 | return self.current_line |
|
128 | return self.current_line | |
129 |
|
129 | |||
130 | def push(self, line): |
|
130 | def push(self, line): | |
131 | self.current_line += line + "\n" |
|
131 | self.current_line += line + "\n" | |
132 | if self.current_line.isspace(): |
|
132 | if self.current_line.isspace(): | |
133 | return self.reset() |
|
133 | return self.reset() | |
134 |
|
134 | |||
135 | self.line_used = False |
|
135 | self.line_used = False | |
136 | tokens = [] |
|
136 | tokens = [] | |
137 | stop_at_NL = False |
|
137 | stop_at_NL = False | |
138 | try: |
|
138 | try: | |
139 | for intok in self.tokenizer: |
|
139 | for intok in self.tokenizer: | |
140 | tokens.append(intok) |
|
140 | tokens.append(intok) | |
141 | t = intok[0] |
|
141 | t = intok[0] | |
142 | if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL): |
|
142 | if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL): | |
143 | # Stop before we try to pull a line we don't have yet |
|
143 | # Stop before we try to pull a line we don't have yet | |
144 | break |
|
144 | break | |
145 | elif t == tokenize2.ERRORTOKEN: |
|
145 | elif t == tokenize2.ERRORTOKEN: | |
146 | stop_at_NL = True |
|
146 | stop_at_NL = True | |
147 | except TokenError: |
|
147 | except TokenError: | |
148 | # Multi-line statement - stop and try again with the next line |
|
148 | # Multi-line statement - stop and try again with the next line | |
149 | self.reset_tokenizer() |
|
149 | self.reset_tokenizer() | |
150 | return None |
|
150 | return None | |
151 |
|
151 | |||
152 | return self.output(tokens) |
|
152 | return self.output(tokens) | |
153 |
|
153 | |||
154 | def output(self, tokens): |
|
154 | def output(self, tokens): | |
155 | self.current_line = "" |
|
155 | self.current_line = "" | |
156 | self.reset_tokenizer() |
|
156 | self.reset_tokenizer() | |
157 | return untokenize(self.func(tokens)).rstrip('\n') |
|
157 | return untokenize(self.func(tokens)).rstrip('\n') | |
158 |
|
158 | |||
159 | def reset(self): |
|
159 | def reset(self): | |
160 | l = self.current_line |
|
160 | l = self.current_line | |
161 | self.current_line = "" |
|
161 | self.current_line = "" | |
162 | self.reset_tokenizer() |
|
162 | self.reset_tokenizer() | |
163 | if l: |
|
163 | if l: | |
164 | return l.rstrip('\n') |
|
164 | return l.rstrip('\n') | |
165 |
|
165 | |||
166 | class assemble_python_lines(TokenInputTransformer): |
|
166 | class assemble_python_lines(TokenInputTransformer): | |
167 | def __init__(self): |
|
167 | def __init__(self): | |
168 | super(assemble_python_lines, self).__init__(None) |
|
168 | super(assemble_python_lines, self).__init__(None) | |
169 |
|
169 | |||
170 | def output(self, tokens): |
|
170 | def output(self, tokens): | |
171 | return self.reset() |
|
171 | return self.reset() | |
172 |
|
172 | |||
173 | @CoroutineInputTransformer.wrap |
|
173 | @CoroutineInputTransformer.wrap | |
174 | def assemble_logical_lines(): |
|
174 | def assemble_logical_lines(): | |
175 | """Join lines following explicit line continuations (\)""" |
|
175 | """Join lines following explicit line continuations (\)""" | |
176 | line = '' |
|
176 | line = '' | |
177 | while True: |
|
177 | while True: | |
178 | line = (yield line) |
|
178 | line = (yield line) | |
179 | if not line or line.isspace(): |
|
179 | if not line or line.isspace(): | |
180 | continue |
|
180 | continue | |
181 |
|
181 | |||
182 | parts = [] |
|
182 | parts = [] | |
183 | while line is not None: |
|
183 | while line is not None: | |
184 | if line.endswith('\\') and (not has_comment(line)): |
|
184 | if line.endswith('\\') and (not has_comment(line)): | |
185 | parts.append(line[:-1]) |
|
185 | parts.append(line[:-1]) | |
186 | line = (yield None) # Get another line |
|
186 | line = (yield None) # Get another line | |
187 | else: |
|
187 | else: | |
188 | parts.append(line) |
|
188 | parts.append(line) | |
189 | break |
|
189 | break | |
190 |
|
190 | |||
191 | # Output |
|
191 | # Output | |
192 | line = ''.join(parts) |
|
192 | line = ''.join(parts) | |
193 |
|
193 | |||
194 | # Utilities |
|
194 | # Utilities | |
195 | def _make_help_call(target, esc, lspace, next_input=None): |
|
195 | def _make_help_call(target, esc, lspace, next_input=None): | |
196 | """Prepares a pinfo(2)/psearch call from a target name and the escape |
|
196 | """Prepares a pinfo(2)/psearch call from a target name and the escape | |
197 | (i.e. ? or ??)""" |
|
197 | (i.e. ? or ??)""" | |
198 | method = 'pinfo2' if esc == '??' \ |
|
198 | method = 'pinfo2' if esc == '??' \ | |
199 | else 'psearch' if '*' in target \ |
|
199 | else 'psearch' if '*' in target \ | |
200 | else 'pinfo' |
|
200 | else 'pinfo' | |
201 | arg = " ".join([method, target]) |
|
201 | arg = " ".join([method, target]) | |
202 | if next_input is None: |
|
202 | if next_input is None: | |
203 | return '%sget_ipython().magic(%r)' % (lspace, arg) |
|
203 | return '%sget_ipython().magic(%r)' % (lspace, arg) | |
204 | else: |
|
204 | else: | |
205 | return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \ |
|
205 | return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \ | |
206 | (lspace, next_input, arg) |
|
206 | (lspace, next_input, arg) | |
207 |
|
207 | |||
208 | # These define the transformations for the different escape characters. |
|
208 | # These define the transformations for the different escape characters. | |
209 | def _tr_system(line_info): |
|
209 | def _tr_system(line_info): | |
210 | "Translate lines escaped with: !" |
|
210 | "Translate lines escaped with: !" | |
211 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) |
|
211 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) | |
212 | return '%sget_ipython().system(%r)' % (line_info.pre, cmd) |
|
212 | return '%sget_ipython().system(%r)' % (line_info.pre, cmd) | |
213 |
|
213 | |||
214 | def _tr_system2(line_info): |
|
214 | def _tr_system2(line_info): | |
215 | "Translate lines escaped with: !!" |
|
215 | "Translate lines escaped with: !!" | |
216 | cmd = line_info.line.lstrip()[2:] |
|
216 | cmd = line_info.line.lstrip()[2:] | |
217 | return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd) |
|
217 | return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd) | |
218 |
|
218 | |||
219 | def _tr_help(line_info): |
|
219 | def _tr_help(line_info): | |
220 | "Translate lines escaped with: ?/??" |
|
220 | "Translate lines escaped with: ?/??" | |
221 | # A naked help line should just fire the intro help screen |
|
221 | # A naked help line should just fire the intro help screen | |
222 | if not line_info.line[1:]: |
|
222 | if not line_info.line[1:]: | |
223 | return 'get_ipython().show_usage()' |
|
223 | return 'get_ipython().show_usage()' | |
224 |
|
224 | |||
225 | return _make_help_call(line_info.ifun, line_info.esc, line_info.pre) |
|
225 | return _make_help_call(line_info.ifun, line_info.esc, line_info.pre) | |
226 |
|
226 | |||
227 | def _tr_magic(line_info): |
|
227 | def _tr_magic(line_info): | |
228 | "Translate lines escaped with: %" |
|
228 | "Translate lines escaped with: %" | |
229 | tpl = '%sget_ipython().magic(%r)' |
|
229 | tpl = '%sget_ipython().magic(%r)' | |
230 | if line_info.line.startswith(ESC_MAGIC2): |
|
230 | if line_info.line.startswith(ESC_MAGIC2): | |
231 | return line_info.line |
|
231 | return line_info.line | |
232 | cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() |
|
232 | cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip() | |
233 | return tpl % (line_info.pre, cmd) |
|
233 | return tpl % (line_info.pre, cmd) | |
234 |
|
234 | |||
235 | def _tr_quote(line_info): |
|
235 | def _tr_quote(line_info): | |
236 | "Translate lines escaped with: ," |
|
236 | "Translate lines escaped with: ," | |
237 | return '%s%s("%s")' % (line_info.pre, line_info.ifun, |
|
237 | return '%s%s("%s")' % (line_info.pre, line_info.ifun, | |
238 | '", "'.join(line_info.the_rest.split()) ) |
|
238 | '", "'.join(line_info.the_rest.split()) ) | |
239 |
|
239 | |||
240 | def _tr_quote2(line_info): |
|
240 | def _tr_quote2(line_info): | |
241 | "Translate lines escaped with: ;" |
|
241 | "Translate lines escaped with: ;" | |
242 | return '%s%s("%s")' % (line_info.pre, line_info.ifun, |
|
242 | return '%s%s("%s")' % (line_info.pre, line_info.ifun, | |
243 | line_info.the_rest) |
|
243 | line_info.the_rest) | |
244 |
|
244 | |||
245 | def _tr_paren(line_info): |
|
245 | def _tr_paren(line_info): | |
246 | "Translate lines escaped with: /" |
|
246 | "Translate lines escaped with: /" | |
247 | return '%s%s(%s)' % (line_info.pre, line_info.ifun, |
|
247 | return '%s%s(%s)' % (line_info.pre, line_info.ifun, | |
248 | ", ".join(line_info.the_rest.split())) |
|
248 | ", ".join(line_info.the_rest.split())) | |
249 |
|
249 | |||
250 | tr = { ESC_SHELL : _tr_system, |
|
250 | tr = { ESC_SHELL : _tr_system, | |
251 | ESC_SH_CAP : _tr_system2, |
|
251 | ESC_SH_CAP : _tr_system2, | |
252 | ESC_HELP : _tr_help, |
|
252 | ESC_HELP : _tr_help, | |
253 | ESC_HELP2 : _tr_help, |
|
253 | ESC_HELP2 : _tr_help, | |
254 | ESC_MAGIC : _tr_magic, |
|
254 | ESC_MAGIC : _tr_magic, | |
255 | ESC_QUOTE : _tr_quote, |
|
255 | ESC_QUOTE : _tr_quote, | |
256 | ESC_QUOTE2 : _tr_quote2, |
|
256 | ESC_QUOTE2 : _tr_quote2, | |
257 | ESC_PAREN : _tr_paren } |
|
257 | ESC_PAREN : _tr_paren } | |
258 |
|
258 | |||
259 | @StatelessInputTransformer.wrap |
|
259 | @StatelessInputTransformer.wrap | |
260 | def escaped_commands(line): |
|
260 | def escaped_commands(line): | |
261 | """Transform escaped commands - %magic, !system, ?help + various autocalls. |
|
261 | """Transform escaped commands - %magic, !system, ?help + various autocalls. | |
262 | """ |
|
262 | """ | |
263 | if not line or line.isspace(): |
|
263 | if not line or line.isspace(): | |
264 | return line |
|
264 | return line | |
265 | lineinf = LineInfo(line) |
|
265 | lineinf = LineInfo(line) | |
266 | if lineinf.esc not in tr: |
|
266 | if lineinf.esc not in tr: | |
267 | return line |
|
267 | return line | |
268 |
|
268 | |||
269 | return tr[lineinf.esc](lineinf) |
|
269 | return tr[lineinf.esc](lineinf) | |
270 |
|
270 | |||
271 | _initial_space_re = re.compile(r'\s*') |
|
271 | _initial_space_re = re.compile(r'\s*') | |
272 |
|
272 | |||
273 | _help_end_re = re.compile(r"""(%{0,2} |
|
273 | _help_end_re = re.compile(r"""(%{0,2} | |
274 | [a-zA-Z_*][\w*]* # Variable name |
|
274 | [a-zA-Z_*][\w*]* # Variable name | |
275 | (\.[a-zA-Z_*][\w*]*)* # .etc.etc |
|
275 | (\.[a-zA-Z_*][\w*]*)* # .etc.etc | |
276 | ) |
|
276 | ) | |
277 | (\?\??)$ # ? or ?? |
|
277 | (\?\??)$ # ? or ?? | |
278 | """, |
|
278 | """, | |
279 | re.VERBOSE) |
|
279 | re.VERBOSE) | |
280 |
|
280 | |||
281 | # Extra pseudotokens for multiline strings and data structures |
|
281 | # Extra pseudotokens for multiline strings and data structures | |
282 | _MULTILINE_STRING = object() |
|
282 | _MULTILINE_STRING = object() | |
283 | _MULTILINE_STRUCTURE = object() |
|
283 | _MULTILINE_STRUCTURE = object() | |
284 |
|
284 | |||
285 | def _line_tokens(line): |
|
285 | def _line_tokens(line): | |
286 | """Helper for has_comment and ends_in_comment_or_string.""" |
|
286 | """Helper for has_comment and ends_in_comment_or_string.""" | |
287 | readline = StringIO(line).readline |
|
287 | readline = StringIO(line).readline | |
288 | toktypes = set() |
|
288 | toktypes = set() | |
289 | try: |
|
289 | try: | |
290 | for t in generate_tokens(readline): |
|
290 | for t in generate_tokens(readline): | |
291 | toktypes.add(t[0]) |
|
291 | toktypes.add(t[0]) | |
292 | except TokenError as e: |
|
292 | except TokenError as e: | |
293 | # There are only two cases where a TokenError is raised. |
|
293 | # There are only two cases where a TokenError is raised. | |
294 | if 'multi-line string' in e.args[0]: |
|
294 | if 'multi-line string' in e.args[0]: | |
295 | toktypes.add(_MULTILINE_STRING) |
|
295 | toktypes.add(_MULTILINE_STRING) | |
296 | else: |
|
296 | else: | |
297 | toktypes.add(_MULTILINE_STRUCTURE) |
|
297 | toktypes.add(_MULTILINE_STRUCTURE) | |
298 | return toktypes |
|
298 | return toktypes | |
299 |
|
299 | |||
300 | def has_comment(src): |
|
300 | def has_comment(src): | |
301 | """Indicate whether an input line has (i.e. ends in, or is) a comment. |
|
301 | """Indicate whether an input line has (i.e. ends in, or is) a comment. | |
302 |
|
302 | |||
303 | This uses tokenize, so it can distinguish comments from # inside strings. |
|
303 | This uses tokenize, so it can distinguish comments from # inside strings. | |
304 |
|
304 | |||
305 | Parameters |
|
305 | Parameters | |
306 | ---------- |
|
306 | ---------- | |
307 | src : string |
|
307 | src : string | |
308 | A single line input string. |
|
308 | A single line input string. | |
309 |
|
309 | |||
310 | Returns |
|
310 | Returns | |
311 | ------- |
|
311 | ------- | |
312 | comment : bool |
|
312 | comment : bool | |
313 | True if source has a comment. |
|
313 | True if source has a comment. | |
314 | """ |
|
314 | """ | |
315 | return (tokenize2.COMMENT in _line_tokens(src)) |
|
315 | return (tokenize2.COMMENT in _line_tokens(src)) | |
316 |
|
316 | |||
317 | def ends_in_comment_or_string(src): |
|
317 | def ends_in_comment_or_string(src): | |
318 | """Indicates whether or not an input line ends in a comment or within |
|
318 | """Indicates whether or not an input line ends in a comment or within | |
319 | a multiline string. |
|
319 | a multiline string. | |
320 |
|
320 | |||
321 | Parameters |
|
321 | Parameters | |
322 | ---------- |
|
322 | ---------- | |
323 | src : string |
|
323 | src : string | |
324 | A single line input string. |
|
324 | A single line input string. | |
325 |
|
325 | |||
326 | Returns |
|
326 | Returns | |
327 | ------- |
|
327 | ------- | |
328 | comment : bool |
|
328 | comment : bool | |
329 | True if source ends in a comment or multiline string. |
|
329 | True if source ends in a comment or multiline string. | |
330 | """ |
|
330 | """ | |
331 | toktypes = _line_tokens(src) |
|
331 | toktypes = _line_tokens(src) | |
332 | return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes) |
|
332 | return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes) | |
333 |
|
333 | |||
334 |
|
334 | |||
335 | @StatelessInputTransformer.wrap |
|
335 | @StatelessInputTransformer.wrap | |
336 | def help_end(line): |
|
336 | def help_end(line): | |
337 | """Translate lines with ?/?? at the end""" |
|
337 | """Translate lines with ?/?? at the end""" | |
338 | m = _help_end_re.search(line) |
|
338 | m = _help_end_re.search(line) | |
339 | if m is None or ends_in_comment_or_string(line): |
|
339 | if m is None or ends_in_comment_or_string(line): | |
340 | return line |
|
340 | return line | |
341 | target = m.group(1) |
|
341 | target = m.group(1) | |
342 | esc = m.group(3) |
|
342 | esc = m.group(3) | |
343 | lspace = _initial_space_re.match(line).group(0) |
|
343 | lspace = _initial_space_re.match(line).group(0) | |
344 |
|
344 | |||
345 | # If we're mid-command, put it back on the next prompt for the user. |
|
345 | # If we're mid-command, put it back on the next prompt for the user. | |
346 | next_input = line.rstrip('?') if line.strip() != m.group(0) else None |
|
346 | next_input = line.rstrip('?') if line.strip() != m.group(0) else None | |
347 |
|
347 | |||
348 | return _make_help_call(target, esc, lspace, next_input) |
|
348 | return _make_help_call(target, esc, lspace, next_input) | |
349 |
|
349 | |||
350 |
|
350 | |||
351 | @CoroutineInputTransformer.wrap |
|
351 | @CoroutineInputTransformer.wrap | |
352 | def cellmagic(end_on_blank_line=False): |
|
352 | def cellmagic(end_on_blank_line=False): | |
353 | """Captures & transforms cell magics. |
|
353 | """Captures & transforms cell magics. | |
354 |
|
354 | |||
355 | After a cell magic is started, this stores up any lines it gets until it is |
|
355 | After a cell magic is started, this stores up any lines it gets until it is | |
356 | reset (sent None). |
|
356 | reset (sent None). | |
357 | """ |
|
357 | """ | |
358 | tpl = 'get_ipython().run_cell_magic(%r, %r, %r)' |
|
358 | tpl = 'get_ipython().run_cell_magic(%r, %r, %r)' | |
359 | cellmagic_help_re = re.compile('%%\w+\?') |
|
359 | cellmagic_help_re = re.compile('%%\w+\?') | |
360 | line = '' |
|
360 | line = '' | |
361 | while True: |
|
361 | while True: | |
362 | line = (yield line) |
|
362 | line = (yield line) | |
363 | # consume leading empty lines |
|
363 | # consume leading empty lines | |
364 | while not line: |
|
364 | while not line: | |
365 | line = (yield line) |
|
365 | line = (yield line) | |
366 |
|
366 | |||
367 | if not line.startswith(ESC_MAGIC2): |
|
367 | if not line.startswith(ESC_MAGIC2): | |
368 | # This isn't a cell magic, idle waiting for reset then start over |
|
368 | # This isn't a cell magic, idle waiting for reset then start over | |
369 | while line is not None: |
|
369 | while line is not None: | |
370 | line = (yield line) |
|
370 | line = (yield line) | |
371 | continue |
|
371 | continue | |
372 |
|
372 | |||
373 | if cellmagic_help_re.match(line): |
|
373 | if cellmagic_help_re.match(line): | |
374 | # This case will be handled by help_end |
|
374 | # This case will be handled by help_end | |
375 | continue |
|
375 | continue | |
376 |
|
376 | |||
377 | first = line |
|
377 | first = line | |
378 | body = [] |
|
378 | body = [] | |
379 | line = (yield None) |
|
379 | line = (yield None) | |
380 | while (line is not None) and \ |
|
380 | while (line is not None) and \ | |
381 | ((line.strip() != '') or not end_on_blank_line): |
|
381 | ((line.strip() != '') or not end_on_blank_line): | |
382 | body.append(line) |
|
382 | body.append(line) | |
383 | line = (yield None) |
|
383 | line = (yield None) | |
384 |
|
384 | |||
385 | # Output |
|
385 | # Output | |
386 | magic_name, _, first = first.partition(' ') |
|
386 | magic_name, _, first = first.partition(' ') | |
387 | magic_name = magic_name.lstrip(ESC_MAGIC2) |
|
387 | magic_name = magic_name.lstrip(ESC_MAGIC2) | |
388 | line = tpl % (magic_name, first, u'\n'.join(body)) |
|
388 | line = tpl % (magic_name, first, u'\n'.join(body)) | |
389 |
|
389 | |||
390 |
|
390 | |||
391 | def _strip_prompts(prompt_re, initial_re=None): |
|
391 | def _strip_prompts(prompt_re, initial_re=None): | |
392 | """Remove matching input prompts from a block of input. |
|
392 | """Remove matching input prompts from a block of input. | |
393 |
|
393 | |||
394 | Parameters |
|
394 | Parameters | |
395 | ---------- |
|
395 | ---------- | |
396 | prompt_re : regular expression |
|
396 | prompt_re : regular expression | |
397 | A regular expression matching any input prompt (including continuation) |
|
397 | A regular expression matching any input prompt (including continuation) | |
398 | initial_re : regular expression, optional |
|
398 | initial_re : regular expression, optional | |
399 | A regular expression matching only the initial prompt, but not continuation. |
|
399 | A regular expression matching only the initial prompt, but not continuation. | |
400 | If no initial expression is given, prompt_re will be used everywhere. |
|
400 | If no initial expression is given, prompt_re will be used everywhere. | |
401 | Used mainly for plain Python prompts, where the continuation prompt |
|
401 | Used mainly for plain Python prompts, where the continuation prompt | |
402 | ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. |
|
402 | ``...`` is a valid Python expression in Python 3, so shouldn't be stripped. | |
403 |
|
403 | |||
404 | If initial_re and prompt_re differ, |
|
404 | If initial_re and prompt_re differ, | |
405 | only initial_re will be tested against the first line. |
|
405 | only initial_re will be tested against the first line. | |
406 | If any prompt is found on the first two lines, |
|
406 | If any prompt is found on the first two lines, | |
407 | prompts will be stripped from the rest of the block. |
|
407 | prompts will be stripped from the rest of the block. | |
408 | """ |
|
408 | """ | |
409 | if initial_re is None: |
|
409 | if initial_re is None: | |
410 | initial_re = prompt_re |
|
410 | initial_re = prompt_re | |
411 | line = '' |
|
411 | line = '' | |
412 | while True: |
|
412 | while True: | |
413 | line = (yield line) |
|
413 | line = (yield line) | |
414 |
|
414 | |||
415 | # First line of cell |
|
415 | # First line of cell | |
416 | if line is None: |
|
416 | if line is None: | |
417 | continue |
|
417 | continue | |
418 | out, n1 = initial_re.subn('', line, count=1) |
|
418 | out, n1 = initial_re.subn('', line, count=1) | |
419 | line = (yield out) |
|
419 | line = (yield out) | |
420 |
|
420 | |||
421 | if line is None: |
|
421 | if line is None: | |
422 | continue |
|
422 | continue | |
423 | # check for any prompt on the second line of the cell, |
|
423 | # check for any prompt on the second line of the cell, | |
424 | # because people often copy from just after the first prompt, |
|
424 | # because people often copy from just after the first prompt, | |
425 | # so we might not see it in the first line. |
|
425 | # so we might not see it in the first line. | |
426 | out, n2 = prompt_re.subn('', line, count=1) |
|
426 | out, n2 = prompt_re.subn('', line, count=1) | |
427 | line = (yield out) |
|
427 | line = (yield out) | |
428 |
|
428 | |||
429 | if n1 or n2: |
|
429 | if n1 or n2: | |
430 | # Found a prompt in the first two lines - check for it in |
|
430 | # Found a prompt in the first two lines - check for it in | |
431 | # the rest of the cell as well. |
|
431 | # the rest of the cell as well. | |
432 | while line is not None: |
|
432 | while line is not None: | |
433 | line = (yield prompt_re.sub('', line, count=1)) |
|
433 | line = (yield prompt_re.sub('', line, count=1)) | |
434 |
|
434 | |||
435 | else: |
|
435 | else: | |
436 | # Prompts not in input - wait for reset |
|
436 | # Prompts not in input - wait for reset | |
437 | while line is not None: |
|
437 | while line is not None: | |
438 | line = (yield line) |
|
438 | line = (yield line) | |
439 |
|
439 | |||
440 | @CoroutineInputTransformer.wrap |
|
440 | @CoroutineInputTransformer.wrap | |
441 | def classic_prompt(): |
|
441 | def classic_prompt(): | |
442 | """Strip the >>>/... prompts of the Python interactive shell.""" |
|
442 | """Strip the >>>/... prompts of the Python interactive shell.""" | |
443 | # FIXME: non-capturing version (?:...) usable? |
|
443 | # FIXME: non-capturing version (?:...) usable? | |
444 | prompt_re = re.compile(r'^(>>> ?|\.\.\. ?)') |
|
444 | prompt_re = re.compile(r'^(>>> ?|\.\.\. ?)') | |
445 | initial_re = re.compile(r'^(>>> ?)') |
|
445 | initial_re = re.compile(r'^(>>> ?)') | |
446 | return _strip_prompts(prompt_re, initial_re) |
|
446 | return _strip_prompts(prompt_re, initial_re) | |
447 |
|
447 | |||
448 | @CoroutineInputTransformer.wrap |
|
448 | @CoroutineInputTransformer.wrap | |
449 | def ipy_prompt(): |
|
449 | def ipy_prompt(): | |
450 | """Strip IPython's In [1]:/...: prompts.""" |
|
450 | """Strip IPython's In [1]:/...: prompts.""" | |
451 | # FIXME: non-capturing version (?:...) usable? |
|
451 | # FIXME: non-capturing version (?:...) usable? | |
452 | # FIXME: r'^(In \[\d+\]: | {3}\.{3,}: )' clearer? |
|
452 | # FIXME: r'^(In \[\d+\]: | {3}\.{3,}: )' clearer? | |
453 | prompt_re = re.compile(r'^(In \[\d+\]: |\ \ \ \.\.\.+: )') |
|
453 | prompt_re = re.compile(r'^(In \[\d+\]: |\ \ \ \.\.\.+: )') | |
454 | return _strip_prompts(prompt_re) |
|
454 | return _strip_prompts(prompt_re) | |
455 |
|
455 | |||
456 |
|
456 | |||
457 | @CoroutineInputTransformer.wrap |
|
457 | @CoroutineInputTransformer.wrap | |
458 | def leading_indent(): |
|
458 | def leading_indent(): | |
459 | """Remove leading indentation. |
|
459 | """Remove leading indentation. | |
460 |
|
460 | |||
461 | If the first line starts with a spaces or tabs, the same whitespace will be |
|
461 | If the first line starts with a spaces or tabs, the same whitespace will be | |
462 | removed from each following line until it is reset. |
|
462 | removed from each following line until it is reset. | |
463 | """ |
|
463 | """ | |
464 | space_re = re.compile(r'^[ \t]+') |
|
464 | space_re = re.compile(r'^[ \t]+') | |
465 | line = '' |
|
465 | line = '' | |
466 | while True: |
|
466 | while True: | |
467 | line = (yield line) |
|
467 | line = (yield line) | |
468 |
|
468 | |||
469 | if line is None: |
|
469 | if line is None: | |
470 | continue |
|
470 | continue | |
471 |
|
471 | |||
472 | m = space_re.match(line) |
|
472 | m = space_re.match(line) | |
473 | if m: |
|
473 | if m: | |
474 | space = m.group(0) |
|
474 | space = m.group(0) | |
475 | while line is not None: |
|
475 | while line is not None: | |
476 | if line.startswith(space): |
|
476 | if line.startswith(space): | |
477 | line = line[len(space):] |
|
477 | line = line[len(space):] | |
478 | line = (yield line) |
|
478 | line = (yield line) | |
479 | else: |
|
479 | else: | |
480 | # No leading spaces - wait for reset |
|
480 | # No leading spaces - wait for reset | |
481 | while line is not None: |
|
481 | while line is not None: | |
482 | line = (yield line) |
|
482 | line = (yield line) | |
483 |
|
483 | |||
484 |
|
484 | |||
485 | @CoroutineInputTransformer.wrap |
|
485 | @CoroutineInputTransformer.wrap | |
486 | def strip_encoding_cookie(): |
|
486 | def strip_encoding_cookie(): | |
487 | """Remove encoding comment if found in first two lines |
|
487 | """Remove encoding comment if found in first two lines | |
488 |
|
488 | |||
489 | If the first or second line has the `# coding: utf-8` comment, |
|
489 | If the first or second line has the `# coding: utf-8` comment, | |
490 | it will be removed. |
|
490 | it will be removed. | |
491 | """ |
|
491 | """ | |
492 | line = '' |
|
492 | line = '' | |
493 | while True: |
|
493 | while True: | |
494 | line = (yield line) |
|
494 | line = (yield line) | |
495 | # check comment on first two lines |
|
495 | # check comment on first two lines | |
496 | for i in range(2): |
|
496 | for i in range(2): | |
497 | if line is None: |
|
497 | if line is None: | |
498 | break |
|
498 | break | |
499 | if cookie_comment_re.match(line): |
|
499 | if cookie_comment_re.match(line): | |
500 | line = (yield "") |
|
500 | line = (yield "") | |
501 | else: |
|
501 | else: | |
502 | line = (yield line) |
|
502 | line = (yield line) | |
503 |
|
503 | |||
504 | # no-op on the rest of the cell |
|
504 | # no-op on the rest of the cell | |
505 | while line is not None: |
|
505 | while line is not None: | |
506 | line = (yield line) |
|
506 | line = (yield line) | |
507 |
|
507 | |||
508 |
|
508 | |||
509 | assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
509 | assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
510 | r'\s*=\s*!\s*(?P<cmd>.*)') |
|
510 | r'\s*=\s*!\s*(?P<cmd>.*)') | |
511 | assign_system_template = '%s = get_ipython().getoutput(%r)' |
|
511 | assign_system_template = '%s = get_ipython().getoutput(%r)' | |
512 | @StatelessInputTransformer.wrap |
|
512 | @StatelessInputTransformer.wrap | |
513 | def assign_from_system(line): |
|
513 | def assign_from_system(line): | |
514 | """Transform assignment from system commands (e.g. files = !ls)""" |
|
514 | """Transform assignment from system commands (e.g. files = !ls)""" | |
515 | m = assign_system_re.match(line) |
|
515 | m = assign_system_re.match(line) | |
516 | if m is None: |
|
516 | if m is None: | |
517 | return line |
|
517 | return line | |
518 |
|
518 | |||
519 | return assign_system_template % m.group('lhs', 'cmd') |
|
519 | return assign_system_template % m.group('lhs', 'cmd') | |
520 |
|
520 | |||
521 | assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
521 | assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
522 | r'\s*=\s*%\s*(?P<cmd>.*)') |
|
522 | r'\s*=\s*%\s*(?P<cmd>.*)') | |
523 | assign_magic_template = '%s = get_ipython().magic(%r)' |
|
523 | assign_magic_template = '%s = get_ipython().magic(%r)' | |
524 | @StatelessInputTransformer.wrap |
|
524 | @StatelessInputTransformer.wrap | |
525 | def assign_from_magic(line): |
|
525 | def assign_from_magic(line): | |
526 | """Transform assignment from magic commands (e.g. a = %who_ls)""" |
|
526 | """Transform assignment from magic commands (e.g. a = %who_ls)""" | |
527 | m = assign_magic_re.match(line) |
|
527 | m = assign_magic_re.match(line) | |
528 | if m is None: |
|
528 | if m is None: | |
529 | return line |
|
529 | return line | |
530 |
|
530 | |||
531 | return assign_magic_template % m.group('lhs', 'cmd') |
|
531 | return assign_magic_template % m.group('lhs', 'cmd') |
@@ -1,3164 +1,3164 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import absolute_import |
|
17 | from __future__ import absolute_import | |
18 | from __future__ import print_function |
|
18 | from __future__ import print_function | |
19 |
|
19 | |||
20 | import __future__ |
|
20 | import __future__ | |
21 | import abc |
|
21 | import abc | |
22 | import ast |
|
22 | import ast | |
23 | import atexit |
|
23 | import atexit | |
24 | import functools |
|
24 | import functools | |
25 | import os |
|
25 | import os | |
26 | import re |
|
26 | import re | |
27 | import runpy |
|
27 | import runpy | |
28 | import sys |
|
28 | import sys | |
29 | import tempfile |
|
29 | import tempfile | |
30 | import types |
|
30 | import types | |
31 | import subprocess |
|
31 | import subprocess | |
32 | from io import open as io_open |
|
32 | from io import open as io_open | |
33 |
|
33 | |||
34 | from IPython.config.configurable import SingletonConfigurable |
|
34 | from IPython.config.configurable import SingletonConfigurable | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import magic |
|
36 | from IPython.core import magic | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core import shadowns |
|
39 | from IPython.core import shadowns | |
40 | from IPython.core import ultratb |
|
40 | from IPython.core import ultratb | |
41 | from IPython.core.alias import AliasManager, AliasError |
|
41 | from IPython.core.alias import AliasManager, AliasError | |
42 | from IPython.core.autocall import ExitAutocall |
|
42 | from IPython.core.autocall import ExitAutocall | |
43 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | from IPython.core.builtin_trap import BuiltinTrap | |
44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython | |
45 | from IPython.core.display_trap import DisplayTrap |
|
45 | from IPython.core.display_trap import DisplayTrap | |
46 | from IPython.core.displayhook import DisplayHook |
|
46 | from IPython.core.displayhook import DisplayHook | |
47 | from IPython.core.displaypub import DisplayPublisher |
|
47 | from IPython.core.displaypub import DisplayPublisher | |
48 | from IPython.core.error import UsageError |
|
48 | from IPython.core.error import UsageError | |
49 | from IPython.core.extensions import ExtensionManager |
|
49 | from IPython.core.extensions import ExtensionManager | |
50 | from IPython.core.formatters import DisplayFormatter |
|
50 | from IPython.core.formatters import DisplayFormatter | |
51 | from IPython.core.history import HistoryManager |
|
51 | from IPython.core.history import HistoryManager | |
52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 |
|
52 | from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2 | |
53 | from IPython.core.logger import Logger |
|
53 | from IPython.core.logger import Logger | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core.payload import PayloadManager |
|
55 | from IPython.core.payload import PayloadManager | |
56 | from IPython.core.prefilter import PrefilterManager |
|
56 | from IPython.core.prefilter import PrefilterManager | |
57 | from IPython.core.profiledir import ProfileDir |
|
57 | from IPython.core.profiledir import ProfileDir | |
58 | from IPython.core.prompts import PromptManager |
|
58 | from IPython.core.prompts import PromptManager | |
59 | from IPython.lib.latextools import LaTeXTool |
|
59 | from IPython.lib.latextools import LaTeXTool | |
60 | from IPython.testing.skipdoctest import skip_doctest |
|
60 | from IPython.testing.skipdoctest import skip_doctest | |
61 | from IPython.utils import PyColorize |
|
61 | from IPython.utils import PyColorize | |
62 | from IPython.utils import io |
|
62 | from IPython.utils import io | |
63 | from IPython.utils import py3compat |
|
63 | from IPython.utils import py3compat | |
64 | from IPython.utils import openpy |
|
64 | from IPython.utils import openpy | |
65 | from IPython.utils.decorators import undoc |
|
65 | from IPython.utils.decorators import undoc | |
66 | from IPython.utils.io import ask_yes_no |
|
66 | from IPython.utils.io import ask_yes_no | |
67 | from IPython.utils.ipstruct import Struct |
|
67 | from IPython.utils.ipstruct import Struct | |
68 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename |
|
68 | from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename | |
69 | from IPython.utils.pickleshare import PickleShareDB |
|
69 | from IPython.utils.pickleshare import PickleShareDB | |
70 | from IPython.utils.process import system, getoutput |
|
70 | from IPython.utils.process import system, getoutput | |
71 | from IPython.utils.py3compat import builtin_mod, unicode_type, string_types |
|
71 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, | |
|
72 | with_metaclass) | |||
72 | from IPython.utils.strdispatch import StrDispatch |
|
73 | from IPython.utils.strdispatch import StrDispatch | |
73 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
74 | from IPython.utils.syspathcontext import prepended_to_syspath | |
74 | from IPython.utils.text import (format_screen, LSString, SList, |
|
75 | from IPython.utils.text import (format_screen, LSString, SList, | |
75 | DollarFormatter) |
|
76 | DollarFormatter) | |
76 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, |
|
77 | from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum, | |
77 | List, Unicode, Instance, Type) |
|
78 | List, Unicode, Instance, Type) | |
78 | from IPython.utils.warn import warn, error |
|
79 | from IPython.utils.warn import warn, error | |
79 | import IPython.core.hooks |
|
80 | import IPython.core.hooks | |
80 |
|
81 | |||
81 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
82 | # Globals |
|
83 | # Globals | |
83 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
84 |
|
85 | |||
85 | # compiled regexps for autoindent management |
|
86 | # compiled regexps for autoindent management | |
86 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
87 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
87 |
|
88 | |||
88 | #----------------------------------------------------------------------------- |
|
89 | #----------------------------------------------------------------------------- | |
89 | # Utilities |
|
90 | # Utilities | |
90 | #----------------------------------------------------------------------------- |
|
91 | #----------------------------------------------------------------------------- | |
91 |
|
92 | |||
92 | @undoc |
|
93 | @undoc | |
93 | def softspace(file, newvalue): |
|
94 | def softspace(file, newvalue): | |
94 | """Copied from code.py, to remove the dependency""" |
|
95 | """Copied from code.py, to remove the dependency""" | |
95 |
|
96 | |||
96 | oldvalue = 0 |
|
97 | oldvalue = 0 | |
97 | try: |
|
98 | try: | |
98 | oldvalue = file.softspace |
|
99 | oldvalue = file.softspace | |
99 | except AttributeError: |
|
100 | except AttributeError: | |
100 | pass |
|
101 | pass | |
101 | try: |
|
102 | try: | |
102 | file.softspace = newvalue |
|
103 | file.softspace = newvalue | |
103 | except (AttributeError, TypeError): |
|
104 | except (AttributeError, TypeError): | |
104 | # "attribute-less object" or "read-only attributes" |
|
105 | # "attribute-less object" or "read-only attributes" | |
105 | pass |
|
106 | pass | |
106 | return oldvalue |
|
107 | return oldvalue | |
107 |
|
108 | |||
108 | @undoc |
|
109 | @undoc | |
109 | def no_op(*a, **kw): pass |
|
110 | def no_op(*a, **kw): pass | |
110 |
|
111 | |||
111 | @undoc |
|
112 | @undoc | |
112 | class NoOpContext(object): |
|
113 | class NoOpContext(object): | |
113 | def __enter__(self): pass |
|
114 | def __enter__(self): pass | |
114 | def __exit__(self, type, value, traceback): pass |
|
115 | def __exit__(self, type, value, traceback): pass | |
115 | no_op_context = NoOpContext() |
|
116 | no_op_context = NoOpContext() | |
116 |
|
117 | |||
117 | class SpaceInInput(Exception): pass |
|
118 | class SpaceInInput(Exception): pass | |
118 |
|
119 | |||
119 | @undoc |
|
120 | @undoc | |
120 | class Bunch: pass |
|
121 | class Bunch: pass | |
121 |
|
122 | |||
122 |
|
123 | |||
123 | def get_default_colors(): |
|
124 | def get_default_colors(): | |
124 | if sys.platform=='darwin': |
|
125 | if sys.platform=='darwin': | |
125 | return "LightBG" |
|
126 | return "LightBG" | |
126 | elif os.name=='nt': |
|
127 | elif os.name=='nt': | |
127 | return 'Linux' |
|
128 | return 'Linux' | |
128 | else: |
|
129 | else: | |
129 | return 'Linux' |
|
130 | return 'Linux' | |
130 |
|
131 | |||
131 |
|
132 | |||
132 | class SeparateUnicode(Unicode): |
|
133 | class SeparateUnicode(Unicode): | |
133 | """A Unicode subclass to validate separate_in, separate_out, etc. |
|
134 | """A Unicode subclass to validate separate_in, separate_out, etc. | |
134 |
|
135 | |||
135 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. |
|
136 | This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'. | |
136 | """ |
|
137 | """ | |
137 |
|
138 | |||
138 | def validate(self, obj, value): |
|
139 | def validate(self, obj, value): | |
139 | if value == '0': value = '' |
|
140 | if value == '0': value = '' | |
140 | value = value.replace('\\n','\n') |
|
141 | value = value.replace('\\n','\n') | |
141 | return super(SeparateUnicode, self).validate(obj, value) |
|
142 | return super(SeparateUnicode, self).validate(obj, value) | |
142 |
|
143 | |||
143 |
|
144 | |||
144 | class ReadlineNoRecord(object): |
|
145 | class ReadlineNoRecord(object): | |
145 | """Context manager to execute some code, then reload readline history |
|
146 | """Context manager to execute some code, then reload readline history | |
146 | so that interactive input to the code doesn't appear when pressing up.""" |
|
147 | so that interactive input to the code doesn't appear when pressing up.""" | |
147 | def __init__(self, shell): |
|
148 | def __init__(self, shell): | |
148 | self.shell = shell |
|
149 | self.shell = shell | |
149 | self._nested_level = 0 |
|
150 | self._nested_level = 0 | |
150 |
|
151 | |||
151 | def __enter__(self): |
|
152 | def __enter__(self): | |
152 | if self._nested_level == 0: |
|
153 | if self._nested_level == 0: | |
153 | try: |
|
154 | try: | |
154 | self.orig_length = self.current_length() |
|
155 | self.orig_length = self.current_length() | |
155 | self.readline_tail = self.get_readline_tail() |
|
156 | self.readline_tail = self.get_readline_tail() | |
156 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
157 | except (AttributeError, IndexError): # Can fail with pyreadline | |
157 | self.orig_length, self.readline_tail = 999999, [] |
|
158 | self.orig_length, self.readline_tail = 999999, [] | |
158 | self._nested_level += 1 |
|
159 | self._nested_level += 1 | |
159 |
|
160 | |||
160 | def __exit__(self, type, value, traceback): |
|
161 | def __exit__(self, type, value, traceback): | |
161 | self._nested_level -= 1 |
|
162 | self._nested_level -= 1 | |
162 | if self._nested_level == 0: |
|
163 | if self._nested_level == 0: | |
163 | # Try clipping the end if it's got longer |
|
164 | # Try clipping the end if it's got longer | |
164 | try: |
|
165 | try: | |
165 | e = self.current_length() - self.orig_length |
|
166 | e = self.current_length() - self.orig_length | |
166 | if e > 0: |
|
167 | if e > 0: | |
167 | for _ in range(e): |
|
168 | for _ in range(e): | |
168 | self.shell.readline.remove_history_item(self.orig_length) |
|
169 | self.shell.readline.remove_history_item(self.orig_length) | |
169 |
|
170 | |||
170 | # If it still doesn't match, just reload readline history. |
|
171 | # If it still doesn't match, just reload readline history. | |
171 | if self.current_length() != self.orig_length \ |
|
172 | if self.current_length() != self.orig_length \ | |
172 | or self.get_readline_tail() != self.readline_tail: |
|
173 | or self.get_readline_tail() != self.readline_tail: | |
173 | self.shell.refill_readline_hist() |
|
174 | self.shell.refill_readline_hist() | |
174 | except (AttributeError, IndexError): |
|
175 | except (AttributeError, IndexError): | |
175 | pass |
|
176 | pass | |
176 | # Returning False will cause exceptions to propagate |
|
177 | # Returning False will cause exceptions to propagate | |
177 | return False |
|
178 | return False | |
178 |
|
179 | |||
179 | def current_length(self): |
|
180 | def current_length(self): | |
180 | return self.shell.readline.get_current_history_length() |
|
181 | return self.shell.readline.get_current_history_length() | |
181 |
|
182 | |||
182 | def get_readline_tail(self, n=10): |
|
183 | def get_readline_tail(self, n=10): | |
183 | """Get the last n items in readline history.""" |
|
184 | """Get the last n items in readline history.""" | |
184 | end = self.shell.readline.get_current_history_length() + 1 |
|
185 | end = self.shell.readline.get_current_history_length() + 1 | |
185 | start = max(end-n, 1) |
|
186 | start = max(end-n, 1) | |
186 | ghi = self.shell.readline.get_history_item |
|
187 | ghi = self.shell.readline.get_history_item | |
187 | return [ghi(x) for x in range(start, end)] |
|
188 | return [ghi(x) for x in range(start, end)] | |
188 |
|
189 | |||
189 |
|
190 | |||
190 | @undoc |
|
191 | @undoc | |
191 | class DummyMod(object): |
|
192 | class DummyMod(object): | |
192 | """A dummy module used for IPython's interactive module when |
|
193 | """A dummy module used for IPython's interactive module when | |
193 | a namespace must be assigned to the module's __dict__.""" |
|
194 | a namespace must be assigned to the module's __dict__.""" | |
194 | pass |
|
195 | pass | |
195 |
|
196 | |||
196 | #----------------------------------------------------------------------------- |
|
197 | #----------------------------------------------------------------------------- | |
197 | # Main IPython class |
|
198 | # Main IPython class | |
198 | #----------------------------------------------------------------------------- |
|
199 | #----------------------------------------------------------------------------- | |
199 |
|
200 | |||
200 | class InteractiveShell(SingletonConfigurable): |
|
201 | class InteractiveShell(SingletonConfigurable): | |
201 | """An enhanced, interactive shell for Python.""" |
|
202 | """An enhanced, interactive shell for Python.""" | |
202 |
|
203 | |||
203 | _instance = None |
|
204 | _instance = None | |
204 |
|
205 | |||
205 | ast_transformers = List([], config=True, help= |
|
206 | ast_transformers = List([], config=True, help= | |
206 | """ |
|
207 | """ | |
207 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
208 | A list of ast.NodeTransformer subclass instances, which will be applied | |
208 | to user input before code is run. |
|
209 | to user input before code is run. | |
209 | """ |
|
210 | """ | |
210 | ) |
|
211 | ) | |
211 |
|
212 | |||
212 | autocall = Enum((0,1,2), default_value=0, config=True, help= |
|
213 | autocall = Enum((0,1,2), default_value=0, config=True, help= | |
213 | """ |
|
214 | """ | |
214 | Make IPython automatically call any callable object even if you didn't |
|
215 | Make IPython automatically call any callable object even if you didn't | |
215 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
216 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
216 | automatically. The value can be '0' to disable the feature, '1' for |
|
217 | automatically. The value can be '0' to disable the feature, '1' for | |
217 | 'smart' autocall, where it is not applied if there are no more |
|
218 | 'smart' autocall, where it is not applied if there are no more | |
218 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
219 | arguments on the line, and '2' for 'full' autocall, where all callable | |
219 | objects are automatically called (even if no arguments are present). |
|
220 | objects are automatically called (even if no arguments are present). | |
220 | """ |
|
221 | """ | |
221 | ) |
|
222 | ) | |
222 | # TODO: remove all autoindent logic and put into frontends. |
|
223 | # TODO: remove all autoindent logic and put into frontends. | |
223 | # We can't do this yet because even runlines uses the autoindent. |
|
224 | # We can't do this yet because even runlines uses the autoindent. | |
224 | autoindent = CBool(True, config=True, help= |
|
225 | autoindent = CBool(True, config=True, help= | |
225 | """ |
|
226 | """ | |
226 | Autoindent IPython code entered interactively. |
|
227 | Autoindent IPython code entered interactively. | |
227 | """ |
|
228 | """ | |
228 | ) |
|
229 | ) | |
229 | automagic = CBool(True, config=True, help= |
|
230 | automagic = CBool(True, config=True, help= | |
230 | """ |
|
231 | """ | |
231 | Enable magic commands to be called without the leading %. |
|
232 | Enable magic commands to be called without the leading %. | |
232 | """ |
|
233 | """ | |
233 | ) |
|
234 | ) | |
234 | cache_size = Integer(1000, config=True, help= |
|
235 | cache_size = Integer(1000, config=True, help= | |
235 | """ |
|
236 | """ | |
236 | Set the size of the output cache. The default is 1000, you can |
|
237 | Set the size of the output cache. The default is 1000, you can | |
237 | change it permanently in your config file. Setting it to 0 completely |
|
238 | change it permanently in your config file. Setting it to 0 completely | |
238 | disables the caching system, and the minimum value accepted is 20 (if |
|
239 | disables the caching system, and the minimum value accepted is 20 (if | |
239 | you provide a value less than 20, it is reset to 0 and a warning is |
|
240 | you provide a value less than 20, it is reset to 0 and a warning is | |
240 | issued). This limit is defined because otherwise you'll spend more |
|
241 | issued). This limit is defined because otherwise you'll spend more | |
241 | time re-flushing a too small cache than working |
|
242 | time re-flushing a too small cache than working | |
242 | """ |
|
243 | """ | |
243 | ) |
|
244 | ) | |
244 | color_info = CBool(True, config=True, help= |
|
245 | color_info = CBool(True, config=True, help= | |
245 | """ |
|
246 | """ | |
246 | Use colors for displaying information about objects. Because this |
|
247 | Use colors for displaying information about objects. Because this | |
247 | information is passed through a pager (like 'less'), and some pagers |
|
248 | information is passed through a pager (like 'less'), and some pagers | |
248 | get confused with color codes, this capability can be turned off. |
|
249 | get confused with color codes, this capability can be turned off. | |
249 | """ |
|
250 | """ | |
250 | ) |
|
251 | ) | |
251 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
252 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
252 | default_value=get_default_colors(), config=True, |
|
253 | default_value=get_default_colors(), config=True, | |
253 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
254 | help="Set the color scheme (NoColor, Linux, or LightBG)." | |
254 | ) |
|
255 | ) | |
255 | colors_force = CBool(False, help= |
|
256 | colors_force = CBool(False, help= | |
256 | """ |
|
257 | """ | |
257 | Force use of ANSI color codes, regardless of OS and readline |
|
258 | Force use of ANSI color codes, regardless of OS and readline | |
258 | availability. |
|
259 | availability. | |
259 | """ |
|
260 | """ | |
260 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
261 | # FIXME: This is essentially a hack to allow ZMQShell to show colors | |
261 | # without readline on Win32. When the ZMQ formatting system is |
|
262 | # without readline on Win32. When the ZMQ formatting system is | |
262 | # refactored, this should be removed. |
|
263 | # refactored, this should be removed. | |
263 | ) |
|
264 | ) | |
264 | debug = CBool(False, config=True) |
|
265 | debug = CBool(False, config=True) | |
265 | deep_reload = CBool(False, config=True, help= |
|
266 | deep_reload = CBool(False, config=True, help= | |
266 | """ |
|
267 | """ | |
267 | Enable deep (recursive) reloading by default. IPython can use the |
|
268 | Enable deep (recursive) reloading by default. IPython can use the | |
268 | deep_reload module which reloads changes in modules recursively (it |
|
269 | deep_reload module which reloads changes in modules recursively (it | |
269 | replaces the reload() function, so you don't need to change anything to |
|
270 | replaces the reload() function, so you don't need to change anything to | |
270 | use it). deep_reload() forces a full reload of modules whose code may |
|
271 | use it). deep_reload() forces a full reload of modules whose code may | |
271 | have changed, which the default reload() function does not. When |
|
272 | have changed, which the default reload() function does not. When | |
272 | deep_reload is off, IPython will use the normal reload(), but |
|
273 | deep_reload is off, IPython will use the normal reload(), but | |
273 | deep_reload will still be available as dreload(). |
|
274 | deep_reload will still be available as dreload(). | |
274 | """ |
|
275 | """ | |
275 | ) |
|
276 | ) | |
276 | disable_failing_post_execute = CBool(False, config=True, |
|
277 | disable_failing_post_execute = CBool(False, config=True, | |
277 | help="Don't call post-execute functions that have failed in the past." |
|
278 | help="Don't call post-execute functions that have failed in the past." | |
278 | ) |
|
279 | ) | |
279 | display_formatter = Instance(DisplayFormatter) |
|
280 | display_formatter = Instance(DisplayFormatter) | |
280 | displayhook_class = Type(DisplayHook) |
|
281 | displayhook_class = Type(DisplayHook) | |
281 | display_pub_class = Type(DisplayPublisher) |
|
282 | display_pub_class = Type(DisplayPublisher) | |
282 | data_pub_class = None |
|
283 | data_pub_class = None | |
283 |
|
284 | |||
284 | exit_now = CBool(False) |
|
285 | exit_now = CBool(False) | |
285 | exiter = Instance(ExitAutocall) |
|
286 | exiter = Instance(ExitAutocall) | |
286 | def _exiter_default(self): |
|
287 | def _exiter_default(self): | |
287 | return ExitAutocall(self) |
|
288 | return ExitAutocall(self) | |
288 | # Monotonically increasing execution counter |
|
289 | # Monotonically increasing execution counter | |
289 | execution_count = Integer(1) |
|
290 | execution_count = Integer(1) | |
290 | filename = Unicode("<ipython console>") |
|
291 | filename = Unicode("<ipython console>") | |
291 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
292 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
292 |
|
293 | |||
293 | # Input splitter, to transform input line by line and detect when a block |
|
294 | # Input splitter, to transform input line by line and detect when a block | |
294 | # is ready to be executed. |
|
295 | # is ready to be executed. | |
295 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
296 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
296 | (), {'line_input_checker': True}) |
|
297 | (), {'line_input_checker': True}) | |
297 |
|
298 | |||
298 | # This InputSplitter instance is used to transform completed cells before |
|
299 | # This InputSplitter instance is used to transform completed cells before | |
299 | # running them. It allows cell magics to contain blank lines. |
|
300 | # running them. It allows cell magics to contain blank lines. | |
300 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
301 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', | |
301 | (), {'line_input_checker': False}) |
|
302 | (), {'line_input_checker': False}) | |
302 |
|
303 | |||
303 | logstart = CBool(False, config=True, help= |
|
304 | logstart = CBool(False, config=True, help= | |
304 | """ |
|
305 | """ | |
305 | Start logging to the default log file. |
|
306 | Start logging to the default log file. | |
306 | """ |
|
307 | """ | |
307 | ) |
|
308 | ) | |
308 | logfile = Unicode('', config=True, help= |
|
309 | logfile = Unicode('', config=True, help= | |
309 | """ |
|
310 | """ | |
310 | The name of the logfile to use. |
|
311 | The name of the logfile to use. | |
311 | """ |
|
312 | """ | |
312 | ) |
|
313 | ) | |
313 | logappend = Unicode('', config=True, help= |
|
314 | logappend = Unicode('', config=True, help= | |
314 | """ |
|
315 | """ | |
315 | Start logging to the given file in append mode. |
|
316 | Start logging to the given file in append mode. | |
316 | """ |
|
317 | """ | |
317 | ) |
|
318 | ) | |
318 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
319 | object_info_string_level = Enum((0,1,2), default_value=0, | |
319 | config=True) |
|
320 | config=True) | |
320 | pdb = CBool(False, config=True, help= |
|
321 | pdb = CBool(False, config=True, help= | |
321 | """ |
|
322 | """ | |
322 | Automatically call the pdb debugger after every exception. |
|
323 | Automatically call the pdb debugger after every exception. | |
323 | """ |
|
324 | """ | |
324 | ) |
|
325 | ) | |
325 | multiline_history = CBool(sys.platform != 'win32', config=True, |
|
326 | multiline_history = CBool(sys.platform != 'win32', config=True, | |
326 | help="Save multi-line entries as one entry in readline history" |
|
327 | help="Save multi-line entries as one entry in readline history" | |
327 | ) |
|
328 | ) | |
328 |
|
329 | |||
329 | # deprecated prompt traits: |
|
330 | # deprecated prompt traits: | |
330 |
|
331 | |||
331 | prompt_in1 = Unicode('In [\\#]: ', config=True, |
|
332 | prompt_in1 = Unicode('In [\\#]: ', config=True, | |
332 | help="Deprecated, use PromptManager.in_template") |
|
333 | help="Deprecated, use PromptManager.in_template") | |
333 | prompt_in2 = Unicode(' .\\D.: ', config=True, |
|
334 | prompt_in2 = Unicode(' .\\D.: ', config=True, | |
334 | help="Deprecated, use PromptManager.in2_template") |
|
335 | help="Deprecated, use PromptManager.in2_template") | |
335 | prompt_out = Unicode('Out[\\#]: ', config=True, |
|
336 | prompt_out = Unicode('Out[\\#]: ', config=True, | |
336 | help="Deprecated, use PromptManager.out_template") |
|
337 | help="Deprecated, use PromptManager.out_template") | |
337 | prompts_pad_left = CBool(True, config=True, |
|
338 | prompts_pad_left = CBool(True, config=True, | |
338 | help="Deprecated, use PromptManager.justify") |
|
339 | help="Deprecated, use PromptManager.justify") | |
339 |
|
340 | |||
340 | def _prompt_trait_changed(self, name, old, new): |
|
341 | def _prompt_trait_changed(self, name, old, new): | |
341 | table = { |
|
342 | table = { | |
342 | 'prompt_in1' : 'in_template', |
|
343 | 'prompt_in1' : 'in_template', | |
343 | 'prompt_in2' : 'in2_template', |
|
344 | 'prompt_in2' : 'in2_template', | |
344 | 'prompt_out' : 'out_template', |
|
345 | 'prompt_out' : 'out_template', | |
345 | 'prompts_pad_left' : 'justify', |
|
346 | 'prompts_pad_left' : 'justify', | |
346 | } |
|
347 | } | |
347 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( |
|
348 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( | |
348 | name=name, newname=table[name]) |
|
349 | name=name, newname=table[name]) | |
349 | ) |
|
350 | ) | |
350 | # protect against weird cases where self.config may not exist: |
|
351 | # protect against weird cases where self.config may not exist: | |
351 | if self.config is not None: |
|
352 | if self.config is not None: | |
352 | # propagate to corresponding PromptManager trait |
|
353 | # propagate to corresponding PromptManager trait | |
353 | setattr(self.config.PromptManager, table[name], new) |
|
354 | setattr(self.config.PromptManager, table[name], new) | |
354 |
|
355 | |||
355 | _prompt_in1_changed = _prompt_trait_changed |
|
356 | _prompt_in1_changed = _prompt_trait_changed | |
356 | _prompt_in2_changed = _prompt_trait_changed |
|
357 | _prompt_in2_changed = _prompt_trait_changed | |
357 | _prompt_out_changed = _prompt_trait_changed |
|
358 | _prompt_out_changed = _prompt_trait_changed | |
358 | _prompt_pad_left_changed = _prompt_trait_changed |
|
359 | _prompt_pad_left_changed = _prompt_trait_changed | |
359 |
|
360 | |||
360 | show_rewritten_input = CBool(True, config=True, |
|
361 | show_rewritten_input = CBool(True, config=True, | |
361 | help="Show rewritten input, e.g. for autocall." |
|
362 | help="Show rewritten input, e.g. for autocall." | |
362 | ) |
|
363 | ) | |
363 |
|
364 | |||
364 | quiet = CBool(False, config=True) |
|
365 | quiet = CBool(False, config=True) | |
365 |
|
366 | |||
366 | history_length = Integer(10000, config=True) |
|
367 | history_length = Integer(10000, config=True) | |
367 |
|
368 | |||
368 | # The readline stuff will eventually be moved to the terminal subclass |
|
369 | # The readline stuff will eventually be moved to the terminal subclass | |
369 | # but for now, we can't do that as readline is welded in everywhere. |
|
370 | # but for now, we can't do that as readline is welded in everywhere. | |
370 | readline_use = CBool(True, config=True) |
|
371 | readline_use = CBool(True, config=True) | |
371 | readline_remove_delims = Unicode('-/~', config=True) |
|
372 | readline_remove_delims = Unicode('-/~', config=True) | |
372 | readline_delims = Unicode() # set by init_readline() |
|
373 | readline_delims = Unicode() # set by init_readline() | |
373 | # don't use \M- bindings by default, because they |
|
374 | # don't use \M- bindings by default, because they | |
374 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
375 | # conflict with 8-bit encodings. See gh-58,gh-88 | |
375 | readline_parse_and_bind = List([ |
|
376 | readline_parse_and_bind = List([ | |
376 | 'tab: complete', |
|
377 | 'tab: complete', | |
377 | '"\C-l": clear-screen', |
|
378 | '"\C-l": clear-screen', | |
378 | 'set show-all-if-ambiguous on', |
|
379 | 'set show-all-if-ambiguous on', | |
379 | '"\C-o": tab-insert', |
|
380 | '"\C-o": tab-insert', | |
380 | '"\C-r": reverse-search-history', |
|
381 | '"\C-r": reverse-search-history', | |
381 | '"\C-s": forward-search-history', |
|
382 | '"\C-s": forward-search-history', | |
382 | '"\C-p": history-search-backward', |
|
383 | '"\C-p": history-search-backward', | |
383 | '"\C-n": history-search-forward', |
|
384 | '"\C-n": history-search-forward', | |
384 | '"\e[A": history-search-backward', |
|
385 | '"\e[A": history-search-backward', | |
385 | '"\e[B": history-search-forward', |
|
386 | '"\e[B": history-search-forward', | |
386 | '"\C-k": kill-line', |
|
387 | '"\C-k": kill-line', | |
387 | '"\C-u": unix-line-discard', |
|
388 | '"\C-u": unix-line-discard', | |
388 | ], allow_none=False, config=True) |
|
389 | ], allow_none=False, config=True) | |
389 |
|
390 | |||
390 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
391 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], | |
391 | default_value='last_expr', config=True, |
|
392 | default_value='last_expr', config=True, | |
392 | help=""" |
|
393 | help=""" | |
393 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
394 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
394 | run interactively (displaying output from expressions).""") |
|
395 | run interactively (displaying output from expressions).""") | |
395 |
|
396 | |||
396 | # TODO: this part of prompt management should be moved to the frontends. |
|
397 | # TODO: this part of prompt management should be moved to the frontends. | |
397 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
398 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
398 | separate_in = SeparateUnicode('\n', config=True) |
|
399 | separate_in = SeparateUnicode('\n', config=True) | |
399 | separate_out = SeparateUnicode('', config=True) |
|
400 | separate_out = SeparateUnicode('', config=True) | |
400 | separate_out2 = SeparateUnicode('', config=True) |
|
401 | separate_out2 = SeparateUnicode('', config=True) | |
401 | wildcards_case_sensitive = CBool(True, config=True) |
|
402 | wildcards_case_sensitive = CBool(True, config=True) | |
402 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
403 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
403 | default_value='Context', config=True) |
|
404 | default_value='Context', config=True) | |
404 |
|
405 | |||
405 | # Subcomponents of InteractiveShell |
|
406 | # Subcomponents of InteractiveShell | |
406 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
407 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
407 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
408 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
408 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
409 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
409 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
410 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
410 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
411 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
411 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
412 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
412 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
413 | history_manager = Instance('IPython.core.history.HistoryManager') | |
413 | magics_manager = Instance('IPython.core.magic.MagicsManager') |
|
414 | magics_manager = Instance('IPython.core.magic.MagicsManager') | |
414 |
|
415 | |||
415 | profile_dir = Instance('IPython.core.application.ProfileDir') |
|
416 | profile_dir = Instance('IPython.core.application.ProfileDir') | |
416 | @property |
|
417 | @property | |
417 | def profile(self): |
|
418 | def profile(self): | |
418 | if self.profile_dir is not None: |
|
419 | if self.profile_dir is not None: | |
419 | name = os.path.basename(self.profile_dir.location) |
|
420 | name = os.path.basename(self.profile_dir.location) | |
420 | return name.replace('profile_','') |
|
421 | return name.replace('profile_','') | |
421 |
|
422 | |||
422 |
|
423 | |||
423 | # Private interface |
|
424 | # Private interface | |
424 | _post_execute = Instance(dict) |
|
425 | _post_execute = Instance(dict) | |
425 |
|
426 | |||
426 | # Tracks any GUI loop loaded for pylab |
|
427 | # Tracks any GUI loop loaded for pylab | |
427 | pylab_gui_select = None |
|
428 | pylab_gui_select = None | |
428 |
|
429 | |||
429 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
430 | def __init__(self, ipython_dir=None, profile_dir=None, | |
430 | user_module=None, user_ns=None, |
|
431 | user_module=None, user_ns=None, | |
431 | custom_exceptions=((), None), **kwargs): |
|
432 | custom_exceptions=((), None), **kwargs): | |
432 |
|
433 | |||
433 | # This is where traits with a config_key argument are updated |
|
434 | # This is where traits with a config_key argument are updated | |
434 | # from the values on config. |
|
435 | # from the values on config. | |
435 | super(InteractiveShell, self).__init__(**kwargs) |
|
436 | super(InteractiveShell, self).__init__(**kwargs) | |
436 | self.configurables = [self] |
|
437 | self.configurables = [self] | |
437 |
|
438 | |||
438 | # These are relatively independent and stateless |
|
439 | # These are relatively independent and stateless | |
439 | self.init_ipython_dir(ipython_dir) |
|
440 | self.init_ipython_dir(ipython_dir) | |
440 | self.init_profile_dir(profile_dir) |
|
441 | self.init_profile_dir(profile_dir) | |
441 | self.init_instance_attrs() |
|
442 | self.init_instance_attrs() | |
442 | self.init_environment() |
|
443 | self.init_environment() | |
443 |
|
444 | |||
444 | # Check if we're in a virtualenv, and set up sys.path. |
|
445 | # Check if we're in a virtualenv, and set up sys.path. | |
445 | self.init_virtualenv() |
|
446 | self.init_virtualenv() | |
446 |
|
447 | |||
447 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
448 | # Create namespaces (user_ns, user_global_ns, etc.) | |
448 | self.init_create_namespaces(user_module, user_ns) |
|
449 | self.init_create_namespaces(user_module, user_ns) | |
449 | # This has to be done after init_create_namespaces because it uses |
|
450 | # This has to be done after init_create_namespaces because it uses | |
450 | # something in self.user_ns, but before init_sys_modules, which |
|
451 | # something in self.user_ns, but before init_sys_modules, which | |
451 | # is the first thing to modify sys. |
|
452 | # is the first thing to modify sys. | |
452 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
453 | # TODO: When we override sys.stdout and sys.stderr before this class | |
453 | # is created, we are saving the overridden ones here. Not sure if this |
|
454 | # is created, we are saving the overridden ones here. Not sure if this | |
454 | # is what we want to do. |
|
455 | # is what we want to do. | |
455 | self.save_sys_module_state() |
|
456 | self.save_sys_module_state() | |
456 | self.init_sys_modules() |
|
457 | self.init_sys_modules() | |
457 |
|
458 | |||
458 | # While we're trying to have each part of the code directly access what |
|
459 | # While we're trying to have each part of the code directly access what | |
459 | # it needs without keeping redundant references to objects, we have too |
|
460 | # it needs without keeping redundant references to objects, we have too | |
460 | # much legacy code that expects ip.db to exist. |
|
461 | # much legacy code that expects ip.db to exist. | |
461 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
462 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
462 |
|
463 | |||
463 | self.init_history() |
|
464 | self.init_history() | |
464 | self.init_encoding() |
|
465 | self.init_encoding() | |
465 | self.init_prefilter() |
|
466 | self.init_prefilter() | |
466 |
|
467 | |||
467 | self.init_syntax_highlighting() |
|
468 | self.init_syntax_highlighting() | |
468 | self.init_hooks() |
|
469 | self.init_hooks() | |
469 | self.init_pushd_popd_magic() |
|
470 | self.init_pushd_popd_magic() | |
470 | # self.init_traceback_handlers use to be here, but we moved it below |
|
471 | # self.init_traceback_handlers use to be here, but we moved it below | |
471 | # because it and init_io have to come after init_readline. |
|
472 | # because it and init_io have to come after init_readline. | |
472 | self.init_user_ns() |
|
473 | self.init_user_ns() | |
473 | self.init_logger() |
|
474 | self.init_logger() | |
474 | self.init_builtins() |
|
475 | self.init_builtins() | |
475 |
|
476 | |||
476 | # The following was in post_config_initialization |
|
477 | # The following was in post_config_initialization | |
477 | self.init_inspector() |
|
478 | self.init_inspector() | |
478 | # init_readline() must come before init_io(), because init_io uses |
|
479 | # init_readline() must come before init_io(), because init_io uses | |
479 | # readline related things. |
|
480 | # readline related things. | |
480 | self.init_readline() |
|
481 | self.init_readline() | |
481 | # We save this here in case user code replaces raw_input, but it needs |
|
482 | # We save this here in case user code replaces raw_input, but it needs | |
482 | # to be after init_readline(), because PyPy's readline works by replacing |
|
483 | # to be after init_readline(), because PyPy's readline works by replacing | |
483 | # raw_input. |
|
484 | # raw_input. | |
484 | if py3compat.PY3: |
|
485 | if py3compat.PY3: | |
485 | self.raw_input_original = input |
|
486 | self.raw_input_original = input | |
486 | else: |
|
487 | else: | |
487 | self.raw_input_original = raw_input |
|
488 | self.raw_input_original = raw_input | |
488 | # init_completer must come after init_readline, because it needs to |
|
489 | # init_completer must come after init_readline, because it needs to | |
489 | # know whether readline is present or not system-wide to configure the |
|
490 | # know whether readline is present or not system-wide to configure the | |
490 | # completers, since the completion machinery can now operate |
|
491 | # completers, since the completion machinery can now operate | |
491 | # independently of readline (e.g. over the network) |
|
492 | # independently of readline (e.g. over the network) | |
492 | self.init_completer() |
|
493 | self.init_completer() | |
493 | # TODO: init_io() needs to happen before init_traceback handlers |
|
494 | # TODO: init_io() needs to happen before init_traceback handlers | |
494 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
495 | # because the traceback handlers hardcode the stdout/stderr streams. | |
495 | # This logic in in debugger.Pdb and should eventually be changed. |
|
496 | # This logic in in debugger.Pdb and should eventually be changed. | |
496 | self.init_io() |
|
497 | self.init_io() | |
497 | self.init_traceback_handlers(custom_exceptions) |
|
498 | self.init_traceback_handlers(custom_exceptions) | |
498 | self.init_prompts() |
|
499 | self.init_prompts() | |
499 | self.init_display_formatter() |
|
500 | self.init_display_formatter() | |
500 | self.init_display_pub() |
|
501 | self.init_display_pub() | |
501 | self.init_data_pub() |
|
502 | self.init_data_pub() | |
502 | self.init_displayhook() |
|
503 | self.init_displayhook() | |
503 | self.init_latextool() |
|
504 | self.init_latextool() | |
504 | self.init_magics() |
|
505 | self.init_magics() | |
505 | self.init_alias() |
|
506 | self.init_alias() | |
506 | self.init_logstart() |
|
507 | self.init_logstart() | |
507 | self.init_pdb() |
|
508 | self.init_pdb() | |
508 | self.init_extension_manager() |
|
509 | self.init_extension_manager() | |
509 | self.init_payload() |
|
510 | self.init_payload() | |
510 | self.init_comms() |
|
511 | self.init_comms() | |
511 | self.hooks.late_startup_hook() |
|
512 | self.hooks.late_startup_hook() | |
512 | atexit.register(self.atexit_operations) |
|
513 | atexit.register(self.atexit_operations) | |
513 |
|
514 | |||
514 | def get_ipython(self): |
|
515 | def get_ipython(self): | |
515 | """Return the currently running IPython instance.""" |
|
516 | """Return the currently running IPython instance.""" | |
516 | return self |
|
517 | return self | |
517 |
|
518 | |||
518 | #------------------------------------------------------------------------- |
|
519 | #------------------------------------------------------------------------- | |
519 | # Trait changed handlers |
|
520 | # Trait changed handlers | |
520 | #------------------------------------------------------------------------- |
|
521 | #------------------------------------------------------------------------- | |
521 |
|
522 | |||
522 | def _ipython_dir_changed(self, name, new): |
|
523 | def _ipython_dir_changed(self, name, new): | |
523 | if not os.path.isdir(new): |
|
524 | if not os.path.isdir(new): | |
524 | os.makedirs(new, mode = 0o777) |
|
525 | os.makedirs(new, mode = 0o777) | |
525 |
|
526 | |||
526 | def set_autoindent(self,value=None): |
|
527 | def set_autoindent(self,value=None): | |
527 | """Set the autoindent flag, checking for readline support. |
|
528 | """Set the autoindent flag, checking for readline support. | |
528 |
|
529 | |||
529 | If called with no arguments, it acts as a toggle.""" |
|
530 | If called with no arguments, it acts as a toggle.""" | |
530 |
|
531 | |||
531 | if value != 0 and not self.has_readline: |
|
532 | if value != 0 and not self.has_readline: | |
532 | if os.name == 'posix': |
|
533 | if os.name == 'posix': | |
533 | warn("The auto-indent feature requires the readline library") |
|
534 | warn("The auto-indent feature requires the readline library") | |
534 | self.autoindent = 0 |
|
535 | self.autoindent = 0 | |
535 | return |
|
536 | return | |
536 | if value is None: |
|
537 | if value is None: | |
537 | self.autoindent = not self.autoindent |
|
538 | self.autoindent = not self.autoindent | |
538 | else: |
|
539 | else: | |
539 | self.autoindent = value |
|
540 | self.autoindent = value | |
540 |
|
541 | |||
541 | #------------------------------------------------------------------------- |
|
542 | #------------------------------------------------------------------------- | |
542 | # init_* methods called by __init__ |
|
543 | # init_* methods called by __init__ | |
543 | #------------------------------------------------------------------------- |
|
544 | #------------------------------------------------------------------------- | |
544 |
|
545 | |||
545 | def init_ipython_dir(self, ipython_dir): |
|
546 | def init_ipython_dir(self, ipython_dir): | |
546 | if ipython_dir is not None: |
|
547 | if ipython_dir is not None: | |
547 | self.ipython_dir = ipython_dir |
|
548 | self.ipython_dir = ipython_dir | |
548 | return |
|
549 | return | |
549 |
|
550 | |||
550 | self.ipython_dir = get_ipython_dir() |
|
551 | self.ipython_dir = get_ipython_dir() | |
551 |
|
552 | |||
552 | def init_profile_dir(self, profile_dir): |
|
553 | def init_profile_dir(self, profile_dir): | |
553 | if profile_dir is not None: |
|
554 | if profile_dir is not None: | |
554 | self.profile_dir = profile_dir |
|
555 | self.profile_dir = profile_dir | |
555 | return |
|
556 | return | |
556 | self.profile_dir =\ |
|
557 | self.profile_dir =\ | |
557 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
558 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
558 |
|
559 | |||
559 | def init_instance_attrs(self): |
|
560 | def init_instance_attrs(self): | |
560 | self.more = False |
|
561 | self.more = False | |
561 |
|
562 | |||
562 | # command compiler |
|
563 | # command compiler | |
563 | self.compile = CachingCompiler() |
|
564 | self.compile = CachingCompiler() | |
564 |
|
565 | |||
565 | # Make an empty namespace, which extension writers can rely on both |
|
566 | # Make an empty namespace, which extension writers can rely on both | |
566 | # existing and NEVER being used by ipython itself. This gives them a |
|
567 | # existing and NEVER being used by ipython itself. This gives them a | |
567 | # convenient location for storing additional information and state |
|
568 | # convenient location for storing additional information and state | |
568 | # their extensions may require, without fear of collisions with other |
|
569 | # their extensions may require, without fear of collisions with other | |
569 | # ipython names that may develop later. |
|
570 | # ipython names that may develop later. | |
570 | self.meta = Struct() |
|
571 | self.meta = Struct() | |
571 |
|
572 | |||
572 | # Temporary files used for various purposes. Deleted at exit. |
|
573 | # Temporary files used for various purposes. Deleted at exit. | |
573 | self.tempfiles = [] |
|
574 | self.tempfiles = [] | |
574 |
|
575 | |||
575 | # Keep track of readline usage (later set by init_readline) |
|
576 | # Keep track of readline usage (later set by init_readline) | |
576 | self.has_readline = False |
|
577 | self.has_readline = False | |
577 |
|
578 | |||
578 | # keep track of where we started running (mainly for crash post-mortem) |
|
579 | # keep track of where we started running (mainly for crash post-mortem) | |
579 | # This is not being used anywhere currently. |
|
580 | # This is not being used anywhere currently. | |
580 | self.starting_dir = os.getcwdu() |
|
581 | self.starting_dir = os.getcwdu() | |
581 |
|
582 | |||
582 | # Indentation management |
|
583 | # Indentation management | |
583 | self.indent_current_nsp = 0 |
|
584 | self.indent_current_nsp = 0 | |
584 |
|
585 | |||
585 | # Dict to track post-execution functions that have been registered |
|
586 | # Dict to track post-execution functions that have been registered | |
586 | self._post_execute = {} |
|
587 | self._post_execute = {} | |
587 |
|
588 | |||
588 | def init_environment(self): |
|
589 | def init_environment(self): | |
589 | """Any changes we need to make to the user's environment.""" |
|
590 | """Any changes we need to make to the user's environment.""" | |
590 | pass |
|
591 | pass | |
591 |
|
592 | |||
592 | def init_encoding(self): |
|
593 | def init_encoding(self): | |
593 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
594 | # Get system encoding at startup time. Certain terminals (like Emacs | |
594 | # under Win32 have it set to None, and we need to have a known valid |
|
595 | # under Win32 have it set to None, and we need to have a known valid | |
595 | # encoding to use in the raw_input() method |
|
596 | # encoding to use in the raw_input() method | |
596 | try: |
|
597 | try: | |
597 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
598 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
598 | except AttributeError: |
|
599 | except AttributeError: | |
599 | self.stdin_encoding = 'ascii' |
|
600 | self.stdin_encoding = 'ascii' | |
600 |
|
601 | |||
601 | def init_syntax_highlighting(self): |
|
602 | def init_syntax_highlighting(self): | |
602 | # Python source parser/formatter for syntax highlighting |
|
603 | # Python source parser/formatter for syntax highlighting | |
603 | pyformat = PyColorize.Parser().format |
|
604 | pyformat = PyColorize.Parser().format | |
604 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
605 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
605 |
|
606 | |||
606 | def init_pushd_popd_magic(self): |
|
607 | def init_pushd_popd_magic(self): | |
607 | # for pushd/popd management |
|
608 | # for pushd/popd management | |
608 | self.home_dir = get_home_dir() |
|
609 | self.home_dir = get_home_dir() | |
609 |
|
610 | |||
610 | self.dir_stack = [] |
|
611 | self.dir_stack = [] | |
611 |
|
612 | |||
612 | def init_logger(self): |
|
613 | def init_logger(self): | |
613 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
614 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
614 | logmode='rotate') |
|
615 | logmode='rotate') | |
615 |
|
616 | |||
616 | def init_logstart(self): |
|
617 | def init_logstart(self): | |
617 | """Initialize logging in case it was requested at the command line. |
|
618 | """Initialize logging in case it was requested at the command line. | |
618 | """ |
|
619 | """ | |
619 | if self.logappend: |
|
620 | if self.logappend: | |
620 | self.magic('logstart %s append' % self.logappend) |
|
621 | self.magic('logstart %s append' % self.logappend) | |
621 | elif self.logfile: |
|
622 | elif self.logfile: | |
622 | self.magic('logstart %s' % self.logfile) |
|
623 | self.magic('logstart %s' % self.logfile) | |
623 | elif self.logstart: |
|
624 | elif self.logstart: | |
624 | self.magic('logstart') |
|
625 | self.magic('logstart') | |
625 |
|
626 | |||
626 | def init_builtins(self): |
|
627 | def init_builtins(self): | |
627 | # A single, static flag that we set to True. Its presence indicates |
|
628 | # A single, static flag that we set to True. Its presence indicates | |
628 | # that an IPython shell has been created, and we make no attempts at |
|
629 | # that an IPython shell has been created, and we make no attempts at | |
629 | # removing on exit or representing the existence of more than one |
|
630 | # removing on exit or representing the existence of more than one | |
630 | # IPython at a time. |
|
631 | # IPython at a time. | |
631 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
632 | builtin_mod.__dict__['__IPYTHON__'] = True | |
632 |
|
633 | |||
633 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
634 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to | |
634 | # manage on enter/exit, but with all our shells it's virtually |
|
635 | # manage on enter/exit, but with all our shells it's virtually | |
635 | # impossible to get all the cases right. We're leaving the name in for |
|
636 | # impossible to get all the cases right. We're leaving the name in for | |
636 | # those who adapted their codes to check for this flag, but will |
|
637 | # those who adapted their codes to check for this flag, but will | |
637 | # eventually remove it after a few more releases. |
|
638 | # eventually remove it after a few more releases. | |
638 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
639 | builtin_mod.__dict__['__IPYTHON__active'] = \ | |
639 | 'Deprecated, check for __IPYTHON__' |
|
640 | 'Deprecated, check for __IPYTHON__' | |
640 |
|
641 | |||
641 | self.builtin_trap = BuiltinTrap(shell=self) |
|
642 | self.builtin_trap = BuiltinTrap(shell=self) | |
642 |
|
643 | |||
643 | def init_inspector(self): |
|
644 | def init_inspector(self): | |
644 | # Object inspector |
|
645 | # Object inspector | |
645 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
646 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
646 | PyColorize.ANSICodeColors, |
|
647 | PyColorize.ANSICodeColors, | |
647 | 'NoColor', |
|
648 | 'NoColor', | |
648 | self.object_info_string_level) |
|
649 | self.object_info_string_level) | |
649 |
|
650 | |||
650 | def init_io(self): |
|
651 | def init_io(self): | |
651 | # This will just use sys.stdout and sys.stderr. If you want to |
|
652 | # This will just use sys.stdout and sys.stderr. If you want to | |
652 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
653 | # override sys.stdout and sys.stderr themselves, you need to do that | |
653 | # *before* instantiating this class, because io holds onto |
|
654 | # *before* instantiating this class, because io holds onto | |
654 | # references to the underlying streams. |
|
655 | # references to the underlying streams. | |
655 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
656 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: | |
656 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
657 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
657 | else: |
|
658 | else: | |
658 | io.stdout = io.IOStream(sys.stdout) |
|
659 | io.stdout = io.IOStream(sys.stdout) | |
659 | io.stderr = io.IOStream(sys.stderr) |
|
660 | io.stderr = io.IOStream(sys.stderr) | |
660 |
|
661 | |||
661 | def init_prompts(self): |
|
662 | def init_prompts(self): | |
662 | self.prompt_manager = PromptManager(shell=self, parent=self) |
|
663 | self.prompt_manager = PromptManager(shell=self, parent=self) | |
663 | self.configurables.append(self.prompt_manager) |
|
664 | self.configurables.append(self.prompt_manager) | |
664 | # Set system prompts, so that scripts can decide if they are running |
|
665 | # Set system prompts, so that scripts can decide if they are running | |
665 | # interactively. |
|
666 | # interactively. | |
666 | sys.ps1 = 'In : ' |
|
667 | sys.ps1 = 'In : ' | |
667 | sys.ps2 = '...: ' |
|
668 | sys.ps2 = '...: ' | |
668 | sys.ps3 = 'Out: ' |
|
669 | sys.ps3 = 'Out: ' | |
669 |
|
670 | |||
670 | def init_display_formatter(self): |
|
671 | def init_display_formatter(self): | |
671 | self.display_formatter = DisplayFormatter(parent=self) |
|
672 | self.display_formatter = DisplayFormatter(parent=self) | |
672 | self.configurables.append(self.display_formatter) |
|
673 | self.configurables.append(self.display_formatter) | |
673 |
|
674 | |||
674 | def init_display_pub(self): |
|
675 | def init_display_pub(self): | |
675 | self.display_pub = self.display_pub_class(parent=self) |
|
676 | self.display_pub = self.display_pub_class(parent=self) | |
676 | self.configurables.append(self.display_pub) |
|
677 | self.configurables.append(self.display_pub) | |
677 |
|
678 | |||
678 | def init_data_pub(self): |
|
679 | def init_data_pub(self): | |
679 | if not self.data_pub_class: |
|
680 | if not self.data_pub_class: | |
680 | self.data_pub = None |
|
681 | self.data_pub = None | |
681 | return |
|
682 | return | |
682 | self.data_pub = self.data_pub_class(parent=self) |
|
683 | self.data_pub = self.data_pub_class(parent=self) | |
683 | self.configurables.append(self.data_pub) |
|
684 | self.configurables.append(self.data_pub) | |
684 |
|
685 | |||
685 | def init_displayhook(self): |
|
686 | def init_displayhook(self): | |
686 | # Initialize displayhook, set in/out prompts and printing system |
|
687 | # Initialize displayhook, set in/out prompts and printing system | |
687 | self.displayhook = self.displayhook_class( |
|
688 | self.displayhook = self.displayhook_class( | |
688 | parent=self, |
|
689 | parent=self, | |
689 | shell=self, |
|
690 | shell=self, | |
690 | cache_size=self.cache_size, |
|
691 | cache_size=self.cache_size, | |
691 | ) |
|
692 | ) | |
692 | self.configurables.append(self.displayhook) |
|
693 | self.configurables.append(self.displayhook) | |
693 | # This is a context manager that installs/revmoes the displayhook at |
|
694 | # This is a context manager that installs/revmoes the displayhook at | |
694 | # the appropriate time. |
|
695 | # the appropriate time. | |
695 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
696 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
696 |
|
697 | |||
697 | def init_latextool(self): |
|
698 | def init_latextool(self): | |
698 | """Configure LaTeXTool.""" |
|
699 | """Configure LaTeXTool.""" | |
699 | cfg = LaTeXTool.instance(parent=self) |
|
700 | cfg = LaTeXTool.instance(parent=self) | |
700 | if cfg not in self.configurables: |
|
701 | if cfg not in self.configurables: | |
701 | self.configurables.append(cfg) |
|
702 | self.configurables.append(cfg) | |
702 |
|
703 | |||
703 | def init_virtualenv(self): |
|
704 | def init_virtualenv(self): | |
704 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
705 | """Add a virtualenv to sys.path so the user can import modules from it. | |
705 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
706 | This isn't perfect: it doesn't use the Python interpreter with which the | |
706 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
707 | virtualenv was built, and it ignores the --no-site-packages option. A | |
707 | warning will appear suggesting the user installs IPython in the |
|
708 | warning will appear suggesting the user installs IPython in the | |
708 | virtualenv, but for many cases, it probably works well enough. |
|
709 | virtualenv, but for many cases, it probably works well enough. | |
709 |
|
710 | |||
710 | Adapted from code snippets online. |
|
711 | Adapted from code snippets online. | |
711 |
|
712 | |||
712 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
713 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
713 | """ |
|
714 | """ | |
714 | if 'VIRTUAL_ENV' not in os.environ: |
|
715 | if 'VIRTUAL_ENV' not in os.environ: | |
715 | # Not in a virtualenv |
|
716 | # Not in a virtualenv | |
716 | return |
|
717 | return | |
717 |
|
718 | |||
718 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): |
|
719 | if sys.executable.startswith(os.environ['VIRTUAL_ENV']): | |
719 | # Running properly in the virtualenv, don't need to do anything |
|
720 | # Running properly in the virtualenv, don't need to do anything | |
720 | return |
|
721 | return | |
721 |
|
722 | |||
722 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
723 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
723 | "install IPython inside the virtualenv.") |
|
724 | "install IPython inside the virtualenv.") | |
724 | if sys.platform == "win32": |
|
725 | if sys.platform == "win32": | |
725 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
726 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
726 | else: |
|
727 | else: | |
727 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
728 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
728 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
729 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
729 |
|
730 | |||
730 | import site |
|
731 | import site | |
731 | sys.path.insert(0, virtual_env) |
|
732 | sys.path.insert(0, virtual_env) | |
732 | site.addsitedir(virtual_env) |
|
733 | site.addsitedir(virtual_env) | |
733 |
|
734 | |||
734 | #------------------------------------------------------------------------- |
|
735 | #------------------------------------------------------------------------- | |
735 | # Things related to injections into the sys module |
|
736 | # Things related to injections into the sys module | |
736 | #------------------------------------------------------------------------- |
|
737 | #------------------------------------------------------------------------- | |
737 |
|
738 | |||
738 | def save_sys_module_state(self): |
|
739 | def save_sys_module_state(self): | |
739 | """Save the state of hooks in the sys module. |
|
740 | """Save the state of hooks in the sys module. | |
740 |
|
741 | |||
741 | This has to be called after self.user_module is created. |
|
742 | This has to be called after self.user_module is created. | |
742 | """ |
|
743 | """ | |
743 | self._orig_sys_module_state = {} |
|
744 | self._orig_sys_module_state = {} | |
744 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
745 | self._orig_sys_module_state['stdin'] = sys.stdin | |
745 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
746 | self._orig_sys_module_state['stdout'] = sys.stdout | |
746 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
747 | self._orig_sys_module_state['stderr'] = sys.stderr | |
747 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
748 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
748 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
749 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
749 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
750 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
750 |
|
751 | |||
751 | def restore_sys_module_state(self): |
|
752 | def restore_sys_module_state(self): | |
752 | """Restore the state of the sys module.""" |
|
753 | """Restore the state of the sys module.""" | |
753 | try: |
|
754 | try: | |
754 | for k, v in self._orig_sys_module_state.iteritems(): |
|
755 | for k, v in self._orig_sys_module_state.iteritems(): | |
755 | setattr(sys, k, v) |
|
756 | setattr(sys, k, v) | |
756 | except AttributeError: |
|
757 | except AttributeError: | |
757 | pass |
|
758 | pass | |
758 | # Reset what what done in self.init_sys_modules |
|
759 | # Reset what what done in self.init_sys_modules | |
759 | if self._orig_sys_modules_main_mod is not None: |
|
760 | if self._orig_sys_modules_main_mod is not None: | |
760 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
761 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
761 |
|
762 | |||
762 | #------------------------------------------------------------------------- |
|
763 | #------------------------------------------------------------------------- | |
763 | # Things related to hooks |
|
764 | # Things related to hooks | |
764 | #------------------------------------------------------------------------- |
|
765 | #------------------------------------------------------------------------- | |
765 |
|
766 | |||
766 | def init_hooks(self): |
|
767 | def init_hooks(self): | |
767 | # hooks holds pointers used for user-side customizations |
|
768 | # hooks holds pointers used for user-side customizations | |
768 | self.hooks = Struct() |
|
769 | self.hooks = Struct() | |
769 |
|
770 | |||
770 | self.strdispatchers = {} |
|
771 | self.strdispatchers = {} | |
771 |
|
772 | |||
772 | # Set all default hooks, defined in the IPython.hooks module. |
|
773 | # Set all default hooks, defined in the IPython.hooks module. | |
773 | hooks = IPython.core.hooks |
|
774 | hooks = IPython.core.hooks | |
774 | for hook_name in hooks.__all__: |
|
775 | for hook_name in hooks.__all__: | |
775 | # default hooks have priority 100, i.e. low; user hooks should have |
|
776 | # default hooks have priority 100, i.e. low; user hooks should have | |
776 | # 0-100 priority |
|
777 | # 0-100 priority | |
777 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
778 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
778 |
|
779 | |||
779 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
780 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
780 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
781 | """set_hook(name,hook) -> sets an internal IPython hook. | |
781 |
|
782 | |||
782 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
783 | IPython exposes some of its internal API as user-modifiable hooks. By | |
783 | adding your function to one of these hooks, you can modify IPython's |
|
784 | adding your function to one of these hooks, you can modify IPython's | |
784 | behavior to call at runtime your own routines.""" |
|
785 | behavior to call at runtime your own routines.""" | |
785 |
|
786 | |||
786 | # At some point in the future, this should validate the hook before it |
|
787 | # At some point in the future, this should validate the hook before it | |
787 | # accepts it. Probably at least check that the hook takes the number |
|
788 | # accepts it. Probably at least check that the hook takes the number | |
788 | # of args it's supposed to. |
|
789 | # of args it's supposed to. | |
789 |
|
790 | |||
790 | f = types.MethodType(hook,self) |
|
791 | f = types.MethodType(hook,self) | |
791 |
|
792 | |||
792 | # check if the hook is for strdispatcher first |
|
793 | # check if the hook is for strdispatcher first | |
793 | if str_key is not None: |
|
794 | if str_key is not None: | |
794 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
795 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
795 | sdp.add_s(str_key, f, priority ) |
|
796 | sdp.add_s(str_key, f, priority ) | |
796 | self.strdispatchers[name] = sdp |
|
797 | self.strdispatchers[name] = sdp | |
797 | return |
|
798 | return | |
798 | if re_key is not None: |
|
799 | if re_key is not None: | |
799 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
800 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
800 | sdp.add_re(re.compile(re_key), f, priority ) |
|
801 | sdp.add_re(re.compile(re_key), f, priority ) | |
801 | self.strdispatchers[name] = sdp |
|
802 | self.strdispatchers[name] = sdp | |
802 | return |
|
803 | return | |
803 |
|
804 | |||
804 | dp = getattr(self.hooks, name, None) |
|
805 | dp = getattr(self.hooks, name, None) | |
805 | if name not in IPython.core.hooks.__all__: |
|
806 | if name not in IPython.core.hooks.__all__: | |
806 | print("Warning! Hook '%s' is not one of %s" % \ |
|
807 | print("Warning! Hook '%s' is not one of %s" % \ | |
807 | (name, IPython.core.hooks.__all__ )) |
|
808 | (name, IPython.core.hooks.__all__ )) | |
808 | if not dp: |
|
809 | if not dp: | |
809 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
810 | dp = IPython.core.hooks.CommandChainDispatcher() | |
810 |
|
811 | |||
811 | try: |
|
812 | try: | |
812 | dp.add(f,priority) |
|
813 | dp.add(f,priority) | |
813 | except AttributeError: |
|
814 | except AttributeError: | |
814 | # it was not commandchain, plain old func - replace |
|
815 | # it was not commandchain, plain old func - replace | |
815 | dp = f |
|
816 | dp = f | |
816 |
|
817 | |||
817 | setattr(self.hooks,name, dp) |
|
818 | setattr(self.hooks,name, dp) | |
818 |
|
819 | |||
819 | def register_post_execute(self, func): |
|
820 | def register_post_execute(self, func): | |
820 | """Register a function for calling after code execution. |
|
821 | """Register a function for calling after code execution. | |
821 | """ |
|
822 | """ | |
822 | if not callable(func): |
|
823 | if not callable(func): | |
823 | raise ValueError('argument %s must be callable' % func) |
|
824 | raise ValueError('argument %s must be callable' % func) | |
824 | self._post_execute[func] = True |
|
825 | self._post_execute[func] = True | |
825 |
|
826 | |||
826 | #------------------------------------------------------------------------- |
|
827 | #------------------------------------------------------------------------- | |
827 | # Things related to the "main" module |
|
828 | # Things related to the "main" module | |
828 | #------------------------------------------------------------------------- |
|
829 | #------------------------------------------------------------------------- | |
829 |
|
830 | |||
830 | def new_main_mod(self, filename, modname): |
|
831 | def new_main_mod(self, filename, modname): | |
831 | """Return a new 'main' module object for user code execution. |
|
832 | """Return a new 'main' module object for user code execution. | |
832 |
|
833 | |||
833 | ``filename`` should be the path of the script which will be run in the |
|
834 | ``filename`` should be the path of the script which will be run in the | |
834 | module. Requests with the same filename will get the same module, with |
|
835 | module. Requests with the same filename will get the same module, with | |
835 | its namespace cleared. |
|
836 | its namespace cleared. | |
836 |
|
837 | |||
837 | ``modname`` should be the module name - normally either '__main__' or |
|
838 | ``modname`` should be the module name - normally either '__main__' or | |
838 | the basename of the file without the extension. |
|
839 | the basename of the file without the extension. | |
839 |
|
840 | |||
840 | When scripts are executed via %run, we must keep a reference to their |
|
841 | When scripts are executed via %run, we must keep a reference to their | |
841 | __main__ module around so that Python doesn't |
|
842 | __main__ module around so that Python doesn't | |
842 | clear it, rendering references to module globals useless. |
|
843 | clear it, rendering references to module globals useless. | |
843 |
|
844 | |||
844 | This method keeps said reference in a private dict, keyed by the |
|
845 | This method keeps said reference in a private dict, keyed by the | |
845 | absolute path of the script. This way, for multiple executions of the |
|
846 | absolute path of the script. This way, for multiple executions of the | |
846 | same script we only keep one copy of the namespace (the last one), |
|
847 | same script we only keep one copy of the namespace (the last one), | |
847 | thus preventing memory leaks from old references while allowing the |
|
848 | thus preventing memory leaks from old references while allowing the | |
848 | objects from the last execution to be accessible. |
|
849 | objects from the last execution to be accessible. | |
849 | """ |
|
850 | """ | |
850 | filename = os.path.abspath(filename) |
|
851 | filename = os.path.abspath(filename) | |
851 | try: |
|
852 | try: | |
852 | main_mod = self._main_mod_cache[filename] |
|
853 | main_mod = self._main_mod_cache[filename] | |
853 | except KeyError: |
|
854 | except KeyError: | |
854 | main_mod = self._main_mod_cache[filename] = types.ModuleType(modname, |
|
855 | main_mod = self._main_mod_cache[filename] = types.ModuleType(modname, | |
855 | doc="Module created for script run in IPython") |
|
856 | doc="Module created for script run in IPython") | |
856 | else: |
|
857 | else: | |
857 | main_mod.__dict__.clear() |
|
858 | main_mod.__dict__.clear() | |
858 | main_mod.__name__ = modname |
|
859 | main_mod.__name__ = modname | |
859 |
|
860 | |||
860 | main_mod.__file__ = filename |
|
861 | main_mod.__file__ = filename | |
861 | # It seems pydoc (and perhaps others) needs any module instance to |
|
862 | # It seems pydoc (and perhaps others) needs any module instance to | |
862 | # implement a __nonzero__ method |
|
863 | # implement a __nonzero__ method | |
863 | main_mod.__nonzero__ = lambda : True |
|
864 | main_mod.__nonzero__ = lambda : True | |
864 |
|
865 | |||
865 | return main_mod |
|
866 | return main_mod | |
866 |
|
867 | |||
867 | def clear_main_mod_cache(self): |
|
868 | def clear_main_mod_cache(self): | |
868 | """Clear the cache of main modules. |
|
869 | """Clear the cache of main modules. | |
869 |
|
870 | |||
870 | Mainly for use by utilities like %reset. |
|
871 | Mainly for use by utilities like %reset. | |
871 |
|
872 | |||
872 | Examples |
|
873 | Examples | |
873 | -------- |
|
874 | -------- | |
874 |
|
875 | |||
875 | In [15]: import IPython |
|
876 | In [15]: import IPython | |
876 |
|
877 | |||
877 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
878 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') | |
878 |
|
879 | |||
879 | In [17]: len(_ip._main_mod_cache) > 0 |
|
880 | In [17]: len(_ip._main_mod_cache) > 0 | |
880 | Out[17]: True |
|
881 | Out[17]: True | |
881 |
|
882 | |||
882 | In [18]: _ip.clear_main_mod_cache() |
|
883 | In [18]: _ip.clear_main_mod_cache() | |
883 |
|
884 | |||
884 | In [19]: len(_ip._main_mod_cache) == 0 |
|
885 | In [19]: len(_ip._main_mod_cache) == 0 | |
885 | Out[19]: True |
|
886 | Out[19]: True | |
886 | """ |
|
887 | """ | |
887 | self._main_mod_cache.clear() |
|
888 | self._main_mod_cache.clear() | |
888 |
|
889 | |||
889 | #------------------------------------------------------------------------- |
|
890 | #------------------------------------------------------------------------- | |
890 | # Things related to debugging |
|
891 | # Things related to debugging | |
891 | #------------------------------------------------------------------------- |
|
892 | #------------------------------------------------------------------------- | |
892 |
|
893 | |||
893 | def init_pdb(self): |
|
894 | def init_pdb(self): | |
894 | # Set calling of pdb on exceptions |
|
895 | # Set calling of pdb on exceptions | |
895 | # self.call_pdb is a property |
|
896 | # self.call_pdb is a property | |
896 | self.call_pdb = self.pdb |
|
897 | self.call_pdb = self.pdb | |
897 |
|
898 | |||
898 | def _get_call_pdb(self): |
|
899 | def _get_call_pdb(self): | |
899 | return self._call_pdb |
|
900 | return self._call_pdb | |
900 |
|
901 | |||
901 | def _set_call_pdb(self,val): |
|
902 | def _set_call_pdb(self,val): | |
902 |
|
903 | |||
903 | if val not in (0,1,False,True): |
|
904 | if val not in (0,1,False,True): | |
904 | raise ValueError('new call_pdb value must be boolean') |
|
905 | raise ValueError('new call_pdb value must be boolean') | |
905 |
|
906 | |||
906 | # store value in instance |
|
907 | # store value in instance | |
907 | self._call_pdb = val |
|
908 | self._call_pdb = val | |
908 |
|
909 | |||
909 | # notify the actual exception handlers |
|
910 | # notify the actual exception handlers | |
910 | self.InteractiveTB.call_pdb = val |
|
911 | self.InteractiveTB.call_pdb = val | |
911 |
|
912 | |||
912 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
913 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
913 | 'Control auto-activation of pdb at exceptions') |
|
914 | 'Control auto-activation of pdb at exceptions') | |
914 |
|
915 | |||
915 | def debugger(self,force=False): |
|
916 | def debugger(self,force=False): | |
916 | """Call the pydb/pdb debugger. |
|
917 | """Call the pydb/pdb debugger. | |
917 |
|
918 | |||
918 | Keywords: |
|
919 | Keywords: | |
919 |
|
920 | |||
920 | - force(False): by default, this routine checks the instance call_pdb |
|
921 | - force(False): by default, this routine checks the instance call_pdb | |
921 | flag and does not actually invoke the debugger if the flag is false. |
|
922 | flag and does not actually invoke the debugger if the flag is false. | |
922 | The 'force' option forces the debugger to activate even if the flag |
|
923 | The 'force' option forces the debugger to activate even if the flag | |
923 | is false. |
|
924 | is false. | |
924 | """ |
|
925 | """ | |
925 |
|
926 | |||
926 | if not (force or self.call_pdb): |
|
927 | if not (force or self.call_pdb): | |
927 | return |
|
928 | return | |
928 |
|
929 | |||
929 | if not hasattr(sys,'last_traceback'): |
|
930 | if not hasattr(sys,'last_traceback'): | |
930 | error('No traceback has been produced, nothing to debug.') |
|
931 | error('No traceback has been produced, nothing to debug.') | |
931 | return |
|
932 | return | |
932 |
|
933 | |||
933 | # use pydb if available |
|
934 | # use pydb if available | |
934 | if debugger.has_pydb: |
|
935 | if debugger.has_pydb: | |
935 | from pydb import pm |
|
936 | from pydb import pm | |
936 | else: |
|
937 | else: | |
937 | # fallback to our internal debugger |
|
938 | # fallback to our internal debugger | |
938 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
939 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
939 |
|
940 | |||
940 | with self.readline_no_record: |
|
941 | with self.readline_no_record: | |
941 | pm() |
|
942 | pm() | |
942 |
|
943 | |||
943 | #------------------------------------------------------------------------- |
|
944 | #------------------------------------------------------------------------- | |
944 | # Things related to IPython's various namespaces |
|
945 | # Things related to IPython's various namespaces | |
945 | #------------------------------------------------------------------------- |
|
946 | #------------------------------------------------------------------------- | |
946 | default_user_namespaces = True |
|
947 | default_user_namespaces = True | |
947 |
|
948 | |||
948 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
949 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
949 | # Create the namespace where the user will operate. user_ns is |
|
950 | # Create the namespace where the user will operate. user_ns is | |
950 | # normally the only one used, and it is passed to the exec calls as |
|
951 | # normally the only one used, and it is passed to the exec calls as | |
951 | # the locals argument. But we do carry a user_global_ns namespace |
|
952 | # the locals argument. But we do carry a user_global_ns namespace | |
952 | # given as the exec 'globals' argument, This is useful in embedding |
|
953 | # given as the exec 'globals' argument, This is useful in embedding | |
953 | # situations where the ipython shell opens in a context where the |
|
954 | # situations where the ipython shell opens in a context where the | |
954 | # distinction between locals and globals is meaningful. For |
|
955 | # distinction between locals and globals is meaningful. For | |
955 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
956 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
956 |
|
957 | |||
957 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
958 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
958 | # level as a dict instead of a module. This is a manual fix, but I |
|
959 | # level as a dict instead of a module. This is a manual fix, but I | |
959 | # should really track down where the problem is coming from. Alex |
|
960 | # should really track down where the problem is coming from. Alex | |
960 | # Schmolck reported this problem first. |
|
961 | # Schmolck reported this problem first. | |
961 |
|
962 | |||
962 | # A useful post by Alex Martelli on this topic: |
|
963 | # A useful post by Alex Martelli on this topic: | |
963 | # Re: inconsistent value from __builtins__ |
|
964 | # Re: inconsistent value from __builtins__ | |
964 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
965 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
965 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
966 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
966 | # Gruppen: comp.lang.python |
|
967 | # Gruppen: comp.lang.python | |
967 |
|
968 | |||
968 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
969 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
969 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
970 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
970 | # > <type 'dict'> |
|
971 | # > <type 'dict'> | |
971 | # > >>> print type(__builtins__) |
|
972 | # > >>> print type(__builtins__) | |
972 | # > <type 'module'> |
|
973 | # > <type 'module'> | |
973 | # > Is this difference in return value intentional? |
|
974 | # > Is this difference in return value intentional? | |
974 |
|
975 | |||
975 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
976 | # Well, it's documented that '__builtins__' can be either a dictionary | |
976 | # or a module, and it's been that way for a long time. Whether it's |
|
977 | # or a module, and it's been that way for a long time. Whether it's | |
977 | # intentional (or sensible), I don't know. In any case, the idea is |
|
978 | # intentional (or sensible), I don't know. In any case, the idea is | |
978 | # that if you need to access the built-in namespace directly, you |
|
979 | # that if you need to access the built-in namespace directly, you | |
979 | # should start with "import __builtin__" (note, no 's') which will |
|
980 | # should start with "import __builtin__" (note, no 's') which will | |
980 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
981 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
981 |
|
982 | |||
982 | # These routines return a properly built module and dict as needed by |
|
983 | # These routines return a properly built module and dict as needed by | |
983 | # the rest of the code, and can also be used by extension writers to |
|
984 | # the rest of the code, and can also be used by extension writers to | |
984 | # generate properly initialized namespaces. |
|
985 | # generate properly initialized namespaces. | |
985 | if (user_ns is not None) or (user_module is not None): |
|
986 | if (user_ns is not None) or (user_module is not None): | |
986 | self.default_user_namespaces = False |
|
987 | self.default_user_namespaces = False | |
987 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
988 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
988 |
|
989 | |||
989 | # A record of hidden variables we have added to the user namespace, so |
|
990 | # A record of hidden variables we have added to the user namespace, so | |
990 | # we can list later only variables defined in actual interactive use. |
|
991 | # we can list later only variables defined in actual interactive use. | |
991 | self.user_ns_hidden = {} |
|
992 | self.user_ns_hidden = {} | |
992 |
|
993 | |||
993 | # Now that FakeModule produces a real module, we've run into a nasty |
|
994 | # Now that FakeModule produces a real module, we've run into a nasty | |
994 | # problem: after script execution (via %run), the module where the user |
|
995 | # problem: after script execution (via %run), the module where the user | |
995 | # code ran is deleted. Now that this object is a true module (needed |
|
996 | # code ran is deleted. Now that this object is a true module (needed | |
996 | # so docetst and other tools work correctly), the Python module |
|
997 | # so docetst and other tools work correctly), the Python module | |
997 | # teardown mechanism runs over it, and sets to None every variable |
|
998 | # teardown mechanism runs over it, and sets to None every variable | |
998 | # present in that module. Top-level references to objects from the |
|
999 | # present in that module. Top-level references to objects from the | |
999 | # script survive, because the user_ns is updated with them. However, |
|
1000 | # script survive, because the user_ns is updated with them. However, | |
1000 | # calling functions defined in the script that use other things from |
|
1001 | # calling functions defined in the script that use other things from | |
1001 | # the script will fail, because the function's closure had references |
|
1002 | # the script will fail, because the function's closure had references | |
1002 | # to the original objects, which are now all None. So we must protect |
|
1003 | # to the original objects, which are now all None. So we must protect | |
1003 | # these modules from deletion by keeping a cache. |
|
1004 | # these modules from deletion by keeping a cache. | |
1004 | # |
|
1005 | # | |
1005 | # To avoid keeping stale modules around (we only need the one from the |
|
1006 | # To avoid keeping stale modules around (we only need the one from the | |
1006 | # last run), we use a dict keyed with the full path to the script, so |
|
1007 | # last run), we use a dict keyed with the full path to the script, so | |
1007 | # only the last version of the module is held in the cache. Note, |
|
1008 | # only the last version of the module is held in the cache. Note, | |
1008 | # however, that we must cache the module *namespace contents* (their |
|
1009 | # however, that we must cache the module *namespace contents* (their | |
1009 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1010 | # __dict__). Because if we try to cache the actual modules, old ones | |
1010 | # (uncached) could be destroyed while still holding references (such as |
|
1011 | # (uncached) could be destroyed while still holding references (such as | |
1011 | # those held by GUI objects that tend to be long-lived)> |
|
1012 | # those held by GUI objects that tend to be long-lived)> | |
1012 | # |
|
1013 | # | |
1013 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1014 | # The %reset command will flush this cache. See the cache_main_mod() | |
1014 | # and clear_main_mod_cache() methods for details on use. |
|
1015 | # and clear_main_mod_cache() methods for details on use. | |
1015 |
|
1016 | |||
1016 | # This is the cache used for 'main' namespaces |
|
1017 | # This is the cache used for 'main' namespaces | |
1017 | self._main_mod_cache = {} |
|
1018 | self._main_mod_cache = {} | |
1018 |
|
1019 | |||
1019 | # A table holding all the namespaces IPython deals with, so that |
|
1020 | # A table holding all the namespaces IPython deals with, so that | |
1020 | # introspection facilities can search easily. |
|
1021 | # introspection facilities can search easily. | |
1021 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1022 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1022 | 'user_local':self.user_ns, |
|
1023 | 'user_local':self.user_ns, | |
1023 | 'builtin':builtin_mod.__dict__ |
|
1024 | 'builtin':builtin_mod.__dict__ | |
1024 | } |
|
1025 | } | |
1025 |
|
1026 | |||
1026 | @property |
|
1027 | @property | |
1027 | def user_global_ns(self): |
|
1028 | def user_global_ns(self): | |
1028 | return self.user_module.__dict__ |
|
1029 | return self.user_module.__dict__ | |
1029 |
|
1030 | |||
1030 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1031 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1031 | """Prepare the module and namespace in which user code will be run. |
|
1032 | """Prepare the module and namespace in which user code will be run. | |
1032 |
|
1033 | |||
1033 | When IPython is started normally, both parameters are None: a new module |
|
1034 | When IPython is started normally, both parameters are None: a new module | |
1034 | is created automatically, and its __dict__ used as the namespace. |
|
1035 | is created automatically, and its __dict__ used as the namespace. | |
1035 |
|
1036 | |||
1036 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1037 | If only user_module is provided, its __dict__ is used as the namespace. | |
1037 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1038 | If only user_ns is provided, a dummy module is created, and user_ns | |
1038 | becomes the global namespace. If both are provided (as they may be |
|
1039 | becomes the global namespace. If both are provided (as they may be | |
1039 | when embedding), user_ns is the local namespace, and user_module |
|
1040 | when embedding), user_ns is the local namespace, and user_module | |
1040 | provides the global namespace. |
|
1041 | provides the global namespace. | |
1041 |
|
1042 | |||
1042 | Parameters |
|
1043 | Parameters | |
1043 | ---------- |
|
1044 | ---------- | |
1044 | user_module : module, optional |
|
1045 | user_module : module, optional | |
1045 | The current user module in which IPython is being run. If None, |
|
1046 | The current user module in which IPython is being run. If None, | |
1046 | a clean module will be created. |
|
1047 | a clean module will be created. | |
1047 | user_ns : dict, optional |
|
1048 | user_ns : dict, optional | |
1048 | A namespace in which to run interactive commands. |
|
1049 | A namespace in which to run interactive commands. | |
1049 |
|
1050 | |||
1050 | Returns |
|
1051 | Returns | |
1051 | ------- |
|
1052 | ------- | |
1052 | A tuple of user_module and user_ns, each properly initialised. |
|
1053 | A tuple of user_module and user_ns, each properly initialised. | |
1053 | """ |
|
1054 | """ | |
1054 | if user_module is None and user_ns is not None: |
|
1055 | if user_module is None and user_ns is not None: | |
1055 | user_ns.setdefault("__name__", "__main__") |
|
1056 | user_ns.setdefault("__name__", "__main__") | |
1056 | user_module = DummyMod() |
|
1057 | user_module = DummyMod() | |
1057 | user_module.__dict__ = user_ns |
|
1058 | user_module.__dict__ = user_ns | |
1058 |
|
1059 | |||
1059 | if user_module is None: |
|
1060 | if user_module is None: | |
1060 | user_module = types.ModuleType("__main__", |
|
1061 | user_module = types.ModuleType("__main__", | |
1061 | doc="Automatically created module for IPython interactive environment") |
|
1062 | doc="Automatically created module for IPython interactive environment") | |
1062 |
|
1063 | |||
1063 | # We must ensure that __builtin__ (without the final 's') is always |
|
1064 | # We must ensure that __builtin__ (without the final 's') is always | |
1064 | # available and pointing to the __builtin__ *module*. For more details: |
|
1065 | # available and pointing to the __builtin__ *module*. For more details: | |
1065 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1066 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1066 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1067 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1067 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1068 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1068 |
|
1069 | |||
1069 | if user_ns is None: |
|
1070 | if user_ns is None: | |
1070 | user_ns = user_module.__dict__ |
|
1071 | user_ns = user_module.__dict__ | |
1071 |
|
1072 | |||
1072 | return user_module, user_ns |
|
1073 | return user_module, user_ns | |
1073 |
|
1074 | |||
1074 | def init_sys_modules(self): |
|
1075 | def init_sys_modules(self): | |
1075 | # We need to insert into sys.modules something that looks like a |
|
1076 | # We need to insert into sys.modules something that looks like a | |
1076 | # module but which accesses the IPython namespace, for shelve and |
|
1077 | # module but which accesses the IPython namespace, for shelve and | |
1077 | # pickle to work interactively. Normally they rely on getting |
|
1078 | # pickle to work interactively. Normally they rely on getting | |
1078 | # everything out of __main__, but for embedding purposes each IPython |
|
1079 | # everything out of __main__, but for embedding purposes each IPython | |
1079 | # instance has its own private namespace, so we can't go shoving |
|
1080 | # instance has its own private namespace, so we can't go shoving | |
1080 | # everything into __main__. |
|
1081 | # everything into __main__. | |
1081 |
|
1082 | |||
1082 | # note, however, that we should only do this for non-embedded |
|
1083 | # note, however, that we should only do this for non-embedded | |
1083 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1084 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1084 | # namespace. Embedded instances, on the other hand, should not do |
|
1085 | # namespace. Embedded instances, on the other hand, should not do | |
1085 | # this because they need to manage the user local/global namespaces |
|
1086 | # this because they need to manage the user local/global namespaces | |
1086 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1087 | # only, but they live within a 'normal' __main__ (meaning, they | |
1087 | # shouldn't overtake the execution environment of the script they're |
|
1088 | # shouldn't overtake the execution environment of the script they're | |
1088 | # embedded in). |
|
1089 | # embedded in). | |
1089 |
|
1090 | |||
1090 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1091 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1091 | main_name = self.user_module.__name__ |
|
1092 | main_name = self.user_module.__name__ | |
1092 | sys.modules[main_name] = self.user_module |
|
1093 | sys.modules[main_name] = self.user_module | |
1093 |
|
1094 | |||
1094 | def init_user_ns(self): |
|
1095 | def init_user_ns(self): | |
1095 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1096 | """Initialize all user-visible namespaces to their minimum defaults. | |
1096 |
|
1097 | |||
1097 | Certain history lists are also initialized here, as they effectively |
|
1098 | Certain history lists are also initialized here, as they effectively | |
1098 | act as user namespaces. |
|
1099 | act as user namespaces. | |
1099 |
|
1100 | |||
1100 | Notes |
|
1101 | Notes | |
1101 | ----- |
|
1102 | ----- | |
1102 | All data structures here are only filled in, they are NOT reset by this |
|
1103 | All data structures here are only filled in, they are NOT reset by this | |
1103 | method. If they were not empty before, data will simply be added to |
|
1104 | method. If they were not empty before, data will simply be added to | |
1104 | therm. |
|
1105 | therm. | |
1105 | """ |
|
1106 | """ | |
1106 | # This function works in two parts: first we put a few things in |
|
1107 | # This function works in two parts: first we put a few things in | |
1107 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1108 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1108 | # initial variables aren't shown by %who. After the sync, we add the |
|
1109 | # initial variables aren't shown by %who. After the sync, we add the | |
1109 | # rest of what we *do* want the user to see with %who even on a new |
|
1110 | # rest of what we *do* want the user to see with %who even on a new | |
1110 | # session (probably nothing, so theye really only see their own stuff) |
|
1111 | # session (probably nothing, so theye really only see their own stuff) | |
1111 |
|
1112 | |||
1112 | # The user dict must *always* have a __builtin__ reference to the |
|
1113 | # The user dict must *always* have a __builtin__ reference to the | |
1113 | # Python standard __builtin__ namespace, which must be imported. |
|
1114 | # Python standard __builtin__ namespace, which must be imported. | |
1114 | # This is so that certain operations in prompt evaluation can be |
|
1115 | # This is so that certain operations in prompt evaluation can be | |
1115 | # reliably executed with builtins. Note that we can NOT use |
|
1116 | # reliably executed with builtins. Note that we can NOT use | |
1116 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1117 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1117 | # module, and can even mutate at runtime, depending on the context |
|
1118 | # module, and can even mutate at runtime, depending on the context | |
1118 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1119 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1119 | # always a module object, though it must be explicitly imported. |
|
1120 | # always a module object, though it must be explicitly imported. | |
1120 |
|
1121 | |||
1121 | # For more details: |
|
1122 | # For more details: | |
1122 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1123 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1123 | ns = dict() |
|
1124 | ns = dict() | |
1124 |
|
1125 | |||
1125 | # Put 'help' in the user namespace |
|
1126 | # Put 'help' in the user namespace | |
1126 | try: |
|
1127 | try: | |
1127 | from site import _Helper |
|
1128 | from site import _Helper | |
1128 | ns['help'] = _Helper() |
|
1129 | ns['help'] = _Helper() | |
1129 | except ImportError: |
|
1130 | except ImportError: | |
1130 | warn('help() not available - check site.py') |
|
1131 | warn('help() not available - check site.py') | |
1131 |
|
1132 | |||
1132 | # make global variables for user access to the histories |
|
1133 | # make global variables for user access to the histories | |
1133 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1134 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1134 | ns['_oh'] = self.history_manager.output_hist |
|
1135 | ns['_oh'] = self.history_manager.output_hist | |
1135 | ns['_dh'] = self.history_manager.dir_hist |
|
1136 | ns['_dh'] = self.history_manager.dir_hist | |
1136 |
|
1137 | |||
1137 | ns['_sh'] = shadowns |
|
1138 | ns['_sh'] = shadowns | |
1138 |
|
1139 | |||
1139 | # user aliases to input and output histories. These shouldn't show up |
|
1140 | # user aliases to input and output histories. These shouldn't show up | |
1140 | # in %who, as they can have very large reprs. |
|
1141 | # in %who, as they can have very large reprs. | |
1141 | ns['In'] = self.history_manager.input_hist_parsed |
|
1142 | ns['In'] = self.history_manager.input_hist_parsed | |
1142 | ns['Out'] = self.history_manager.output_hist |
|
1143 | ns['Out'] = self.history_manager.output_hist | |
1143 |
|
1144 | |||
1144 | # Store myself as the public api!!! |
|
1145 | # Store myself as the public api!!! | |
1145 | ns['get_ipython'] = self.get_ipython |
|
1146 | ns['get_ipython'] = self.get_ipython | |
1146 |
|
1147 | |||
1147 | ns['exit'] = self.exiter |
|
1148 | ns['exit'] = self.exiter | |
1148 | ns['quit'] = self.exiter |
|
1149 | ns['quit'] = self.exiter | |
1149 |
|
1150 | |||
1150 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1151 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1151 | # by %who |
|
1152 | # by %who | |
1152 | self.user_ns_hidden.update(ns) |
|
1153 | self.user_ns_hidden.update(ns) | |
1153 |
|
1154 | |||
1154 | # Anything put into ns now would show up in %who. Think twice before |
|
1155 | # Anything put into ns now would show up in %who. Think twice before | |
1155 | # putting anything here, as we really want %who to show the user their |
|
1156 | # putting anything here, as we really want %who to show the user their | |
1156 | # stuff, not our variables. |
|
1157 | # stuff, not our variables. | |
1157 |
|
1158 | |||
1158 | # Finally, update the real user's namespace |
|
1159 | # Finally, update the real user's namespace | |
1159 | self.user_ns.update(ns) |
|
1160 | self.user_ns.update(ns) | |
1160 |
|
1161 | |||
1161 | @property |
|
1162 | @property | |
1162 | def all_ns_refs(self): |
|
1163 | def all_ns_refs(self): | |
1163 | """Get a list of references to all the namespace dictionaries in which |
|
1164 | """Get a list of references to all the namespace dictionaries in which | |
1164 | IPython might store a user-created object. |
|
1165 | IPython might store a user-created object. | |
1165 |
|
1166 | |||
1166 | Note that this does not include the displayhook, which also caches |
|
1167 | Note that this does not include the displayhook, which also caches | |
1167 | objects from the output.""" |
|
1168 | objects from the output.""" | |
1168 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1169 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ | |
1169 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1170 | [m.__dict__ for m in self._main_mod_cache.values()] | |
1170 |
|
1171 | |||
1171 | def reset(self, new_session=True): |
|
1172 | def reset(self, new_session=True): | |
1172 | """Clear all internal namespaces, and attempt to release references to |
|
1173 | """Clear all internal namespaces, and attempt to release references to | |
1173 | user objects. |
|
1174 | user objects. | |
1174 |
|
1175 | |||
1175 | If new_session is True, a new history session will be opened. |
|
1176 | If new_session is True, a new history session will be opened. | |
1176 | """ |
|
1177 | """ | |
1177 | # Clear histories |
|
1178 | # Clear histories | |
1178 | self.history_manager.reset(new_session) |
|
1179 | self.history_manager.reset(new_session) | |
1179 | # Reset counter used to index all histories |
|
1180 | # Reset counter used to index all histories | |
1180 | if new_session: |
|
1181 | if new_session: | |
1181 | self.execution_count = 1 |
|
1182 | self.execution_count = 1 | |
1182 |
|
1183 | |||
1183 | # Flush cached output items |
|
1184 | # Flush cached output items | |
1184 | if self.displayhook.do_full_cache: |
|
1185 | if self.displayhook.do_full_cache: | |
1185 | self.displayhook.flush() |
|
1186 | self.displayhook.flush() | |
1186 |
|
1187 | |||
1187 | # The main execution namespaces must be cleared very carefully, |
|
1188 | # The main execution namespaces must be cleared very carefully, | |
1188 | # skipping the deletion of the builtin-related keys, because doing so |
|
1189 | # skipping the deletion of the builtin-related keys, because doing so | |
1189 | # would cause errors in many object's __del__ methods. |
|
1190 | # would cause errors in many object's __del__ methods. | |
1190 | if self.user_ns is not self.user_global_ns: |
|
1191 | if self.user_ns is not self.user_global_ns: | |
1191 | self.user_ns.clear() |
|
1192 | self.user_ns.clear() | |
1192 | ns = self.user_global_ns |
|
1193 | ns = self.user_global_ns | |
1193 | drop_keys = set(ns.keys()) |
|
1194 | drop_keys = set(ns.keys()) | |
1194 | drop_keys.discard('__builtin__') |
|
1195 | drop_keys.discard('__builtin__') | |
1195 | drop_keys.discard('__builtins__') |
|
1196 | drop_keys.discard('__builtins__') | |
1196 | drop_keys.discard('__name__') |
|
1197 | drop_keys.discard('__name__') | |
1197 | for k in drop_keys: |
|
1198 | for k in drop_keys: | |
1198 | del ns[k] |
|
1199 | del ns[k] | |
1199 |
|
1200 | |||
1200 | self.user_ns_hidden.clear() |
|
1201 | self.user_ns_hidden.clear() | |
1201 |
|
1202 | |||
1202 | # Restore the user namespaces to minimal usability |
|
1203 | # Restore the user namespaces to minimal usability | |
1203 | self.init_user_ns() |
|
1204 | self.init_user_ns() | |
1204 |
|
1205 | |||
1205 | # Restore the default and user aliases |
|
1206 | # Restore the default and user aliases | |
1206 | self.alias_manager.clear_aliases() |
|
1207 | self.alias_manager.clear_aliases() | |
1207 | self.alias_manager.init_aliases() |
|
1208 | self.alias_manager.init_aliases() | |
1208 |
|
1209 | |||
1209 | # Flush the private list of module references kept for script |
|
1210 | # Flush the private list of module references kept for script | |
1210 | # execution protection |
|
1211 | # execution protection | |
1211 | self.clear_main_mod_cache() |
|
1212 | self.clear_main_mod_cache() | |
1212 |
|
1213 | |||
1213 | def del_var(self, varname, by_name=False): |
|
1214 | def del_var(self, varname, by_name=False): | |
1214 | """Delete a variable from the various namespaces, so that, as |
|
1215 | """Delete a variable from the various namespaces, so that, as | |
1215 | far as possible, we're not keeping any hidden references to it. |
|
1216 | far as possible, we're not keeping any hidden references to it. | |
1216 |
|
1217 | |||
1217 | Parameters |
|
1218 | Parameters | |
1218 | ---------- |
|
1219 | ---------- | |
1219 | varname : str |
|
1220 | varname : str | |
1220 | The name of the variable to delete. |
|
1221 | The name of the variable to delete. | |
1221 | by_name : bool |
|
1222 | by_name : bool | |
1222 | If True, delete variables with the given name in each |
|
1223 | If True, delete variables with the given name in each | |
1223 | namespace. If False (default), find the variable in the user |
|
1224 | namespace. If False (default), find the variable in the user | |
1224 | namespace, and delete references to it. |
|
1225 | namespace, and delete references to it. | |
1225 | """ |
|
1226 | """ | |
1226 | if varname in ('__builtin__', '__builtins__'): |
|
1227 | if varname in ('__builtin__', '__builtins__'): | |
1227 | raise ValueError("Refusing to delete %s" % varname) |
|
1228 | raise ValueError("Refusing to delete %s" % varname) | |
1228 |
|
1229 | |||
1229 | ns_refs = self.all_ns_refs |
|
1230 | ns_refs = self.all_ns_refs | |
1230 |
|
1231 | |||
1231 | if by_name: # Delete by name |
|
1232 | if by_name: # Delete by name | |
1232 | for ns in ns_refs: |
|
1233 | for ns in ns_refs: | |
1233 | try: |
|
1234 | try: | |
1234 | del ns[varname] |
|
1235 | del ns[varname] | |
1235 | except KeyError: |
|
1236 | except KeyError: | |
1236 | pass |
|
1237 | pass | |
1237 | else: # Delete by object |
|
1238 | else: # Delete by object | |
1238 | try: |
|
1239 | try: | |
1239 | obj = self.user_ns[varname] |
|
1240 | obj = self.user_ns[varname] | |
1240 | except KeyError: |
|
1241 | except KeyError: | |
1241 | raise NameError("name '%s' is not defined" % varname) |
|
1242 | raise NameError("name '%s' is not defined" % varname) | |
1242 | # Also check in output history |
|
1243 | # Also check in output history | |
1243 | ns_refs.append(self.history_manager.output_hist) |
|
1244 | ns_refs.append(self.history_manager.output_hist) | |
1244 | for ns in ns_refs: |
|
1245 | for ns in ns_refs: | |
1245 | to_delete = [n for n, o in ns.iteritems() if o is obj] |
|
1246 | to_delete = [n for n, o in ns.iteritems() if o is obj] | |
1246 | for name in to_delete: |
|
1247 | for name in to_delete: | |
1247 | del ns[name] |
|
1248 | del ns[name] | |
1248 |
|
1249 | |||
1249 | # displayhook keeps extra references, but not in a dictionary |
|
1250 | # displayhook keeps extra references, but not in a dictionary | |
1250 | for name in ('_', '__', '___'): |
|
1251 | for name in ('_', '__', '___'): | |
1251 | if getattr(self.displayhook, name) is obj: |
|
1252 | if getattr(self.displayhook, name) is obj: | |
1252 | setattr(self.displayhook, name, None) |
|
1253 | setattr(self.displayhook, name, None) | |
1253 |
|
1254 | |||
1254 | def reset_selective(self, regex=None): |
|
1255 | def reset_selective(self, regex=None): | |
1255 | """Clear selective variables from internal namespaces based on a |
|
1256 | """Clear selective variables from internal namespaces based on a | |
1256 | specified regular expression. |
|
1257 | specified regular expression. | |
1257 |
|
1258 | |||
1258 | Parameters |
|
1259 | Parameters | |
1259 | ---------- |
|
1260 | ---------- | |
1260 | regex : string or compiled pattern, optional |
|
1261 | regex : string or compiled pattern, optional | |
1261 | A regular expression pattern that will be used in searching |
|
1262 | A regular expression pattern that will be used in searching | |
1262 | variable names in the users namespaces. |
|
1263 | variable names in the users namespaces. | |
1263 | """ |
|
1264 | """ | |
1264 | if regex is not None: |
|
1265 | if regex is not None: | |
1265 | try: |
|
1266 | try: | |
1266 | m = re.compile(regex) |
|
1267 | m = re.compile(regex) | |
1267 | except TypeError: |
|
1268 | except TypeError: | |
1268 | raise TypeError('regex must be a string or compiled pattern') |
|
1269 | raise TypeError('regex must be a string or compiled pattern') | |
1269 | # Search for keys in each namespace that match the given regex |
|
1270 | # Search for keys in each namespace that match the given regex | |
1270 | # If a match is found, delete the key/value pair. |
|
1271 | # If a match is found, delete the key/value pair. | |
1271 | for ns in self.all_ns_refs: |
|
1272 | for ns in self.all_ns_refs: | |
1272 | for var in ns: |
|
1273 | for var in ns: | |
1273 | if m.search(var): |
|
1274 | if m.search(var): | |
1274 | del ns[var] |
|
1275 | del ns[var] | |
1275 |
|
1276 | |||
1276 | def push(self, variables, interactive=True): |
|
1277 | def push(self, variables, interactive=True): | |
1277 | """Inject a group of variables into the IPython user namespace. |
|
1278 | """Inject a group of variables into the IPython user namespace. | |
1278 |
|
1279 | |||
1279 | Parameters |
|
1280 | Parameters | |
1280 | ---------- |
|
1281 | ---------- | |
1281 | variables : dict, str or list/tuple of str |
|
1282 | variables : dict, str or list/tuple of str | |
1282 | The variables to inject into the user's namespace. If a dict, a |
|
1283 | The variables to inject into the user's namespace. If a dict, a | |
1283 | simple update is done. If a str, the string is assumed to have |
|
1284 | simple update is done. If a str, the string is assumed to have | |
1284 | variable names separated by spaces. A list/tuple of str can also |
|
1285 | variable names separated by spaces. A list/tuple of str can also | |
1285 | be used to give the variable names. If just the variable names are |
|
1286 | be used to give the variable names. If just the variable names are | |
1286 | give (list/tuple/str) then the variable values looked up in the |
|
1287 | give (list/tuple/str) then the variable values looked up in the | |
1287 | callers frame. |
|
1288 | callers frame. | |
1288 | interactive : bool |
|
1289 | interactive : bool | |
1289 | If True (default), the variables will be listed with the ``who`` |
|
1290 | If True (default), the variables will be listed with the ``who`` | |
1290 | magic. |
|
1291 | magic. | |
1291 | """ |
|
1292 | """ | |
1292 | vdict = None |
|
1293 | vdict = None | |
1293 |
|
1294 | |||
1294 | # We need a dict of name/value pairs to do namespace updates. |
|
1295 | # We need a dict of name/value pairs to do namespace updates. | |
1295 | if isinstance(variables, dict): |
|
1296 | if isinstance(variables, dict): | |
1296 | vdict = variables |
|
1297 | vdict = variables | |
1297 | elif isinstance(variables, string_types+(list, tuple)): |
|
1298 | elif isinstance(variables, string_types+(list, tuple)): | |
1298 | if isinstance(variables, string_types): |
|
1299 | if isinstance(variables, string_types): | |
1299 | vlist = variables.split() |
|
1300 | vlist = variables.split() | |
1300 | else: |
|
1301 | else: | |
1301 | vlist = variables |
|
1302 | vlist = variables | |
1302 | vdict = {} |
|
1303 | vdict = {} | |
1303 | cf = sys._getframe(1) |
|
1304 | cf = sys._getframe(1) | |
1304 | for name in vlist: |
|
1305 | for name in vlist: | |
1305 | try: |
|
1306 | try: | |
1306 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1307 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1307 | except: |
|
1308 | except: | |
1308 | print('Could not get variable %s from %s' % |
|
1309 | print('Could not get variable %s from %s' % | |
1309 | (name,cf.f_code.co_name)) |
|
1310 | (name,cf.f_code.co_name)) | |
1310 | else: |
|
1311 | else: | |
1311 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1312 | raise ValueError('variables must be a dict/str/list/tuple') | |
1312 |
|
1313 | |||
1313 | # Propagate variables to user namespace |
|
1314 | # Propagate variables to user namespace | |
1314 | self.user_ns.update(vdict) |
|
1315 | self.user_ns.update(vdict) | |
1315 |
|
1316 | |||
1316 | # And configure interactive visibility |
|
1317 | # And configure interactive visibility | |
1317 | user_ns_hidden = self.user_ns_hidden |
|
1318 | user_ns_hidden = self.user_ns_hidden | |
1318 | if interactive: |
|
1319 | if interactive: | |
1319 | for name in vdict: |
|
1320 | for name in vdict: | |
1320 | user_ns_hidden.pop(name, None) |
|
1321 | user_ns_hidden.pop(name, None) | |
1321 | else: |
|
1322 | else: | |
1322 | user_ns_hidden.update(vdict) |
|
1323 | user_ns_hidden.update(vdict) | |
1323 |
|
1324 | |||
1324 | def drop_by_id(self, variables): |
|
1325 | def drop_by_id(self, variables): | |
1325 | """Remove a dict of variables from the user namespace, if they are the |
|
1326 | """Remove a dict of variables from the user namespace, if they are the | |
1326 | same as the values in the dictionary. |
|
1327 | same as the values in the dictionary. | |
1327 |
|
1328 | |||
1328 | This is intended for use by extensions: variables that they've added can |
|
1329 | This is intended for use by extensions: variables that they've added can | |
1329 | be taken back out if they are unloaded, without removing any that the |
|
1330 | be taken back out if they are unloaded, without removing any that the | |
1330 | user has overwritten. |
|
1331 | user has overwritten. | |
1331 |
|
1332 | |||
1332 | Parameters |
|
1333 | Parameters | |
1333 | ---------- |
|
1334 | ---------- | |
1334 | variables : dict |
|
1335 | variables : dict | |
1335 | A dictionary mapping object names (as strings) to the objects. |
|
1336 | A dictionary mapping object names (as strings) to the objects. | |
1336 | """ |
|
1337 | """ | |
1337 | for name, obj in variables.iteritems(): |
|
1338 | for name, obj in variables.iteritems(): | |
1338 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1339 | if name in self.user_ns and self.user_ns[name] is obj: | |
1339 | del self.user_ns[name] |
|
1340 | del self.user_ns[name] | |
1340 | self.user_ns_hidden.pop(name, None) |
|
1341 | self.user_ns_hidden.pop(name, None) | |
1341 |
|
1342 | |||
1342 | #------------------------------------------------------------------------- |
|
1343 | #------------------------------------------------------------------------- | |
1343 | # Things related to object introspection |
|
1344 | # Things related to object introspection | |
1344 | #------------------------------------------------------------------------- |
|
1345 | #------------------------------------------------------------------------- | |
1345 |
|
1346 | |||
1346 | def _ofind(self, oname, namespaces=None): |
|
1347 | def _ofind(self, oname, namespaces=None): | |
1347 | """Find an object in the available namespaces. |
|
1348 | """Find an object in the available namespaces. | |
1348 |
|
1349 | |||
1349 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1350 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1350 |
|
1351 | |||
1351 | Has special code to detect magic functions. |
|
1352 | Has special code to detect magic functions. | |
1352 | """ |
|
1353 | """ | |
1353 | oname = oname.strip() |
|
1354 | oname = oname.strip() | |
1354 | #print '1- oname: <%r>' % oname # dbg |
|
1355 | #print '1- oname: <%r>' % oname # dbg | |
1355 | if not oname.startswith(ESC_MAGIC) and \ |
|
1356 | if not oname.startswith(ESC_MAGIC) and \ | |
1356 | not oname.startswith(ESC_MAGIC2) and \ |
|
1357 | not oname.startswith(ESC_MAGIC2) and \ | |
1357 | not py3compat.isidentifier(oname, dotted=True): |
|
1358 | not py3compat.isidentifier(oname, dotted=True): | |
1358 | return dict(found=False) |
|
1359 | return dict(found=False) | |
1359 |
|
1360 | |||
1360 | alias_ns = None |
|
1361 | alias_ns = None | |
1361 | if namespaces is None: |
|
1362 | if namespaces is None: | |
1362 | # Namespaces to search in: |
|
1363 | # Namespaces to search in: | |
1363 | # Put them in a list. The order is important so that we |
|
1364 | # Put them in a list. The order is important so that we | |
1364 | # find things in the same order that Python finds them. |
|
1365 | # find things in the same order that Python finds them. | |
1365 | namespaces = [ ('Interactive', self.user_ns), |
|
1366 | namespaces = [ ('Interactive', self.user_ns), | |
1366 | ('Interactive (global)', self.user_global_ns), |
|
1367 | ('Interactive (global)', self.user_global_ns), | |
1367 | ('Python builtin', builtin_mod.__dict__), |
|
1368 | ('Python builtin', builtin_mod.__dict__), | |
1368 | ] |
|
1369 | ] | |
1369 |
|
1370 | |||
1370 | # initialize results to 'null' |
|
1371 | # initialize results to 'null' | |
1371 | found = False; obj = None; ospace = None; ds = None; |
|
1372 | found = False; obj = None; ospace = None; ds = None; | |
1372 | ismagic = False; isalias = False; parent = None |
|
1373 | ismagic = False; isalias = False; parent = None | |
1373 |
|
1374 | |||
1374 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1375 | # We need to special-case 'print', which as of python2.6 registers as a | |
1375 | # function but should only be treated as one if print_function was |
|
1376 | # function but should only be treated as one if print_function was | |
1376 | # loaded with a future import. In this case, just bail. |
|
1377 | # loaded with a future import. In this case, just bail. | |
1377 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1378 | if (oname == 'print' and not py3compat.PY3 and not \ | |
1378 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1379 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1379 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1380 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1380 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1381 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1381 |
|
1382 | |||
1382 | # Look for the given name by splitting it in parts. If the head is |
|
1383 | # Look for the given name by splitting it in parts. If the head is | |
1383 | # found, then we look for all the remaining parts as members, and only |
|
1384 | # found, then we look for all the remaining parts as members, and only | |
1384 | # declare success if we can find them all. |
|
1385 | # declare success if we can find them all. | |
1385 | oname_parts = oname.split('.') |
|
1386 | oname_parts = oname.split('.') | |
1386 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1387 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1387 | for nsname,ns in namespaces: |
|
1388 | for nsname,ns in namespaces: | |
1388 | try: |
|
1389 | try: | |
1389 | obj = ns[oname_head] |
|
1390 | obj = ns[oname_head] | |
1390 | except KeyError: |
|
1391 | except KeyError: | |
1391 | continue |
|
1392 | continue | |
1392 | else: |
|
1393 | else: | |
1393 | #print 'oname_rest:', oname_rest # dbg |
|
1394 | #print 'oname_rest:', oname_rest # dbg | |
1394 | for part in oname_rest: |
|
1395 | for part in oname_rest: | |
1395 | try: |
|
1396 | try: | |
1396 | parent = obj |
|
1397 | parent = obj | |
1397 | obj = getattr(obj,part) |
|
1398 | obj = getattr(obj,part) | |
1398 | except: |
|
1399 | except: | |
1399 | # Blanket except b/c some badly implemented objects |
|
1400 | # Blanket except b/c some badly implemented objects | |
1400 | # allow __getattr__ to raise exceptions other than |
|
1401 | # allow __getattr__ to raise exceptions other than | |
1401 | # AttributeError, which then crashes IPython. |
|
1402 | # AttributeError, which then crashes IPython. | |
1402 | break |
|
1403 | break | |
1403 | else: |
|
1404 | else: | |
1404 | # If we finish the for loop (no break), we got all members |
|
1405 | # If we finish the for loop (no break), we got all members | |
1405 | found = True |
|
1406 | found = True | |
1406 | ospace = nsname |
|
1407 | ospace = nsname | |
1407 | break # namespace loop |
|
1408 | break # namespace loop | |
1408 |
|
1409 | |||
1409 | # Try to see if it's magic |
|
1410 | # Try to see if it's magic | |
1410 | if not found: |
|
1411 | if not found: | |
1411 | obj = None |
|
1412 | obj = None | |
1412 | if oname.startswith(ESC_MAGIC2): |
|
1413 | if oname.startswith(ESC_MAGIC2): | |
1413 | oname = oname.lstrip(ESC_MAGIC2) |
|
1414 | oname = oname.lstrip(ESC_MAGIC2) | |
1414 | obj = self.find_cell_magic(oname) |
|
1415 | obj = self.find_cell_magic(oname) | |
1415 | elif oname.startswith(ESC_MAGIC): |
|
1416 | elif oname.startswith(ESC_MAGIC): | |
1416 | oname = oname.lstrip(ESC_MAGIC) |
|
1417 | oname = oname.lstrip(ESC_MAGIC) | |
1417 | obj = self.find_line_magic(oname) |
|
1418 | obj = self.find_line_magic(oname) | |
1418 | else: |
|
1419 | else: | |
1419 | # search without prefix, so run? will find %run? |
|
1420 | # search without prefix, so run? will find %run? | |
1420 | obj = self.find_line_magic(oname) |
|
1421 | obj = self.find_line_magic(oname) | |
1421 | if obj is None: |
|
1422 | if obj is None: | |
1422 | obj = self.find_cell_magic(oname) |
|
1423 | obj = self.find_cell_magic(oname) | |
1423 | if obj is not None: |
|
1424 | if obj is not None: | |
1424 | found = True |
|
1425 | found = True | |
1425 | ospace = 'IPython internal' |
|
1426 | ospace = 'IPython internal' | |
1426 | ismagic = True |
|
1427 | ismagic = True | |
1427 |
|
1428 | |||
1428 | # Last try: special-case some literals like '', [], {}, etc: |
|
1429 | # Last try: special-case some literals like '', [], {}, etc: | |
1429 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1430 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1430 | obj = eval(oname_head) |
|
1431 | obj = eval(oname_head) | |
1431 | found = True |
|
1432 | found = True | |
1432 | ospace = 'Interactive' |
|
1433 | ospace = 'Interactive' | |
1433 |
|
1434 | |||
1434 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1435 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1435 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1436 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1436 |
|
1437 | |||
1437 | def _ofind_property(self, oname, info): |
|
1438 | def _ofind_property(self, oname, info): | |
1438 | """Second part of object finding, to look for property details.""" |
|
1439 | """Second part of object finding, to look for property details.""" | |
1439 | if info.found: |
|
1440 | if info.found: | |
1440 | # Get the docstring of the class property if it exists. |
|
1441 | # Get the docstring of the class property if it exists. | |
1441 | path = oname.split('.') |
|
1442 | path = oname.split('.') | |
1442 | root = '.'.join(path[:-1]) |
|
1443 | root = '.'.join(path[:-1]) | |
1443 | if info.parent is not None: |
|
1444 | if info.parent is not None: | |
1444 | try: |
|
1445 | try: | |
1445 | target = getattr(info.parent, '__class__') |
|
1446 | target = getattr(info.parent, '__class__') | |
1446 | # The object belongs to a class instance. |
|
1447 | # The object belongs to a class instance. | |
1447 | try: |
|
1448 | try: | |
1448 | target = getattr(target, path[-1]) |
|
1449 | target = getattr(target, path[-1]) | |
1449 | # The class defines the object. |
|
1450 | # The class defines the object. | |
1450 | if isinstance(target, property): |
|
1451 | if isinstance(target, property): | |
1451 | oname = root + '.__class__.' + path[-1] |
|
1452 | oname = root + '.__class__.' + path[-1] | |
1452 | info = Struct(self._ofind(oname)) |
|
1453 | info = Struct(self._ofind(oname)) | |
1453 | except AttributeError: pass |
|
1454 | except AttributeError: pass | |
1454 | except AttributeError: pass |
|
1455 | except AttributeError: pass | |
1455 |
|
1456 | |||
1456 | # We return either the new info or the unmodified input if the object |
|
1457 | # We return either the new info or the unmodified input if the object | |
1457 | # hadn't been found |
|
1458 | # hadn't been found | |
1458 | return info |
|
1459 | return info | |
1459 |
|
1460 | |||
1460 | def _object_find(self, oname, namespaces=None): |
|
1461 | def _object_find(self, oname, namespaces=None): | |
1461 | """Find an object and return a struct with info about it.""" |
|
1462 | """Find an object and return a struct with info about it.""" | |
1462 | inf = Struct(self._ofind(oname, namespaces)) |
|
1463 | inf = Struct(self._ofind(oname, namespaces)) | |
1463 | return Struct(self._ofind_property(oname, inf)) |
|
1464 | return Struct(self._ofind_property(oname, inf)) | |
1464 |
|
1465 | |||
1465 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1466 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1466 | """Generic interface to the inspector system. |
|
1467 | """Generic interface to the inspector system. | |
1467 |
|
1468 | |||
1468 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1469 | This function is meant to be called by pdef, pdoc & friends.""" | |
1469 | info = self._object_find(oname, namespaces) |
|
1470 | info = self._object_find(oname, namespaces) | |
1470 | if info.found: |
|
1471 | if info.found: | |
1471 | pmethod = getattr(self.inspector, meth) |
|
1472 | pmethod = getattr(self.inspector, meth) | |
1472 | formatter = format_screen if info.ismagic else None |
|
1473 | formatter = format_screen if info.ismagic else None | |
1473 | if meth == 'pdoc': |
|
1474 | if meth == 'pdoc': | |
1474 | pmethod(info.obj, oname, formatter) |
|
1475 | pmethod(info.obj, oname, formatter) | |
1475 | elif meth == 'pinfo': |
|
1476 | elif meth == 'pinfo': | |
1476 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1477 | pmethod(info.obj, oname, formatter, info, **kw) | |
1477 | else: |
|
1478 | else: | |
1478 | pmethod(info.obj, oname) |
|
1479 | pmethod(info.obj, oname) | |
1479 | else: |
|
1480 | else: | |
1480 | print('Object `%s` not found.' % oname) |
|
1481 | print('Object `%s` not found.' % oname) | |
1481 | return 'not found' # so callers can take other action |
|
1482 | return 'not found' # so callers can take other action | |
1482 |
|
1483 | |||
1483 | def object_inspect(self, oname, detail_level=0): |
|
1484 | def object_inspect(self, oname, detail_level=0): | |
1484 | with self.builtin_trap: |
|
1485 | with self.builtin_trap: | |
1485 | info = self._object_find(oname) |
|
1486 | info = self._object_find(oname) | |
1486 | if info.found: |
|
1487 | if info.found: | |
1487 | return self.inspector.info(info.obj, oname, info=info, |
|
1488 | return self.inspector.info(info.obj, oname, info=info, | |
1488 | detail_level=detail_level |
|
1489 | detail_level=detail_level | |
1489 | ) |
|
1490 | ) | |
1490 | else: |
|
1491 | else: | |
1491 | return oinspect.object_info(name=oname, found=False) |
|
1492 | return oinspect.object_info(name=oname, found=False) | |
1492 |
|
1493 | |||
1493 | #------------------------------------------------------------------------- |
|
1494 | #------------------------------------------------------------------------- | |
1494 | # Things related to history management |
|
1495 | # Things related to history management | |
1495 | #------------------------------------------------------------------------- |
|
1496 | #------------------------------------------------------------------------- | |
1496 |
|
1497 | |||
1497 | def init_history(self): |
|
1498 | def init_history(self): | |
1498 | """Sets up the command history, and starts regular autosaves.""" |
|
1499 | """Sets up the command history, and starts regular autosaves.""" | |
1499 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1500 | self.history_manager = HistoryManager(shell=self, parent=self) | |
1500 | self.configurables.append(self.history_manager) |
|
1501 | self.configurables.append(self.history_manager) | |
1501 |
|
1502 | |||
1502 | #------------------------------------------------------------------------- |
|
1503 | #------------------------------------------------------------------------- | |
1503 | # Things related to exception handling and tracebacks (not debugging) |
|
1504 | # Things related to exception handling and tracebacks (not debugging) | |
1504 | #------------------------------------------------------------------------- |
|
1505 | #------------------------------------------------------------------------- | |
1505 |
|
1506 | |||
1506 | def init_traceback_handlers(self, custom_exceptions): |
|
1507 | def init_traceback_handlers(self, custom_exceptions): | |
1507 | # Syntax error handler. |
|
1508 | # Syntax error handler. | |
1508 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1509 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1509 |
|
1510 | |||
1510 | # The interactive one is initialized with an offset, meaning we always |
|
1511 | # The interactive one is initialized with an offset, meaning we always | |
1511 | # want to remove the topmost item in the traceback, which is our own |
|
1512 | # want to remove the topmost item in the traceback, which is our own | |
1512 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1513 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1513 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1514 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1514 | color_scheme='NoColor', |
|
1515 | color_scheme='NoColor', | |
1515 | tb_offset = 1, |
|
1516 | tb_offset = 1, | |
1516 | check_cache=check_linecache_ipython) |
|
1517 | check_cache=check_linecache_ipython) | |
1517 |
|
1518 | |||
1518 | # The instance will store a pointer to the system-wide exception hook, |
|
1519 | # The instance will store a pointer to the system-wide exception hook, | |
1519 | # so that runtime code (such as magics) can access it. This is because |
|
1520 | # so that runtime code (such as magics) can access it. This is because | |
1520 | # during the read-eval loop, it may get temporarily overwritten. |
|
1521 | # during the read-eval loop, it may get temporarily overwritten. | |
1521 | self.sys_excepthook = sys.excepthook |
|
1522 | self.sys_excepthook = sys.excepthook | |
1522 |
|
1523 | |||
1523 | # and add any custom exception handlers the user may have specified |
|
1524 | # and add any custom exception handlers the user may have specified | |
1524 | self.set_custom_exc(*custom_exceptions) |
|
1525 | self.set_custom_exc(*custom_exceptions) | |
1525 |
|
1526 | |||
1526 | # Set the exception mode |
|
1527 | # Set the exception mode | |
1527 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1528 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1528 |
|
1529 | |||
1529 | def set_custom_exc(self, exc_tuple, handler): |
|
1530 | def set_custom_exc(self, exc_tuple, handler): | |
1530 | """set_custom_exc(exc_tuple,handler) |
|
1531 | """set_custom_exc(exc_tuple,handler) | |
1531 |
|
1532 | |||
1532 | Set a custom exception handler, which will be called if any of the |
|
1533 | Set a custom exception handler, which will be called if any of the | |
1533 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1534 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1534 | run_code() method). |
|
1535 | run_code() method). | |
1535 |
|
1536 | |||
1536 | Parameters |
|
1537 | Parameters | |
1537 | ---------- |
|
1538 | ---------- | |
1538 |
|
1539 | |||
1539 | exc_tuple : tuple of exception classes |
|
1540 | exc_tuple : tuple of exception classes | |
1540 | A *tuple* of exception classes, for which to call the defined |
|
1541 | A *tuple* of exception classes, for which to call the defined | |
1541 | handler. It is very important that you use a tuple, and NOT A |
|
1542 | handler. It is very important that you use a tuple, and NOT A | |
1542 | LIST here, because of the way Python's except statement works. If |
|
1543 | LIST here, because of the way Python's except statement works. If | |
1543 | you only want to trap a single exception, use a singleton tuple:: |
|
1544 | you only want to trap a single exception, use a singleton tuple:: | |
1544 |
|
1545 | |||
1545 | exc_tuple == (MyCustomException,) |
|
1546 | exc_tuple == (MyCustomException,) | |
1546 |
|
1547 | |||
1547 | handler : callable |
|
1548 | handler : callable | |
1548 | handler must have the following signature:: |
|
1549 | handler must have the following signature:: | |
1549 |
|
1550 | |||
1550 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1551 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1551 | ... |
|
1552 | ... | |
1552 | return structured_traceback |
|
1553 | return structured_traceback | |
1553 |
|
1554 | |||
1554 | Your handler must return a structured traceback (a list of strings), |
|
1555 | Your handler must return a structured traceback (a list of strings), | |
1555 | or None. |
|
1556 | or None. | |
1556 |
|
1557 | |||
1557 | This will be made into an instance method (via types.MethodType) |
|
1558 | This will be made into an instance method (via types.MethodType) | |
1558 | of IPython itself, and it will be called if any of the exceptions |
|
1559 | of IPython itself, and it will be called if any of the exceptions | |
1559 | listed in the exc_tuple are caught. If the handler is None, an |
|
1560 | listed in the exc_tuple are caught. If the handler is None, an | |
1560 | internal basic one is used, which just prints basic info. |
|
1561 | internal basic one is used, which just prints basic info. | |
1561 |
|
1562 | |||
1562 | To protect IPython from crashes, if your handler ever raises an |
|
1563 | To protect IPython from crashes, if your handler ever raises an | |
1563 | exception or returns an invalid result, it will be immediately |
|
1564 | exception or returns an invalid result, it will be immediately | |
1564 | disabled. |
|
1565 | disabled. | |
1565 |
|
1566 | |||
1566 | WARNING: by putting in your own exception handler into IPython's main |
|
1567 | WARNING: by putting in your own exception handler into IPython's main | |
1567 | execution loop, you run a very good chance of nasty crashes. This |
|
1568 | execution loop, you run a very good chance of nasty crashes. This | |
1568 | facility should only be used if you really know what you are doing.""" |
|
1569 | facility should only be used if you really know what you are doing.""" | |
1569 |
|
1570 | |||
1570 | assert type(exc_tuple)==type(()) , \ |
|
1571 | assert type(exc_tuple)==type(()) , \ | |
1571 | "The custom exceptions must be given AS A TUPLE." |
|
1572 | "The custom exceptions must be given AS A TUPLE." | |
1572 |
|
1573 | |||
1573 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1574 | def dummy_handler(self,etype,value,tb,tb_offset=None): | |
1574 | print('*** Simple custom exception handler ***') |
|
1575 | print('*** Simple custom exception handler ***') | |
1575 | print('Exception type :',etype) |
|
1576 | print('Exception type :',etype) | |
1576 | print('Exception value:',value) |
|
1577 | print('Exception value:',value) | |
1577 | print('Traceback :',tb) |
|
1578 | print('Traceback :',tb) | |
1578 | #print 'Source code :','\n'.join(self.buffer) |
|
1579 | #print 'Source code :','\n'.join(self.buffer) | |
1579 |
|
1580 | |||
1580 | def validate_stb(stb): |
|
1581 | def validate_stb(stb): | |
1581 | """validate structured traceback return type |
|
1582 | """validate structured traceback return type | |
1582 |
|
1583 | |||
1583 | return type of CustomTB *should* be a list of strings, but allow |
|
1584 | return type of CustomTB *should* be a list of strings, but allow | |
1584 | single strings or None, which are harmless. |
|
1585 | single strings or None, which are harmless. | |
1585 |
|
1586 | |||
1586 | This function will *always* return a list of strings, |
|
1587 | This function will *always* return a list of strings, | |
1587 | and will raise a TypeError if stb is inappropriate. |
|
1588 | and will raise a TypeError if stb is inappropriate. | |
1588 | """ |
|
1589 | """ | |
1589 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1590 | msg = "CustomTB must return list of strings, not %r" % stb | |
1590 | if stb is None: |
|
1591 | if stb is None: | |
1591 | return [] |
|
1592 | return [] | |
1592 | elif isinstance(stb, string_types): |
|
1593 | elif isinstance(stb, string_types): | |
1593 | return [stb] |
|
1594 | return [stb] | |
1594 | elif not isinstance(stb, list): |
|
1595 | elif not isinstance(stb, list): | |
1595 | raise TypeError(msg) |
|
1596 | raise TypeError(msg) | |
1596 | # it's a list |
|
1597 | # it's a list | |
1597 | for line in stb: |
|
1598 | for line in stb: | |
1598 | # check every element |
|
1599 | # check every element | |
1599 | if not isinstance(line, string_types): |
|
1600 | if not isinstance(line, string_types): | |
1600 | raise TypeError(msg) |
|
1601 | raise TypeError(msg) | |
1601 | return stb |
|
1602 | return stb | |
1602 |
|
1603 | |||
1603 | if handler is None: |
|
1604 | if handler is None: | |
1604 | wrapped = dummy_handler |
|
1605 | wrapped = dummy_handler | |
1605 | else: |
|
1606 | else: | |
1606 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1607 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1607 | """wrap CustomTB handler, to protect IPython from user code |
|
1608 | """wrap CustomTB handler, to protect IPython from user code | |
1608 |
|
1609 | |||
1609 | This makes it harder (but not impossible) for custom exception |
|
1610 | This makes it harder (but not impossible) for custom exception | |
1610 | handlers to crash IPython. |
|
1611 | handlers to crash IPython. | |
1611 | """ |
|
1612 | """ | |
1612 | try: |
|
1613 | try: | |
1613 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1614 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1614 | return validate_stb(stb) |
|
1615 | return validate_stb(stb) | |
1615 | except: |
|
1616 | except: | |
1616 | # clear custom handler immediately |
|
1617 | # clear custom handler immediately | |
1617 | self.set_custom_exc((), None) |
|
1618 | self.set_custom_exc((), None) | |
1618 | print("Custom TB Handler failed, unregistering", file=io.stderr) |
|
1619 | print("Custom TB Handler failed, unregistering", file=io.stderr) | |
1619 | # show the exception in handler first |
|
1620 | # show the exception in handler first | |
1620 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1621 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1621 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1622 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1622 | print("The original exception:", file=io.stdout) |
|
1623 | print("The original exception:", file=io.stdout) | |
1623 | stb = self.InteractiveTB.structured_traceback( |
|
1624 | stb = self.InteractiveTB.structured_traceback( | |
1624 | (etype,value,tb), tb_offset=tb_offset |
|
1625 | (etype,value,tb), tb_offset=tb_offset | |
1625 | ) |
|
1626 | ) | |
1626 | return stb |
|
1627 | return stb | |
1627 |
|
1628 | |||
1628 | self.CustomTB = types.MethodType(wrapped,self) |
|
1629 | self.CustomTB = types.MethodType(wrapped,self) | |
1629 | self.custom_exceptions = exc_tuple |
|
1630 | self.custom_exceptions = exc_tuple | |
1630 |
|
1631 | |||
1631 | def excepthook(self, etype, value, tb): |
|
1632 | def excepthook(self, etype, value, tb): | |
1632 | """One more defense for GUI apps that call sys.excepthook. |
|
1633 | """One more defense for GUI apps that call sys.excepthook. | |
1633 |
|
1634 | |||
1634 | GUI frameworks like wxPython trap exceptions and call |
|
1635 | GUI frameworks like wxPython trap exceptions and call | |
1635 | sys.excepthook themselves. I guess this is a feature that |
|
1636 | sys.excepthook themselves. I guess this is a feature that | |
1636 | enables them to keep running after exceptions that would |
|
1637 | enables them to keep running after exceptions that would | |
1637 | otherwise kill their mainloop. This is a bother for IPython |
|
1638 | otherwise kill their mainloop. This is a bother for IPython | |
1638 | which excepts to catch all of the program exceptions with a try: |
|
1639 | which excepts to catch all of the program exceptions with a try: | |
1639 | except: statement. |
|
1640 | except: statement. | |
1640 |
|
1641 | |||
1641 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1642 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1642 | any app directly invokes sys.excepthook, it will look to the user like |
|
1643 | any app directly invokes sys.excepthook, it will look to the user like | |
1643 | IPython crashed. In order to work around this, we can disable the |
|
1644 | IPython crashed. In order to work around this, we can disable the | |
1644 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1645 | CrashHandler and replace it with this excepthook instead, which prints a | |
1645 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1646 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1646 | call sys.excepthook will generate a regular-looking exception from |
|
1647 | call sys.excepthook will generate a regular-looking exception from | |
1647 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1648 | IPython, and the CrashHandler will only be triggered by real IPython | |
1648 | crashes. |
|
1649 | crashes. | |
1649 |
|
1650 | |||
1650 | This hook should be used sparingly, only in places which are not likely |
|
1651 | This hook should be used sparingly, only in places which are not likely | |
1651 | to be true IPython errors. |
|
1652 | to be true IPython errors. | |
1652 | """ |
|
1653 | """ | |
1653 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1654 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1654 |
|
1655 | |||
1655 | def _get_exc_info(self, exc_tuple=None): |
|
1656 | def _get_exc_info(self, exc_tuple=None): | |
1656 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1657 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1657 |
|
1658 | |||
1658 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1659 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1659 | from whichever source. |
|
1660 | from whichever source. | |
1660 |
|
1661 | |||
1661 | raises ValueError if none of these contain any information |
|
1662 | raises ValueError if none of these contain any information | |
1662 | """ |
|
1663 | """ | |
1663 | if exc_tuple is None: |
|
1664 | if exc_tuple is None: | |
1664 | etype, value, tb = sys.exc_info() |
|
1665 | etype, value, tb = sys.exc_info() | |
1665 | else: |
|
1666 | else: | |
1666 | etype, value, tb = exc_tuple |
|
1667 | etype, value, tb = exc_tuple | |
1667 |
|
1668 | |||
1668 | if etype is None: |
|
1669 | if etype is None: | |
1669 | if hasattr(sys, 'last_type'): |
|
1670 | if hasattr(sys, 'last_type'): | |
1670 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1671 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1671 | sys.last_traceback |
|
1672 | sys.last_traceback | |
1672 |
|
1673 | |||
1673 | if etype is None: |
|
1674 | if etype is None: | |
1674 | raise ValueError("No exception to find") |
|
1675 | raise ValueError("No exception to find") | |
1675 |
|
1676 | |||
1676 | # Now store the exception info in sys.last_type etc. |
|
1677 | # Now store the exception info in sys.last_type etc. | |
1677 | # WARNING: these variables are somewhat deprecated and not |
|
1678 | # WARNING: these variables are somewhat deprecated and not | |
1678 | # necessarily safe to use in a threaded environment, but tools |
|
1679 | # necessarily safe to use in a threaded environment, but tools | |
1679 | # like pdb depend on their existence, so let's set them. If we |
|
1680 | # like pdb depend on their existence, so let's set them. If we | |
1680 | # find problems in the field, we'll need to revisit their use. |
|
1681 | # find problems in the field, we'll need to revisit their use. | |
1681 | sys.last_type = etype |
|
1682 | sys.last_type = etype | |
1682 | sys.last_value = value |
|
1683 | sys.last_value = value | |
1683 | sys.last_traceback = tb |
|
1684 | sys.last_traceback = tb | |
1684 |
|
1685 | |||
1685 | return etype, value, tb |
|
1686 | return etype, value, tb | |
1686 |
|
1687 | |||
1687 | def show_usage_error(self, exc): |
|
1688 | def show_usage_error(self, exc): | |
1688 | """Show a short message for UsageErrors |
|
1689 | """Show a short message for UsageErrors | |
1689 |
|
1690 | |||
1690 | These are special exceptions that shouldn't show a traceback. |
|
1691 | These are special exceptions that shouldn't show a traceback. | |
1691 | """ |
|
1692 | """ | |
1692 | self.write_err("UsageError: %s" % exc) |
|
1693 | self.write_err("UsageError: %s" % exc) | |
1693 |
|
1694 | |||
1694 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1695 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1695 | exception_only=False): |
|
1696 | exception_only=False): | |
1696 | """Display the exception that just occurred. |
|
1697 | """Display the exception that just occurred. | |
1697 |
|
1698 | |||
1698 | If nothing is known about the exception, this is the method which |
|
1699 | If nothing is known about the exception, this is the method which | |
1699 | should be used throughout the code for presenting user tracebacks, |
|
1700 | should be used throughout the code for presenting user tracebacks, | |
1700 | rather than directly invoking the InteractiveTB object. |
|
1701 | rather than directly invoking the InteractiveTB object. | |
1701 |
|
1702 | |||
1702 | A specific showsyntaxerror() also exists, but this method can take |
|
1703 | A specific showsyntaxerror() also exists, but this method can take | |
1703 | care of calling it if needed, so unless you are explicitly catching a |
|
1704 | care of calling it if needed, so unless you are explicitly catching a | |
1704 | SyntaxError exception, don't try to analyze the stack manually and |
|
1705 | SyntaxError exception, don't try to analyze the stack manually and | |
1705 | simply call this method.""" |
|
1706 | simply call this method.""" | |
1706 |
|
1707 | |||
1707 | try: |
|
1708 | try: | |
1708 | try: |
|
1709 | try: | |
1709 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1710 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1710 | except ValueError: |
|
1711 | except ValueError: | |
1711 | self.write_err('No traceback available to show.\n') |
|
1712 | self.write_err('No traceback available to show.\n') | |
1712 | return |
|
1713 | return | |
1713 |
|
1714 | |||
1714 | if issubclass(etype, SyntaxError): |
|
1715 | if issubclass(etype, SyntaxError): | |
1715 | # Though this won't be called by syntax errors in the input |
|
1716 | # Though this won't be called by syntax errors in the input | |
1716 | # line, there may be SyntaxError cases with imported code. |
|
1717 | # line, there may be SyntaxError cases with imported code. | |
1717 | self.showsyntaxerror(filename) |
|
1718 | self.showsyntaxerror(filename) | |
1718 | elif etype is UsageError: |
|
1719 | elif etype is UsageError: | |
1719 | self.show_usage_error(value) |
|
1720 | self.show_usage_error(value) | |
1720 | else: |
|
1721 | else: | |
1721 | if exception_only: |
|
1722 | if exception_only: | |
1722 | stb = ['An exception has occurred, use %tb to see ' |
|
1723 | stb = ['An exception has occurred, use %tb to see ' | |
1723 | 'the full traceback.\n'] |
|
1724 | 'the full traceback.\n'] | |
1724 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1725 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1725 | value)) |
|
1726 | value)) | |
1726 | else: |
|
1727 | else: | |
1727 | try: |
|
1728 | try: | |
1728 | # Exception classes can customise their traceback - we |
|
1729 | # Exception classes can customise their traceback - we | |
1729 | # use this in IPython.parallel for exceptions occurring |
|
1730 | # use this in IPython.parallel for exceptions occurring | |
1730 | # in the engines. This should return a list of strings. |
|
1731 | # in the engines. This should return a list of strings. | |
1731 | stb = value._render_traceback_() |
|
1732 | stb = value._render_traceback_() | |
1732 | except Exception: |
|
1733 | except Exception: | |
1733 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1734 | stb = self.InteractiveTB.structured_traceback(etype, | |
1734 | value, tb, tb_offset=tb_offset) |
|
1735 | value, tb, tb_offset=tb_offset) | |
1735 |
|
1736 | |||
1736 | self._showtraceback(etype, value, stb) |
|
1737 | self._showtraceback(etype, value, stb) | |
1737 | if self.call_pdb: |
|
1738 | if self.call_pdb: | |
1738 | # drop into debugger |
|
1739 | # drop into debugger | |
1739 | self.debugger(force=True) |
|
1740 | self.debugger(force=True) | |
1740 | return |
|
1741 | return | |
1741 |
|
1742 | |||
1742 | # Actually show the traceback |
|
1743 | # Actually show the traceback | |
1743 | self._showtraceback(etype, value, stb) |
|
1744 | self._showtraceback(etype, value, stb) | |
1744 |
|
1745 | |||
1745 | except KeyboardInterrupt: |
|
1746 | except KeyboardInterrupt: | |
1746 | self.write_err("\nKeyboardInterrupt\n") |
|
1747 | self.write_err("\nKeyboardInterrupt\n") | |
1747 |
|
1748 | |||
1748 | def _showtraceback(self, etype, evalue, stb): |
|
1749 | def _showtraceback(self, etype, evalue, stb): | |
1749 | """Actually show a traceback. |
|
1750 | """Actually show a traceback. | |
1750 |
|
1751 | |||
1751 | Subclasses may override this method to put the traceback on a different |
|
1752 | Subclasses may override this method to put the traceback on a different | |
1752 | place, like a side channel. |
|
1753 | place, like a side channel. | |
1753 | """ |
|
1754 | """ | |
1754 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) |
|
1755 | print(self.InteractiveTB.stb2text(stb), file=io.stdout) | |
1755 |
|
1756 | |||
1756 | def showsyntaxerror(self, filename=None): |
|
1757 | def showsyntaxerror(self, filename=None): | |
1757 | """Display the syntax error that just occurred. |
|
1758 | """Display the syntax error that just occurred. | |
1758 |
|
1759 | |||
1759 | This doesn't display a stack trace because there isn't one. |
|
1760 | This doesn't display a stack trace because there isn't one. | |
1760 |
|
1761 | |||
1761 | If a filename is given, it is stuffed in the exception instead |
|
1762 | If a filename is given, it is stuffed in the exception instead | |
1762 | of what was there before (because Python's parser always uses |
|
1763 | of what was there before (because Python's parser always uses | |
1763 | "<string>" when reading from a string). |
|
1764 | "<string>" when reading from a string). | |
1764 | """ |
|
1765 | """ | |
1765 | etype, value, last_traceback = self._get_exc_info() |
|
1766 | etype, value, last_traceback = self._get_exc_info() | |
1766 |
|
1767 | |||
1767 | if filename and issubclass(etype, SyntaxError): |
|
1768 | if filename and issubclass(etype, SyntaxError): | |
1768 | try: |
|
1769 | try: | |
1769 | value.filename = filename |
|
1770 | value.filename = filename | |
1770 | except: |
|
1771 | except: | |
1771 | # Not the format we expect; leave it alone |
|
1772 | # Not the format we expect; leave it alone | |
1772 | pass |
|
1773 | pass | |
1773 |
|
1774 | |||
1774 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1775 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1775 | self._showtraceback(etype, value, stb) |
|
1776 | self._showtraceback(etype, value, stb) | |
1776 |
|
1777 | |||
1777 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1778 | # This is overridden in TerminalInteractiveShell to show a message about | |
1778 | # the %paste magic. |
|
1779 | # the %paste magic. | |
1779 | def showindentationerror(self): |
|
1780 | def showindentationerror(self): | |
1780 | """Called by run_cell when there's an IndentationError in code entered |
|
1781 | """Called by run_cell when there's an IndentationError in code entered | |
1781 | at the prompt. |
|
1782 | at the prompt. | |
1782 |
|
1783 | |||
1783 | This is overridden in TerminalInteractiveShell to show a message about |
|
1784 | This is overridden in TerminalInteractiveShell to show a message about | |
1784 | the %paste magic.""" |
|
1785 | the %paste magic.""" | |
1785 | self.showsyntaxerror() |
|
1786 | self.showsyntaxerror() | |
1786 |
|
1787 | |||
1787 | #------------------------------------------------------------------------- |
|
1788 | #------------------------------------------------------------------------- | |
1788 | # Things related to readline |
|
1789 | # Things related to readline | |
1789 | #------------------------------------------------------------------------- |
|
1790 | #------------------------------------------------------------------------- | |
1790 |
|
1791 | |||
1791 | def init_readline(self): |
|
1792 | def init_readline(self): | |
1792 | """Command history completion/saving/reloading.""" |
|
1793 | """Command history completion/saving/reloading.""" | |
1793 |
|
1794 | |||
1794 | if self.readline_use: |
|
1795 | if self.readline_use: | |
1795 | import IPython.utils.rlineimpl as readline |
|
1796 | import IPython.utils.rlineimpl as readline | |
1796 |
|
1797 | |||
1797 | self.rl_next_input = None |
|
1798 | self.rl_next_input = None | |
1798 | self.rl_do_indent = False |
|
1799 | self.rl_do_indent = False | |
1799 |
|
1800 | |||
1800 | if not self.readline_use or not readline.have_readline: |
|
1801 | if not self.readline_use or not readline.have_readline: | |
1801 | self.has_readline = False |
|
1802 | self.has_readline = False | |
1802 | self.readline = None |
|
1803 | self.readline = None | |
1803 | # Set a number of methods that depend on readline to be no-op |
|
1804 | # Set a number of methods that depend on readline to be no-op | |
1804 | self.readline_no_record = no_op_context |
|
1805 | self.readline_no_record = no_op_context | |
1805 | self.set_readline_completer = no_op |
|
1806 | self.set_readline_completer = no_op | |
1806 | self.set_custom_completer = no_op |
|
1807 | self.set_custom_completer = no_op | |
1807 | if self.readline_use: |
|
1808 | if self.readline_use: | |
1808 | warn('Readline services not available or not loaded.') |
|
1809 | warn('Readline services not available or not loaded.') | |
1809 | else: |
|
1810 | else: | |
1810 | self.has_readline = True |
|
1811 | self.has_readline = True | |
1811 | self.readline = readline |
|
1812 | self.readline = readline | |
1812 | sys.modules['readline'] = readline |
|
1813 | sys.modules['readline'] = readline | |
1813 |
|
1814 | |||
1814 | # Platform-specific configuration |
|
1815 | # Platform-specific configuration | |
1815 | if os.name == 'nt': |
|
1816 | if os.name == 'nt': | |
1816 | # FIXME - check with Frederick to see if we can harmonize |
|
1817 | # FIXME - check with Frederick to see if we can harmonize | |
1817 | # naming conventions with pyreadline to avoid this |
|
1818 | # naming conventions with pyreadline to avoid this | |
1818 | # platform-dependent check |
|
1819 | # platform-dependent check | |
1819 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1820 | self.readline_startup_hook = readline.set_pre_input_hook | |
1820 | else: |
|
1821 | else: | |
1821 | self.readline_startup_hook = readline.set_startup_hook |
|
1822 | self.readline_startup_hook = readline.set_startup_hook | |
1822 |
|
1823 | |||
1823 | # Load user's initrc file (readline config) |
|
1824 | # Load user's initrc file (readline config) | |
1824 | # Or if libedit is used, load editrc. |
|
1825 | # Or if libedit is used, load editrc. | |
1825 | inputrc_name = os.environ.get('INPUTRC') |
|
1826 | inputrc_name = os.environ.get('INPUTRC') | |
1826 | if inputrc_name is None: |
|
1827 | if inputrc_name is None: | |
1827 | inputrc_name = '.inputrc' |
|
1828 | inputrc_name = '.inputrc' | |
1828 | if readline.uses_libedit: |
|
1829 | if readline.uses_libedit: | |
1829 | inputrc_name = '.editrc' |
|
1830 | inputrc_name = '.editrc' | |
1830 | inputrc_name = os.path.join(self.home_dir, inputrc_name) |
|
1831 | inputrc_name = os.path.join(self.home_dir, inputrc_name) | |
1831 | if os.path.isfile(inputrc_name): |
|
1832 | if os.path.isfile(inputrc_name): | |
1832 | try: |
|
1833 | try: | |
1833 | readline.read_init_file(inputrc_name) |
|
1834 | readline.read_init_file(inputrc_name) | |
1834 | except: |
|
1835 | except: | |
1835 | warn('Problems reading readline initialization file <%s>' |
|
1836 | warn('Problems reading readline initialization file <%s>' | |
1836 | % inputrc_name) |
|
1837 | % inputrc_name) | |
1837 |
|
1838 | |||
1838 | # Configure readline according to user's prefs |
|
1839 | # Configure readline according to user's prefs | |
1839 | # This is only done if GNU readline is being used. If libedit |
|
1840 | # This is only done if GNU readline is being used. If libedit | |
1840 | # is being used (as on Leopard) the readline config is |
|
1841 | # is being used (as on Leopard) the readline config is | |
1841 | # not run as the syntax for libedit is different. |
|
1842 | # not run as the syntax for libedit is different. | |
1842 | if not readline.uses_libedit: |
|
1843 | if not readline.uses_libedit: | |
1843 | for rlcommand in self.readline_parse_and_bind: |
|
1844 | for rlcommand in self.readline_parse_and_bind: | |
1844 | #print "loading rl:",rlcommand # dbg |
|
1845 | #print "loading rl:",rlcommand # dbg | |
1845 | readline.parse_and_bind(rlcommand) |
|
1846 | readline.parse_and_bind(rlcommand) | |
1846 |
|
1847 | |||
1847 | # Remove some chars from the delimiters list. If we encounter |
|
1848 | # Remove some chars from the delimiters list. If we encounter | |
1848 | # unicode chars, discard them. |
|
1849 | # unicode chars, discard them. | |
1849 | delims = readline.get_completer_delims() |
|
1850 | delims = readline.get_completer_delims() | |
1850 | if not py3compat.PY3: |
|
1851 | if not py3compat.PY3: | |
1851 | delims = delims.encode("ascii", "ignore") |
|
1852 | delims = delims.encode("ascii", "ignore") | |
1852 | for d in self.readline_remove_delims: |
|
1853 | for d in self.readline_remove_delims: | |
1853 | delims = delims.replace(d, "") |
|
1854 | delims = delims.replace(d, "") | |
1854 | delims = delims.replace(ESC_MAGIC, '') |
|
1855 | delims = delims.replace(ESC_MAGIC, '') | |
1855 | readline.set_completer_delims(delims) |
|
1856 | readline.set_completer_delims(delims) | |
1856 | # Store these so we can restore them if something like rpy2 modifies |
|
1857 | # Store these so we can restore them if something like rpy2 modifies | |
1857 | # them. |
|
1858 | # them. | |
1858 | self.readline_delims = delims |
|
1859 | self.readline_delims = delims | |
1859 | # otherwise we end up with a monster history after a while: |
|
1860 | # otherwise we end up with a monster history after a while: | |
1860 | readline.set_history_length(self.history_length) |
|
1861 | readline.set_history_length(self.history_length) | |
1861 |
|
1862 | |||
1862 | self.refill_readline_hist() |
|
1863 | self.refill_readline_hist() | |
1863 | self.readline_no_record = ReadlineNoRecord(self) |
|
1864 | self.readline_no_record = ReadlineNoRecord(self) | |
1864 |
|
1865 | |||
1865 | # Configure auto-indent for all platforms |
|
1866 | # Configure auto-indent for all platforms | |
1866 | self.set_autoindent(self.autoindent) |
|
1867 | self.set_autoindent(self.autoindent) | |
1867 |
|
1868 | |||
1868 | def refill_readline_hist(self): |
|
1869 | def refill_readline_hist(self): | |
1869 | # Load the last 1000 lines from history |
|
1870 | # Load the last 1000 lines from history | |
1870 | self.readline.clear_history() |
|
1871 | self.readline.clear_history() | |
1871 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1872 | stdin_encoding = sys.stdin.encoding or "utf-8" | |
1872 | last_cell = u"" |
|
1873 | last_cell = u"" | |
1873 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1874 | for _, _, cell in self.history_manager.get_tail(1000, | |
1874 | include_latest=True): |
|
1875 | include_latest=True): | |
1875 | # Ignore blank lines and consecutive duplicates |
|
1876 | # Ignore blank lines and consecutive duplicates | |
1876 | cell = cell.rstrip() |
|
1877 | cell = cell.rstrip() | |
1877 | if cell and (cell != last_cell): |
|
1878 | if cell and (cell != last_cell): | |
1878 | try: |
|
1879 | try: | |
1879 | if self.multiline_history: |
|
1880 | if self.multiline_history: | |
1880 | self.readline.add_history(py3compat.unicode_to_str(cell, |
|
1881 | self.readline.add_history(py3compat.unicode_to_str(cell, | |
1881 | stdin_encoding)) |
|
1882 | stdin_encoding)) | |
1882 | else: |
|
1883 | else: | |
1883 | for line in cell.splitlines(): |
|
1884 | for line in cell.splitlines(): | |
1884 | self.readline.add_history(py3compat.unicode_to_str(line, |
|
1885 | self.readline.add_history(py3compat.unicode_to_str(line, | |
1885 | stdin_encoding)) |
|
1886 | stdin_encoding)) | |
1886 | last_cell = cell |
|
1887 | last_cell = cell | |
1887 |
|
1888 | |||
1888 | except TypeError: |
|
1889 | except TypeError: | |
1889 | # The history DB can get corrupted so it returns strings |
|
1890 | # The history DB can get corrupted so it returns strings | |
1890 | # containing null bytes, which readline objects to. |
|
1891 | # containing null bytes, which readline objects to. | |
1891 | continue |
|
1892 | continue | |
1892 |
|
1893 | |||
1893 | @skip_doctest |
|
1894 | @skip_doctest | |
1894 | def set_next_input(self, s): |
|
1895 | def set_next_input(self, s): | |
1895 | """ Sets the 'default' input string for the next command line. |
|
1896 | """ Sets the 'default' input string for the next command line. | |
1896 |
|
1897 | |||
1897 | Requires readline. |
|
1898 | Requires readline. | |
1898 |
|
1899 | |||
1899 | Example:: |
|
1900 | Example:: | |
1900 |
|
1901 | |||
1901 | In [1]: _ip.set_next_input("Hello Word") |
|
1902 | In [1]: _ip.set_next_input("Hello Word") | |
1902 | In [2]: Hello Word_ # cursor is here |
|
1903 | In [2]: Hello Word_ # cursor is here | |
1903 | """ |
|
1904 | """ | |
1904 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1905 | self.rl_next_input = py3compat.cast_bytes_py2(s) | |
1905 |
|
1906 | |||
1906 | # Maybe move this to the terminal subclass? |
|
1907 | # Maybe move this to the terminal subclass? | |
1907 | def pre_readline(self): |
|
1908 | def pre_readline(self): | |
1908 | """readline hook to be used at the start of each line. |
|
1909 | """readline hook to be used at the start of each line. | |
1909 |
|
1910 | |||
1910 | Currently it handles auto-indent only.""" |
|
1911 | Currently it handles auto-indent only.""" | |
1911 |
|
1912 | |||
1912 | if self.rl_do_indent: |
|
1913 | if self.rl_do_indent: | |
1913 | self.readline.insert_text(self._indent_current_str()) |
|
1914 | self.readline.insert_text(self._indent_current_str()) | |
1914 | if self.rl_next_input is not None: |
|
1915 | if self.rl_next_input is not None: | |
1915 | self.readline.insert_text(self.rl_next_input) |
|
1916 | self.readline.insert_text(self.rl_next_input) | |
1916 | self.rl_next_input = None |
|
1917 | self.rl_next_input = None | |
1917 |
|
1918 | |||
1918 | def _indent_current_str(self): |
|
1919 | def _indent_current_str(self): | |
1919 | """return the current level of indentation as a string""" |
|
1920 | """return the current level of indentation as a string""" | |
1920 | return self.input_splitter.indent_spaces * ' ' |
|
1921 | return self.input_splitter.indent_spaces * ' ' | |
1921 |
|
1922 | |||
1922 | #------------------------------------------------------------------------- |
|
1923 | #------------------------------------------------------------------------- | |
1923 | # Things related to text completion |
|
1924 | # Things related to text completion | |
1924 | #------------------------------------------------------------------------- |
|
1925 | #------------------------------------------------------------------------- | |
1925 |
|
1926 | |||
1926 | def init_completer(self): |
|
1927 | def init_completer(self): | |
1927 | """Initialize the completion machinery. |
|
1928 | """Initialize the completion machinery. | |
1928 |
|
1929 | |||
1929 | This creates completion machinery that can be used by client code, |
|
1930 | This creates completion machinery that can be used by client code, | |
1930 | either interactively in-process (typically triggered by the readline |
|
1931 | either interactively in-process (typically triggered by the readline | |
1931 | library), programatically (such as in test suites) or out-of-prcess |
|
1932 | library), programatically (such as in test suites) or out-of-prcess | |
1932 | (typically over the network by remote frontends). |
|
1933 | (typically over the network by remote frontends). | |
1933 | """ |
|
1934 | """ | |
1934 | from IPython.core.completer import IPCompleter |
|
1935 | from IPython.core.completer import IPCompleter | |
1935 | from IPython.core.completerlib import (module_completer, |
|
1936 | from IPython.core.completerlib import (module_completer, | |
1936 | magic_run_completer, cd_completer, reset_completer) |
|
1937 | magic_run_completer, cd_completer, reset_completer) | |
1937 |
|
1938 | |||
1938 | self.Completer = IPCompleter(shell=self, |
|
1939 | self.Completer = IPCompleter(shell=self, | |
1939 | namespace=self.user_ns, |
|
1940 | namespace=self.user_ns, | |
1940 | global_namespace=self.user_global_ns, |
|
1941 | global_namespace=self.user_global_ns, | |
1941 | use_readline=self.has_readline, |
|
1942 | use_readline=self.has_readline, | |
1942 | parent=self, |
|
1943 | parent=self, | |
1943 | ) |
|
1944 | ) | |
1944 | self.configurables.append(self.Completer) |
|
1945 | self.configurables.append(self.Completer) | |
1945 |
|
1946 | |||
1946 | # Add custom completers to the basic ones built into IPCompleter |
|
1947 | # Add custom completers to the basic ones built into IPCompleter | |
1947 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1948 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1948 | self.strdispatchers['complete_command'] = sdisp |
|
1949 | self.strdispatchers['complete_command'] = sdisp | |
1949 | self.Completer.custom_completers = sdisp |
|
1950 | self.Completer.custom_completers = sdisp | |
1950 |
|
1951 | |||
1951 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1952 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1952 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1953 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1953 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1954 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1954 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1955 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1955 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1956 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1956 |
|
1957 | |||
1957 | # Only configure readline if we truly are using readline. IPython can |
|
1958 | # Only configure readline if we truly are using readline. IPython can | |
1958 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1959 | # do tab-completion over the network, in GUIs, etc, where readline | |
1959 | # itself may be absent |
|
1960 | # itself may be absent | |
1960 | if self.has_readline: |
|
1961 | if self.has_readline: | |
1961 | self.set_readline_completer() |
|
1962 | self.set_readline_completer() | |
1962 |
|
1963 | |||
1963 | def complete(self, text, line=None, cursor_pos=None): |
|
1964 | def complete(self, text, line=None, cursor_pos=None): | |
1964 | """Return the completed text and a list of completions. |
|
1965 | """Return the completed text and a list of completions. | |
1965 |
|
1966 | |||
1966 | Parameters |
|
1967 | Parameters | |
1967 | ---------- |
|
1968 | ---------- | |
1968 |
|
1969 | |||
1969 | text : string |
|
1970 | text : string | |
1970 | A string of text to be completed on. It can be given as empty and |
|
1971 | A string of text to be completed on. It can be given as empty and | |
1971 | instead a line/position pair are given. In this case, the |
|
1972 | instead a line/position pair are given. In this case, the | |
1972 | completer itself will split the line like readline does. |
|
1973 | completer itself will split the line like readline does. | |
1973 |
|
1974 | |||
1974 | line : string, optional |
|
1975 | line : string, optional | |
1975 | The complete line that text is part of. |
|
1976 | The complete line that text is part of. | |
1976 |
|
1977 | |||
1977 | cursor_pos : int, optional |
|
1978 | cursor_pos : int, optional | |
1978 | The position of the cursor on the input line. |
|
1979 | The position of the cursor on the input line. | |
1979 |
|
1980 | |||
1980 | Returns |
|
1981 | Returns | |
1981 | ------- |
|
1982 | ------- | |
1982 | text : string |
|
1983 | text : string | |
1983 | The actual text that was completed. |
|
1984 | The actual text that was completed. | |
1984 |
|
1985 | |||
1985 | matches : list |
|
1986 | matches : list | |
1986 | A sorted list with all possible completions. |
|
1987 | A sorted list with all possible completions. | |
1987 |
|
1988 | |||
1988 | The optional arguments allow the completion to take more context into |
|
1989 | The optional arguments allow the completion to take more context into | |
1989 | account, and are part of the low-level completion API. |
|
1990 | account, and are part of the low-level completion API. | |
1990 |
|
1991 | |||
1991 | This is a wrapper around the completion mechanism, similar to what |
|
1992 | This is a wrapper around the completion mechanism, similar to what | |
1992 | readline does at the command line when the TAB key is hit. By |
|
1993 | readline does at the command line when the TAB key is hit. By | |
1993 | exposing it as a method, it can be used by other non-readline |
|
1994 | exposing it as a method, it can be used by other non-readline | |
1994 | environments (such as GUIs) for text completion. |
|
1995 | environments (such as GUIs) for text completion. | |
1995 |
|
1996 | |||
1996 | Simple usage example: |
|
1997 | Simple usage example: | |
1997 |
|
1998 | |||
1998 | In [1]: x = 'hello' |
|
1999 | In [1]: x = 'hello' | |
1999 |
|
2000 | |||
2000 | In [2]: _ip.complete('x.l') |
|
2001 | In [2]: _ip.complete('x.l') | |
2001 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2002 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
2002 | """ |
|
2003 | """ | |
2003 |
|
2004 | |||
2004 | # Inject names into __builtin__ so we can complete on the added names. |
|
2005 | # Inject names into __builtin__ so we can complete on the added names. | |
2005 | with self.builtin_trap: |
|
2006 | with self.builtin_trap: | |
2006 | return self.Completer.complete(text, line, cursor_pos) |
|
2007 | return self.Completer.complete(text, line, cursor_pos) | |
2007 |
|
2008 | |||
2008 | def set_custom_completer(self, completer, pos=0): |
|
2009 | def set_custom_completer(self, completer, pos=0): | |
2009 | """Adds a new custom completer function. |
|
2010 | """Adds a new custom completer function. | |
2010 |
|
2011 | |||
2011 | The position argument (defaults to 0) is the index in the completers |
|
2012 | The position argument (defaults to 0) is the index in the completers | |
2012 | list where you want the completer to be inserted.""" |
|
2013 | list where you want the completer to be inserted.""" | |
2013 |
|
2014 | |||
2014 | newcomp = types.MethodType(completer,self.Completer) |
|
2015 | newcomp = types.MethodType(completer,self.Completer) | |
2015 | self.Completer.matchers.insert(pos,newcomp) |
|
2016 | self.Completer.matchers.insert(pos,newcomp) | |
2016 |
|
2017 | |||
2017 | def set_readline_completer(self): |
|
2018 | def set_readline_completer(self): | |
2018 | """Reset readline's completer to be our own.""" |
|
2019 | """Reset readline's completer to be our own.""" | |
2019 | self.readline.set_completer(self.Completer.rlcomplete) |
|
2020 | self.readline.set_completer(self.Completer.rlcomplete) | |
2020 |
|
2021 | |||
2021 | def set_completer_frame(self, frame=None): |
|
2022 | def set_completer_frame(self, frame=None): | |
2022 | """Set the frame of the completer.""" |
|
2023 | """Set the frame of the completer.""" | |
2023 | if frame: |
|
2024 | if frame: | |
2024 | self.Completer.namespace = frame.f_locals |
|
2025 | self.Completer.namespace = frame.f_locals | |
2025 | self.Completer.global_namespace = frame.f_globals |
|
2026 | self.Completer.global_namespace = frame.f_globals | |
2026 | else: |
|
2027 | else: | |
2027 | self.Completer.namespace = self.user_ns |
|
2028 | self.Completer.namespace = self.user_ns | |
2028 | self.Completer.global_namespace = self.user_global_ns |
|
2029 | self.Completer.global_namespace = self.user_global_ns | |
2029 |
|
2030 | |||
2030 | #------------------------------------------------------------------------- |
|
2031 | #------------------------------------------------------------------------- | |
2031 | # Things related to magics |
|
2032 | # Things related to magics | |
2032 | #------------------------------------------------------------------------- |
|
2033 | #------------------------------------------------------------------------- | |
2033 |
|
2034 | |||
2034 | def init_magics(self): |
|
2035 | def init_magics(self): | |
2035 | from IPython.core import magics as m |
|
2036 | from IPython.core import magics as m | |
2036 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2037 | self.magics_manager = magic.MagicsManager(shell=self, | |
2037 | parent=self, |
|
2038 | parent=self, | |
2038 | user_magics=m.UserMagics(self)) |
|
2039 | user_magics=m.UserMagics(self)) | |
2039 | self.configurables.append(self.magics_manager) |
|
2040 | self.configurables.append(self.magics_manager) | |
2040 |
|
2041 | |||
2041 | # Expose as public API from the magics manager |
|
2042 | # Expose as public API from the magics manager | |
2042 | self.register_magics = self.magics_manager.register |
|
2043 | self.register_magics = self.magics_manager.register | |
2043 | self.define_magic = self.magics_manager.define_magic |
|
2044 | self.define_magic = self.magics_manager.define_magic | |
2044 |
|
2045 | |||
2045 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2046 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
2046 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2047 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, | |
2047 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2048 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2048 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2049 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2049 | ) |
|
2050 | ) | |
2050 |
|
2051 | |||
2051 | # Register Magic Aliases |
|
2052 | # Register Magic Aliases | |
2052 | mman = self.magics_manager |
|
2053 | mman = self.magics_manager | |
2053 | # FIXME: magic aliases should be defined by the Magics classes |
|
2054 | # FIXME: magic aliases should be defined by the Magics classes | |
2054 | # or in MagicsManager, not here |
|
2055 | # or in MagicsManager, not here | |
2055 | mman.register_alias('ed', 'edit') |
|
2056 | mman.register_alias('ed', 'edit') | |
2056 | mman.register_alias('hist', 'history') |
|
2057 | mman.register_alias('hist', 'history') | |
2057 | mman.register_alias('rep', 'recall') |
|
2058 | mman.register_alias('rep', 'recall') | |
2058 | mman.register_alias('SVG', 'svg', 'cell') |
|
2059 | mman.register_alias('SVG', 'svg', 'cell') | |
2059 | mman.register_alias('HTML', 'html', 'cell') |
|
2060 | mman.register_alias('HTML', 'html', 'cell') | |
2060 | mman.register_alias('file', 'writefile', 'cell') |
|
2061 | mman.register_alias('file', 'writefile', 'cell') | |
2061 |
|
2062 | |||
2062 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2063 | # FIXME: Move the color initialization to the DisplayHook, which | |
2063 | # should be split into a prompt manager and displayhook. We probably |
|
2064 | # should be split into a prompt manager and displayhook. We probably | |
2064 | # even need a centralize colors management object. |
|
2065 | # even need a centralize colors management object. | |
2065 | self.magic('colors %s' % self.colors) |
|
2066 | self.magic('colors %s' % self.colors) | |
2066 |
|
2067 | |||
2067 | # Defined here so that it's included in the documentation |
|
2068 | # Defined here so that it's included in the documentation | |
2068 | @functools.wraps(magic.MagicsManager.register_function) |
|
2069 | @functools.wraps(magic.MagicsManager.register_function) | |
2069 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2070 | def register_magic_function(self, func, magic_kind='line', magic_name=None): | |
2070 | self.magics_manager.register_function(func, |
|
2071 | self.magics_manager.register_function(func, | |
2071 | magic_kind=magic_kind, magic_name=magic_name) |
|
2072 | magic_kind=magic_kind, magic_name=magic_name) | |
2072 |
|
2073 | |||
2073 | def run_line_magic(self, magic_name, line): |
|
2074 | def run_line_magic(self, magic_name, line): | |
2074 | """Execute the given line magic. |
|
2075 | """Execute the given line magic. | |
2075 |
|
2076 | |||
2076 | Parameters |
|
2077 | Parameters | |
2077 | ---------- |
|
2078 | ---------- | |
2078 | magic_name : str |
|
2079 | magic_name : str | |
2079 | Name of the desired magic function, without '%' prefix. |
|
2080 | Name of the desired magic function, without '%' prefix. | |
2080 |
|
2081 | |||
2081 | line : str |
|
2082 | line : str | |
2082 | The rest of the input line as a single string. |
|
2083 | The rest of the input line as a single string. | |
2083 | """ |
|
2084 | """ | |
2084 | fn = self.find_line_magic(magic_name) |
|
2085 | fn = self.find_line_magic(magic_name) | |
2085 | if fn is None: |
|
2086 | if fn is None: | |
2086 | cm = self.find_cell_magic(magic_name) |
|
2087 | cm = self.find_cell_magic(magic_name) | |
2087 | etpl = "Line magic function `%%%s` not found%s." |
|
2088 | etpl = "Line magic function `%%%s` not found%s." | |
2088 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2089 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2089 | 'did you mean that instead?)' % magic_name ) |
|
2090 | 'did you mean that instead?)' % magic_name ) | |
2090 | error(etpl % (magic_name, extra)) |
|
2091 | error(etpl % (magic_name, extra)) | |
2091 | else: |
|
2092 | else: | |
2092 | # Note: this is the distance in the stack to the user's frame. |
|
2093 | # Note: this is the distance in the stack to the user's frame. | |
2093 | # This will need to be updated if the internal calling logic gets |
|
2094 | # This will need to be updated if the internal calling logic gets | |
2094 | # refactored, or else we'll be expanding the wrong variables. |
|
2095 | # refactored, or else we'll be expanding the wrong variables. | |
2095 | stack_depth = 2 |
|
2096 | stack_depth = 2 | |
2096 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2097 | magic_arg_s = self.var_expand(line, stack_depth) | |
2097 | # Put magic args in a list so we can call with f(*a) syntax |
|
2098 | # Put magic args in a list so we can call with f(*a) syntax | |
2098 | args = [magic_arg_s] |
|
2099 | args = [magic_arg_s] | |
2099 | kwargs = {} |
|
2100 | kwargs = {} | |
2100 | # Grab local namespace if we need it: |
|
2101 | # Grab local namespace if we need it: | |
2101 | if getattr(fn, "needs_local_scope", False): |
|
2102 | if getattr(fn, "needs_local_scope", False): | |
2102 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2103 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals | |
2103 | with self.builtin_trap: |
|
2104 | with self.builtin_trap: | |
2104 | result = fn(*args,**kwargs) |
|
2105 | result = fn(*args,**kwargs) | |
2105 | return result |
|
2106 | return result | |
2106 |
|
2107 | |||
2107 | def run_cell_magic(self, magic_name, line, cell): |
|
2108 | def run_cell_magic(self, magic_name, line, cell): | |
2108 | """Execute the given cell magic. |
|
2109 | """Execute the given cell magic. | |
2109 |
|
2110 | |||
2110 | Parameters |
|
2111 | Parameters | |
2111 | ---------- |
|
2112 | ---------- | |
2112 | magic_name : str |
|
2113 | magic_name : str | |
2113 | Name of the desired magic function, without '%' prefix. |
|
2114 | Name of the desired magic function, without '%' prefix. | |
2114 |
|
2115 | |||
2115 | line : str |
|
2116 | line : str | |
2116 | The rest of the first input line as a single string. |
|
2117 | The rest of the first input line as a single string. | |
2117 |
|
2118 | |||
2118 | cell : str |
|
2119 | cell : str | |
2119 | The body of the cell as a (possibly multiline) string. |
|
2120 | The body of the cell as a (possibly multiline) string. | |
2120 | """ |
|
2121 | """ | |
2121 | fn = self.find_cell_magic(magic_name) |
|
2122 | fn = self.find_cell_magic(magic_name) | |
2122 | if fn is None: |
|
2123 | if fn is None: | |
2123 | lm = self.find_line_magic(magic_name) |
|
2124 | lm = self.find_line_magic(magic_name) | |
2124 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2125 | etpl = "Cell magic `%%{0}` not found{1}." | |
2125 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2126 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' | |
2126 | 'did you mean that instead?)'.format(magic_name)) |
|
2127 | 'did you mean that instead?)'.format(magic_name)) | |
2127 | error(etpl.format(magic_name, extra)) |
|
2128 | error(etpl.format(magic_name, extra)) | |
2128 | elif cell == '': |
|
2129 | elif cell == '': | |
2129 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2130 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) | |
2130 | if self.find_line_magic(magic_name) is not None: |
|
2131 | if self.find_line_magic(magic_name) is not None: | |
2131 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2132 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) | |
2132 | raise UsageError(message) |
|
2133 | raise UsageError(message) | |
2133 | else: |
|
2134 | else: | |
2134 | # Note: this is the distance in the stack to the user's frame. |
|
2135 | # Note: this is the distance in the stack to the user's frame. | |
2135 | # This will need to be updated if the internal calling logic gets |
|
2136 | # This will need to be updated if the internal calling logic gets | |
2136 | # refactored, or else we'll be expanding the wrong variables. |
|
2137 | # refactored, or else we'll be expanding the wrong variables. | |
2137 | stack_depth = 2 |
|
2138 | stack_depth = 2 | |
2138 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2139 | magic_arg_s = self.var_expand(line, stack_depth) | |
2139 | with self.builtin_trap: |
|
2140 | with self.builtin_trap: | |
2140 | result = fn(magic_arg_s, cell) |
|
2141 | result = fn(magic_arg_s, cell) | |
2141 | return result |
|
2142 | return result | |
2142 |
|
2143 | |||
2143 | def find_line_magic(self, magic_name): |
|
2144 | def find_line_magic(self, magic_name): | |
2144 | """Find and return a line magic by name. |
|
2145 | """Find and return a line magic by name. | |
2145 |
|
2146 | |||
2146 | Returns None if the magic isn't found.""" |
|
2147 | Returns None if the magic isn't found.""" | |
2147 | return self.magics_manager.magics['line'].get(magic_name) |
|
2148 | return self.magics_manager.magics['line'].get(magic_name) | |
2148 |
|
2149 | |||
2149 | def find_cell_magic(self, magic_name): |
|
2150 | def find_cell_magic(self, magic_name): | |
2150 | """Find and return a cell magic by name. |
|
2151 | """Find and return a cell magic by name. | |
2151 |
|
2152 | |||
2152 | Returns None if the magic isn't found.""" |
|
2153 | Returns None if the magic isn't found.""" | |
2153 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2154 | return self.magics_manager.magics['cell'].get(magic_name) | |
2154 |
|
2155 | |||
2155 | def find_magic(self, magic_name, magic_kind='line'): |
|
2156 | def find_magic(self, magic_name, magic_kind='line'): | |
2156 | """Find and return a magic of the given type by name. |
|
2157 | """Find and return a magic of the given type by name. | |
2157 |
|
2158 | |||
2158 | Returns None if the magic isn't found.""" |
|
2159 | Returns None if the magic isn't found.""" | |
2159 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2160 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2160 |
|
2161 | |||
2161 | def magic(self, arg_s): |
|
2162 | def magic(self, arg_s): | |
2162 | """DEPRECATED. Use run_line_magic() instead. |
|
2163 | """DEPRECATED. Use run_line_magic() instead. | |
2163 |
|
2164 | |||
2164 | Call a magic function by name. |
|
2165 | Call a magic function by name. | |
2165 |
|
2166 | |||
2166 | Input: a string containing the name of the magic function to call and |
|
2167 | Input: a string containing the name of the magic function to call and | |
2167 | any additional arguments to be passed to the magic. |
|
2168 | any additional arguments to be passed to the magic. | |
2168 |
|
2169 | |||
2169 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2170 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2170 | prompt: |
|
2171 | prompt: | |
2171 |
|
2172 | |||
2172 | In[1]: %name -opt foo bar |
|
2173 | In[1]: %name -opt foo bar | |
2173 |
|
2174 | |||
2174 | To call a magic without arguments, simply use magic('name'). |
|
2175 | To call a magic without arguments, simply use magic('name'). | |
2175 |
|
2176 | |||
2176 | This provides a proper Python function to call IPython's magics in any |
|
2177 | This provides a proper Python function to call IPython's magics in any | |
2177 | valid Python code you can type at the interpreter, including loops and |
|
2178 | valid Python code you can type at the interpreter, including loops and | |
2178 | compound statements. |
|
2179 | compound statements. | |
2179 | """ |
|
2180 | """ | |
2180 | # TODO: should we issue a loud deprecation warning here? |
|
2181 | # TODO: should we issue a loud deprecation warning here? | |
2181 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2182 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2182 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2183 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2183 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2184 | return self.run_line_magic(magic_name, magic_arg_s) | |
2184 |
|
2185 | |||
2185 | #------------------------------------------------------------------------- |
|
2186 | #------------------------------------------------------------------------- | |
2186 | # Things related to macros |
|
2187 | # Things related to macros | |
2187 | #------------------------------------------------------------------------- |
|
2188 | #------------------------------------------------------------------------- | |
2188 |
|
2189 | |||
2189 | def define_macro(self, name, themacro): |
|
2190 | def define_macro(self, name, themacro): | |
2190 | """Define a new macro |
|
2191 | """Define a new macro | |
2191 |
|
2192 | |||
2192 | Parameters |
|
2193 | Parameters | |
2193 | ---------- |
|
2194 | ---------- | |
2194 | name : str |
|
2195 | name : str | |
2195 | The name of the macro. |
|
2196 | The name of the macro. | |
2196 | themacro : str or Macro |
|
2197 | themacro : str or Macro | |
2197 | The action to do upon invoking the macro. If a string, a new |
|
2198 | The action to do upon invoking the macro. If a string, a new | |
2198 | Macro object is created by passing the string to it. |
|
2199 | Macro object is created by passing the string to it. | |
2199 | """ |
|
2200 | """ | |
2200 |
|
2201 | |||
2201 | from IPython.core import macro |
|
2202 | from IPython.core import macro | |
2202 |
|
2203 | |||
2203 | if isinstance(themacro, string_types): |
|
2204 | if isinstance(themacro, string_types): | |
2204 | themacro = macro.Macro(themacro) |
|
2205 | themacro = macro.Macro(themacro) | |
2205 | if not isinstance(themacro, macro.Macro): |
|
2206 | if not isinstance(themacro, macro.Macro): | |
2206 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2207 | raise ValueError('A macro must be a string or a Macro instance.') | |
2207 | self.user_ns[name] = themacro |
|
2208 | self.user_ns[name] = themacro | |
2208 |
|
2209 | |||
2209 | #------------------------------------------------------------------------- |
|
2210 | #------------------------------------------------------------------------- | |
2210 | # Things related to the running of system commands |
|
2211 | # Things related to the running of system commands | |
2211 | #------------------------------------------------------------------------- |
|
2212 | #------------------------------------------------------------------------- | |
2212 |
|
2213 | |||
2213 | def system_piped(self, cmd): |
|
2214 | def system_piped(self, cmd): | |
2214 | """Call the given cmd in a subprocess, piping stdout/err |
|
2215 | """Call the given cmd in a subprocess, piping stdout/err | |
2215 |
|
2216 | |||
2216 | Parameters |
|
2217 | Parameters | |
2217 | ---------- |
|
2218 | ---------- | |
2218 | cmd : str |
|
2219 | cmd : str | |
2219 | Command to execute (can not end in '&', as background processes are |
|
2220 | Command to execute (can not end in '&', as background processes are | |
2220 | not supported. Should not be a command that expects input |
|
2221 | not supported. Should not be a command that expects input | |
2221 | other than simple text. |
|
2222 | other than simple text. | |
2222 | """ |
|
2223 | """ | |
2223 | if cmd.rstrip().endswith('&'): |
|
2224 | if cmd.rstrip().endswith('&'): | |
2224 | # this is *far* from a rigorous test |
|
2225 | # this is *far* from a rigorous test | |
2225 | # We do not support backgrounding processes because we either use |
|
2226 | # We do not support backgrounding processes because we either use | |
2226 | # pexpect or pipes to read from. Users can always just call |
|
2227 | # pexpect or pipes to read from. Users can always just call | |
2227 | # os.system() or use ip.system=ip.system_raw |
|
2228 | # os.system() or use ip.system=ip.system_raw | |
2228 | # if they really want a background process. |
|
2229 | # if they really want a background process. | |
2229 | raise OSError("Background processes not supported.") |
|
2230 | raise OSError("Background processes not supported.") | |
2230 |
|
2231 | |||
2231 | # we explicitly do NOT return the subprocess status code, because |
|
2232 | # we explicitly do NOT return the subprocess status code, because | |
2232 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2233 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2233 | # Instead, we store the exit_code in user_ns. |
|
2234 | # Instead, we store the exit_code in user_ns. | |
2234 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2235 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2235 |
|
2236 | |||
2236 | def system_raw(self, cmd): |
|
2237 | def system_raw(self, cmd): | |
2237 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2238 | """Call the given cmd in a subprocess using os.system on Windows or | |
2238 | subprocess.call using the system shell on other platforms. |
|
2239 | subprocess.call using the system shell on other platforms. | |
2239 |
|
2240 | |||
2240 | Parameters |
|
2241 | Parameters | |
2241 | ---------- |
|
2242 | ---------- | |
2242 | cmd : str |
|
2243 | cmd : str | |
2243 | Command to execute. |
|
2244 | Command to execute. | |
2244 | """ |
|
2245 | """ | |
2245 | cmd = self.var_expand(cmd, depth=1) |
|
2246 | cmd = self.var_expand(cmd, depth=1) | |
2246 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2247 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2247 | if sys.platform == 'win32': |
|
2248 | if sys.platform == 'win32': | |
2248 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2249 | from IPython.utils._process_win32 import AvoidUNCPath | |
2249 | with AvoidUNCPath() as path: |
|
2250 | with AvoidUNCPath() as path: | |
2250 | if path is not None: |
|
2251 | if path is not None: | |
2251 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2252 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2252 | cmd = py3compat.unicode_to_str(cmd) |
|
2253 | cmd = py3compat.unicode_to_str(cmd) | |
2253 | ec = os.system(cmd) |
|
2254 | ec = os.system(cmd) | |
2254 | else: |
|
2255 | else: | |
2255 | cmd = py3compat.unicode_to_str(cmd) |
|
2256 | cmd = py3compat.unicode_to_str(cmd) | |
2256 | # Call the cmd using the OS shell, instead of the default /bin/sh, if set. |
|
2257 | # Call the cmd using the OS shell, instead of the default /bin/sh, if set. | |
2257 | ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None)) |
|
2258 | ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None)) | |
2258 | # exit code is positive for program failure, or negative for |
|
2259 | # exit code is positive for program failure, or negative for | |
2259 | # terminating signal number. |
|
2260 | # terminating signal number. | |
2260 |
|
2261 | |||
2261 | # We explicitly do NOT return the subprocess status code, because |
|
2262 | # We explicitly do NOT return the subprocess status code, because | |
2262 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2263 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2263 | # Instead, we store the exit_code in user_ns. |
|
2264 | # Instead, we store the exit_code in user_ns. | |
2264 | self.user_ns['_exit_code'] = ec |
|
2265 | self.user_ns['_exit_code'] = ec | |
2265 |
|
2266 | |||
2266 | # use piped system by default, because it is better behaved |
|
2267 | # use piped system by default, because it is better behaved | |
2267 | system = system_piped |
|
2268 | system = system_piped | |
2268 |
|
2269 | |||
2269 | def getoutput(self, cmd, split=True, depth=0): |
|
2270 | def getoutput(self, cmd, split=True, depth=0): | |
2270 | """Get output (possibly including stderr) from a subprocess. |
|
2271 | """Get output (possibly including stderr) from a subprocess. | |
2271 |
|
2272 | |||
2272 | Parameters |
|
2273 | Parameters | |
2273 | ---------- |
|
2274 | ---------- | |
2274 | cmd : str |
|
2275 | cmd : str | |
2275 | Command to execute (can not end in '&', as background processes are |
|
2276 | Command to execute (can not end in '&', as background processes are | |
2276 | not supported. |
|
2277 | not supported. | |
2277 | split : bool, optional |
|
2278 | split : bool, optional | |
2278 | If True, split the output into an IPython SList. Otherwise, an |
|
2279 | If True, split the output into an IPython SList. Otherwise, an | |
2279 | IPython LSString is returned. These are objects similar to normal |
|
2280 | IPython LSString is returned. These are objects similar to normal | |
2280 | lists and strings, with a few convenience attributes for easier |
|
2281 | lists and strings, with a few convenience attributes for easier | |
2281 | manipulation of line-based output. You can use '?' on them for |
|
2282 | manipulation of line-based output. You can use '?' on them for | |
2282 | details. |
|
2283 | details. | |
2283 | depth : int, optional |
|
2284 | depth : int, optional | |
2284 | How many frames above the caller are the local variables which should |
|
2285 | How many frames above the caller are the local variables which should | |
2285 | be expanded in the command string? The default (0) assumes that the |
|
2286 | be expanded in the command string? The default (0) assumes that the | |
2286 | expansion variables are in the stack frame calling this function. |
|
2287 | expansion variables are in the stack frame calling this function. | |
2287 | """ |
|
2288 | """ | |
2288 | if cmd.rstrip().endswith('&'): |
|
2289 | if cmd.rstrip().endswith('&'): | |
2289 | # this is *far* from a rigorous test |
|
2290 | # this is *far* from a rigorous test | |
2290 | raise OSError("Background processes not supported.") |
|
2291 | raise OSError("Background processes not supported.") | |
2291 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2292 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2292 | if split: |
|
2293 | if split: | |
2293 | out = SList(out.splitlines()) |
|
2294 | out = SList(out.splitlines()) | |
2294 | else: |
|
2295 | else: | |
2295 | out = LSString(out) |
|
2296 | out = LSString(out) | |
2296 | return out |
|
2297 | return out | |
2297 |
|
2298 | |||
2298 | #------------------------------------------------------------------------- |
|
2299 | #------------------------------------------------------------------------- | |
2299 | # Things related to aliases |
|
2300 | # Things related to aliases | |
2300 | #------------------------------------------------------------------------- |
|
2301 | #------------------------------------------------------------------------- | |
2301 |
|
2302 | |||
2302 | def init_alias(self): |
|
2303 | def init_alias(self): | |
2303 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2304 | self.alias_manager = AliasManager(shell=self, parent=self) | |
2304 | self.configurables.append(self.alias_manager) |
|
2305 | self.configurables.append(self.alias_manager) | |
2305 |
|
2306 | |||
2306 | #------------------------------------------------------------------------- |
|
2307 | #------------------------------------------------------------------------- | |
2307 | # Things related to extensions |
|
2308 | # Things related to extensions | |
2308 | #------------------------------------------------------------------------- |
|
2309 | #------------------------------------------------------------------------- | |
2309 |
|
2310 | |||
2310 | def init_extension_manager(self): |
|
2311 | def init_extension_manager(self): | |
2311 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2312 | self.extension_manager = ExtensionManager(shell=self, parent=self) | |
2312 | self.configurables.append(self.extension_manager) |
|
2313 | self.configurables.append(self.extension_manager) | |
2313 |
|
2314 | |||
2314 | #------------------------------------------------------------------------- |
|
2315 | #------------------------------------------------------------------------- | |
2315 | # Things related to payloads |
|
2316 | # Things related to payloads | |
2316 | #------------------------------------------------------------------------- |
|
2317 | #------------------------------------------------------------------------- | |
2317 |
|
2318 | |||
2318 | def init_payload(self): |
|
2319 | def init_payload(self): | |
2319 | self.payload_manager = PayloadManager(parent=self) |
|
2320 | self.payload_manager = PayloadManager(parent=self) | |
2320 | self.configurables.append(self.payload_manager) |
|
2321 | self.configurables.append(self.payload_manager) | |
2321 |
|
2322 | |||
2322 | #------------------------------------------------------------------------- |
|
2323 | #------------------------------------------------------------------------- | |
2323 | # Things related to widgets |
|
2324 | # Things related to widgets | |
2324 | #------------------------------------------------------------------------- |
|
2325 | #------------------------------------------------------------------------- | |
2325 |
|
2326 | |||
2326 | def init_comms(self): |
|
2327 | def init_comms(self): | |
2327 | # not implemented in the base class |
|
2328 | # not implemented in the base class | |
2328 | pass |
|
2329 | pass | |
2329 |
|
2330 | |||
2330 | #------------------------------------------------------------------------- |
|
2331 | #------------------------------------------------------------------------- | |
2331 | # Things related to the prefilter |
|
2332 | # Things related to the prefilter | |
2332 | #------------------------------------------------------------------------- |
|
2333 | #------------------------------------------------------------------------- | |
2333 |
|
2334 | |||
2334 | def init_prefilter(self): |
|
2335 | def init_prefilter(self): | |
2335 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2336 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) | |
2336 | self.configurables.append(self.prefilter_manager) |
|
2337 | self.configurables.append(self.prefilter_manager) | |
2337 | # Ultimately this will be refactored in the new interpreter code, but |
|
2338 | # Ultimately this will be refactored in the new interpreter code, but | |
2338 | # for now, we should expose the main prefilter method (there's legacy |
|
2339 | # for now, we should expose the main prefilter method (there's legacy | |
2339 | # code out there that may rely on this). |
|
2340 | # code out there that may rely on this). | |
2340 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2341 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2341 |
|
2342 | |||
2342 | def auto_rewrite_input(self, cmd): |
|
2343 | def auto_rewrite_input(self, cmd): | |
2343 | """Print to the screen the rewritten form of the user's command. |
|
2344 | """Print to the screen the rewritten form of the user's command. | |
2344 |
|
2345 | |||
2345 | This shows visual feedback by rewriting input lines that cause |
|
2346 | This shows visual feedback by rewriting input lines that cause | |
2346 | automatic calling to kick in, like:: |
|
2347 | automatic calling to kick in, like:: | |
2347 |
|
2348 | |||
2348 | /f x |
|
2349 | /f x | |
2349 |
|
2350 | |||
2350 | into:: |
|
2351 | into:: | |
2351 |
|
2352 | |||
2352 | ------> f(x) |
|
2353 | ------> f(x) | |
2353 |
|
2354 | |||
2354 | after the user's input prompt. This helps the user understand that the |
|
2355 | after the user's input prompt. This helps the user understand that the | |
2355 | input line was transformed automatically by IPython. |
|
2356 | input line was transformed automatically by IPython. | |
2356 | """ |
|
2357 | """ | |
2357 | if not self.show_rewritten_input: |
|
2358 | if not self.show_rewritten_input: | |
2358 | return |
|
2359 | return | |
2359 |
|
2360 | |||
2360 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2361 | rw = self.prompt_manager.render('rewrite') + cmd | |
2361 |
|
2362 | |||
2362 | try: |
|
2363 | try: | |
2363 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2364 | # plain ascii works better w/ pyreadline, on some machines, so | |
2364 | # we use it and only print uncolored rewrite if we have unicode |
|
2365 | # we use it and only print uncolored rewrite if we have unicode | |
2365 | rw = str(rw) |
|
2366 | rw = str(rw) | |
2366 | print(rw, file=io.stdout) |
|
2367 | print(rw, file=io.stdout) | |
2367 | except UnicodeEncodeError: |
|
2368 | except UnicodeEncodeError: | |
2368 | print("------> " + cmd) |
|
2369 | print("------> " + cmd) | |
2369 |
|
2370 | |||
2370 | #------------------------------------------------------------------------- |
|
2371 | #------------------------------------------------------------------------- | |
2371 | # Things related to extracting values/expressions from kernel and user_ns |
|
2372 | # Things related to extracting values/expressions from kernel and user_ns | |
2372 | #------------------------------------------------------------------------- |
|
2373 | #------------------------------------------------------------------------- | |
2373 |
|
2374 | |||
2374 | def _user_obj_error(self): |
|
2375 | def _user_obj_error(self): | |
2375 | """return simple exception dict |
|
2376 | """return simple exception dict | |
2376 |
|
2377 | |||
2377 | for use in user_variables / expressions |
|
2378 | for use in user_variables / expressions | |
2378 | """ |
|
2379 | """ | |
2379 |
|
2380 | |||
2380 | etype, evalue, tb = self._get_exc_info() |
|
2381 | etype, evalue, tb = self._get_exc_info() | |
2381 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2382 | stb = self.InteractiveTB.get_exception_only(etype, evalue) | |
2382 |
|
2383 | |||
2383 | exc_info = { |
|
2384 | exc_info = { | |
2384 | u'status' : 'error', |
|
2385 | u'status' : 'error', | |
2385 | u'traceback' : stb, |
|
2386 | u'traceback' : stb, | |
2386 | u'ename' : unicode_type(etype.__name__), |
|
2387 | u'ename' : unicode_type(etype.__name__), | |
2387 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2388 | u'evalue' : py3compat.safe_unicode(evalue), | |
2388 | } |
|
2389 | } | |
2389 |
|
2390 | |||
2390 | return exc_info |
|
2391 | return exc_info | |
2391 |
|
2392 | |||
2392 | def _format_user_obj(self, obj): |
|
2393 | def _format_user_obj(self, obj): | |
2393 | """format a user object to display dict |
|
2394 | """format a user object to display dict | |
2394 |
|
2395 | |||
2395 | for use in user_expressions / variables |
|
2396 | for use in user_expressions / variables | |
2396 | """ |
|
2397 | """ | |
2397 |
|
2398 | |||
2398 | data, md = self.display_formatter.format(obj) |
|
2399 | data, md = self.display_formatter.format(obj) | |
2399 | value = { |
|
2400 | value = { | |
2400 | 'status' : 'ok', |
|
2401 | 'status' : 'ok', | |
2401 | 'data' : data, |
|
2402 | 'data' : data, | |
2402 | 'metadata' : md, |
|
2403 | 'metadata' : md, | |
2403 | } |
|
2404 | } | |
2404 | return value |
|
2405 | return value | |
2405 |
|
2406 | |||
2406 | def user_variables(self, names): |
|
2407 | def user_variables(self, names): | |
2407 | """Get a list of variable names from the user's namespace. |
|
2408 | """Get a list of variable names from the user's namespace. | |
2408 |
|
2409 | |||
2409 | Parameters |
|
2410 | Parameters | |
2410 | ---------- |
|
2411 | ---------- | |
2411 | names : list of strings |
|
2412 | names : list of strings | |
2412 | A list of names of variables to be read from the user namespace. |
|
2413 | A list of names of variables to be read from the user namespace. | |
2413 |
|
2414 | |||
2414 | Returns |
|
2415 | Returns | |
2415 | ------- |
|
2416 | ------- | |
2416 | A dict, keyed by the input names and with the rich mime-type repr(s) of each value. |
|
2417 | A dict, keyed by the input names and with the rich mime-type repr(s) of each value. | |
2417 | Each element will be a sub-dict of the same form as a display_data message. |
|
2418 | Each element will be a sub-dict of the same form as a display_data message. | |
2418 | """ |
|
2419 | """ | |
2419 | out = {} |
|
2420 | out = {} | |
2420 | user_ns = self.user_ns |
|
2421 | user_ns = self.user_ns | |
2421 |
|
2422 | |||
2422 | for varname in names: |
|
2423 | for varname in names: | |
2423 | try: |
|
2424 | try: | |
2424 | value = self._format_user_obj(user_ns[varname]) |
|
2425 | value = self._format_user_obj(user_ns[varname]) | |
2425 | except: |
|
2426 | except: | |
2426 | value = self._user_obj_error() |
|
2427 | value = self._user_obj_error() | |
2427 | out[varname] = value |
|
2428 | out[varname] = value | |
2428 | return out |
|
2429 | return out | |
2429 |
|
2430 | |||
2430 | def user_expressions(self, expressions): |
|
2431 | def user_expressions(self, expressions): | |
2431 | """Evaluate a dict of expressions in the user's namespace. |
|
2432 | """Evaluate a dict of expressions in the user's namespace. | |
2432 |
|
2433 | |||
2433 | Parameters |
|
2434 | Parameters | |
2434 | ---------- |
|
2435 | ---------- | |
2435 | expressions : dict |
|
2436 | expressions : dict | |
2436 | A dict with string keys and string values. The expression values |
|
2437 | A dict with string keys and string values. The expression values | |
2437 | should be valid Python expressions, each of which will be evaluated |
|
2438 | should be valid Python expressions, each of which will be evaluated | |
2438 | in the user namespace. |
|
2439 | in the user namespace. | |
2439 |
|
2440 | |||
2440 | Returns |
|
2441 | Returns | |
2441 | ------- |
|
2442 | ------- | |
2442 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2443 | A dict, keyed like the input expressions dict, with the rich mime-typed | |
2443 | display_data of each value. |
|
2444 | display_data of each value. | |
2444 | """ |
|
2445 | """ | |
2445 | out = {} |
|
2446 | out = {} | |
2446 | user_ns = self.user_ns |
|
2447 | user_ns = self.user_ns | |
2447 | global_ns = self.user_global_ns |
|
2448 | global_ns = self.user_global_ns | |
2448 |
|
2449 | |||
2449 | for key, expr in expressions.iteritems(): |
|
2450 | for key, expr in expressions.iteritems(): | |
2450 | try: |
|
2451 | try: | |
2451 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2452 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) | |
2452 | except: |
|
2453 | except: | |
2453 | value = self._user_obj_error() |
|
2454 | value = self._user_obj_error() | |
2454 | out[key] = value |
|
2455 | out[key] = value | |
2455 | return out |
|
2456 | return out | |
2456 |
|
2457 | |||
2457 | #------------------------------------------------------------------------- |
|
2458 | #------------------------------------------------------------------------- | |
2458 | # Things related to the running of code |
|
2459 | # Things related to the running of code | |
2459 | #------------------------------------------------------------------------- |
|
2460 | #------------------------------------------------------------------------- | |
2460 |
|
2461 | |||
2461 | def ex(self, cmd): |
|
2462 | def ex(self, cmd): | |
2462 | """Execute a normal python statement in user namespace.""" |
|
2463 | """Execute a normal python statement in user namespace.""" | |
2463 | with self.builtin_trap: |
|
2464 | with self.builtin_trap: | |
2464 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2465 | exec(cmd, self.user_global_ns, self.user_ns) | |
2465 |
|
2466 | |||
2466 | def ev(self, expr): |
|
2467 | def ev(self, expr): | |
2467 | """Evaluate python expression expr in user namespace. |
|
2468 | """Evaluate python expression expr in user namespace. | |
2468 |
|
2469 | |||
2469 | Returns the result of evaluation |
|
2470 | Returns the result of evaluation | |
2470 | """ |
|
2471 | """ | |
2471 | with self.builtin_trap: |
|
2472 | with self.builtin_trap: | |
2472 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2473 | return eval(expr, self.user_global_ns, self.user_ns) | |
2473 |
|
2474 | |||
2474 | def safe_execfile(self, fname, *where, **kw): |
|
2475 | def safe_execfile(self, fname, *where, **kw): | |
2475 | """A safe version of the builtin execfile(). |
|
2476 | """A safe version of the builtin execfile(). | |
2476 |
|
2477 | |||
2477 | This version will never throw an exception, but instead print |
|
2478 | This version will never throw an exception, but instead print | |
2478 | helpful error messages to the screen. This only works on pure |
|
2479 | helpful error messages to the screen. This only works on pure | |
2479 | Python files with the .py extension. |
|
2480 | Python files with the .py extension. | |
2480 |
|
2481 | |||
2481 | Parameters |
|
2482 | Parameters | |
2482 | ---------- |
|
2483 | ---------- | |
2483 | fname : string |
|
2484 | fname : string | |
2484 | The name of the file to be executed. |
|
2485 | The name of the file to be executed. | |
2485 | where : tuple |
|
2486 | where : tuple | |
2486 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2487 | One or two namespaces, passed to execfile() as (globals,locals). | |
2487 | If only one is given, it is passed as both. |
|
2488 | If only one is given, it is passed as both. | |
2488 | exit_ignore : bool (False) |
|
2489 | exit_ignore : bool (False) | |
2489 | If True, then silence SystemExit for non-zero status (it is always |
|
2490 | If True, then silence SystemExit for non-zero status (it is always | |
2490 | silenced for zero status, as it is so common). |
|
2491 | silenced for zero status, as it is so common). | |
2491 | raise_exceptions : bool (False) |
|
2492 | raise_exceptions : bool (False) | |
2492 | If True raise exceptions everywhere. Meant for testing. |
|
2493 | If True raise exceptions everywhere. Meant for testing. | |
2493 |
|
2494 | |||
2494 | """ |
|
2495 | """ | |
2495 | kw.setdefault('exit_ignore', False) |
|
2496 | kw.setdefault('exit_ignore', False) | |
2496 | kw.setdefault('raise_exceptions', False) |
|
2497 | kw.setdefault('raise_exceptions', False) | |
2497 |
|
2498 | |||
2498 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2499 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2499 |
|
2500 | |||
2500 | # Make sure we can open the file |
|
2501 | # Make sure we can open the file | |
2501 | try: |
|
2502 | try: | |
2502 | with open(fname) as thefile: |
|
2503 | with open(fname) as thefile: | |
2503 | pass |
|
2504 | pass | |
2504 | except: |
|
2505 | except: | |
2505 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2506 | warn('Could not open file <%s> for safe execution.' % fname) | |
2506 | return |
|
2507 | return | |
2507 |
|
2508 | |||
2508 | # Find things also in current directory. This is needed to mimic the |
|
2509 | # Find things also in current directory. This is needed to mimic the | |
2509 | # behavior of running a script from the system command line, where |
|
2510 | # behavior of running a script from the system command line, where | |
2510 | # Python inserts the script's directory into sys.path |
|
2511 | # Python inserts the script's directory into sys.path | |
2511 | dname = os.path.dirname(fname) |
|
2512 | dname = os.path.dirname(fname) | |
2512 |
|
2513 | |||
2513 | with prepended_to_syspath(dname): |
|
2514 | with prepended_to_syspath(dname): | |
2514 | try: |
|
2515 | try: | |
2515 | py3compat.execfile(fname,*where) |
|
2516 | py3compat.execfile(fname,*where) | |
2516 | except SystemExit as status: |
|
2517 | except SystemExit as status: | |
2517 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2518 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2518 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2519 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2519 | # these are considered normal by the OS: |
|
2520 | # these are considered normal by the OS: | |
2520 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2521 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2521 | # 0 |
|
2522 | # 0 | |
2522 | # > python -c'import sys;sys.exit()'; echo $? |
|
2523 | # > python -c'import sys;sys.exit()'; echo $? | |
2523 | # 0 |
|
2524 | # 0 | |
2524 | # For other exit status, we show the exception unless |
|
2525 | # For other exit status, we show the exception unless | |
2525 | # explicitly silenced, but only in short form. |
|
2526 | # explicitly silenced, but only in short form. | |
2526 | if kw['raise_exceptions']: |
|
2527 | if kw['raise_exceptions']: | |
2527 | raise |
|
2528 | raise | |
2528 | if status.code and not kw['exit_ignore']: |
|
2529 | if status.code and not kw['exit_ignore']: | |
2529 | self.showtraceback(exception_only=True) |
|
2530 | self.showtraceback(exception_only=True) | |
2530 | except: |
|
2531 | except: | |
2531 | if kw['raise_exceptions']: |
|
2532 | if kw['raise_exceptions']: | |
2532 | raise |
|
2533 | raise | |
2533 | self.showtraceback() |
|
2534 | self.showtraceback() | |
2534 |
|
2535 | |||
2535 | def safe_execfile_ipy(self, fname): |
|
2536 | def safe_execfile_ipy(self, fname): | |
2536 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2537 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2537 |
|
2538 | |||
2538 | Parameters |
|
2539 | Parameters | |
2539 | ---------- |
|
2540 | ---------- | |
2540 | fname : str |
|
2541 | fname : str | |
2541 | The name of the file to execute. The filename must have a |
|
2542 | The name of the file to execute. The filename must have a | |
2542 | .ipy extension. |
|
2543 | .ipy extension. | |
2543 | """ |
|
2544 | """ | |
2544 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2545 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2545 |
|
2546 | |||
2546 | # Make sure we can open the file |
|
2547 | # Make sure we can open the file | |
2547 | try: |
|
2548 | try: | |
2548 | with open(fname) as thefile: |
|
2549 | with open(fname) as thefile: | |
2549 | pass |
|
2550 | pass | |
2550 | except: |
|
2551 | except: | |
2551 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2552 | warn('Could not open file <%s> for safe execution.' % fname) | |
2552 | return |
|
2553 | return | |
2553 |
|
2554 | |||
2554 | # Find things also in current directory. This is needed to mimic the |
|
2555 | # Find things also in current directory. This is needed to mimic the | |
2555 | # behavior of running a script from the system command line, where |
|
2556 | # behavior of running a script from the system command line, where | |
2556 | # Python inserts the script's directory into sys.path |
|
2557 | # Python inserts the script's directory into sys.path | |
2557 | dname = os.path.dirname(fname) |
|
2558 | dname = os.path.dirname(fname) | |
2558 |
|
2559 | |||
2559 | with prepended_to_syspath(dname): |
|
2560 | with prepended_to_syspath(dname): | |
2560 | try: |
|
2561 | try: | |
2561 | with open(fname) as thefile: |
|
2562 | with open(fname) as thefile: | |
2562 | # self.run_cell currently captures all exceptions |
|
2563 | # self.run_cell currently captures all exceptions | |
2563 | # raised in user code. It would be nice if there were |
|
2564 | # raised in user code. It would be nice if there were | |
2564 | # versions of runlines, execfile that did raise, so |
|
2565 | # versions of runlines, execfile that did raise, so | |
2565 | # we could catch the errors. |
|
2566 | # we could catch the errors. | |
2566 | self.run_cell(thefile.read(), store_history=False, shell_futures=False) |
|
2567 | self.run_cell(thefile.read(), store_history=False, shell_futures=False) | |
2567 | except: |
|
2568 | except: | |
2568 | self.showtraceback() |
|
2569 | self.showtraceback() | |
2569 | warn('Unknown failure executing file: <%s>' % fname) |
|
2570 | warn('Unknown failure executing file: <%s>' % fname) | |
2570 |
|
2571 | |||
2571 | def safe_run_module(self, mod_name, where): |
|
2572 | def safe_run_module(self, mod_name, where): | |
2572 | """A safe version of runpy.run_module(). |
|
2573 | """A safe version of runpy.run_module(). | |
2573 |
|
2574 | |||
2574 | This version will never throw an exception, but instead print |
|
2575 | This version will never throw an exception, but instead print | |
2575 | helpful error messages to the screen. |
|
2576 | helpful error messages to the screen. | |
2576 |
|
2577 | |||
2577 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2578 | `SystemExit` exceptions with status code 0 or None are ignored. | |
2578 |
|
2579 | |||
2579 | Parameters |
|
2580 | Parameters | |
2580 | ---------- |
|
2581 | ---------- | |
2581 | mod_name : string |
|
2582 | mod_name : string | |
2582 | The name of the module to be executed. |
|
2583 | The name of the module to be executed. | |
2583 | where : dict |
|
2584 | where : dict | |
2584 | The globals namespace. |
|
2585 | The globals namespace. | |
2585 | """ |
|
2586 | """ | |
2586 | try: |
|
2587 | try: | |
2587 | try: |
|
2588 | try: | |
2588 | where.update( |
|
2589 | where.update( | |
2589 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2590 | runpy.run_module(str(mod_name), run_name="__main__", | |
2590 | alter_sys=True) |
|
2591 | alter_sys=True) | |
2591 | ) |
|
2592 | ) | |
2592 | except SystemExit as status: |
|
2593 | except SystemExit as status: | |
2593 | if status.code: |
|
2594 | if status.code: | |
2594 | raise |
|
2595 | raise | |
2595 | except: |
|
2596 | except: | |
2596 | self.showtraceback() |
|
2597 | self.showtraceback() | |
2597 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2598 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2598 |
|
2599 | |||
2599 | def _run_cached_cell_magic(self, magic_name, line): |
|
2600 | def _run_cached_cell_magic(self, magic_name, line): | |
2600 | """Special method to call a cell magic with the data stored in self. |
|
2601 | """Special method to call a cell magic with the data stored in self. | |
2601 | """ |
|
2602 | """ | |
2602 | cell = self._current_cell_magic_body |
|
2603 | cell = self._current_cell_magic_body | |
2603 | self._current_cell_magic_body = None |
|
2604 | self._current_cell_magic_body = None | |
2604 | return self.run_cell_magic(magic_name, line, cell) |
|
2605 | return self.run_cell_magic(magic_name, line, cell) | |
2605 |
|
2606 | |||
2606 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2607 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
2607 | """Run a complete IPython cell. |
|
2608 | """Run a complete IPython cell. | |
2608 |
|
2609 | |||
2609 | Parameters |
|
2610 | Parameters | |
2610 | ---------- |
|
2611 | ---------- | |
2611 | raw_cell : str |
|
2612 | raw_cell : str | |
2612 | The code (including IPython code such as %magic functions) to run. |
|
2613 | The code (including IPython code such as %magic functions) to run. | |
2613 | store_history : bool |
|
2614 | store_history : bool | |
2614 | If True, the raw and translated cell will be stored in IPython's |
|
2615 | If True, the raw and translated cell will be stored in IPython's | |
2615 | history. For user code calling back into IPython's machinery, this |
|
2616 | history. For user code calling back into IPython's machinery, this | |
2616 | should be set to False. |
|
2617 | should be set to False. | |
2617 | silent : bool |
|
2618 | silent : bool | |
2618 | If True, avoid side-effects, such as implicit displayhooks and |
|
2619 | If True, avoid side-effects, such as implicit displayhooks and | |
2619 | and logging. silent=True forces store_history=False. |
|
2620 | and logging. silent=True forces store_history=False. | |
2620 | shell_futures : bool |
|
2621 | shell_futures : bool | |
2621 | If True, the code will share future statements with the interactive |
|
2622 | If True, the code will share future statements with the interactive | |
2622 | shell. It will both be affected by previous __future__ imports, and |
|
2623 | shell. It will both be affected by previous __future__ imports, and | |
2623 | any __future__ imports in the code will affect the shell. If False, |
|
2624 | any __future__ imports in the code will affect the shell. If False, | |
2624 | __future__ imports are not shared in either direction. |
|
2625 | __future__ imports are not shared in either direction. | |
2625 | """ |
|
2626 | """ | |
2626 | if (not raw_cell) or raw_cell.isspace(): |
|
2627 | if (not raw_cell) or raw_cell.isspace(): | |
2627 | return |
|
2628 | return | |
2628 |
|
2629 | |||
2629 | if silent: |
|
2630 | if silent: | |
2630 | store_history = False |
|
2631 | store_history = False | |
2631 |
|
2632 | |||
2632 | self.input_transformer_manager.push(raw_cell) |
|
2633 | self.input_transformer_manager.push(raw_cell) | |
2633 | cell = self.input_transformer_manager.source_reset() |
|
2634 | cell = self.input_transformer_manager.source_reset() | |
2634 |
|
2635 | |||
2635 | # Our own compiler remembers the __future__ environment. If we want to |
|
2636 | # Our own compiler remembers the __future__ environment. If we want to | |
2636 | # run code with a separate __future__ environment, use the default |
|
2637 | # run code with a separate __future__ environment, use the default | |
2637 | # compiler |
|
2638 | # compiler | |
2638 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2639 | compiler = self.compile if shell_futures else CachingCompiler() | |
2639 |
|
2640 | |||
2640 | with self.builtin_trap: |
|
2641 | with self.builtin_trap: | |
2641 | prefilter_failed = False |
|
2642 | prefilter_failed = False | |
2642 | if len(cell.splitlines()) == 1: |
|
2643 | if len(cell.splitlines()) == 1: | |
2643 | try: |
|
2644 | try: | |
2644 | # use prefilter_lines to handle trailing newlines |
|
2645 | # use prefilter_lines to handle trailing newlines | |
2645 | # restore trailing newline for ast.parse |
|
2646 | # restore trailing newline for ast.parse | |
2646 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2647 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2647 | except AliasError as e: |
|
2648 | except AliasError as e: | |
2648 | error(e) |
|
2649 | error(e) | |
2649 | prefilter_failed = True |
|
2650 | prefilter_failed = True | |
2650 | except Exception: |
|
2651 | except Exception: | |
2651 | # don't allow prefilter errors to crash IPython |
|
2652 | # don't allow prefilter errors to crash IPython | |
2652 | self.showtraceback() |
|
2653 | self.showtraceback() | |
2653 | prefilter_failed = True |
|
2654 | prefilter_failed = True | |
2654 |
|
2655 | |||
2655 | # Store raw and processed history |
|
2656 | # Store raw and processed history | |
2656 | if store_history: |
|
2657 | if store_history: | |
2657 | self.history_manager.store_inputs(self.execution_count, |
|
2658 | self.history_manager.store_inputs(self.execution_count, | |
2658 | cell, raw_cell) |
|
2659 | cell, raw_cell) | |
2659 | if not silent: |
|
2660 | if not silent: | |
2660 | self.logger.log(cell, raw_cell) |
|
2661 | self.logger.log(cell, raw_cell) | |
2661 |
|
2662 | |||
2662 | if not prefilter_failed: |
|
2663 | if not prefilter_failed: | |
2663 | # don't run if prefilter failed |
|
2664 | # don't run if prefilter failed | |
2664 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2665 | cell_name = self.compile.cache(cell, self.execution_count) | |
2665 |
|
2666 | |||
2666 | with self.display_trap: |
|
2667 | with self.display_trap: | |
2667 | try: |
|
2668 | try: | |
2668 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2669 | code_ast = compiler.ast_parse(cell, filename=cell_name) | |
2669 | except IndentationError: |
|
2670 | except IndentationError: | |
2670 | self.showindentationerror() |
|
2671 | self.showindentationerror() | |
2671 | if store_history: |
|
2672 | if store_history: | |
2672 | self.execution_count += 1 |
|
2673 | self.execution_count += 1 | |
2673 | return None |
|
2674 | return None | |
2674 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2675 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2675 | MemoryError): |
|
2676 | MemoryError): | |
2676 | self.showsyntaxerror() |
|
2677 | self.showsyntaxerror() | |
2677 | if store_history: |
|
2678 | if store_history: | |
2678 | self.execution_count += 1 |
|
2679 | self.execution_count += 1 | |
2679 | return None |
|
2680 | return None | |
2680 |
|
2681 | |||
2681 | code_ast = self.transform_ast(code_ast) |
|
2682 | code_ast = self.transform_ast(code_ast) | |
2682 |
|
2683 | |||
2683 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2684 | interactivity = "none" if silent else self.ast_node_interactivity | |
2684 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2685 | self.run_ast_nodes(code_ast.body, cell_name, | |
2685 | interactivity=interactivity, compiler=compiler) |
|
2686 | interactivity=interactivity, compiler=compiler) | |
2686 |
|
2687 | |||
2687 | # Execute any registered post-execution functions. |
|
2688 | # Execute any registered post-execution functions. | |
2688 | # unless we are silent |
|
2689 | # unless we are silent | |
2689 | post_exec = [] if silent else self._post_execute.iteritems() |
|
2690 | post_exec = [] if silent else self._post_execute.iteritems() | |
2690 |
|
2691 | |||
2691 | for func, status in post_exec: |
|
2692 | for func, status in post_exec: | |
2692 | if self.disable_failing_post_execute and not status: |
|
2693 | if self.disable_failing_post_execute and not status: | |
2693 | continue |
|
2694 | continue | |
2694 | try: |
|
2695 | try: | |
2695 | func() |
|
2696 | func() | |
2696 | except KeyboardInterrupt: |
|
2697 | except KeyboardInterrupt: | |
2697 | print("\nKeyboardInterrupt", file=io.stderr) |
|
2698 | print("\nKeyboardInterrupt", file=io.stderr) | |
2698 | except Exception: |
|
2699 | except Exception: | |
2699 | # register as failing: |
|
2700 | # register as failing: | |
2700 | self._post_execute[func] = False |
|
2701 | self._post_execute[func] = False | |
2701 | self.showtraceback() |
|
2702 | self.showtraceback() | |
2702 | print('\n'.join([ |
|
2703 | print('\n'.join([ | |
2703 | "post-execution function %r produced an error." % func, |
|
2704 | "post-execution function %r produced an error." % func, | |
2704 | "If this problem persists, you can disable failing post-exec functions with:", |
|
2705 | "If this problem persists, you can disable failing post-exec functions with:", | |
2705 | "", |
|
2706 | "", | |
2706 | " get_ipython().disable_failing_post_execute = True" |
|
2707 | " get_ipython().disable_failing_post_execute = True" | |
2707 | ]), file=io.stderr) |
|
2708 | ]), file=io.stderr) | |
2708 |
|
2709 | |||
2709 | if store_history: |
|
2710 | if store_history: | |
2710 | # Write output to the database. Does nothing unless |
|
2711 | # Write output to the database. Does nothing unless | |
2711 | # history output logging is enabled. |
|
2712 | # history output logging is enabled. | |
2712 | self.history_manager.store_output(self.execution_count) |
|
2713 | self.history_manager.store_output(self.execution_count) | |
2713 | # Each cell is a *single* input, regardless of how many lines it has |
|
2714 | # Each cell is a *single* input, regardless of how many lines it has | |
2714 | self.execution_count += 1 |
|
2715 | self.execution_count += 1 | |
2715 |
|
2716 | |||
2716 | def transform_ast(self, node): |
|
2717 | def transform_ast(self, node): | |
2717 | """Apply the AST transformations from self.ast_transformers |
|
2718 | """Apply the AST transformations from self.ast_transformers | |
2718 |
|
2719 | |||
2719 | Parameters |
|
2720 | Parameters | |
2720 | ---------- |
|
2721 | ---------- | |
2721 | node : ast.Node |
|
2722 | node : ast.Node | |
2722 | The root node to be transformed. Typically called with the ast.Module |
|
2723 | The root node to be transformed. Typically called with the ast.Module | |
2723 | produced by parsing user input. |
|
2724 | produced by parsing user input. | |
2724 |
|
2725 | |||
2725 | Returns |
|
2726 | Returns | |
2726 | ------- |
|
2727 | ------- | |
2727 | An ast.Node corresponding to the node it was called with. Note that it |
|
2728 | An ast.Node corresponding to the node it was called with. Note that it | |
2728 | may also modify the passed object, so don't rely on references to the |
|
2729 | may also modify the passed object, so don't rely on references to the | |
2729 | original AST. |
|
2730 | original AST. | |
2730 | """ |
|
2731 | """ | |
2731 | for transformer in self.ast_transformers: |
|
2732 | for transformer in self.ast_transformers: | |
2732 | try: |
|
2733 | try: | |
2733 | node = transformer.visit(node) |
|
2734 | node = transformer.visit(node) | |
2734 | except Exception: |
|
2735 | except Exception: | |
2735 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2736 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) | |
2736 | self.ast_transformers.remove(transformer) |
|
2737 | self.ast_transformers.remove(transformer) | |
2737 |
|
2738 | |||
2738 | if self.ast_transformers: |
|
2739 | if self.ast_transformers: | |
2739 | ast.fix_missing_locations(node) |
|
2740 | ast.fix_missing_locations(node) | |
2740 | return node |
|
2741 | return node | |
2741 |
|
2742 | |||
2742 |
|
2743 | |||
2743 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2744 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', | |
2744 | compiler=compile): |
|
2745 | compiler=compile): | |
2745 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2746 | """Run a sequence of AST nodes. The execution mode depends on the | |
2746 | interactivity parameter. |
|
2747 | interactivity parameter. | |
2747 |
|
2748 | |||
2748 | Parameters |
|
2749 | Parameters | |
2749 | ---------- |
|
2750 | ---------- | |
2750 | nodelist : list |
|
2751 | nodelist : list | |
2751 | A sequence of AST nodes to run. |
|
2752 | A sequence of AST nodes to run. | |
2752 | cell_name : str |
|
2753 | cell_name : str | |
2753 | Will be passed to the compiler as the filename of the cell. Typically |
|
2754 | Will be passed to the compiler as the filename of the cell. Typically | |
2754 | the value returned by ip.compile.cache(cell). |
|
2755 | the value returned by ip.compile.cache(cell). | |
2755 | interactivity : str |
|
2756 | interactivity : str | |
2756 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2757 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be | |
2757 | run interactively (displaying output from expressions). 'last_expr' |
|
2758 | run interactively (displaying output from expressions). 'last_expr' | |
2758 | will run the last node interactively only if it is an expression (i.e. |
|
2759 | will run the last node interactively only if it is an expression (i.e. | |
2759 | expressions in loops or other blocks are not displayed. Other values |
|
2760 | expressions in loops or other blocks are not displayed. Other values | |
2760 | for this parameter will raise a ValueError. |
|
2761 | for this parameter will raise a ValueError. | |
2761 | compiler : callable |
|
2762 | compiler : callable | |
2762 | A function with the same interface as the built-in compile(), to turn |
|
2763 | A function with the same interface as the built-in compile(), to turn | |
2763 | the AST nodes into code objects. Default is the built-in compile(). |
|
2764 | the AST nodes into code objects. Default is the built-in compile(). | |
2764 | """ |
|
2765 | """ | |
2765 | if not nodelist: |
|
2766 | if not nodelist: | |
2766 | return |
|
2767 | return | |
2767 |
|
2768 | |||
2768 | if interactivity == 'last_expr': |
|
2769 | if interactivity == 'last_expr': | |
2769 | if isinstance(nodelist[-1], ast.Expr): |
|
2770 | if isinstance(nodelist[-1], ast.Expr): | |
2770 | interactivity = "last" |
|
2771 | interactivity = "last" | |
2771 | else: |
|
2772 | else: | |
2772 | interactivity = "none" |
|
2773 | interactivity = "none" | |
2773 |
|
2774 | |||
2774 | if interactivity == 'none': |
|
2775 | if interactivity == 'none': | |
2775 | to_run_exec, to_run_interactive = nodelist, [] |
|
2776 | to_run_exec, to_run_interactive = nodelist, [] | |
2776 | elif interactivity == 'last': |
|
2777 | elif interactivity == 'last': | |
2777 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2778 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2778 | elif interactivity == 'all': |
|
2779 | elif interactivity == 'all': | |
2779 | to_run_exec, to_run_interactive = [], nodelist |
|
2780 | to_run_exec, to_run_interactive = [], nodelist | |
2780 | else: |
|
2781 | else: | |
2781 | raise ValueError("Interactivity was %r" % interactivity) |
|
2782 | raise ValueError("Interactivity was %r" % interactivity) | |
2782 |
|
2783 | |||
2783 | exec_count = self.execution_count |
|
2784 | exec_count = self.execution_count | |
2784 |
|
2785 | |||
2785 | try: |
|
2786 | try: | |
2786 | for i, node in enumerate(to_run_exec): |
|
2787 | for i, node in enumerate(to_run_exec): | |
2787 | mod = ast.Module([node]) |
|
2788 | mod = ast.Module([node]) | |
2788 | code = compiler(mod, cell_name, "exec") |
|
2789 | code = compiler(mod, cell_name, "exec") | |
2789 | if self.run_code(code): |
|
2790 | if self.run_code(code): | |
2790 | return True |
|
2791 | return True | |
2791 |
|
2792 | |||
2792 | for i, node in enumerate(to_run_interactive): |
|
2793 | for i, node in enumerate(to_run_interactive): | |
2793 | mod = ast.Interactive([node]) |
|
2794 | mod = ast.Interactive([node]) | |
2794 | code = compiler(mod, cell_name, "single") |
|
2795 | code = compiler(mod, cell_name, "single") | |
2795 | if self.run_code(code): |
|
2796 | if self.run_code(code): | |
2796 | return True |
|
2797 | return True | |
2797 |
|
2798 | |||
2798 | # Flush softspace |
|
2799 | # Flush softspace | |
2799 | if softspace(sys.stdout, 0): |
|
2800 | if softspace(sys.stdout, 0): | |
2800 | print() |
|
2801 | print() | |
2801 |
|
2802 | |||
2802 | except: |
|
2803 | except: | |
2803 | # It's possible to have exceptions raised here, typically by |
|
2804 | # It's possible to have exceptions raised here, typically by | |
2804 | # compilation of odd code (such as a naked 'return' outside a |
|
2805 | # compilation of odd code (such as a naked 'return' outside a | |
2805 | # function) that did parse but isn't valid. Typically the exception |
|
2806 | # function) that did parse but isn't valid. Typically the exception | |
2806 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2807 | # is a SyntaxError, but it's safest just to catch anything and show | |
2807 | # the user a traceback. |
|
2808 | # the user a traceback. | |
2808 |
|
2809 | |||
2809 | # We do only one try/except outside the loop to minimize the impact |
|
2810 | # We do only one try/except outside the loop to minimize the impact | |
2810 | # on runtime, and also because if any node in the node list is |
|
2811 | # on runtime, and also because if any node in the node list is | |
2811 | # broken, we should stop execution completely. |
|
2812 | # broken, we should stop execution completely. | |
2812 | self.showtraceback() |
|
2813 | self.showtraceback() | |
2813 |
|
2814 | |||
2814 | return False |
|
2815 | return False | |
2815 |
|
2816 | |||
2816 | def run_code(self, code_obj): |
|
2817 | def run_code(self, code_obj): | |
2817 | """Execute a code object. |
|
2818 | """Execute a code object. | |
2818 |
|
2819 | |||
2819 | When an exception occurs, self.showtraceback() is called to display a |
|
2820 | When an exception occurs, self.showtraceback() is called to display a | |
2820 | traceback. |
|
2821 | traceback. | |
2821 |
|
2822 | |||
2822 | Parameters |
|
2823 | Parameters | |
2823 | ---------- |
|
2824 | ---------- | |
2824 | code_obj : code object |
|
2825 | code_obj : code object | |
2825 | A compiled code object, to be executed |
|
2826 | A compiled code object, to be executed | |
2826 |
|
2827 | |||
2827 | Returns |
|
2828 | Returns | |
2828 | ------- |
|
2829 | ------- | |
2829 | False : successful execution. |
|
2830 | False : successful execution. | |
2830 | True : an error occurred. |
|
2831 | True : an error occurred. | |
2831 | """ |
|
2832 | """ | |
2832 |
|
2833 | |||
2833 | # Set our own excepthook in case the user code tries to call it |
|
2834 | # Set our own excepthook in case the user code tries to call it | |
2834 | # directly, so that the IPython crash handler doesn't get triggered |
|
2835 | # directly, so that the IPython crash handler doesn't get triggered | |
2835 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2836 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2836 |
|
2837 | |||
2837 | # we save the original sys.excepthook in the instance, in case config |
|
2838 | # we save the original sys.excepthook in the instance, in case config | |
2838 | # code (such as magics) needs access to it. |
|
2839 | # code (such as magics) needs access to it. | |
2839 | self.sys_excepthook = old_excepthook |
|
2840 | self.sys_excepthook = old_excepthook | |
2840 | outflag = 1 # happens in more places, so it's easier as default |
|
2841 | outflag = 1 # happens in more places, so it's easier as default | |
2841 | try: |
|
2842 | try: | |
2842 | try: |
|
2843 | try: | |
2843 | self.hooks.pre_run_code_hook() |
|
2844 | self.hooks.pre_run_code_hook() | |
2844 | #rprint('Running code', repr(code_obj)) # dbg |
|
2845 | #rprint('Running code', repr(code_obj)) # dbg | |
2845 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2846 | exec(code_obj, self.user_global_ns, self.user_ns) | |
2846 | finally: |
|
2847 | finally: | |
2847 | # Reset our crash handler in place |
|
2848 | # Reset our crash handler in place | |
2848 | sys.excepthook = old_excepthook |
|
2849 | sys.excepthook = old_excepthook | |
2849 | except SystemExit: |
|
2850 | except SystemExit: | |
2850 | self.showtraceback(exception_only=True) |
|
2851 | self.showtraceback(exception_only=True) | |
2851 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2852 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) | |
2852 | except self.custom_exceptions: |
|
2853 | except self.custom_exceptions: | |
2853 | etype,value,tb = sys.exc_info() |
|
2854 | etype,value,tb = sys.exc_info() | |
2854 | self.CustomTB(etype,value,tb) |
|
2855 | self.CustomTB(etype,value,tb) | |
2855 | except: |
|
2856 | except: | |
2856 | self.showtraceback() |
|
2857 | self.showtraceback() | |
2857 | else: |
|
2858 | else: | |
2858 | outflag = 0 |
|
2859 | outflag = 0 | |
2859 | return outflag |
|
2860 | return outflag | |
2860 |
|
2861 | |||
2861 | # For backwards compatibility |
|
2862 | # For backwards compatibility | |
2862 | runcode = run_code |
|
2863 | runcode = run_code | |
2863 |
|
2864 | |||
2864 | #------------------------------------------------------------------------- |
|
2865 | #------------------------------------------------------------------------- | |
2865 | # Things related to GUI support and pylab |
|
2866 | # Things related to GUI support and pylab | |
2866 | #------------------------------------------------------------------------- |
|
2867 | #------------------------------------------------------------------------- | |
2867 |
|
2868 | |||
2868 | def enable_gui(self, gui=None): |
|
2869 | def enable_gui(self, gui=None): | |
2869 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2870 | raise NotImplementedError('Implement enable_gui in a subclass') | |
2870 |
|
2871 | |||
2871 | def enable_matplotlib(self, gui=None): |
|
2872 | def enable_matplotlib(self, gui=None): | |
2872 | """Enable interactive matplotlib and inline figure support. |
|
2873 | """Enable interactive matplotlib and inline figure support. | |
2873 |
|
2874 | |||
2874 | This takes the following steps: |
|
2875 | This takes the following steps: | |
2875 |
|
2876 | |||
2876 | 1. select the appropriate eventloop and matplotlib backend |
|
2877 | 1. select the appropriate eventloop and matplotlib backend | |
2877 | 2. set up matplotlib for interactive use with that backend |
|
2878 | 2. set up matplotlib for interactive use with that backend | |
2878 | 3. configure formatters for inline figure display |
|
2879 | 3. configure formatters for inline figure display | |
2879 | 4. enable the selected gui eventloop |
|
2880 | 4. enable the selected gui eventloop | |
2880 |
|
2881 | |||
2881 | Parameters |
|
2882 | Parameters | |
2882 | ---------- |
|
2883 | ---------- | |
2883 | gui : optional, string |
|
2884 | gui : optional, string | |
2884 | If given, dictates the choice of matplotlib GUI backend to use |
|
2885 | If given, dictates the choice of matplotlib GUI backend to use | |
2885 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2886 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2886 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2887 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2887 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2888 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2888 | user's matplotlibrc configuration file). Note that not all backends |
|
2889 | user's matplotlibrc configuration file). Note that not all backends | |
2889 | make sense in all contexts, for example a terminal ipython can't |
|
2890 | make sense in all contexts, for example a terminal ipython can't | |
2890 | display figures inline. |
|
2891 | display figures inline. | |
2891 | """ |
|
2892 | """ | |
2892 | from IPython.core import pylabtools as pt |
|
2893 | from IPython.core import pylabtools as pt | |
2893 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2894 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) | |
2894 |
|
2895 | |||
2895 | if gui != 'inline': |
|
2896 | if gui != 'inline': | |
2896 | # If we have our first gui selection, store it |
|
2897 | # If we have our first gui selection, store it | |
2897 | if self.pylab_gui_select is None: |
|
2898 | if self.pylab_gui_select is None: | |
2898 | self.pylab_gui_select = gui |
|
2899 | self.pylab_gui_select = gui | |
2899 | # Otherwise if they are different |
|
2900 | # Otherwise if they are different | |
2900 | elif gui != self.pylab_gui_select: |
|
2901 | elif gui != self.pylab_gui_select: | |
2901 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2902 | print ('Warning: Cannot change to a different GUI toolkit: %s.' | |
2902 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2903 | ' Using %s instead.' % (gui, self.pylab_gui_select)) | |
2903 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2904 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) | |
2904 |
|
2905 | |||
2905 | pt.activate_matplotlib(backend) |
|
2906 | pt.activate_matplotlib(backend) | |
2906 | pt.configure_inline_support(self, backend) |
|
2907 | pt.configure_inline_support(self, backend) | |
2907 |
|
2908 | |||
2908 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2909 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
2909 | # plot updates into account |
|
2910 | # plot updates into account | |
2910 | self.enable_gui(gui) |
|
2911 | self.enable_gui(gui) | |
2911 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2912 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
2912 | pt.mpl_runner(self.safe_execfile) |
|
2913 | pt.mpl_runner(self.safe_execfile) | |
2913 |
|
2914 | |||
2914 | return gui, backend |
|
2915 | return gui, backend | |
2915 |
|
2916 | |||
2916 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2917 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): | |
2917 | """Activate pylab support at runtime. |
|
2918 | """Activate pylab support at runtime. | |
2918 |
|
2919 | |||
2919 | This turns on support for matplotlib, preloads into the interactive |
|
2920 | This turns on support for matplotlib, preloads into the interactive | |
2920 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2921 | namespace all of numpy and pylab, and configures IPython to correctly | |
2921 | interact with the GUI event loop. The GUI backend to be used can be |
|
2922 | interact with the GUI event loop. The GUI backend to be used can be | |
2922 | optionally selected with the optional ``gui`` argument. |
|
2923 | optionally selected with the optional ``gui`` argument. | |
2923 |
|
2924 | |||
2924 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2925 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. | |
2925 |
|
2926 | |||
2926 | Parameters |
|
2927 | Parameters | |
2927 | ---------- |
|
2928 | ---------- | |
2928 | gui : optional, string |
|
2929 | gui : optional, string | |
2929 | If given, dictates the choice of matplotlib GUI backend to use |
|
2930 | If given, dictates the choice of matplotlib GUI backend to use | |
2930 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2931 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
2931 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2932 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
2932 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2933 | matplotlib (as dictated by the matplotlib build-time options plus the | |
2933 | user's matplotlibrc configuration file). Note that not all backends |
|
2934 | user's matplotlibrc configuration file). Note that not all backends | |
2934 | make sense in all contexts, for example a terminal ipython can't |
|
2935 | make sense in all contexts, for example a terminal ipython can't | |
2935 | display figures inline. |
|
2936 | display figures inline. | |
2936 | import_all : optional, bool, default: True |
|
2937 | import_all : optional, bool, default: True | |
2937 | Whether to do `from numpy import *` and `from pylab import *` |
|
2938 | Whether to do `from numpy import *` and `from pylab import *` | |
2938 | in addition to module imports. |
|
2939 | in addition to module imports. | |
2939 | welcome_message : deprecated |
|
2940 | welcome_message : deprecated | |
2940 | This argument is ignored, no welcome message will be displayed. |
|
2941 | This argument is ignored, no welcome message will be displayed. | |
2941 | """ |
|
2942 | """ | |
2942 | from IPython.core.pylabtools import import_pylab |
|
2943 | from IPython.core.pylabtools import import_pylab | |
2943 |
|
2944 | |||
2944 | gui, backend = self.enable_matplotlib(gui) |
|
2945 | gui, backend = self.enable_matplotlib(gui) | |
2945 |
|
2946 | |||
2946 | # We want to prevent the loading of pylab to pollute the user's |
|
2947 | # We want to prevent the loading of pylab to pollute the user's | |
2947 | # namespace as shown by the %who* magics, so we execute the activation |
|
2948 | # namespace as shown by the %who* magics, so we execute the activation | |
2948 | # code in an empty namespace, and we update *both* user_ns and |
|
2949 | # code in an empty namespace, and we update *both* user_ns and | |
2949 | # user_ns_hidden with this information. |
|
2950 | # user_ns_hidden with this information. | |
2950 | ns = {} |
|
2951 | ns = {} | |
2951 | import_pylab(ns, import_all) |
|
2952 | import_pylab(ns, import_all) | |
2952 | # warn about clobbered names |
|
2953 | # warn about clobbered names | |
2953 | ignored = set(["__builtins__"]) |
|
2954 | ignored = set(["__builtins__"]) | |
2954 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
2955 | both = set(ns).intersection(self.user_ns).difference(ignored) | |
2955 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
2956 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] | |
2956 | self.user_ns.update(ns) |
|
2957 | self.user_ns.update(ns) | |
2957 | self.user_ns_hidden.update(ns) |
|
2958 | self.user_ns_hidden.update(ns) | |
2958 | return gui, backend, clobbered |
|
2959 | return gui, backend, clobbered | |
2959 |
|
2960 | |||
2960 | #------------------------------------------------------------------------- |
|
2961 | #------------------------------------------------------------------------- | |
2961 | # Utilities |
|
2962 | # Utilities | |
2962 | #------------------------------------------------------------------------- |
|
2963 | #------------------------------------------------------------------------- | |
2963 |
|
2964 | |||
2964 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
2965 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
2965 | """Expand python variables in a string. |
|
2966 | """Expand python variables in a string. | |
2966 |
|
2967 | |||
2967 | The depth argument indicates how many frames above the caller should |
|
2968 | The depth argument indicates how many frames above the caller should | |
2968 | be walked to look for the local namespace where to expand variables. |
|
2969 | be walked to look for the local namespace where to expand variables. | |
2969 |
|
2970 | |||
2970 | The global namespace for expansion is always the user's interactive |
|
2971 | The global namespace for expansion is always the user's interactive | |
2971 | namespace. |
|
2972 | namespace. | |
2972 | """ |
|
2973 | """ | |
2973 | ns = self.user_ns.copy() |
|
2974 | ns = self.user_ns.copy() | |
2974 | ns.update(sys._getframe(depth+1).f_locals) |
|
2975 | ns.update(sys._getframe(depth+1).f_locals) | |
2975 | try: |
|
2976 | try: | |
2976 | # We have to use .vformat() here, because 'self' is a valid and common |
|
2977 | # We have to use .vformat() here, because 'self' is a valid and common | |
2977 | # name, and expanding **ns for .format() would make it collide with |
|
2978 | # name, and expanding **ns for .format() would make it collide with | |
2978 | # the 'self' argument of the method. |
|
2979 | # the 'self' argument of the method. | |
2979 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
2980 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) | |
2980 | except Exception: |
|
2981 | except Exception: | |
2981 | # if formatter couldn't format, just let it go untransformed |
|
2982 | # if formatter couldn't format, just let it go untransformed | |
2982 | pass |
|
2983 | pass | |
2983 | return cmd |
|
2984 | return cmd | |
2984 |
|
2985 | |||
2985 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2986 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
2986 | """Make a new tempfile and return its filename. |
|
2987 | """Make a new tempfile and return its filename. | |
2987 |
|
2988 | |||
2988 | This makes a call to tempfile.mktemp, but it registers the created |
|
2989 | This makes a call to tempfile.mktemp, but it registers the created | |
2989 | filename internally so ipython cleans it up at exit time. |
|
2990 | filename internally so ipython cleans it up at exit time. | |
2990 |
|
2991 | |||
2991 | Optional inputs: |
|
2992 | Optional inputs: | |
2992 |
|
2993 | |||
2993 | - data(None): if data is given, it gets written out to the temp file |
|
2994 | - data(None): if data is given, it gets written out to the temp file | |
2994 | immediately, and the file is closed again.""" |
|
2995 | immediately, and the file is closed again.""" | |
2995 |
|
2996 | |||
2996 | filename = tempfile.mktemp('.py', prefix) |
|
2997 | filename = tempfile.mktemp('.py', prefix) | |
2997 | self.tempfiles.append(filename) |
|
2998 | self.tempfiles.append(filename) | |
2998 |
|
2999 | |||
2999 | if data: |
|
3000 | if data: | |
3000 | tmp_file = open(filename,'w') |
|
3001 | tmp_file = open(filename,'w') | |
3001 | tmp_file.write(data) |
|
3002 | tmp_file.write(data) | |
3002 | tmp_file.close() |
|
3003 | tmp_file.close() | |
3003 | return filename |
|
3004 | return filename | |
3004 |
|
3005 | |||
3005 | # TODO: This should be removed when Term is refactored. |
|
3006 | # TODO: This should be removed when Term is refactored. | |
3006 | def write(self,data): |
|
3007 | def write(self,data): | |
3007 | """Write a string to the default output""" |
|
3008 | """Write a string to the default output""" | |
3008 | io.stdout.write(data) |
|
3009 | io.stdout.write(data) | |
3009 |
|
3010 | |||
3010 | # TODO: This should be removed when Term is refactored. |
|
3011 | # TODO: This should be removed when Term is refactored. | |
3011 | def write_err(self,data): |
|
3012 | def write_err(self,data): | |
3012 | """Write a string to the default error output""" |
|
3013 | """Write a string to the default error output""" | |
3013 | io.stderr.write(data) |
|
3014 | io.stderr.write(data) | |
3014 |
|
3015 | |||
3015 | def ask_yes_no(self, prompt, default=None): |
|
3016 | def ask_yes_no(self, prompt, default=None): | |
3016 | if self.quiet: |
|
3017 | if self.quiet: | |
3017 | return True |
|
3018 | return True | |
3018 | return ask_yes_no(prompt,default) |
|
3019 | return ask_yes_no(prompt,default) | |
3019 |
|
3020 | |||
3020 | def show_usage(self): |
|
3021 | def show_usage(self): | |
3021 | """Show a usage message""" |
|
3022 | """Show a usage message""" | |
3022 | page.page(IPython.core.usage.interactive_usage) |
|
3023 | page.page(IPython.core.usage.interactive_usage) | |
3023 |
|
3024 | |||
3024 | def extract_input_lines(self, range_str, raw=False): |
|
3025 | def extract_input_lines(self, range_str, raw=False): | |
3025 | """Return as a string a set of input history slices. |
|
3026 | """Return as a string a set of input history slices. | |
3026 |
|
3027 | |||
3027 | Parameters |
|
3028 | Parameters | |
3028 | ---------- |
|
3029 | ---------- | |
3029 | range_str : string |
|
3030 | range_str : string | |
3030 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3031 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
3031 | since this function is for use by magic functions which get their |
|
3032 | since this function is for use by magic functions which get their | |
3032 | arguments as strings. The number before the / is the session |
|
3033 | arguments as strings. The number before the / is the session | |
3033 | number: ~n goes n back from the current session. |
|
3034 | number: ~n goes n back from the current session. | |
3034 |
|
3035 | |||
3035 | Optional Parameters: |
|
3036 | Optional Parameters: | |
3036 | - raw(False): by default, the processed input is used. If this is |
|
3037 | - raw(False): by default, the processed input is used. If this is | |
3037 | true, the raw input history is used instead. |
|
3038 | true, the raw input history is used instead. | |
3038 |
|
3039 | |||
3039 | Note that slices can be called with two notations: |
|
3040 | Note that slices can be called with two notations: | |
3040 |
|
3041 | |||
3041 | N:M -> standard python form, means including items N...(M-1). |
|
3042 | N:M -> standard python form, means including items N...(M-1). | |
3042 |
|
3043 | |||
3043 | N-M -> include items N..M (closed endpoint). |
|
3044 | N-M -> include items N..M (closed endpoint). | |
3044 | """ |
|
3045 | """ | |
3045 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3046 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
3046 | return "\n".join(x for _, _, x in lines) |
|
3047 | return "\n".join(x for _, _, x in lines) | |
3047 |
|
3048 | |||
3048 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True): |
|
3049 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True): | |
3049 | """Get a code string from history, file, url, or a string or macro. |
|
3050 | """Get a code string from history, file, url, or a string or macro. | |
3050 |
|
3051 | |||
3051 | This is mainly used by magic functions. |
|
3052 | This is mainly used by magic functions. | |
3052 |
|
3053 | |||
3053 | Parameters |
|
3054 | Parameters | |
3054 | ---------- |
|
3055 | ---------- | |
3055 |
|
3056 | |||
3056 | target : str |
|
3057 | target : str | |
3057 |
|
3058 | |||
3058 | A string specifying code to retrieve. This will be tried respectively |
|
3059 | A string specifying code to retrieve. This will be tried respectively | |
3059 | as: ranges of input history (see %history for syntax), url, |
|
3060 | as: ranges of input history (see %history for syntax), url, | |
3060 | correspnding .py file, filename, or an expression evaluating to a |
|
3061 | correspnding .py file, filename, or an expression evaluating to a | |
3061 | string or Macro in the user namespace. |
|
3062 | string or Macro in the user namespace. | |
3062 |
|
3063 | |||
3063 | raw : bool |
|
3064 | raw : bool | |
3064 | If true (default), retrieve raw history. Has no effect on the other |
|
3065 | If true (default), retrieve raw history. Has no effect on the other | |
3065 | retrieval mechanisms. |
|
3066 | retrieval mechanisms. | |
3066 |
|
3067 | |||
3067 | py_only : bool (default False) |
|
3068 | py_only : bool (default False) | |
3068 | Only try to fetch python code, do not try alternative methods to decode file |
|
3069 | Only try to fetch python code, do not try alternative methods to decode file | |
3069 | if unicode fails. |
|
3070 | if unicode fails. | |
3070 |
|
3071 | |||
3071 | Returns |
|
3072 | Returns | |
3072 | ------- |
|
3073 | ------- | |
3073 | A string of code. |
|
3074 | A string of code. | |
3074 |
|
3075 | |||
3075 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3076 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
3076 | to an object of another type. In each case, .args[0] is a printable |
|
3077 | to an object of another type. In each case, .args[0] is a printable | |
3077 | message. |
|
3078 | message. | |
3078 | """ |
|
3079 | """ | |
3079 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3080 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
3080 | if code: |
|
3081 | if code: | |
3081 | return code |
|
3082 | return code | |
3082 | utarget = unquote_filename(target) |
|
3083 | utarget = unquote_filename(target) | |
3083 | try: |
|
3084 | try: | |
3084 | if utarget.startswith(('http://', 'https://')): |
|
3085 | if utarget.startswith(('http://', 'https://')): | |
3085 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) |
|
3086 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) | |
3086 | except UnicodeDecodeError: |
|
3087 | except UnicodeDecodeError: | |
3087 | if not py_only : |
|
3088 | if not py_only : | |
3088 | from urllib import urlopen # Deferred import |
|
3089 | from urllib import urlopen # Deferred import | |
3089 | response = urlopen(target) |
|
3090 | response = urlopen(target) | |
3090 | return response.read().decode('latin1') |
|
3091 | return response.read().decode('latin1') | |
3091 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
3092 | raise ValueError(("'%s' seem to be unreadable.") % utarget) | |
3092 |
|
3093 | |||
3093 | potential_target = [target] |
|
3094 | potential_target = [target] | |
3094 | try : |
|
3095 | try : | |
3095 | potential_target.insert(0,get_py_filename(target)) |
|
3096 | potential_target.insert(0,get_py_filename(target)) | |
3096 | except IOError: |
|
3097 | except IOError: | |
3097 | pass |
|
3098 | pass | |
3098 |
|
3099 | |||
3099 | for tgt in potential_target : |
|
3100 | for tgt in potential_target : | |
3100 | if os.path.isfile(tgt): # Read file |
|
3101 | if os.path.isfile(tgt): # Read file | |
3101 | try : |
|
3102 | try : | |
3102 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3103 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) | |
3103 | except UnicodeDecodeError : |
|
3104 | except UnicodeDecodeError : | |
3104 | if not py_only : |
|
3105 | if not py_only : | |
3105 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3106 | with io_open(tgt,'r', encoding='latin1') as f : | |
3106 | return f.read() |
|
3107 | return f.read() | |
3107 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3108 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3108 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3109 | elif os.path.isdir(os.path.expanduser(tgt)): | |
3109 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3110 | raise ValueError("'%s' is a directory, not a regular file." % target) | |
3110 |
|
3111 | |||
3111 | try: # User namespace |
|
3112 | try: # User namespace | |
3112 | codeobj = eval(target, self.user_ns) |
|
3113 | codeobj = eval(target, self.user_ns) | |
3113 | except Exception: |
|
3114 | except Exception: | |
3114 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3115 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
3115 | "nor in the user namespace.") % target) |
|
3116 | "nor in the user namespace.") % target) | |
3116 | if isinstance(codeobj, string_types): |
|
3117 | if isinstance(codeobj, string_types): | |
3117 | return codeobj |
|
3118 | return codeobj | |
3118 | elif isinstance(codeobj, Macro): |
|
3119 | elif isinstance(codeobj, Macro): | |
3119 | return codeobj.value |
|
3120 | return codeobj.value | |
3120 |
|
3121 | |||
3121 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3122 | raise TypeError("%s is neither a string nor a macro." % target, | |
3122 | codeobj) |
|
3123 | codeobj) | |
3123 |
|
3124 | |||
3124 | #------------------------------------------------------------------------- |
|
3125 | #------------------------------------------------------------------------- | |
3125 | # Things related to IPython exiting |
|
3126 | # Things related to IPython exiting | |
3126 | #------------------------------------------------------------------------- |
|
3127 | #------------------------------------------------------------------------- | |
3127 | def atexit_operations(self): |
|
3128 | def atexit_operations(self): | |
3128 | """This will be executed at the time of exit. |
|
3129 | """This will be executed at the time of exit. | |
3129 |
|
3130 | |||
3130 | Cleanup operations and saving of persistent data that is done |
|
3131 | Cleanup operations and saving of persistent data that is done | |
3131 | unconditionally by IPython should be performed here. |
|
3132 | unconditionally by IPython should be performed here. | |
3132 |
|
3133 | |||
3133 | For things that may depend on startup flags or platform specifics (such |
|
3134 | For things that may depend on startup flags or platform specifics (such | |
3134 | as having readline or not), register a separate atexit function in the |
|
3135 | as having readline or not), register a separate atexit function in the | |
3135 | code that has the appropriate information, rather than trying to |
|
3136 | code that has the appropriate information, rather than trying to | |
3136 | clutter |
|
3137 | clutter | |
3137 | """ |
|
3138 | """ | |
3138 | # Close the history session (this stores the end time and line count) |
|
3139 | # Close the history session (this stores the end time and line count) | |
3139 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3140 | # this must be *before* the tempfile cleanup, in case of temporary | |
3140 | # history db |
|
3141 | # history db | |
3141 | self.history_manager.end_session() |
|
3142 | self.history_manager.end_session() | |
3142 |
|
3143 | |||
3143 | # Cleanup all tempfiles left around |
|
3144 | # Cleanup all tempfiles left around | |
3144 | for tfile in self.tempfiles: |
|
3145 | for tfile in self.tempfiles: | |
3145 | try: |
|
3146 | try: | |
3146 | os.unlink(tfile) |
|
3147 | os.unlink(tfile) | |
3147 | except OSError: |
|
3148 | except OSError: | |
3148 | pass |
|
3149 | pass | |
3149 |
|
3150 | |||
3150 | # Clear all user namespaces to release all references cleanly. |
|
3151 | # Clear all user namespaces to release all references cleanly. | |
3151 | self.reset(new_session=False) |
|
3152 | self.reset(new_session=False) | |
3152 |
|
3153 | |||
3153 | # Run user hooks |
|
3154 | # Run user hooks | |
3154 | self.hooks.shutdown_hook() |
|
3155 | self.hooks.shutdown_hook() | |
3155 |
|
3156 | |||
3156 | def cleanup(self): |
|
3157 | def cleanup(self): | |
3157 | self.restore_sys_module_state() |
|
3158 | self.restore_sys_module_state() | |
3158 |
|
3159 | |||
3159 |
|
3160 | |||
3160 | class InteractiveShellABC(object): |
|
3161 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): | |
3161 | """An abstract base class for InteractiveShell.""" |
|
3162 | """An abstract base class for InteractiveShell.""" | |
3162 | __metaclass__ = abc.ABCMeta |
|
|||
3163 |
|
3163 | |||
3164 | InteractiveShellABC.register(InteractiveShell) |
|
3164 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,126 +1,125 b'' | |||||
1 | """Abstract base classes for kernel client channels""" |
|
1 | """Abstract base classes for kernel client channels""" | |
2 |
|
2 | |||
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (C) 2013 The IPython Development Team |
|
4 | # Copyright (C) 2013 The IPython Development Team | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | # Standard library imports |
|
|||
15 | import abc |
|
14 | import abc | |
16 |
|
15 | |||
|
16 | from IPython.utils.py3compat import with_metaclass | |||
|
17 | ||||
17 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
18 | # Channels |
|
19 | # Channels | |
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 |
|
21 | |||
21 |
|
22 | |||
22 | class ChannelABC(object): |
|
23 | class ChannelABC(with_metaclass(abc.ABCMeta, object)): | |
23 | """A base class for all channel ABCs.""" |
|
24 | """A base class for all channel ABCs.""" | |
24 |
|
25 | |||
25 | __metaclass__ = abc.ABCMeta |
|
|||
26 |
|
||||
27 | @abc.abstractmethod |
|
26 | @abc.abstractmethod | |
28 | def start(self): |
|
27 | def start(self): | |
29 | pass |
|
28 | pass | |
30 |
|
29 | |||
31 | @abc.abstractmethod |
|
30 | @abc.abstractmethod | |
32 | def stop(self): |
|
31 | def stop(self): | |
33 | pass |
|
32 | pass | |
34 |
|
33 | |||
35 | @abc.abstractmethod |
|
34 | @abc.abstractmethod | |
36 | def is_alive(self): |
|
35 | def is_alive(self): | |
37 | pass |
|
36 | pass | |
38 |
|
37 | |||
39 |
|
38 | |||
40 | class ShellChannelABC(ChannelABC): |
|
39 | class ShellChannelABC(ChannelABC): | |
41 | """ShellChannel ABC. |
|
40 | """ShellChannel ABC. | |
42 |
|
41 | |||
43 | The docstrings for this class can be found in the base implementation: |
|
42 | The docstrings for this class can be found in the base implementation: | |
44 |
|
43 | |||
45 | `IPython.kernel.channels.ShellChannel` |
|
44 | `IPython.kernel.channels.ShellChannel` | |
46 | """ |
|
45 | """ | |
47 |
|
46 | |||
48 | @abc.abstractproperty |
|
47 | @abc.abstractproperty | |
49 | def allow_stdin(self): |
|
48 | def allow_stdin(self): | |
50 | pass |
|
49 | pass | |
51 |
|
50 | |||
52 | @abc.abstractmethod |
|
51 | @abc.abstractmethod | |
53 | def execute(self, code, silent=False, store_history=True, |
|
52 | def execute(self, code, silent=False, store_history=True, | |
54 | user_variables=None, user_expressions=None, allow_stdin=None): |
|
53 | user_variables=None, user_expressions=None, allow_stdin=None): | |
55 | pass |
|
54 | pass | |
56 |
|
55 | |||
57 | @abc.abstractmethod |
|
56 | @abc.abstractmethod | |
58 | def complete(self, text, line, cursor_pos, block=None): |
|
57 | def complete(self, text, line, cursor_pos, block=None): | |
59 | pass |
|
58 | pass | |
60 |
|
59 | |||
61 | @abc.abstractmethod |
|
60 | @abc.abstractmethod | |
62 | def object_info(self, oname, detail_level=0): |
|
61 | def object_info(self, oname, detail_level=0): | |
63 | pass |
|
62 | pass | |
64 |
|
63 | |||
65 | @abc.abstractmethod |
|
64 | @abc.abstractmethod | |
66 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): |
|
65 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): | |
67 | pass |
|
66 | pass | |
68 |
|
67 | |||
69 | @abc.abstractmethod |
|
68 | @abc.abstractmethod | |
70 | def kernel_info(self): |
|
69 | def kernel_info(self): | |
71 | pass |
|
70 | pass | |
72 |
|
71 | |||
73 | @abc.abstractmethod |
|
72 | @abc.abstractmethod | |
74 | def shutdown(self, restart=False): |
|
73 | def shutdown(self, restart=False): | |
75 | pass |
|
74 | pass | |
76 |
|
75 | |||
77 |
|
76 | |||
78 | class IOPubChannelABC(ChannelABC): |
|
77 | class IOPubChannelABC(ChannelABC): | |
79 | """IOPubChannel ABC. |
|
78 | """IOPubChannel ABC. | |
80 |
|
79 | |||
81 | The docstrings for this class can be found in the base implementation: |
|
80 | The docstrings for this class can be found in the base implementation: | |
82 |
|
81 | |||
83 | `IPython.kernel.channels.IOPubChannel` |
|
82 | `IPython.kernel.channels.IOPubChannel` | |
84 | """ |
|
83 | """ | |
85 |
|
84 | |||
86 | @abc.abstractmethod |
|
85 | @abc.abstractmethod | |
87 | def flush(self, timeout=1.0): |
|
86 | def flush(self, timeout=1.0): | |
88 | pass |
|
87 | pass | |
89 |
|
88 | |||
90 |
|
89 | |||
91 | class StdInChannelABC(ChannelABC): |
|
90 | class StdInChannelABC(ChannelABC): | |
92 | """StdInChannel ABC. |
|
91 | """StdInChannel ABC. | |
93 |
|
92 | |||
94 | The docstrings for this class can be found in the base implementation: |
|
93 | The docstrings for this class can be found in the base implementation: | |
95 |
|
94 | |||
96 | `IPython.kernel.channels.StdInChannel` |
|
95 | `IPython.kernel.channels.StdInChannel` | |
97 | """ |
|
96 | """ | |
98 |
|
97 | |||
99 | @abc.abstractmethod |
|
98 | @abc.abstractmethod | |
100 | def input(self, string): |
|
99 | def input(self, string): | |
101 | pass |
|
100 | pass | |
102 |
|
101 | |||
103 |
|
102 | |||
104 | class HBChannelABC(ChannelABC): |
|
103 | class HBChannelABC(ChannelABC): | |
105 | """HBChannel ABC. |
|
104 | """HBChannel ABC. | |
106 |
|
105 | |||
107 | The docstrings for this class can be found in the base implementation: |
|
106 | The docstrings for this class can be found in the base implementation: | |
108 |
|
107 | |||
109 | `IPython.kernel.channels.HBChannel` |
|
108 | `IPython.kernel.channels.HBChannel` | |
110 | """ |
|
109 | """ | |
111 |
|
110 | |||
112 | @abc.abstractproperty |
|
111 | @abc.abstractproperty | |
113 | def time_to_dead(self): |
|
112 | def time_to_dead(self): | |
114 | pass |
|
113 | pass | |
115 |
|
114 | |||
116 | @abc.abstractmethod |
|
115 | @abc.abstractmethod | |
117 | def pause(self): |
|
116 | def pause(self): | |
118 | pass |
|
117 | pass | |
119 |
|
118 | |||
120 | @abc.abstractmethod |
|
119 | @abc.abstractmethod | |
121 | def unpause(self): |
|
120 | def unpause(self): | |
122 | pass |
|
121 | pass | |
123 |
|
122 | |||
124 | @abc.abstractmethod |
|
123 | @abc.abstractmethod | |
125 | def is_beating(self): |
|
124 | def is_beating(self): | |
126 | pass |
|
125 | pass |
@@ -1,81 +1,80 b'' | |||||
1 | """Abstract base class for kernel clients""" |
|
1 | """Abstract base class for kernel clients""" | |
2 |
|
2 | |||
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (C) 2013 The IPython Development Team |
|
4 | # Copyright (C) 2013 The IPython Development Team | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | # Standard library imports |
|
|||
15 | import abc |
|
14 | import abc | |
16 |
|
15 | |||
|
16 | from IPython.utils.py3compat import with_metaclass | |||
|
17 | ||||
17 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
18 | # Main kernel client class |
|
19 | # Main kernel client class | |
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 |
|
21 | |||
21 | class KernelClientABC(object): |
|
22 | class KernelClientABC(with_metaclass(abc.ABCMeta, object)): | |
22 | """KernelManager ABC. |
|
23 | """KernelManager ABC. | |
23 |
|
24 | |||
24 | The docstrings for this class can be found in the base implementation: |
|
25 | The docstrings for this class can be found in the base implementation: | |
25 |
|
26 | |||
26 | `IPython.kernel.client.KernelClient` |
|
27 | `IPython.kernel.client.KernelClient` | |
27 | """ |
|
28 | """ | |
28 |
|
29 | |||
29 | __metaclass__ = abc.ABCMeta |
|
|||
30 |
|
||||
31 | @abc.abstractproperty |
|
30 | @abc.abstractproperty | |
32 | def kernel(self): |
|
31 | def kernel(self): | |
33 | pass |
|
32 | pass | |
34 |
|
33 | |||
35 | @abc.abstractproperty |
|
34 | @abc.abstractproperty | |
36 | def shell_channel_class(self): |
|
35 | def shell_channel_class(self): | |
37 | pass |
|
36 | pass | |
38 |
|
37 | |||
39 | @abc.abstractproperty |
|
38 | @abc.abstractproperty | |
40 | def iopub_channel_class(self): |
|
39 | def iopub_channel_class(self): | |
41 | pass |
|
40 | pass | |
42 |
|
41 | |||
43 | @abc.abstractproperty |
|
42 | @abc.abstractproperty | |
44 | def hb_channel_class(self): |
|
43 | def hb_channel_class(self): | |
45 | pass |
|
44 | pass | |
46 |
|
45 | |||
47 | @abc.abstractproperty |
|
46 | @abc.abstractproperty | |
48 | def stdin_channel_class(self): |
|
47 | def stdin_channel_class(self): | |
49 | pass |
|
48 | pass | |
50 |
|
49 | |||
51 | #-------------------------------------------------------------------------- |
|
50 | #-------------------------------------------------------------------------- | |
52 | # Channel management methods |
|
51 | # Channel management methods | |
53 | #-------------------------------------------------------------------------- |
|
52 | #-------------------------------------------------------------------------- | |
54 |
|
53 | |||
55 | @abc.abstractmethod |
|
54 | @abc.abstractmethod | |
56 | def start_channels(self, shell=True, iopub=True, stdin=True, hb=True): |
|
55 | def start_channels(self, shell=True, iopub=True, stdin=True, hb=True): | |
57 | pass |
|
56 | pass | |
58 |
|
57 | |||
59 | @abc.abstractmethod |
|
58 | @abc.abstractmethod | |
60 | def stop_channels(self): |
|
59 | def stop_channels(self): | |
61 | pass |
|
60 | pass | |
62 |
|
61 | |||
63 | @abc.abstractproperty |
|
62 | @abc.abstractproperty | |
64 | def channels_running(self): |
|
63 | def channels_running(self): | |
65 | pass |
|
64 | pass | |
66 |
|
65 | |||
67 | @abc.abstractproperty |
|
66 | @abc.abstractproperty | |
68 | def shell_channel(self): |
|
67 | def shell_channel(self): | |
69 | pass |
|
68 | pass | |
70 |
|
69 | |||
71 | @abc.abstractproperty |
|
70 | @abc.abstractproperty | |
72 | def iopub_channel(self): |
|
71 | def iopub_channel(self): | |
73 | pass |
|
72 | pass | |
74 |
|
73 | |||
75 | @abc.abstractproperty |
|
74 | @abc.abstractproperty | |
76 | def stdin_channel(self): |
|
75 | def stdin_channel(self): | |
77 | pass |
|
76 | pass | |
78 |
|
77 | |||
79 | @abc.abstractproperty |
|
78 | @abc.abstractproperty | |
80 | def hb_channel(self): |
|
79 | def hb_channel(self): | |
81 | pass |
|
80 | pass |
@@ -1,66 +1,65 b'' | |||||
1 | """ Defines a dummy socket implementing (part of) the zmq.Socket interface. """ |
|
1 | """ Defines a dummy socket implementing (part of) the zmq.Socket interface. """ | |
2 |
|
2 | |||
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (C) 2012 The IPython Development Team |
|
4 | # Copyright (C) 2012 The IPython Development Team | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | # Standard library imports. |
|
14 | # Standard library imports. | |
15 | import abc |
|
15 | import abc | |
16 | try: |
|
16 | try: | |
17 | from queue import Queue # Py 3 |
|
17 | from queue import Queue # Py 3 | |
18 | except ImportError: |
|
18 | except ImportError: | |
19 | from Queue import Queue # Py 2 |
|
19 | from Queue import Queue # Py 2 | |
20 |
|
20 | |||
21 | # System library imports. |
|
21 | # System library imports. | |
22 | import zmq |
|
22 | import zmq | |
23 |
|
23 | |||
24 | # Local imports. |
|
24 | # Local imports. | |
25 | from IPython.utils.traitlets import HasTraits, Instance, Int |
|
25 | from IPython.utils.traitlets import HasTraits, Instance, Int | |
|
26 | from IPython.utils.py3compat import with_metaclass | |||
26 |
|
27 | |||
27 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
28 | # Generic socket interface |
|
29 | # Generic socket interface | |
29 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
30 |
|
31 | |||
31 | class SocketABC(object): |
|
32 | class SocketABC(with_metaclass(abc.ABCMeta, object)): | |
32 | __metaclass__ = abc.ABCMeta |
|
|||
33 |
|
||||
34 | @abc.abstractmethod |
|
33 | @abc.abstractmethod | |
35 | def recv_multipart(self, flags=0, copy=True, track=False): |
|
34 | def recv_multipart(self, flags=0, copy=True, track=False): | |
36 | raise NotImplementedError |
|
35 | raise NotImplementedError | |
37 |
|
36 | |||
38 | @abc.abstractmethod |
|
37 | @abc.abstractmethod | |
39 | def send_multipart(self, msg_parts, flags=0, copy=True, track=False): |
|
38 | def send_multipart(self, msg_parts, flags=0, copy=True, track=False): | |
40 | raise NotImplementedError |
|
39 | raise NotImplementedError | |
41 |
|
40 | |||
42 | SocketABC.register(zmq.Socket) |
|
41 | SocketABC.register(zmq.Socket) | |
43 |
|
42 | |||
44 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
45 | # Dummy socket class |
|
44 | # Dummy socket class | |
46 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
47 |
|
46 | |||
48 | class DummySocket(HasTraits): |
|
47 | class DummySocket(HasTraits): | |
49 | """ A dummy socket implementing (part of) the zmq.Socket interface. """ |
|
48 | """ A dummy socket implementing (part of) the zmq.Socket interface. """ | |
50 |
|
49 | |||
51 | queue = Instance(Queue, ()) |
|
50 | queue = Instance(Queue, ()) | |
52 | message_sent = Int(0) # Should be an Event |
|
51 | message_sent = Int(0) # Should be an Event | |
53 |
|
52 | |||
54 | #------------------------------------------------------------------------- |
|
53 | #------------------------------------------------------------------------- | |
55 | # Socket interface |
|
54 | # Socket interface | |
56 | #------------------------------------------------------------------------- |
|
55 | #------------------------------------------------------------------------- | |
57 |
|
56 | |||
58 | def recv_multipart(self, flags=0, copy=True, track=False): |
|
57 | def recv_multipart(self, flags=0, copy=True, track=False): | |
59 | return self.queue.get_nowait() |
|
58 | return self.queue.get_nowait() | |
60 |
|
59 | |||
61 | def send_multipart(self, msg_parts, flags=0, copy=True, track=False): |
|
60 | def send_multipart(self, msg_parts, flags=0, copy=True, track=False): | |
62 | msg_parts = map(zmq.Message, msg_parts) |
|
61 | msg_parts = map(zmq.Message, msg_parts) | |
63 | self.queue.put_nowait(msg_parts) |
|
62 | self.queue.put_nowait(msg_parts) | |
64 | self.message_sent += 1 |
|
63 | self.message_sent += 1 | |
65 |
|
64 | |||
66 | SocketABC.register(DummySocket) |
|
65 | SocketABC.register(DummySocket) |
@@ -1,225 +1,222 b'' | |||||
1 | """Abstract base classes for kernel manager and channels.""" |
|
1 | """Abstract base classes for kernel manager and channels.""" | |
2 |
|
2 | |||
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (C) 2013 The IPython Development Team |
|
4 | # Copyright (C) 2013 The IPython Development Team | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the BSD License. The full license is in |
|
6 | # Distributed under the terms of the BSD License. The full license is in | |
7 | # the file COPYING, distributed as part of this software. |
|
7 | # the file COPYING, distributed as part of this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | # Standard library imports. |
|
|||
15 | import abc |
|
14 | import abc | |
16 |
|
15 | |||
|
16 | from IPython.utils.py3compat import with_metaclass | |||
|
17 | ||||
17 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
18 | # Channels |
|
19 | # Channels | |
19 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
20 |
|
21 | |||
21 |
|
22 | |||
22 | class ChannelABC(object): |
|
23 | class ChannelABC(with_metaclass(abc.ABCMeta, object)): | |
23 | """A base class for all channel ABCs.""" |
|
24 | """A base class for all channel ABCs.""" | |
24 |
|
25 | |||
25 | __metaclass__ = abc.ABCMeta |
|
|||
26 |
|
||||
27 | @abc.abstractmethod |
|
26 | @abc.abstractmethod | |
28 | def start(self): |
|
27 | def start(self): | |
29 | pass |
|
28 | pass | |
30 |
|
29 | |||
31 | @abc.abstractmethod |
|
30 | @abc.abstractmethod | |
32 | def stop(self): |
|
31 | def stop(self): | |
33 | pass |
|
32 | pass | |
34 |
|
33 | |||
35 | @abc.abstractmethod |
|
34 | @abc.abstractmethod | |
36 | def is_alive(self): |
|
35 | def is_alive(self): | |
37 | pass |
|
36 | pass | |
38 |
|
37 | |||
39 |
|
38 | |||
40 | class ShellChannelABC(ChannelABC): |
|
39 | class ShellChannelABC(ChannelABC): | |
41 | """ShellChannel ABC. |
|
40 | """ShellChannel ABC. | |
42 |
|
41 | |||
43 | The docstrings for this class can be found in the base implementation: |
|
42 | The docstrings for this class can be found in the base implementation: | |
44 |
|
43 | |||
45 | `IPython.kernel.kernelmanager.ShellChannel` |
|
44 | `IPython.kernel.kernelmanager.ShellChannel` | |
46 | """ |
|
45 | """ | |
47 |
|
46 | |||
48 | @abc.abstractproperty |
|
47 | @abc.abstractproperty | |
49 | def allow_stdin(self): |
|
48 | def allow_stdin(self): | |
50 | pass |
|
49 | pass | |
51 |
|
50 | |||
52 | @abc.abstractmethod |
|
51 | @abc.abstractmethod | |
53 | def execute(self, code, silent=False, store_history=True, |
|
52 | def execute(self, code, silent=False, store_history=True, | |
54 | user_variables=None, user_expressions=None, allow_stdin=None): |
|
53 | user_variables=None, user_expressions=None, allow_stdin=None): | |
55 | pass |
|
54 | pass | |
56 |
|
55 | |||
57 | @abc.abstractmethod |
|
56 | @abc.abstractmethod | |
58 | def complete(self, text, line, cursor_pos, block=None): |
|
57 | def complete(self, text, line, cursor_pos, block=None): | |
59 | pass |
|
58 | pass | |
60 |
|
59 | |||
61 | @abc.abstractmethod |
|
60 | @abc.abstractmethod | |
62 | def object_info(self, oname, detail_level=0): |
|
61 | def object_info(self, oname, detail_level=0): | |
63 | pass |
|
62 | pass | |
64 |
|
63 | |||
65 | @abc.abstractmethod |
|
64 | @abc.abstractmethod | |
66 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): |
|
65 | def history(self, raw=True, output=False, hist_access_type='range', **kwargs): | |
67 | pass |
|
66 | pass | |
68 |
|
67 | |||
69 | @abc.abstractmethod |
|
68 | @abc.abstractmethod | |
70 | def kernel_info(self): |
|
69 | def kernel_info(self): | |
71 | pass |
|
70 | pass | |
72 |
|
71 | |||
73 | @abc.abstractmethod |
|
72 | @abc.abstractmethod | |
74 | def shutdown(self, restart=False): |
|
73 | def shutdown(self, restart=False): | |
75 | pass |
|
74 | pass | |
76 |
|
75 | |||
77 |
|
76 | |||
78 | class IOPubChannelABC(ChannelABC): |
|
77 | class IOPubChannelABC(ChannelABC): | |
79 | """IOPubChannel ABC. |
|
78 | """IOPubChannel ABC. | |
80 |
|
79 | |||
81 | The docstrings for this class can be found in the base implementation: |
|
80 | The docstrings for this class can be found in the base implementation: | |
82 |
|
81 | |||
83 | `IPython.kernel.kernelmanager.IOPubChannel` |
|
82 | `IPython.kernel.kernelmanager.IOPubChannel` | |
84 | """ |
|
83 | """ | |
85 |
|
84 | |||
86 | @abc.abstractmethod |
|
85 | @abc.abstractmethod | |
87 | def flush(self, timeout=1.0): |
|
86 | def flush(self, timeout=1.0): | |
88 | pass |
|
87 | pass | |
89 |
|
88 | |||
90 |
|
89 | |||
91 | class StdInChannelABC(ChannelABC): |
|
90 | class StdInChannelABC(ChannelABC): | |
92 | """StdInChannel ABC. |
|
91 | """StdInChannel ABC. | |
93 |
|
92 | |||
94 | The docstrings for this class can be found in the base implementation: |
|
93 | The docstrings for this class can be found in the base implementation: | |
95 |
|
94 | |||
96 | `IPython.kernel.kernelmanager.StdInChannel` |
|
95 | `IPython.kernel.kernelmanager.StdInChannel` | |
97 | """ |
|
96 | """ | |
98 |
|
97 | |||
99 | @abc.abstractmethod |
|
98 | @abc.abstractmethod | |
100 | def input(self, string): |
|
99 | def input(self, string): | |
101 | pass |
|
100 | pass | |
102 |
|
101 | |||
103 |
|
102 | |||
104 | class HBChannelABC(ChannelABC): |
|
103 | class HBChannelABC(ChannelABC): | |
105 | """HBChannel ABC. |
|
104 | """HBChannel ABC. | |
106 |
|
105 | |||
107 | The docstrings for this class can be found in the base implementation: |
|
106 | The docstrings for this class can be found in the base implementation: | |
108 |
|
107 | |||
109 | `IPython.kernel.kernelmanager.HBChannel` |
|
108 | `IPython.kernel.kernelmanager.HBChannel` | |
110 | """ |
|
109 | """ | |
111 |
|
110 | |||
112 | @abc.abstractproperty |
|
111 | @abc.abstractproperty | |
113 | def time_to_dead(self): |
|
112 | def time_to_dead(self): | |
114 | pass |
|
113 | pass | |
115 |
|
114 | |||
116 | @abc.abstractmethod |
|
115 | @abc.abstractmethod | |
117 | def pause(self): |
|
116 | def pause(self): | |
118 | pass |
|
117 | pass | |
119 |
|
118 | |||
120 | @abc.abstractmethod |
|
119 | @abc.abstractmethod | |
121 | def unpause(self): |
|
120 | def unpause(self): | |
122 | pass |
|
121 | pass | |
123 |
|
122 | |||
124 | @abc.abstractmethod |
|
123 | @abc.abstractmethod | |
125 | def is_beating(self): |
|
124 | def is_beating(self): | |
126 | pass |
|
125 | pass | |
127 |
|
126 | |||
128 |
|
127 | |||
129 | #----------------------------------------------------------------------------- |
|
128 | #----------------------------------------------------------------------------- | |
130 | # Main kernel manager class |
|
129 | # Main kernel manager class | |
131 | #----------------------------------------------------------------------------- |
|
130 | #----------------------------------------------------------------------------- | |
132 |
|
131 | |||
133 | class KernelManagerABC(object): |
|
132 | class KernelManagerABC(with_metaclass(abc.ABCMeta, object)): | |
134 | """KernelManager ABC. |
|
133 | """KernelManager ABC. | |
135 |
|
134 | |||
136 | The docstrings for this class can be found in the base implementation: |
|
135 | The docstrings for this class can be found in the base implementation: | |
137 |
|
136 | |||
138 | `IPython.kernel.kernelmanager.KernelManager` |
|
137 | `IPython.kernel.kernelmanager.KernelManager` | |
139 | """ |
|
138 | """ | |
140 |
|
139 | |||
141 | __metaclass__ = abc.ABCMeta |
|
|||
142 |
|
||||
143 | @abc.abstractproperty |
|
140 | @abc.abstractproperty | |
144 | def kernel(self): |
|
141 | def kernel(self): | |
145 | pass |
|
142 | pass | |
146 |
|
143 | |||
147 | @abc.abstractproperty |
|
144 | @abc.abstractproperty | |
148 | def shell_channel_class(self): |
|
145 | def shell_channel_class(self): | |
149 | pass |
|
146 | pass | |
150 |
|
147 | |||
151 | @abc.abstractproperty |
|
148 | @abc.abstractproperty | |
152 | def iopub_channel_class(self): |
|
149 | def iopub_channel_class(self): | |
153 | pass |
|
150 | pass | |
154 |
|
151 | |||
155 | @abc.abstractproperty |
|
152 | @abc.abstractproperty | |
156 | def hb_channel_class(self): |
|
153 | def hb_channel_class(self): | |
157 | pass |
|
154 | pass | |
158 |
|
155 | |||
159 | @abc.abstractproperty |
|
156 | @abc.abstractproperty | |
160 | def stdin_channel_class(self): |
|
157 | def stdin_channel_class(self): | |
161 | pass |
|
158 | pass | |
162 |
|
159 | |||
163 | #-------------------------------------------------------------------------- |
|
160 | #-------------------------------------------------------------------------- | |
164 | # Channel management methods |
|
161 | # Channel management methods | |
165 | #-------------------------------------------------------------------------- |
|
162 | #-------------------------------------------------------------------------- | |
166 |
|
163 | |||
167 | @abc.abstractmethod |
|
164 | @abc.abstractmethod | |
168 | def start_channels(self, shell=True, iopub=True, stdin=True, hb=True): |
|
165 | def start_channels(self, shell=True, iopub=True, stdin=True, hb=True): | |
169 | pass |
|
166 | pass | |
170 |
|
167 | |||
171 | @abc.abstractmethod |
|
168 | @abc.abstractmethod | |
172 | def stop_channels(self): |
|
169 | def stop_channels(self): | |
173 | pass |
|
170 | pass | |
174 |
|
171 | |||
175 | @abc.abstractproperty |
|
172 | @abc.abstractproperty | |
176 | def channels_running(self): |
|
173 | def channels_running(self): | |
177 | pass |
|
174 | pass | |
178 |
|
175 | |||
179 | @abc.abstractproperty |
|
176 | @abc.abstractproperty | |
180 | def shell_channel(self): |
|
177 | def shell_channel(self): | |
181 | pass |
|
178 | pass | |
182 |
|
179 | |||
183 | @abc.abstractproperty |
|
180 | @abc.abstractproperty | |
184 | def iopub_channel(self): |
|
181 | def iopub_channel(self): | |
185 | pass |
|
182 | pass | |
186 |
|
183 | |||
187 | @abc.abstractproperty |
|
184 | @abc.abstractproperty | |
188 | def stdin_channel(self): |
|
185 | def stdin_channel(self): | |
189 | pass |
|
186 | pass | |
190 |
|
187 | |||
191 | @abc.abstractproperty |
|
188 | @abc.abstractproperty | |
192 | def hb_channel(self): |
|
189 | def hb_channel(self): | |
193 | pass |
|
190 | pass | |
194 |
|
191 | |||
195 | #-------------------------------------------------------------------------- |
|
192 | #-------------------------------------------------------------------------- | |
196 | # Kernel management |
|
193 | # Kernel management | |
197 | #-------------------------------------------------------------------------- |
|
194 | #-------------------------------------------------------------------------- | |
198 |
|
195 | |||
199 | @abc.abstractmethod |
|
196 | @abc.abstractmethod | |
200 | def start_kernel(self, **kw): |
|
197 | def start_kernel(self, **kw): | |
201 | pass |
|
198 | pass | |
202 |
|
199 | |||
203 | @abc.abstractmethod |
|
200 | @abc.abstractmethod | |
204 | def shutdown_kernel(self, now=False, restart=False): |
|
201 | def shutdown_kernel(self, now=False, restart=False): | |
205 | pass |
|
202 | pass | |
206 |
|
203 | |||
207 | @abc.abstractmethod |
|
204 | @abc.abstractmethod | |
208 | def restart_kernel(self, now=False, **kw): |
|
205 | def restart_kernel(self, now=False, **kw): | |
209 | pass |
|
206 | pass | |
210 |
|
207 | |||
211 | @abc.abstractproperty |
|
208 | @abc.abstractproperty | |
212 | def has_kernel(self): |
|
209 | def has_kernel(self): | |
213 | pass |
|
210 | pass | |
214 |
|
211 | |||
215 | @abc.abstractmethod |
|
212 | @abc.abstractmethod | |
216 | def interrupt_kernel(self): |
|
213 | def interrupt_kernel(self): | |
217 | pass |
|
214 | pass | |
218 |
|
215 | |||
219 | @abc.abstractmethod |
|
216 | @abc.abstractmethod | |
220 | def signal_kernel(self, signum): |
|
217 | def signal_kernel(self, signum): | |
221 | pass |
|
218 | pass | |
222 |
|
219 | |||
223 | @abc.abstractmethod |
|
220 | @abc.abstractmethod | |
224 | def is_alive(self): |
|
221 | def is_alive(self): | |
225 | pass |
|
222 | pass |
@@ -1,2110 +1,2110 b'' | |||||
1 | """ An abstract base class for console-type widgets. |
|
1 | """ An abstract base class for console-type widgets. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Imports |
|
4 | # Imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 |
|
6 | |||
7 | # Standard library imports |
|
7 | # Standard library imports | |
8 | import os.path |
|
8 | import os.path | |
9 | import re |
|
9 | import re | |
10 | import sys |
|
10 | import sys | |
11 | from textwrap import dedent |
|
11 | from textwrap import dedent | |
12 | import time |
|
12 | import time | |
13 | from unicodedata import category |
|
13 | from unicodedata import category | |
14 | import webbrowser |
|
14 | import webbrowser | |
15 |
|
15 | |||
16 | # System library imports |
|
16 | # System library imports | |
17 | from IPython.external.qt import QtCore, QtGui |
|
17 | from IPython.external.qt import QtCore, QtGui | |
18 |
|
18 | |||
19 | # Local imports |
|
19 | # Local imports | |
20 | from IPython.config.configurable import LoggingConfigurable |
|
20 | from IPython.config.configurable import LoggingConfigurable | |
21 | from IPython.core.inputsplitter import ESC_SEQUENCES |
|
21 | from IPython.core.inputsplitter import ESC_SEQUENCES | |
22 | from IPython.qt.rich_text import HtmlExporter |
|
22 | from IPython.qt.rich_text import HtmlExporter | |
23 | from IPython.qt.util import MetaQObjectHasTraits, get_font |
|
23 | from IPython.qt.util import MetaQObjectHasTraits, get_font | |
|
24 | from IPython.utils.py3compat import with_metaclass | |||
24 | from IPython.utils.text import columnize |
|
25 | from IPython.utils.text import columnize | |
25 | from IPython.utils.traitlets import Bool, Enum, Integer, Unicode |
|
26 | from IPython.utils.traitlets import Bool, Enum, Integer, Unicode | |
26 | from .ansi_code_processor import QtAnsiCodeProcessor |
|
27 | from .ansi_code_processor import QtAnsiCodeProcessor | |
27 | from .completion_widget import CompletionWidget |
|
28 | from .completion_widget import CompletionWidget | |
28 | from .completion_html import CompletionHtml |
|
29 | from .completion_html import CompletionHtml | |
29 | from .completion_plain import CompletionPlain |
|
30 | from .completion_plain import CompletionPlain | |
30 | from .kill_ring import QtKillRing |
|
31 | from .kill_ring import QtKillRing | |
31 |
|
32 | |||
32 |
|
33 | |||
33 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
34 | # Functions |
|
35 | # Functions | |
35 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
36 |
|
37 | |||
37 | ESCAPE_CHARS = ''.join(ESC_SEQUENCES) |
|
38 | ESCAPE_CHARS = ''.join(ESC_SEQUENCES) | |
38 | ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+") |
|
39 | ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+") | |
39 |
|
40 | |||
40 | def commonprefix(items): |
|
41 | def commonprefix(items): | |
41 | """Get common prefix for completions |
|
42 | """Get common prefix for completions | |
42 |
|
43 | |||
43 | Return the longest common prefix of a list of strings, but with special |
|
44 | Return the longest common prefix of a list of strings, but with special | |
44 | treatment of escape characters that might precede commands in IPython, |
|
45 | treatment of escape characters that might precede commands in IPython, | |
45 | such as %magic functions. Used in tab completion. |
|
46 | such as %magic functions. Used in tab completion. | |
46 |
|
47 | |||
47 | For a more general function, see os.path.commonprefix |
|
48 | For a more general function, see os.path.commonprefix | |
48 | """ |
|
49 | """ | |
49 | # the last item will always have the least leading % symbol |
|
50 | # the last item will always have the least leading % symbol | |
50 | # min / max are first/last in alphabetical order |
|
51 | # min / max are first/last in alphabetical order | |
51 | first_match = ESCAPE_RE.match(min(items)) |
|
52 | first_match = ESCAPE_RE.match(min(items)) | |
52 | last_match = ESCAPE_RE.match(max(items)) |
|
53 | last_match = ESCAPE_RE.match(max(items)) | |
53 | # common suffix is (common prefix of reversed items) reversed |
|
54 | # common suffix is (common prefix of reversed items) reversed | |
54 | if first_match and last_match: |
|
55 | if first_match and last_match: | |
55 | prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1] |
|
56 | prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1] | |
56 | else: |
|
57 | else: | |
57 | prefix = '' |
|
58 | prefix = '' | |
58 |
|
59 | |||
59 | items = [s.lstrip(ESCAPE_CHARS) for s in items] |
|
60 | items = [s.lstrip(ESCAPE_CHARS) for s in items] | |
60 | return prefix+os.path.commonprefix(items) |
|
61 | return prefix+os.path.commonprefix(items) | |
61 |
|
62 | |||
62 | def is_letter_or_number(char): |
|
63 | def is_letter_or_number(char): | |
63 | """ Returns whether the specified unicode character is a letter or a number. |
|
64 | """ Returns whether the specified unicode character is a letter or a number. | |
64 | """ |
|
65 | """ | |
65 | cat = category(char) |
|
66 | cat = category(char) | |
66 | return cat.startswith('L') or cat.startswith('N') |
|
67 | return cat.startswith('L') or cat.startswith('N') | |
67 |
|
68 | |||
68 | #----------------------------------------------------------------------------- |
|
69 | #----------------------------------------------------------------------------- | |
69 | # Classes |
|
70 | # Classes | |
70 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
71 |
|
72 | |||
72 | class ConsoleWidget(LoggingConfigurable, QtGui.QWidget): |
|
73 | class ConsoleWidget(with_metaclass(MetaQObjectHasTraits, type('NewBase', (LoggingConfigurable, QtGui.QWidget), {}))): | |
73 | """ An abstract base class for console-type widgets. This class has |
|
74 | """ An abstract base class for console-type widgets. This class has | |
74 | functionality for: |
|
75 | functionality for: | |
75 |
|
76 | |||
76 | * Maintaining a prompt and editing region |
|
77 | * Maintaining a prompt and editing region | |
77 | * Providing the traditional Unix-style console keyboard shortcuts |
|
78 | * Providing the traditional Unix-style console keyboard shortcuts | |
78 | * Performing tab completion |
|
79 | * Performing tab completion | |
79 | * Paging text |
|
80 | * Paging text | |
80 | * Handling ANSI escape codes |
|
81 | * Handling ANSI escape codes | |
81 |
|
82 | |||
82 | ConsoleWidget also provides a number of utility methods that will be |
|
83 | ConsoleWidget also provides a number of utility methods that will be | |
83 | convenient to implementors of a console-style widget. |
|
84 | convenient to implementors of a console-style widget. | |
84 | """ |
|
85 | """ | |
85 | __metaclass__ = MetaQObjectHasTraits |
|
|||
86 |
|
86 | |||
87 | #------ Configuration ------------------------------------------------------ |
|
87 | #------ Configuration ------------------------------------------------------ | |
88 |
|
88 | |||
89 | ansi_codes = Bool(True, config=True, |
|
89 | ansi_codes = Bool(True, config=True, | |
90 | help="Whether to process ANSI escape codes." |
|
90 | help="Whether to process ANSI escape codes." | |
91 | ) |
|
91 | ) | |
92 | buffer_size = Integer(500, config=True, |
|
92 | buffer_size = Integer(500, config=True, | |
93 | help=""" |
|
93 | help=""" | |
94 | The maximum number of lines of text before truncation. Specifying a |
|
94 | The maximum number of lines of text before truncation. Specifying a | |
95 | non-positive number disables text truncation (not recommended). |
|
95 | non-positive number disables text truncation (not recommended). | |
96 | """ |
|
96 | """ | |
97 | ) |
|
97 | ) | |
98 | execute_on_complete_input = Bool(True, config=True, |
|
98 | execute_on_complete_input = Bool(True, config=True, | |
99 | help="""Whether to automatically execute on syntactically complete input. |
|
99 | help="""Whether to automatically execute on syntactically complete input. | |
100 |
|
100 | |||
101 | If False, Shift-Enter is required to submit each execution. |
|
101 | If False, Shift-Enter is required to submit each execution. | |
102 | Disabling this is mainly useful for non-Python kernels, |
|
102 | Disabling this is mainly useful for non-Python kernels, | |
103 | where the completion check would be wrong. |
|
103 | where the completion check would be wrong. | |
104 | """ |
|
104 | """ | |
105 | ) |
|
105 | ) | |
106 | gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True, |
|
106 | gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True, | |
107 | default_value = 'ncurses', |
|
107 | default_value = 'ncurses', | |
108 | help=""" |
|
108 | help=""" | |
109 | The type of completer to use. Valid values are: |
|
109 | The type of completer to use. Valid values are: | |
110 |
|
110 | |||
111 | 'plain' : Show the available completion as a text list |
|
111 | 'plain' : Show the available completion as a text list | |
112 | Below the editing area. |
|
112 | Below the editing area. | |
113 | 'droplist': Show the completion in a drop down list navigable |
|
113 | 'droplist': Show the completion in a drop down list navigable | |
114 | by the arrow keys, and from which you can select |
|
114 | by the arrow keys, and from which you can select | |
115 | completion by pressing Return. |
|
115 | completion by pressing Return. | |
116 | 'ncurses' : Show the completion as a text list which is navigable by |
|
116 | 'ncurses' : Show the completion as a text list which is navigable by | |
117 | `tab` and arrow keys. |
|
117 | `tab` and arrow keys. | |
118 | """ |
|
118 | """ | |
119 | ) |
|
119 | ) | |
120 | # NOTE: this value can only be specified during initialization. |
|
120 | # NOTE: this value can only be specified during initialization. | |
121 | kind = Enum(['plain', 'rich'], default_value='plain', config=True, |
|
121 | kind = Enum(['plain', 'rich'], default_value='plain', config=True, | |
122 | help=""" |
|
122 | help=""" | |
123 | The type of underlying text widget to use. Valid values are 'plain', |
|
123 | The type of underlying text widget to use. Valid values are 'plain', | |
124 | which specifies a QPlainTextEdit, and 'rich', which specifies a |
|
124 | which specifies a QPlainTextEdit, and 'rich', which specifies a | |
125 | QTextEdit. |
|
125 | QTextEdit. | |
126 | """ |
|
126 | """ | |
127 | ) |
|
127 | ) | |
128 | # NOTE: this value can only be specified during initialization. |
|
128 | # NOTE: this value can only be specified during initialization. | |
129 | paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'], |
|
129 | paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'], | |
130 | default_value='inside', config=True, |
|
130 | default_value='inside', config=True, | |
131 | help=""" |
|
131 | help=""" | |
132 | The type of paging to use. Valid values are: |
|
132 | The type of paging to use. Valid values are: | |
133 |
|
133 | |||
134 | 'inside' : The widget pages like a traditional terminal. |
|
134 | 'inside' : The widget pages like a traditional terminal. | |
135 | 'hsplit' : When paging is requested, the widget is split |
|
135 | 'hsplit' : When paging is requested, the widget is split | |
136 | horizontally. The top pane contains the console, and the |
|
136 | horizontally. The top pane contains the console, and the | |
137 | bottom pane contains the paged text. |
|
137 | bottom pane contains the paged text. | |
138 | 'vsplit' : Similar to 'hsplit', except that a vertical splitter |
|
138 | 'vsplit' : Similar to 'hsplit', except that a vertical splitter | |
139 | used. |
|
139 | used. | |
140 | 'custom' : No action is taken by the widget beyond emitting a |
|
140 | 'custom' : No action is taken by the widget beyond emitting a | |
141 | 'custom_page_requested(str)' signal. |
|
141 | 'custom_page_requested(str)' signal. | |
142 | 'none' : The text is written directly to the console. |
|
142 | 'none' : The text is written directly to the console. | |
143 | """) |
|
143 | """) | |
144 |
|
144 | |||
145 | font_family = Unicode(config=True, |
|
145 | font_family = Unicode(config=True, | |
146 | help="""The font family to use for the console. |
|
146 | help="""The font family to use for the console. | |
147 | On OSX this defaults to Monaco, on Windows the default is |
|
147 | On OSX this defaults to Monaco, on Windows the default is | |
148 | Consolas with fallback of Courier, and on other platforms |
|
148 | Consolas with fallback of Courier, and on other platforms | |
149 | the default is Monospace. |
|
149 | the default is Monospace. | |
150 | """) |
|
150 | """) | |
151 | def _font_family_default(self): |
|
151 | def _font_family_default(self): | |
152 | if sys.platform == 'win32': |
|
152 | if sys.platform == 'win32': | |
153 | # Consolas ships with Vista/Win7, fallback to Courier if needed |
|
153 | # Consolas ships with Vista/Win7, fallback to Courier if needed | |
154 | return 'Consolas' |
|
154 | return 'Consolas' | |
155 | elif sys.platform == 'darwin': |
|
155 | elif sys.platform == 'darwin': | |
156 | # OSX always has Monaco, no need for a fallback |
|
156 | # OSX always has Monaco, no need for a fallback | |
157 | return 'Monaco' |
|
157 | return 'Monaco' | |
158 | else: |
|
158 | else: | |
159 | # Monospace should always exist, no need for a fallback |
|
159 | # Monospace should always exist, no need for a fallback | |
160 | return 'Monospace' |
|
160 | return 'Monospace' | |
161 |
|
161 | |||
162 | font_size = Integer(config=True, |
|
162 | font_size = Integer(config=True, | |
163 | help="""The font size. If unconfigured, Qt will be entrusted |
|
163 | help="""The font size. If unconfigured, Qt will be entrusted | |
164 | with the size of the font. |
|
164 | with the size of the font. | |
165 | """) |
|
165 | """) | |
166 |
|
166 | |||
167 | width = Integer(81, config=True, |
|
167 | width = Integer(81, config=True, | |
168 | help="""The width of the console at start time in number |
|
168 | help="""The width of the console at start time in number | |
169 | of characters (will double with `hsplit` paging) |
|
169 | of characters (will double with `hsplit` paging) | |
170 | """) |
|
170 | """) | |
171 |
|
171 | |||
172 | height = Integer(25, config=True, |
|
172 | height = Integer(25, config=True, | |
173 | help="""The height of the console at start time in number |
|
173 | help="""The height of the console at start time in number | |
174 | of characters (will double with `vsplit` paging) |
|
174 | of characters (will double with `vsplit` paging) | |
175 | """) |
|
175 | """) | |
176 |
|
176 | |||
177 | # Whether to override ShortcutEvents for the keybindings defined by this |
|
177 | # Whether to override ShortcutEvents for the keybindings defined by this | |
178 | # widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take |
|
178 | # widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take | |
179 | # priority (when it has focus) over, e.g., window-level menu shortcuts. |
|
179 | # priority (when it has focus) over, e.g., window-level menu shortcuts. | |
180 | override_shortcuts = Bool(False) |
|
180 | override_shortcuts = Bool(False) | |
181 |
|
181 | |||
182 | # ------ Custom Qt Widgets ------------------------------------------------- |
|
182 | # ------ Custom Qt Widgets ------------------------------------------------- | |
183 |
|
183 | |||
184 | # For other projects to easily override the Qt widgets used by the console |
|
184 | # For other projects to easily override the Qt widgets used by the console | |
185 | # (e.g. Spyder) |
|
185 | # (e.g. Spyder) | |
186 | custom_control = None |
|
186 | custom_control = None | |
187 | custom_page_control = None |
|
187 | custom_page_control = None | |
188 |
|
188 | |||
189 | #------ Signals ------------------------------------------------------------ |
|
189 | #------ Signals ------------------------------------------------------------ | |
190 |
|
190 | |||
191 | # Signals that indicate ConsoleWidget state. |
|
191 | # Signals that indicate ConsoleWidget state. | |
192 | copy_available = QtCore.Signal(bool) |
|
192 | copy_available = QtCore.Signal(bool) | |
193 | redo_available = QtCore.Signal(bool) |
|
193 | redo_available = QtCore.Signal(bool) | |
194 | undo_available = QtCore.Signal(bool) |
|
194 | undo_available = QtCore.Signal(bool) | |
195 |
|
195 | |||
196 | # Signal emitted when paging is needed and the paging style has been |
|
196 | # Signal emitted when paging is needed and the paging style has been | |
197 | # specified as 'custom'. |
|
197 | # specified as 'custom'. | |
198 | custom_page_requested = QtCore.Signal(object) |
|
198 | custom_page_requested = QtCore.Signal(object) | |
199 |
|
199 | |||
200 | # Signal emitted when the font is changed. |
|
200 | # Signal emitted when the font is changed. | |
201 | font_changed = QtCore.Signal(QtGui.QFont) |
|
201 | font_changed = QtCore.Signal(QtGui.QFont) | |
202 |
|
202 | |||
203 | #------ Protected class variables ------------------------------------------ |
|
203 | #------ Protected class variables ------------------------------------------ | |
204 |
|
204 | |||
205 | # control handles |
|
205 | # control handles | |
206 | _control = None |
|
206 | _control = None | |
207 | _page_control = None |
|
207 | _page_control = None | |
208 | _splitter = None |
|
208 | _splitter = None | |
209 |
|
209 | |||
210 | # When the control key is down, these keys are mapped. |
|
210 | # When the control key is down, these keys are mapped. | |
211 | _ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left, |
|
211 | _ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left, | |
212 | QtCore.Qt.Key_F : QtCore.Qt.Key_Right, |
|
212 | QtCore.Qt.Key_F : QtCore.Qt.Key_Right, | |
213 | QtCore.Qt.Key_A : QtCore.Qt.Key_Home, |
|
213 | QtCore.Qt.Key_A : QtCore.Qt.Key_Home, | |
214 | QtCore.Qt.Key_P : QtCore.Qt.Key_Up, |
|
214 | QtCore.Qt.Key_P : QtCore.Qt.Key_Up, | |
215 | QtCore.Qt.Key_N : QtCore.Qt.Key_Down, |
|
215 | QtCore.Qt.Key_N : QtCore.Qt.Key_Down, | |
216 | QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, } |
|
216 | QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, } | |
217 | if not sys.platform == 'darwin': |
|
217 | if not sys.platform == 'darwin': | |
218 | # On OS X, Ctrl-E already does the right thing, whereas End moves the |
|
218 | # On OS X, Ctrl-E already does the right thing, whereas End moves the | |
219 | # cursor to the bottom of the buffer. |
|
219 | # cursor to the bottom of the buffer. | |
220 | _ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End |
|
220 | _ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End | |
221 |
|
221 | |||
222 | # The shortcuts defined by this widget. We need to keep track of these to |
|
222 | # The shortcuts defined by this widget. We need to keep track of these to | |
223 | # support 'override_shortcuts' above. |
|
223 | # support 'override_shortcuts' above. | |
224 | _shortcuts = set(_ctrl_down_remap.keys() + |
|
224 | _shortcuts = set(_ctrl_down_remap.keys() + | |
225 | [ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O, |
|
225 | [ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O, | |
226 | QtCore.Qt.Key_V ]) |
|
226 | QtCore.Qt.Key_V ]) | |
227 |
|
227 | |||
228 | _temp_buffer_filled = False |
|
228 | _temp_buffer_filled = False | |
229 |
|
229 | |||
230 | #--------------------------------------------------------------------------- |
|
230 | #--------------------------------------------------------------------------- | |
231 | # 'QObject' interface |
|
231 | # 'QObject' interface | |
232 | #--------------------------------------------------------------------------- |
|
232 | #--------------------------------------------------------------------------- | |
233 |
|
233 | |||
234 | def __init__(self, parent=None, **kw): |
|
234 | def __init__(self, parent=None, **kw): | |
235 | """ Create a ConsoleWidget. |
|
235 | """ Create a ConsoleWidget. | |
236 |
|
236 | |||
237 | Parameters: |
|
237 | Parameters: | |
238 | ----------- |
|
238 | ----------- | |
239 | parent : QWidget, optional [default None] |
|
239 | parent : QWidget, optional [default None] | |
240 | The parent for this widget. |
|
240 | The parent for this widget. | |
241 | """ |
|
241 | """ | |
242 | QtGui.QWidget.__init__(self, parent) |
|
242 | QtGui.QWidget.__init__(self, parent) | |
243 | LoggingConfigurable.__init__(self, **kw) |
|
243 | LoggingConfigurable.__init__(self, **kw) | |
244 |
|
244 | |||
245 | # While scrolling the pager on Mac OS X, it tears badly. The |
|
245 | # While scrolling the pager on Mac OS X, it tears badly. The | |
246 | # NativeGesture is platform and perhaps build-specific hence |
|
246 | # NativeGesture is platform and perhaps build-specific hence | |
247 | # we take adequate precautions here. |
|
247 | # we take adequate precautions here. | |
248 | self._pager_scroll_events = [QtCore.QEvent.Wheel] |
|
248 | self._pager_scroll_events = [QtCore.QEvent.Wheel] | |
249 | if hasattr(QtCore.QEvent, 'NativeGesture'): |
|
249 | if hasattr(QtCore.QEvent, 'NativeGesture'): | |
250 | self._pager_scroll_events.append(QtCore.QEvent.NativeGesture) |
|
250 | self._pager_scroll_events.append(QtCore.QEvent.NativeGesture) | |
251 |
|
251 | |||
252 | # Create the layout and underlying text widget. |
|
252 | # Create the layout and underlying text widget. | |
253 | layout = QtGui.QStackedLayout(self) |
|
253 | layout = QtGui.QStackedLayout(self) | |
254 | layout.setContentsMargins(0, 0, 0, 0) |
|
254 | layout.setContentsMargins(0, 0, 0, 0) | |
255 | self._control = self._create_control() |
|
255 | self._control = self._create_control() | |
256 | if self.paging in ('hsplit', 'vsplit'): |
|
256 | if self.paging in ('hsplit', 'vsplit'): | |
257 | self._splitter = QtGui.QSplitter() |
|
257 | self._splitter = QtGui.QSplitter() | |
258 | if self.paging == 'hsplit': |
|
258 | if self.paging == 'hsplit': | |
259 | self._splitter.setOrientation(QtCore.Qt.Horizontal) |
|
259 | self._splitter.setOrientation(QtCore.Qt.Horizontal) | |
260 | else: |
|
260 | else: | |
261 | self._splitter.setOrientation(QtCore.Qt.Vertical) |
|
261 | self._splitter.setOrientation(QtCore.Qt.Vertical) | |
262 | self._splitter.addWidget(self._control) |
|
262 | self._splitter.addWidget(self._control) | |
263 | layout.addWidget(self._splitter) |
|
263 | layout.addWidget(self._splitter) | |
264 | else: |
|
264 | else: | |
265 | layout.addWidget(self._control) |
|
265 | layout.addWidget(self._control) | |
266 |
|
266 | |||
267 | # Create the paging widget, if necessary. |
|
267 | # Create the paging widget, if necessary. | |
268 | if self.paging in ('inside', 'hsplit', 'vsplit'): |
|
268 | if self.paging in ('inside', 'hsplit', 'vsplit'): | |
269 | self._page_control = self._create_page_control() |
|
269 | self._page_control = self._create_page_control() | |
270 | if self._splitter: |
|
270 | if self._splitter: | |
271 | self._page_control.hide() |
|
271 | self._page_control.hide() | |
272 | self._splitter.addWidget(self._page_control) |
|
272 | self._splitter.addWidget(self._page_control) | |
273 | else: |
|
273 | else: | |
274 | layout.addWidget(self._page_control) |
|
274 | layout.addWidget(self._page_control) | |
275 |
|
275 | |||
276 | # Initialize protected variables. Some variables contain useful state |
|
276 | # Initialize protected variables. Some variables contain useful state | |
277 | # information for subclasses; they should be considered read-only. |
|
277 | # information for subclasses; they should be considered read-only. | |
278 | self._append_before_prompt_pos = 0 |
|
278 | self._append_before_prompt_pos = 0 | |
279 | self._ansi_processor = QtAnsiCodeProcessor() |
|
279 | self._ansi_processor = QtAnsiCodeProcessor() | |
280 | if self.gui_completion == 'ncurses': |
|
280 | if self.gui_completion == 'ncurses': | |
281 | self._completion_widget = CompletionHtml(self) |
|
281 | self._completion_widget = CompletionHtml(self) | |
282 | elif self.gui_completion == 'droplist': |
|
282 | elif self.gui_completion == 'droplist': | |
283 | self._completion_widget = CompletionWidget(self) |
|
283 | self._completion_widget = CompletionWidget(self) | |
284 | elif self.gui_completion == 'plain': |
|
284 | elif self.gui_completion == 'plain': | |
285 | self._completion_widget = CompletionPlain(self) |
|
285 | self._completion_widget = CompletionPlain(self) | |
286 |
|
286 | |||
287 | self._continuation_prompt = '> ' |
|
287 | self._continuation_prompt = '> ' | |
288 | self._continuation_prompt_html = None |
|
288 | self._continuation_prompt_html = None | |
289 | self._executing = False |
|
289 | self._executing = False | |
290 | self._filter_resize = False |
|
290 | self._filter_resize = False | |
291 | self._html_exporter = HtmlExporter(self._control) |
|
291 | self._html_exporter = HtmlExporter(self._control) | |
292 | self._input_buffer_executing = '' |
|
292 | self._input_buffer_executing = '' | |
293 | self._input_buffer_pending = '' |
|
293 | self._input_buffer_pending = '' | |
294 | self._kill_ring = QtKillRing(self._control) |
|
294 | self._kill_ring = QtKillRing(self._control) | |
295 | self._prompt = '' |
|
295 | self._prompt = '' | |
296 | self._prompt_html = None |
|
296 | self._prompt_html = None | |
297 | self._prompt_pos = 0 |
|
297 | self._prompt_pos = 0 | |
298 | self._prompt_sep = '' |
|
298 | self._prompt_sep = '' | |
299 | self._reading = False |
|
299 | self._reading = False | |
300 | self._reading_callback = None |
|
300 | self._reading_callback = None | |
301 | self._tab_width = 8 |
|
301 | self._tab_width = 8 | |
302 |
|
302 | |||
303 | # List of strings pending to be appended as plain text in the widget. |
|
303 | # List of strings pending to be appended as plain text in the widget. | |
304 | # The text is not immediately inserted when available to not |
|
304 | # The text is not immediately inserted when available to not | |
305 | # choke the Qt event loop with paint events for the widget in |
|
305 | # choke the Qt event loop with paint events for the widget in | |
306 | # case of lots of output from kernel. |
|
306 | # case of lots of output from kernel. | |
307 | self._pending_insert_text = [] |
|
307 | self._pending_insert_text = [] | |
308 |
|
308 | |||
309 | # Timer to flush the pending stream messages. The interval is adjusted |
|
309 | # Timer to flush the pending stream messages. The interval is adjusted | |
310 | # later based on actual time taken for flushing a screen (buffer_size) |
|
310 | # later based on actual time taken for flushing a screen (buffer_size) | |
311 | # of output text. |
|
311 | # of output text. | |
312 | self._pending_text_flush_interval = QtCore.QTimer(self._control) |
|
312 | self._pending_text_flush_interval = QtCore.QTimer(self._control) | |
313 | self._pending_text_flush_interval.setInterval(100) |
|
313 | self._pending_text_flush_interval.setInterval(100) | |
314 | self._pending_text_flush_interval.setSingleShot(True) |
|
314 | self._pending_text_flush_interval.setSingleShot(True) | |
315 | self._pending_text_flush_interval.timeout.connect( |
|
315 | self._pending_text_flush_interval.timeout.connect( | |
316 | self._flush_pending_stream) |
|
316 | self._flush_pending_stream) | |
317 |
|
317 | |||
318 | # Set a monospaced font. |
|
318 | # Set a monospaced font. | |
319 | self.reset_font() |
|
319 | self.reset_font() | |
320 |
|
320 | |||
321 | # Configure actions. |
|
321 | # Configure actions. | |
322 | action = QtGui.QAction('Print', None) |
|
322 | action = QtGui.QAction('Print', None) | |
323 | action.setEnabled(True) |
|
323 | action.setEnabled(True) | |
324 | printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print) |
|
324 | printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print) | |
325 | if printkey.matches("Ctrl+P") and sys.platform != 'darwin': |
|
325 | if printkey.matches("Ctrl+P") and sys.platform != 'darwin': | |
326 | # Only override the default if there is a collision. |
|
326 | # Only override the default if there is a collision. | |
327 | # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. |
|
327 | # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. | |
328 | printkey = "Ctrl+Shift+P" |
|
328 | printkey = "Ctrl+Shift+P" | |
329 | action.setShortcut(printkey) |
|
329 | action.setShortcut(printkey) | |
330 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
330 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | |
331 | action.triggered.connect(self.print_) |
|
331 | action.triggered.connect(self.print_) | |
332 | self.addAction(action) |
|
332 | self.addAction(action) | |
333 | self.print_action = action |
|
333 | self.print_action = action | |
334 |
|
334 | |||
335 | action = QtGui.QAction('Save as HTML/XML', None) |
|
335 | action = QtGui.QAction('Save as HTML/XML', None) | |
336 | action.setShortcut(QtGui.QKeySequence.Save) |
|
336 | action.setShortcut(QtGui.QKeySequence.Save) | |
337 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
337 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | |
338 | action.triggered.connect(self.export_html) |
|
338 | action.triggered.connect(self.export_html) | |
339 | self.addAction(action) |
|
339 | self.addAction(action) | |
340 | self.export_action = action |
|
340 | self.export_action = action | |
341 |
|
341 | |||
342 | action = QtGui.QAction('Select All', None) |
|
342 | action = QtGui.QAction('Select All', None) | |
343 | action.setEnabled(True) |
|
343 | action.setEnabled(True) | |
344 | selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll) |
|
344 | selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll) | |
345 | if selectall.matches("Ctrl+A") and sys.platform != 'darwin': |
|
345 | if selectall.matches("Ctrl+A") and sys.platform != 'darwin': | |
346 | # Only override the default if there is a collision. |
|
346 | # Only override the default if there is a collision. | |
347 | # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. |
|
347 | # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. | |
348 | selectall = "Ctrl+Shift+A" |
|
348 | selectall = "Ctrl+Shift+A" | |
349 | action.setShortcut(selectall) |
|
349 | action.setShortcut(selectall) | |
350 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) |
|
350 | action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) | |
351 | action.triggered.connect(self.select_all) |
|
351 | action.triggered.connect(self.select_all) | |
352 | self.addAction(action) |
|
352 | self.addAction(action) | |
353 | self.select_all_action = action |
|
353 | self.select_all_action = action | |
354 |
|
354 | |||
355 | self.increase_font_size = QtGui.QAction("Bigger Font", |
|
355 | self.increase_font_size = QtGui.QAction("Bigger Font", | |
356 | self, |
|
356 | self, | |
357 | shortcut=QtGui.QKeySequence.ZoomIn, |
|
357 | shortcut=QtGui.QKeySequence.ZoomIn, | |
358 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, |
|
358 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, | |
359 | statusTip="Increase the font size by one point", |
|
359 | statusTip="Increase the font size by one point", | |
360 | triggered=self._increase_font_size) |
|
360 | triggered=self._increase_font_size) | |
361 | self.addAction(self.increase_font_size) |
|
361 | self.addAction(self.increase_font_size) | |
362 |
|
362 | |||
363 | self.decrease_font_size = QtGui.QAction("Smaller Font", |
|
363 | self.decrease_font_size = QtGui.QAction("Smaller Font", | |
364 | self, |
|
364 | self, | |
365 | shortcut=QtGui.QKeySequence.ZoomOut, |
|
365 | shortcut=QtGui.QKeySequence.ZoomOut, | |
366 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, |
|
366 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, | |
367 | statusTip="Decrease the font size by one point", |
|
367 | statusTip="Decrease the font size by one point", | |
368 | triggered=self._decrease_font_size) |
|
368 | triggered=self._decrease_font_size) | |
369 | self.addAction(self.decrease_font_size) |
|
369 | self.addAction(self.decrease_font_size) | |
370 |
|
370 | |||
371 | self.reset_font_size = QtGui.QAction("Normal Font", |
|
371 | self.reset_font_size = QtGui.QAction("Normal Font", | |
372 | self, |
|
372 | self, | |
373 | shortcut="Ctrl+0", |
|
373 | shortcut="Ctrl+0", | |
374 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, |
|
374 | shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut, | |
375 | statusTip="Restore the Normal font size", |
|
375 | statusTip="Restore the Normal font size", | |
376 | triggered=self.reset_font) |
|
376 | triggered=self.reset_font) | |
377 | self.addAction(self.reset_font_size) |
|
377 | self.addAction(self.reset_font_size) | |
378 |
|
378 | |||
379 | # Accept drag and drop events here. Drops were already turned off |
|
379 | # Accept drag and drop events here. Drops were already turned off | |
380 | # in self._control when that widget was created. |
|
380 | # in self._control when that widget was created. | |
381 | self.setAcceptDrops(True) |
|
381 | self.setAcceptDrops(True) | |
382 |
|
382 | |||
383 | #--------------------------------------------------------------------------- |
|
383 | #--------------------------------------------------------------------------- | |
384 | # Drag and drop support |
|
384 | # Drag and drop support | |
385 | #--------------------------------------------------------------------------- |
|
385 | #--------------------------------------------------------------------------- | |
386 |
|
386 | |||
387 | def dragEnterEvent(self, e): |
|
387 | def dragEnterEvent(self, e): | |
388 | if e.mimeData().hasUrls(): |
|
388 | if e.mimeData().hasUrls(): | |
389 | # The link action should indicate to that the drop will insert |
|
389 | # The link action should indicate to that the drop will insert | |
390 | # the file anme. |
|
390 | # the file anme. | |
391 | e.setDropAction(QtCore.Qt.LinkAction) |
|
391 | e.setDropAction(QtCore.Qt.LinkAction) | |
392 | e.accept() |
|
392 | e.accept() | |
393 | elif e.mimeData().hasText(): |
|
393 | elif e.mimeData().hasText(): | |
394 | # By changing the action to copy we don't need to worry about |
|
394 | # By changing the action to copy we don't need to worry about | |
395 | # the user accidentally moving text around in the widget. |
|
395 | # the user accidentally moving text around in the widget. | |
396 | e.setDropAction(QtCore.Qt.CopyAction) |
|
396 | e.setDropAction(QtCore.Qt.CopyAction) | |
397 | e.accept() |
|
397 | e.accept() | |
398 |
|
398 | |||
399 | def dragMoveEvent(self, e): |
|
399 | def dragMoveEvent(self, e): | |
400 | if e.mimeData().hasUrls(): |
|
400 | if e.mimeData().hasUrls(): | |
401 | pass |
|
401 | pass | |
402 | elif e.mimeData().hasText(): |
|
402 | elif e.mimeData().hasText(): | |
403 | cursor = self._control.cursorForPosition(e.pos()) |
|
403 | cursor = self._control.cursorForPosition(e.pos()) | |
404 | if self._in_buffer(cursor.position()): |
|
404 | if self._in_buffer(cursor.position()): | |
405 | e.setDropAction(QtCore.Qt.CopyAction) |
|
405 | e.setDropAction(QtCore.Qt.CopyAction) | |
406 | self._control.setTextCursor(cursor) |
|
406 | self._control.setTextCursor(cursor) | |
407 | else: |
|
407 | else: | |
408 | e.setDropAction(QtCore.Qt.IgnoreAction) |
|
408 | e.setDropAction(QtCore.Qt.IgnoreAction) | |
409 | e.accept() |
|
409 | e.accept() | |
410 |
|
410 | |||
411 | def dropEvent(self, e): |
|
411 | def dropEvent(self, e): | |
412 | if e.mimeData().hasUrls(): |
|
412 | if e.mimeData().hasUrls(): | |
413 | self._keep_cursor_in_buffer() |
|
413 | self._keep_cursor_in_buffer() | |
414 | cursor = self._control.textCursor() |
|
414 | cursor = self._control.textCursor() | |
415 | filenames = [url.toLocalFile() for url in e.mimeData().urls()] |
|
415 | filenames = [url.toLocalFile() for url in e.mimeData().urls()] | |
416 | text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'" |
|
416 | text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'" | |
417 | for f in filenames) |
|
417 | for f in filenames) | |
418 | self._insert_plain_text_into_buffer(cursor, text) |
|
418 | self._insert_plain_text_into_buffer(cursor, text) | |
419 | elif e.mimeData().hasText(): |
|
419 | elif e.mimeData().hasText(): | |
420 | cursor = self._control.cursorForPosition(e.pos()) |
|
420 | cursor = self._control.cursorForPosition(e.pos()) | |
421 | if self._in_buffer(cursor.position()): |
|
421 | if self._in_buffer(cursor.position()): | |
422 | text = e.mimeData().text() |
|
422 | text = e.mimeData().text() | |
423 | self._insert_plain_text_into_buffer(cursor, text) |
|
423 | self._insert_plain_text_into_buffer(cursor, text) | |
424 |
|
424 | |||
425 | def eventFilter(self, obj, event): |
|
425 | def eventFilter(self, obj, event): | |
426 | """ Reimplemented to ensure a console-like behavior in the underlying |
|
426 | """ Reimplemented to ensure a console-like behavior in the underlying | |
427 | text widgets. |
|
427 | text widgets. | |
428 | """ |
|
428 | """ | |
429 | etype = event.type() |
|
429 | etype = event.type() | |
430 | if etype == QtCore.QEvent.KeyPress: |
|
430 | if etype == QtCore.QEvent.KeyPress: | |
431 |
|
431 | |||
432 | # Re-map keys for all filtered widgets. |
|
432 | # Re-map keys for all filtered widgets. | |
433 | key = event.key() |
|
433 | key = event.key() | |
434 | if self._control_key_down(event.modifiers()) and \ |
|
434 | if self._control_key_down(event.modifiers()) and \ | |
435 | key in self._ctrl_down_remap: |
|
435 | key in self._ctrl_down_remap: | |
436 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, |
|
436 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, | |
437 | self._ctrl_down_remap[key], |
|
437 | self._ctrl_down_remap[key], | |
438 | QtCore.Qt.NoModifier) |
|
438 | QtCore.Qt.NoModifier) | |
439 | QtGui.qApp.sendEvent(obj, new_event) |
|
439 | QtGui.qApp.sendEvent(obj, new_event) | |
440 | return True |
|
440 | return True | |
441 |
|
441 | |||
442 | elif obj == self._control: |
|
442 | elif obj == self._control: | |
443 | return self._event_filter_console_keypress(event) |
|
443 | return self._event_filter_console_keypress(event) | |
444 |
|
444 | |||
445 | elif obj == self._page_control: |
|
445 | elif obj == self._page_control: | |
446 | return self._event_filter_page_keypress(event) |
|
446 | return self._event_filter_page_keypress(event) | |
447 |
|
447 | |||
448 | # Make middle-click paste safe. |
|
448 | # Make middle-click paste safe. | |
449 | elif etype == QtCore.QEvent.MouseButtonRelease and \ |
|
449 | elif etype == QtCore.QEvent.MouseButtonRelease and \ | |
450 | event.button() == QtCore.Qt.MidButton and \ |
|
450 | event.button() == QtCore.Qt.MidButton and \ | |
451 | obj == self._control.viewport(): |
|
451 | obj == self._control.viewport(): | |
452 | cursor = self._control.cursorForPosition(event.pos()) |
|
452 | cursor = self._control.cursorForPosition(event.pos()) | |
453 | self._control.setTextCursor(cursor) |
|
453 | self._control.setTextCursor(cursor) | |
454 | self.paste(QtGui.QClipboard.Selection) |
|
454 | self.paste(QtGui.QClipboard.Selection) | |
455 | return True |
|
455 | return True | |
456 |
|
456 | |||
457 | # Manually adjust the scrollbars *after* a resize event is dispatched. |
|
457 | # Manually adjust the scrollbars *after* a resize event is dispatched. | |
458 | elif etype == QtCore.QEvent.Resize and not self._filter_resize: |
|
458 | elif etype == QtCore.QEvent.Resize and not self._filter_resize: | |
459 | self._filter_resize = True |
|
459 | self._filter_resize = True | |
460 | QtGui.qApp.sendEvent(obj, event) |
|
460 | QtGui.qApp.sendEvent(obj, event) | |
461 | self._adjust_scrollbars() |
|
461 | self._adjust_scrollbars() | |
462 | self._filter_resize = False |
|
462 | self._filter_resize = False | |
463 | return True |
|
463 | return True | |
464 |
|
464 | |||
465 | # Override shortcuts for all filtered widgets. |
|
465 | # Override shortcuts for all filtered widgets. | |
466 | elif etype == QtCore.QEvent.ShortcutOverride and \ |
|
466 | elif etype == QtCore.QEvent.ShortcutOverride and \ | |
467 | self.override_shortcuts and \ |
|
467 | self.override_shortcuts and \ | |
468 | self._control_key_down(event.modifiers()) and \ |
|
468 | self._control_key_down(event.modifiers()) and \ | |
469 | event.key() in self._shortcuts: |
|
469 | event.key() in self._shortcuts: | |
470 | event.accept() |
|
470 | event.accept() | |
471 |
|
471 | |||
472 | # Handle scrolling of the vsplit pager. This hack attempts to solve |
|
472 | # Handle scrolling of the vsplit pager. This hack attempts to solve | |
473 | # problems with tearing of the help text inside the pager window. This |
|
473 | # problems with tearing of the help text inside the pager window. This | |
474 | # happens only on Mac OS X with both PySide and PyQt. This fix isn't |
|
474 | # happens only on Mac OS X with both PySide and PyQt. This fix isn't | |
475 | # perfect but makes the pager more usable. |
|
475 | # perfect but makes the pager more usable. | |
476 | elif etype in self._pager_scroll_events and \ |
|
476 | elif etype in self._pager_scroll_events and \ | |
477 | obj == self._page_control: |
|
477 | obj == self._page_control: | |
478 | self._page_control.repaint() |
|
478 | self._page_control.repaint() | |
479 | return True |
|
479 | return True | |
480 |
|
480 | |||
481 | elif etype == QtCore.QEvent.MouseMove: |
|
481 | elif etype == QtCore.QEvent.MouseMove: | |
482 | anchor = self._control.anchorAt(event.pos()) |
|
482 | anchor = self._control.anchorAt(event.pos()) | |
483 | QtGui.QToolTip.showText(event.globalPos(), anchor) |
|
483 | QtGui.QToolTip.showText(event.globalPos(), anchor) | |
484 |
|
484 | |||
485 | return super(ConsoleWidget, self).eventFilter(obj, event) |
|
485 | return super(ConsoleWidget, self).eventFilter(obj, event) | |
486 |
|
486 | |||
487 | #--------------------------------------------------------------------------- |
|
487 | #--------------------------------------------------------------------------- | |
488 | # 'QWidget' interface |
|
488 | # 'QWidget' interface | |
489 | #--------------------------------------------------------------------------- |
|
489 | #--------------------------------------------------------------------------- | |
490 |
|
490 | |||
491 | def sizeHint(self): |
|
491 | def sizeHint(self): | |
492 | """ Reimplemented to suggest a size that is 80 characters wide and |
|
492 | """ Reimplemented to suggest a size that is 80 characters wide and | |
493 | 25 lines high. |
|
493 | 25 lines high. | |
494 | """ |
|
494 | """ | |
495 | font_metrics = QtGui.QFontMetrics(self.font) |
|
495 | font_metrics = QtGui.QFontMetrics(self.font) | |
496 | margin = (self._control.frameWidth() + |
|
496 | margin = (self._control.frameWidth() + | |
497 | self._control.document().documentMargin()) * 2 |
|
497 | self._control.document().documentMargin()) * 2 | |
498 | style = self.style() |
|
498 | style = self.style() | |
499 | splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth) |
|
499 | splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth) | |
500 |
|
500 | |||
501 | # Note 1: Despite my best efforts to take the various margins into |
|
501 | # Note 1: Despite my best efforts to take the various margins into | |
502 | # account, the width is still coming out a bit too small, so we include |
|
502 | # account, the width is still coming out a bit too small, so we include | |
503 | # a fudge factor of one character here. |
|
503 | # a fudge factor of one character here. | |
504 | # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due |
|
504 | # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due | |
505 | # to a Qt bug on certain Mac OS systems where it returns 0. |
|
505 | # to a Qt bug on certain Mac OS systems where it returns 0. | |
506 | width = font_metrics.width(' ') * self.width + margin |
|
506 | width = font_metrics.width(' ') * self.width + margin | |
507 | width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent) |
|
507 | width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent) | |
508 | if self.paging == 'hsplit': |
|
508 | if self.paging == 'hsplit': | |
509 | width = width * 2 + splitwidth |
|
509 | width = width * 2 + splitwidth | |
510 |
|
510 | |||
511 | height = font_metrics.height() * self.height + margin |
|
511 | height = font_metrics.height() * self.height + margin | |
512 | if self.paging == 'vsplit': |
|
512 | if self.paging == 'vsplit': | |
513 | height = height * 2 + splitwidth |
|
513 | height = height * 2 + splitwidth | |
514 |
|
514 | |||
515 | return QtCore.QSize(width, height) |
|
515 | return QtCore.QSize(width, height) | |
516 |
|
516 | |||
517 | #--------------------------------------------------------------------------- |
|
517 | #--------------------------------------------------------------------------- | |
518 | # 'ConsoleWidget' public interface |
|
518 | # 'ConsoleWidget' public interface | |
519 | #--------------------------------------------------------------------------- |
|
519 | #--------------------------------------------------------------------------- | |
520 |
|
520 | |||
521 | def can_copy(self): |
|
521 | def can_copy(self): | |
522 | """ Returns whether text can be copied to the clipboard. |
|
522 | """ Returns whether text can be copied to the clipboard. | |
523 | """ |
|
523 | """ | |
524 | return self._control.textCursor().hasSelection() |
|
524 | return self._control.textCursor().hasSelection() | |
525 |
|
525 | |||
526 | def can_cut(self): |
|
526 | def can_cut(self): | |
527 | """ Returns whether text can be cut to the clipboard. |
|
527 | """ Returns whether text can be cut to the clipboard. | |
528 | """ |
|
528 | """ | |
529 | cursor = self._control.textCursor() |
|
529 | cursor = self._control.textCursor() | |
530 | return (cursor.hasSelection() and |
|
530 | return (cursor.hasSelection() and | |
531 | self._in_buffer(cursor.anchor()) and |
|
531 | self._in_buffer(cursor.anchor()) and | |
532 | self._in_buffer(cursor.position())) |
|
532 | self._in_buffer(cursor.position())) | |
533 |
|
533 | |||
534 | def can_paste(self): |
|
534 | def can_paste(self): | |
535 | """ Returns whether text can be pasted from the clipboard. |
|
535 | """ Returns whether text can be pasted from the clipboard. | |
536 | """ |
|
536 | """ | |
537 | if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: |
|
537 | if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: | |
538 | return bool(QtGui.QApplication.clipboard().text()) |
|
538 | return bool(QtGui.QApplication.clipboard().text()) | |
539 | return False |
|
539 | return False | |
540 |
|
540 | |||
541 | def clear(self, keep_input=True): |
|
541 | def clear(self, keep_input=True): | |
542 | """ Clear the console. |
|
542 | """ Clear the console. | |
543 |
|
543 | |||
544 | Parameters: |
|
544 | Parameters: | |
545 | ----------- |
|
545 | ----------- | |
546 | keep_input : bool, optional (default True) |
|
546 | keep_input : bool, optional (default True) | |
547 | If set, restores the old input buffer if a new prompt is written. |
|
547 | If set, restores the old input buffer if a new prompt is written. | |
548 | """ |
|
548 | """ | |
549 | if self._executing: |
|
549 | if self._executing: | |
550 | self._control.clear() |
|
550 | self._control.clear() | |
551 | else: |
|
551 | else: | |
552 | if keep_input: |
|
552 | if keep_input: | |
553 | input_buffer = self.input_buffer |
|
553 | input_buffer = self.input_buffer | |
554 | self._control.clear() |
|
554 | self._control.clear() | |
555 | self._show_prompt() |
|
555 | self._show_prompt() | |
556 | if keep_input: |
|
556 | if keep_input: | |
557 | self.input_buffer = input_buffer |
|
557 | self.input_buffer = input_buffer | |
558 |
|
558 | |||
559 | def copy(self): |
|
559 | def copy(self): | |
560 | """ Copy the currently selected text to the clipboard. |
|
560 | """ Copy the currently selected text to the clipboard. | |
561 | """ |
|
561 | """ | |
562 | self.layout().currentWidget().copy() |
|
562 | self.layout().currentWidget().copy() | |
563 |
|
563 | |||
564 | def copy_anchor(self, anchor): |
|
564 | def copy_anchor(self, anchor): | |
565 | """ Copy anchor text to the clipboard |
|
565 | """ Copy anchor text to the clipboard | |
566 | """ |
|
566 | """ | |
567 | QtGui.QApplication.clipboard().setText(anchor) |
|
567 | QtGui.QApplication.clipboard().setText(anchor) | |
568 |
|
568 | |||
569 | def cut(self): |
|
569 | def cut(self): | |
570 | """ Copy the currently selected text to the clipboard and delete it |
|
570 | """ Copy the currently selected text to the clipboard and delete it | |
571 | if it's inside the input buffer. |
|
571 | if it's inside the input buffer. | |
572 | """ |
|
572 | """ | |
573 | self.copy() |
|
573 | self.copy() | |
574 | if self.can_cut(): |
|
574 | if self.can_cut(): | |
575 | self._control.textCursor().removeSelectedText() |
|
575 | self._control.textCursor().removeSelectedText() | |
576 |
|
576 | |||
577 | def execute(self, source=None, hidden=False, interactive=False): |
|
577 | def execute(self, source=None, hidden=False, interactive=False): | |
578 | """ Executes source or the input buffer, possibly prompting for more |
|
578 | """ Executes source or the input buffer, possibly prompting for more | |
579 | input. |
|
579 | input. | |
580 |
|
580 | |||
581 | Parameters: |
|
581 | Parameters: | |
582 | ----------- |
|
582 | ----------- | |
583 | source : str, optional |
|
583 | source : str, optional | |
584 |
|
584 | |||
585 | The source to execute. If not specified, the input buffer will be |
|
585 | The source to execute. If not specified, the input buffer will be | |
586 | used. If specified and 'hidden' is False, the input buffer will be |
|
586 | used. If specified and 'hidden' is False, the input buffer will be | |
587 | replaced with the source before execution. |
|
587 | replaced with the source before execution. | |
588 |
|
588 | |||
589 | hidden : bool, optional (default False) |
|
589 | hidden : bool, optional (default False) | |
590 |
|
590 | |||
591 | If set, no output will be shown and the prompt will not be modified. |
|
591 | If set, no output will be shown and the prompt will not be modified. | |
592 | In other words, it will be completely invisible to the user that |
|
592 | In other words, it will be completely invisible to the user that | |
593 | an execution has occurred. |
|
593 | an execution has occurred. | |
594 |
|
594 | |||
595 | interactive : bool, optional (default False) |
|
595 | interactive : bool, optional (default False) | |
596 |
|
596 | |||
597 | Whether the console is to treat the source as having been manually |
|
597 | Whether the console is to treat the source as having been manually | |
598 | entered by the user. The effect of this parameter depends on the |
|
598 | entered by the user. The effect of this parameter depends on the | |
599 | subclass implementation. |
|
599 | subclass implementation. | |
600 |
|
600 | |||
601 | Raises: |
|
601 | Raises: | |
602 | ------- |
|
602 | ------- | |
603 | RuntimeError |
|
603 | RuntimeError | |
604 | If incomplete input is given and 'hidden' is True. In this case, |
|
604 | If incomplete input is given and 'hidden' is True. In this case, | |
605 | it is not possible to prompt for more input. |
|
605 | it is not possible to prompt for more input. | |
606 |
|
606 | |||
607 | Returns: |
|
607 | Returns: | |
608 | -------- |
|
608 | -------- | |
609 | A boolean indicating whether the source was executed. |
|
609 | A boolean indicating whether the source was executed. | |
610 | """ |
|
610 | """ | |
611 | # WARNING: The order in which things happen here is very particular, in |
|
611 | # WARNING: The order in which things happen here is very particular, in | |
612 | # large part because our syntax highlighting is fragile. If you change |
|
612 | # large part because our syntax highlighting is fragile. If you change | |
613 | # something, test carefully! |
|
613 | # something, test carefully! | |
614 |
|
614 | |||
615 | # Decide what to execute. |
|
615 | # Decide what to execute. | |
616 | if source is None: |
|
616 | if source is None: | |
617 | source = self.input_buffer |
|
617 | source = self.input_buffer | |
618 | if not hidden: |
|
618 | if not hidden: | |
619 | # A newline is appended later, but it should be considered part |
|
619 | # A newline is appended later, but it should be considered part | |
620 | # of the input buffer. |
|
620 | # of the input buffer. | |
621 | source += '\n' |
|
621 | source += '\n' | |
622 | elif not hidden: |
|
622 | elif not hidden: | |
623 | self.input_buffer = source |
|
623 | self.input_buffer = source | |
624 |
|
624 | |||
625 | # Execute the source or show a continuation prompt if it is incomplete. |
|
625 | # Execute the source or show a continuation prompt if it is incomplete. | |
626 | if self.execute_on_complete_input: |
|
626 | if self.execute_on_complete_input: | |
627 | complete = self._is_complete(source, interactive) |
|
627 | complete = self._is_complete(source, interactive) | |
628 | else: |
|
628 | else: | |
629 | complete = not interactive |
|
629 | complete = not interactive | |
630 | if hidden: |
|
630 | if hidden: | |
631 | if complete or not self.execute_on_complete_input: |
|
631 | if complete or not self.execute_on_complete_input: | |
632 | self._execute(source, hidden) |
|
632 | self._execute(source, hidden) | |
633 | else: |
|
633 | else: | |
634 | error = 'Incomplete noninteractive input: "%s"' |
|
634 | error = 'Incomplete noninteractive input: "%s"' | |
635 | raise RuntimeError(error % source) |
|
635 | raise RuntimeError(error % source) | |
636 | else: |
|
636 | else: | |
637 | if complete: |
|
637 | if complete: | |
638 | self._append_plain_text('\n') |
|
638 | self._append_plain_text('\n') | |
639 | self._input_buffer_executing = self.input_buffer |
|
639 | self._input_buffer_executing = self.input_buffer | |
640 | self._executing = True |
|
640 | self._executing = True | |
641 | self._prompt_finished() |
|
641 | self._prompt_finished() | |
642 |
|
642 | |||
643 | # The maximum block count is only in effect during execution. |
|
643 | # The maximum block count is only in effect during execution. | |
644 | # This ensures that _prompt_pos does not become invalid due to |
|
644 | # This ensures that _prompt_pos does not become invalid due to | |
645 | # text truncation. |
|
645 | # text truncation. | |
646 | self._control.document().setMaximumBlockCount(self.buffer_size) |
|
646 | self._control.document().setMaximumBlockCount(self.buffer_size) | |
647 |
|
647 | |||
648 | # Setting a positive maximum block count will automatically |
|
648 | # Setting a positive maximum block count will automatically | |
649 | # disable the undo/redo history, but just to be safe: |
|
649 | # disable the undo/redo history, but just to be safe: | |
650 | self._control.setUndoRedoEnabled(False) |
|
650 | self._control.setUndoRedoEnabled(False) | |
651 |
|
651 | |||
652 | # Perform actual execution. |
|
652 | # Perform actual execution. | |
653 | self._execute(source, hidden) |
|
653 | self._execute(source, hidden) | |
654 |
|
654 | |||
655 | else: |
|
655 | else: | |
656 | # Do this inside an edit block so continuation prompts are |
|
656 | # Do this inside an edit block so continuation prompts are | |
657 | # removed seamlessly via undo/redo. |
|
657 | # removed seamlessly via undo/redo. | |
658 | cursor = self._get_end_cursor() |
|
658 | cursor = self._get_end_cursor() | |
659 | cursor.beginEditBlock() |
|
659 | cursor.beginEditBlock() | |
660 | cursor.insertText('\n') |
|
660 | cursor.insertText('\n') | |
661 | self._insert_continuation_prompt(cursor) |
|
661 | self._insert_continuation_prompt(cursor) | |
662 | cursor.endEditBlock() |
|
662 | cursor.endEditBlock() | |
663 |
|
663 | |||
664 | # Do not do this inside the edit block. It works as expected |
|
664 | # Do not do this inside the edit block. It works as expected | |
665 | # when using a QPlainTextEdit control, but does not have an |
|
665 | # when using a QPlainTextEdit control, but does not have an | |
666 | # effect when using a QTextEdit. I believe this is a Qt bug. |
|
666 | # effect when using a QTextEdit. I believe this is a Qt bug. | |
667 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
667 | self._control.moveCursor(QtGui.QTextCursor.End) | |
668 |
|
668 | |||
669 | return complete |
|
669 | return complete | |
670 |
|
670 | |||
671 | def export_html(self): |
|
671 | def export_html(self): | |
672 | """ Shows a dialog to export HTML/XML in various formats. |
|
672 | """ Shows a dialog to export HTML/XML in various formats. | |
673 | """ |
|
673 | """ | |
674 | self._html_exporter.export() |
|
674 | self._html_exporter.export() | |
675 |
|
675 | |||
676 | def _get_input_buffer(self, force=False): |
|
676 | def _get_input_buffer(self, force=False): | |
677 | """ The text that the user has entered entered at the current prompt. |
|
677 | """ The text that the user has entered entered at the current prompt. | |
678 |
|
678 | |||
679 | If the console is currently executing, the text that is executing will |
|
679 | If the console is currently executing, the text that is executing will | |
680 | always be returned. |
|
680 | always be returned. | |
681 | """ |
|
681 | """ | |
682 | # If we're executing, the input buffer may not even exist anymore due to |
|
682 | # If we're executing, the input buffer may not even exist anymore due to | |
683 | # the limit imposed by 'buffer_size'. Therefore, we store it. |
|
683 | # the limit imposed by 'buffer_size'. Therefore, we store it. | |
684 | if self._executing and not force: |
|
684 | if self._executing and not force: | |
685 | return self._input_buffer_executing |
|
685 | return self._input_buffer_executing | |
686 |
|
686 | |||
687 | cursor = self._get_end_cursor() |
|
687 | cursor = self._get_end_cursor() | |
688 | cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) |
|
688 | cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) | |
689 | input_buffer = cursor.selection().toPlainText() |
|
689 | input_buffer = cursor.selection().toPlainText() | |
690 |
|
690 | |||
691 | # Strip out continuation prompts. |
|
691 | # Strip out continuation prompts. | |
692 | return input_buffer.replace('\n' + self._continuation_prompt, '\n') |
|
692 | return input_buffer.replace('\n' + self._continuation_prompt, '\n') | |
693 |
|
693 | |||
694 | def _set_input_buffer(self, string): |
|
694 | def _set_input_buffer(self, string): | |
695 | """ Sets the text in the input buffer. |
|
695 | """ Sets the text in the input buffer. | |
696 |
|
696 | |||
697 | If the console is currently executing, this call has no *immediate* |
|
697 | If the console is currently executing, this call has no *immediate* | |
698 | effect. When the execution is finished, the input buffer will be updated |
|
698 | effect. When the execution is finished, the input buffer will be updated | |
699 | appropriately. |
|
699 | appropriately. | |
700 | """ |
|
700 | """ | |
701 | # If we're executing, store the text for later. |
|
701 | # If we're executing, store the text for later. | |
702 | if self._executing: |
|
702 | if self._executing: | |
703 | self._input_buffer_pending = string |
|
703 | self._input_buffer_pending = string | |
704 | return |
|
704 | return | |
705 |
|
705 | |||
706 | # Remove old text. |
|
706 | # Remove old text. | |
707 | cursor = self._get_end_cursor() |
|
707 | cursor = self._get_end_cursor() | |
708 | cursor.beginEditBlock() |
|
708 | cursor.beginEditBlock() | |
709 | cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) |
|
709 | cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) | |
710 | cursor.removeSelectedText() |
|
710 | cursor.removeSelectedText() | |
711 |
|
711 | |||
712 | # Insert new text with continuation prompts. |
|
712 | # Insert new text with continuation prompts. | |
713 | self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string) |
|
713 | self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string) | |
714 | cursor.endEditBlock() |
|
714 | cursor.endEditBlock() | |
715 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
715 | self._control.moveCursor(QtGui.QTextCursor.End) | |
716 |
|
716 | |||
717 | input_buffer = property(_get_input_buffer, _set_input_buffer) |
|
717 | input_buffer = property(_get_input_buffer, _set_input_buffer) | |
718 |
|
718 | |||
719 | def _get_font(self): |
|
719 | def _get_font(self): | |
720 | """ The base font being used by the ConsoleWidget. |
|
720 | """ The base font being used by the ConsoleWidget. | |
721 | """ |
|
721 | """ | |
722 | return self._control.document().defaultFont() |
|
722 | return self._control.document().defaultFont() | |
723 |
|
723 | |||
724 | def _set_font(self, font): |
|
724 | def _set_font(self, font): | |
725 | """ Sets the base font for the ConsoleWidget to the specified QFont. |
|
725 | """ Sets the base font for the ConsoleWidget to the specified QFont. | |
726 | """ |
|
726 | """ | |
727 | font_metrics = QtGui.QFontMetrics(font) |
|
727 | font_metrics = QtGui.QFontMetrics(font) | |
728 | self._control.setTabStopWidth(self.tab_width * font_metrics.width(' ')) |
|
728 | self._control.setTabStopWidth(self.tab_width * font_metrics.width(' ')) | |
729 |
|
729 | |||
730 | self._completion_widget.setFont(font) |
|
730 | self._completion_widget.setFont(font) | |
731 | self._control.document().setDefaultFont(font) |
|
731 | self._control.document().setDefaultFont(font) | |
732 | if self._page_control: |
|
732 | if self._page_control: | |
733 | self._page_control.document().setDefaultFont(font) |
|
733 | self._page_control.document().setDefaultFont(font) | |
734 |
|
734 | |||
735 | self.font_changed.emit(font) |
|
735 | self.font_changed.emit(font) | |
736 |
|
736 | |||
737 | font = property(_get_font, _set_font) |
|
737 | font = property(_get_font, _set_font) | |
738 |
|
738 | |||
739 | def open_anchor(self, anchor): |
|
739 | def open_anchor(self, anchor): | |
740 | """ Open selected anchor in the default webbrowser |
|
740 | """ Open selected anchor in the default webbrowser | |
741 | """ |
|
741 | """ | |
742 | webbrowser.open( anchor ) |
|
742 | webbrowser.open( anchor ) | |
743 |
|
743 | |||
744 | def paste(self, mode=QtGui.QClipboard.Clipboard): |
|
744 | def paste(self, mode=QtGui.QClipboard.Clipboard): | |
745 | """ Paste the contents of the clipboard into the input region. |
|
745 | """ Paste the contents of the clipboard into the input region. | |
746 |
|
746 | |||
747 | Parameters: |
|
747 | Parameters: | |
748 | ----------- |
|
748 | ----------- | |
749 | mode : QClipboard::Mode, optional [default QClipboard::Clipboard] |
|
749 | mode : QClipboard::Mode, optional [default QClipboard::Clipboard] | |
750 |
|
750 | |||
751 | Controls which part of the system clipboard is used. This can be |
|
751 | Controls which part of the system clipboard is used. This can be | |
752 | used to access the selection clipboard in X11 and the Find buffer |
|
752 | used to access the selection clipboard in X11 and the Find buffer | |
753 | in Mac OS. By default, the regular clipboard is used. |
|
753 | in Mac OS. By default, the regular clipboard is used. | |
754 | """ |
|
754 | """ | |
755 | if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: |
|
755 | if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: | |
756 | # Make sure the paste is safe. |
|
756 | # Make sure the paste is safe. | |
757 | self._keep_cursor_in_buffer() |
|
757 | self._keep_cursor_in_buffer() | |
758 | cursor = self._control.textCursor() |
|
758 | cursor = self._control.textCursor() | |
759 |
|
759 | |||
760 | # Remove any trailing newline, which confuses the GUI and forces the |
|
760 | # Remove any trailing newline, which confuses the GUI and forces the | |
761 | # user to backspace. |
|
761 | # user to backspace. | |
762 | text = QtGui.QApplication.clipboard().text(mode).rstrip() |
|
762 | text = QtGui.QApplication.clipboard().text(mode).rstrip() | |
763 | self._insert_plain_text_into_buffer(cursor, dedent(text)) |
|
763 | self._insert_plain_text_into_buffer(cursor, dedent(text)) | |
764 |
|
764 | |||
765 | def print_(self, printer = None): |
|
765 | def print_(self, printer = None): | |
766 | """ Print the contents of the ConsoleWidget to the specified QPrinter. |
|
766 | """ Print the contents of the ConsoleWidget to the specified QPrinter. | |
767 | """ |
|
767 | """ | |
768 | if (not printer): |
|
768 | if (not printer): | |
769 | printer = QtGui.QPrinter() |
|
769 | printer = QtGui.QPrinter() | |
770 | if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted): |
|
770 | if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted): | |
771 | return |
|
771 | return | |
772 | self._control.print_(printer) |
|
772 | self._control.print_(printer) | |
773 |
|
773 | |||
774 | def prompt_to_top(self): |
|
774 | def prompt_to_top(self): | |
775 | """ Moves the prompt to the top of the viewport. |
|
775 | """ Moves the prompt to the top of the viewport. | |
776 | """ |
|
776 | """ | |
777 | if not self._executing: |
|
777 | if not self._executing: | |
778 | prompt_cursor = self._get_prompt_cursor() |
|
778 | prompt_cursor = self._get_prompt_cursor() | |
779 | if self._get_cursor().blockNumber() < prompt_cursor.blockNumber(): |
|
779 | if self._get_cursor().blockNumber() < prompt_cursor.blockNumber(): | |
780 | self._set_cursor(prompt_cursor) |
|
780 | self._set_cursor(prompt_cursor) | |
781 | self._set_top_cursor(prompt_cursor) |
|
781 | self._set_top_cursor(prompt_cursor) | |
782 |
|
782 | |||
783 | def redo(self): |
|
783 | def redo(self): | |
784 | """ Redo the last operation. If there is no operation to redo, nothing |
|
784 | """ Redo the last operation. If there is no operation to redo, nothing | |
785 | happens. |
|
785 | happens. | |
786 | """ |
|
786 | """ | |
787 | self._control.redo() |
|
787 | self._control.redo() | |
788 |
|
788 | |||
789 | def reset_font(self): |
|
789 | def reset_font(self): | |
790 | """ Sets the font to the default fixed-width font for this platform. |
|
790 | """ Sets the font to the default fixed-width font for this platform. | |
791 | """ |
|
791 | """ | |
792 | if sys.platform == 'win32': |
|
792 | if sys.platform == 'win32': | |
793 | # Consolas ships with Vista/Win7, fallback to Courier if needed |
|
793 | # Consolas ships with Vista/Win7, fallback to Courier if needed | |
794 | fallback = 'Courier' |
|
794 | fallback = 'Courier' | |
795 | elif sys.platform == 'darwin': |
|
795 | elif sys.platform == 'darwin': | |
796 | # OSX always has Monaco |
|
796 | # OSX always has Monaco | |
797 | fallback = 'Monaco' |
|
797 | fallback = 'Monaco' | |
798 | else: |
|
798 | else: | |
799 | # Monospace should always exist |
|
799 | # Monospace should always exist | |
800 | fallback = 'Monospace' |
|
800 | fallback = 'Monospace' | |
801 | font = get_font(self.font_family, fallback) |
|
801 | font = get_font(self.font_family, fallback) | |
802 | if self.font_size: |
|
802 | if self.font_size: | |
803 | font.setPointSize(self.font_size) |
|
803 | font.setPointSize(self.font_size) | |
804 | else: |
|
804 | else: | |
805 | font.setPointSize(QtGui.qApp.font().pointSize()) |
|
805 | font.setPointSize(QtGui.qApp.font().pointSize()) | |
806 | font.setStyleHint(QtGui.QFont.TypeWriter) |
|
806 | font.setStyleHint(QtGui.QFont.TypeWriter) | |
807 | self._set_font(font) |
|
807 | self._set_font(font) | |
808 |
|
808 | |||
809 | def change_font_size(self, delta): |
|
809 | def change_font_size(self, delta): | |
810 | """Change the font size by the specified amount (in points). |
|
810 | """Change the font size by the specified amount (in points). | |
811 | """ |
|
811 | """ | |
812 | font = self.font |
|
812 | font = self.font | |
813 | size = max(font.pointSize() + delta, 1) # minimum 1 point |
|
813 | size = max(font.pointSize() + delta, 1) # minimum 1 point | |
814 | font.setPointSize(size) |
|
814 | font.setPointSize(size) | |
815 | self._set_font(font) |
|
815 | self._set_font(font) | |
816 |
|
816 | |||
817 | def _increase_font_size(self): |
|
817 | def _increase_font_size(self): | |
818 | self.change_font_size(1) |
|
818 | self.change_font_size(1) | |
819 |
|
819 | |||
820 | def _decrease_font_size(self): |
|
820 | def _decrease_font_size(self): | |
821 | self.change_font_size(-1) |
|
821 | self.change_font_size(-1) | |
822 |
|
822 | |||
823 | def select_all(self): |
|
823 | def select_all(self): | |
824 | """ Selects all the text in the buffer. |
|
824 | """ Selects all the text in the buffer. | |
825 | """ |
|
825 | """ | |
826 | self._control.selectAll() |
|
826 | self._control.selectAll() | |
827 |
|
827 | |||
828 | def _get_tab_width(self): |
|
828 | def _get_tab_width(self): | |
829 | """ The width (in terms of space characters) for tab characters. |
|
829 | """ The width (in terms of space characters) for tab characters. | |
830 | """ |
|
830 | """ | |
831 | return self._tab_width |
|
831 | return self._tab_width | |
832 |
|
832 | |||
833 | def _set_tab_width(self, tab_width): |
|
833 | def _set_tab_width(self, tab_width): | |
834 | """ Sets the width (in terms of space characters) for tab characters. |
|
834 | """ Sets the width (in terms of space characters) for tab characters. | |
835 | """ |
|
835 | """ | |
836 | font_metrics = QtGui.QFontMetrics(self.font) |
|
836 | font_metrics = QtGui.QFontMetrics(self.font) | |
837 | self._control.setTabStopWidth(tab_width * font_metrics.width(' ')) |
|
837 | self._control.setTabStopWidth(tab_width * font_metrics.width(' ')) | |
838 |
|
838 | |||
839 | self._tab_width = tab_width |
|
839 | self._tab_width = tab_width | |
840 |
|
840 | |||
841 | tab_width = property(_get_tab_width, _set_tab_width) |
|
841 | tab_width = property(_get_tab_width, _set_tab_width) | |
842 |
|
842 | |||
843 | def undo(self): |
|
843 | def undo(self): | |
844 | """ Undo the last operation. If there is no operation to undo, nothing |
|
844 | """ Undo the last operation. If there is no operation to undo, nothing | |
845 | happens. |
|
845 | happens. | |
846 | """ |
|
846 | """ | |
847 | self._control.undo() |
|
847 | self._control.undo() | |
848 |
|
848 | |||
849 | #--------------------------------------------------------------------------- |
|
849 | #--------------------------------------------------------------------------- | |
850 | # 'ConsoleWidget' abstract interface |
|
850 | # 'ConsoleWidget' abstract interface | |
851 | #--------------------------------------------------------------------------- |
|
851 | #--------------------------------------------------------------------------- | |
852 |
|
852 | |||
853 | def _is_complete(self, source, interactive): |
|
853 | def _is_complete(self, source, interactive): | |
854 | """ Returns whether 'source' can be executed. When triggered by an |
|
854 | """ Returns whether 'source' can be executed. When triggered by an | |
855 | Enter/Return key press, 'interactive' is True; otherwise, it is |
|
855 | Enter/Return key press, 'interactive' is True; otherwise, it is | |
856 | False. |
|
856 | False. | |
857 | """ |
|
857 | """ | |
858 | raise NotImplementedError |
|
858 | raise NotImplementedError | |
859 |
|
859 | |||
860 | def _execute(self, source, hidden): |
|
860 | def _execute(self, source, hidden): | |
861 | """ Execute 'source'. If 'hidden', do not show any output. |
|
861 | """ Execute 'source'. If 'hidden', do not show any output. | |
862 | """ |
|
862 | """ | |
863 | raise NotImplementedError |
|
863 | raise NotImplementedError | |
864 |
|
864 | |||
865 | def _prompt_started_hook(self): |
|
865 | def _prompt_started_hook(self): | |
866 | """ Called immediately after a new prompt is displayed. |
|
866 | """ Called immediately after a new prompt is displayed. | |
867 | """ |
|
867 | """ | |
868 | pass |
|
868 | pass | |
869 |
|
869 | |||
870 | def _prompt_finished_hook(self): |
|
870 | def _prompt_finished_hook(self): | |
871 | """ Called immediately after a prompt is finished, i.e. when some input |
|
871 | """ Called immediately after a prompt is finished, i.e. when some input | |
872 | will be processed and a new prompt displayed. |
|
872 | will be processed and a new prompt displayed. | |
873 | """ |
|
873 | """ | |
874 | pass |
|
874 | pass | |
875 |
|
875 | |||
876 | def _up_pressed(self, shift_modifier): |
|
876 | def _up_pressed(self, shift_modifier): | |
877 | """ Called when the up key is pressed. Returns whether to continue |
|
877 | """ Called when the up key is pressed. Returns whether to continue | |
878 | processing the event. |
|
878 | processing the event. | |
879 | """ |
|
879 | """ | |
880 | return True |
|
880 | return True | |
881 |
|
881 | |||
882 | def _down_pressed(self, shift_modifier): |
|
882 | def _down_pressed(self, shift_modifier): | |
883 | """ Called when the down key is pressed. Returns whether to continue |
|
883 | """ Called when the down key is pressed. Returns whether to continue | |
884 | processing the event. |
|
884 | processing the event. | |
885 | """ |
|
885 | """ | |
886 | return True |
|
886 | return True | |
887 |
|
887 | |||
888 | def _tab_pressed(self): |
|
888 | def _tab_pressed(self): | |
889 | """ Called when the tab key is pressed. Returns whether to continue |
|
889 | """ Called when the tab key is pressed. Returns whether to continue | |
890 | processing the event. |
|
890 | processing the event. | |
891 | """ |
|
891 | """ | |
892 | return False |
|
892 | return False | |
893 |
|
893 | |||
894 | #-------------------------------------------------------------------------- |
|
894 | #-------------------------------------------------------------------------- | |
895 | # 'ConsoleWidget' protected interface |
|
895 | # 'ConsoleWidget' protected interface | |
896 | #-------------------------------------------------------------------------- |
|
896 | #-------------------------------------------------------------------------- | |
897 |
|
897 | |||
898 | def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs): |
|
898 | def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs): | |
899 | """ A low-level method for appending content to the end of the buffer. |
|
899 | """ A low-level method for appending content to the end of the buffer. | |
900 |
|
900 | |||
901 | If 'before_prompt' is enabled, the content will be inserted before the |
|
901 | If 'before_prompt' is enabled, the content will be inserted before the | |
902 | current prompt, if there is one. |
|
902 | current prompt, if there is one. | |
903 | """ |
|
903 | """ | |
904 | # Determine where to insert the content. |
|
904 | # Determine where to insert the content. | |
905 | cursor = self._control.textCursor() |
|
905 | cursor = self._control.textCursor() | |
906 | if before_prompt and (self._reading or not self._executing): |
|
906 | if before_prompt and (self._reading or not self._executing): | |
907 | self._flush_pending_stream() |
|
907 | self._flush_pending_stream() | |
908 | cursor.setPosition(self._append_before_prompt_pos) |
|
908 | cursor.setPosition(self._append_before_prompt_pos) | |
909 | else: |
|
909 | else: | |
910 | if insert != self._insert_plain_text: |
|
910 | if insert != self._insert_plain_text: | |
911 | self._flush_pending_stream() |
|
911 | self._flush_pending_stream() | |
912 | cursor.movePosition(QtGui.QTextCursor.End) |
|
912 | cursor.movePosition(QtGui.QTextCursor.End) | |
913 | start_pos = cursor.position() |
|
913 | start_pos = cursor.position() | |
914 |
|
914 | |||
915 | # Perform the insertion. |
|
915 | # Perform the insertion. | |
916 | result = insert(cursor, input, *args, **kwargs) |
|
916 | result = insert(cursor, input, *args, **kwargs) | |
917 |
|
917 | |||
918 | # Adjust the prompt position if we have inserted before it. This is safe |
|
918 | # Adjust the prompt position if we have inserted before it. This is safe | |
919 | # because buffer truncation is disabled when not executing. |
|
919 | # because buffer truncation is disabled when not executing. | |
920 | if before_prompt and not self._executing: |
|
920 | if before_prompt and not self._executing: | |
921 | diff = cursor.position() - start_pos |
|
921 | diff = cursor.position() - start_pos | |
922 | self._append_before_prompt_pos += diff |
|
922 | self._append_before_prompt_pos += diff | |
923 | self._prompt_pos += diff |
|
923 | self._prompt_pos += diff | |
924 |
|
924 | |||
925 | return result |
|
925 | return result | |
926 |
|
926 | |||
927 | def _append_block(self, block_format=None, before_prompt=False): |
|
927 | def _append_block(self, block_format=None, before_prompt=False): | |
928 | """ Appends an new QTextBlock to the end of the console buffer. |
|
928 | """ Appends an new QTextBlock to the end of the console buffer. | |
929 | """ |
|
929 | """ | |
930 | self._append_custom(self._insert_block, block_format, before_prompt) |
|
930 | self._append_custom(self._insert_block, block_format, before_prompt) | |
931 |
|
931 | |||
932 | def _append_html(self, html, before_prompt=False): |
|
932 | def _append_html(self, html, before_prompt=False): | |
933 | """ Appends HTML at the end of the console buffer. |
|
933 | """ Appends HTML at the end of the console buffer. | |
934 | """ |
|
934 | """ | |
935 | self._append_custom(self._insert_html, html, before_prompt) |
|
935 | self._append_custom(self._insert_html, html, before_prompt) | |
936 |
|
936 | |||
937 | def _append_html_fetching_plain_text(self, html, before_prompt=False): |
|
937 | def _append_html_fetching_plain_text(self, html, before_prompt=False): | |
938 | """ Appends HTML, then returns the plain text version of it. |
|
938 | """ Appends HTML, then returns the plain text version of it. | |
939 | """ |
|
939 | """ | |
940 | return self._append_custom(self._insert_html_fetching_plain_text, |
|
940 | return self._append_custom(self._insert_html_fetching_plain_text, | |
941 | html, before_prompt) |
|
941 | html, before_prompt) | |
942 |
|
942 | |||
943 | def _append_plain_text(self, text, before_prompt=False): |
|
943 | def _append_plain_text(self, text, before_prompt=False): | |
944 | """ Appends plain text, processing ANSI codes if enabled. |
|
944 | """ Appends plain text, processing ANSI codes if enabled. | |
945 | """ |
|
945 | """ | |
946 | self._append_custom(self._insert_plain_text, text, before_prompt) |
|
946 | self._append_custom(self._insert_plain_text, text, before_prompt) | |
947 |
|
947 | |||
948 | def _cancel_completion(self): |
|
948 | def _cancel_completion(self): | |
949 | """ If text completion is progress, cancel it. |
|
949 | """ If text completion is progress, cancel it. | |
950 | """ |
|
950 | """ | |
951 | self._completion_widget.cancel_completion() |
|
951 | self._completion_widget.cancel_completion() | |
952 |
|
952 | |||
953 | def _clear_temporary_buffer(self): |
|
953 | def _clear_temporary_buffer(self): | |
954 | """ Clears the "temporary text" buffer, i.e. all the text following |
|
954 | """ Clears the "temporary text" buffer, i.e. all the text following | |
955 | the prompt region. |
|
955 | the prompt region. | |
956 | """ |
|
956 | """ | |
957 | # Select and remove all text below the input buffer. |
|
957 | # Select and remove all text below the input buffer. | |
958 | cursor = self._get_prompt_cursor() |
|
958 | cursor = self._get_prompt_cursor() | |
959 | prompt = self._continuation_prompt.lstrip() |
|
959 | prompt = self._continuation_prompt.lstrip() | |
960 | if(self._temp_buffer_filled): |
|
960 | if(self._temp_buffer_filled): | |
961 | self._temp_buffer_filled = False |
|
961 | self._temp_buffer_filled = False | |
962 | while cursor.movePosition(QtGui.QTextCursor.NextBlock): |
|
962 | while cursor.movePosition(QtGui.QTextCursor.NextBlock): | |
963 | temp_cursor = QtGui.QTextCursor(cursor) |
|
963 | temp_cursor = QtGui.QTextCursor(cursor) | |
964 | temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor) |
|
964 | temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor) | |
965 | text = temp_cursor.selection().toPlainText().lstrip() |
|
965 | text = temp_cursor.selection().toPlainText().lstrip() | |
966 | if not text.startswith(prompt): |
|
966 | if not text.startswith(prompt): | |
967 | break |
|
967 | break | |
968 | else: |
|
968 | else: | |
969 | # We've reached the end of the input buffer and no text follows. |
|
969 | # We've reached the end of the input buffer and no text follows. | |
970 | return |
|
970 | return | |
971 | cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline. |
|
971 | cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline. | |
972 | cursor.movePosition(QtGui.QTextCursor.End, |
|
972 | cursor.movePosition(QtGui.QTextCursor.End, | |
973 | QtGui.QTextCursor.KeepAnchor) |
|
973 | QtGui.QTextCursor.KeepAnchor) | |
974 | cursor.removeSelectedText() |
|
974 | cursor.removeSelectedText() | |
975 |
|
975 | |||
976 | # After doing this, we have no choice but to clear the undo/redo |
|
976 | # After doing this, we have no choice but to clear the undo/redo | |
977 | # history. Otherwise, the text is not "temporary" at all, because it |
|
977 | # history. Otherwise, the text is not "temporary" at all, because it | |
978 | # can be recalled with undo/redo. Unfortunately, Qt does not expose |
|
978 | # can be recalled with undo/redo. Unfortunately, Qt does not expose | |
979 | # fine-grained control to the undo/redo system. |
|
979 | # fine-grained control to the undo/redo system. | |
980 | if self._control.isUndoRedoEnabled(): |
|
980 | if self._control.isUndoRedoEnabled(): | |
981 | self._control.setUndoRedoEnabled(False) |
|
981 | self._control.setUndoRedoEnabled(False) | |
982 | self._control.setUndoRedoEnabled(True) |
|
982 | self._control.setUndoRedoEnabled(True) | |
983 |
|
983 | |||
984 | def _complete_with_items(self, cursor, items): |
|
984 | def _complete_with_items(self, cursor, items): | |
985 | """ Performs completion with 'items' at the specified cursor location. |
|
985 | """ Performs completion with 'items' at the specified cursor location. | |
986 | """ |
|
986 | """ | |
987 | self._cancel_completion() |
|
987 | self._cancel_completion() | |
988 |
|
988 | |||
989 | if len(items) == 1: |
|
989 | if len(items) == 1: | |
990 | cursor.setPosition(self._control.textCursor().position(), |
|
990 | cursor.setPosition(self._control.textCursor().position(), | |
991 | QtGui.QTextCursor.KeepAnchor) |
|
991 | QtGui.QTextCursor.KeepAnchor) | |
992 | cursor.insertText(items[0]) |
|
992 | cursor.insertText(items[0]) | |
993 |
|
993 | |||
994 | elif len(items) > 1: |
|
994 | elif len(items) > 1: | |
995 | current_pos = self._control.textCursor().position() |
|
995 | current_pos = self._control.textCursor().position() | |
996 | prefix = commonprefix(items) |
|
996 | prefix = commonprefix(items) | |
997 | if prefix: |
|
997 | if prefix: | |
998 | cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor) |
|
998 | cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor) | |
999 | cursor.insertText(prefix) |
|
999 | cursor.insertText(prefix) | |
1000 | current_pos = cursor.position() |
|
1000 | current_pos = cursor.position() | |
1001 |
|
1001 | |||
1002 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix)) |
|
1002 | cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix)) | |
1003 | self._completion_widget.show_items(cursor, items) |
|
1003 | self._completion_widget.show_items(cursor, items) | |
1004 |
|
1004 | |||
1005 |
|
1005 | |||
1006 | def _fill_temporary_buffer(self, cursor, text, html=False): |
|
1006 | def _fill_temporary_buffer(self, cursor, text, html=False): | |
1007 | """fill the area below the active editting zone with text""" |
|
1007 | """fill the area below the active editting zone with text""" | |
1008 |
|
1008 | |||
1009 | current_pos = self._control.textCursor().position() |
|
1009 | current_pos = self._control.textCursor().position() | |
1010 |
|
1010 | |||
1011 | cursor.beginEditBlock() |
|
1011 | cursor.beginEditBlock() | |
1012 | self._append_plain_text('\n') |
|
1012 | self._append_plain_text('\n') | |
1013 | self._page(text, html=html) |
|
1013 | self._page(text, html=html) | |
1014 | cursor.endEditBlock() |
|
1014 | cursor.endEditBlock() | |
1015 |
|
1015 | |||
1016 | cursor.setPosition(current_pos) |
|
1016 | cursor.setPosition(current_pos) | |
1017 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
1017 | self._control.moveCursor(QtGui.QTextCursor.End) | |
1018 | self._control.setTextCursor(cursor) |
|
1018 | self._control.setTextCursor(cursor) | |
1019 |
|
1019 | |||
1020 | self._temp_buffer_filled = True |
|
1020 | self._temp_buffer_filled = True | |
1021 |
|
1021 | |||
1022 |
|
1022 | |||
1023 | def _context_menu_make(self, pos): |
|
1023 | def _context_menu_make(self, pos): | |
1024 | """ Creates a context menu for the given QPoint (in widget coordinates). |
|
1024 | """ Creates a context menu for the given QPoint (in widget coordinates). | |
1025 | """ |
|
1025 | """ | |
1026 | menu = QtGui.QMenu(self) |
|
1026 | menu = QtGui.QMenu(self) | |
1027 |
|
1027 | |||
1028 | self.cut_action = menu.addAction('Cut', self.cut) |
|
1028 | self.cut_action = menu.addAction('Cut', self.cut) | |
1029 | self.cut_action.setEnabled(self.can_cut()) |
|
1029 | self.cut_action.setEnabled(self.can_cut()) | |
1030 | self.cut_action.setShortcut(QtGui.QKeySequence.Cut) |
|
1030 | self.cut_action.setShortcut(QtGui.QKeySequence.Cut) | |
1031 |
|
1031 | |||
1032 | self.copy_action = menu.addAction('Copy', self.copy) |
|
1032 | self.copy_action = menu.addAction('Copy', self.copy) | |
1033 | self.copy_action.setEnabled(self.can_copy()) |
|
1033 | self.copy_action.setEnabled(self.can_copy()) | |
1034 | self.copy_action.setShortcut(QtGui.QKeySequence.Copy) |
|
1034 | self.copy_action.setShortcut(QtGui.QKeySequence.Copy) | |
1035 |
|
1035 | |||
1036 | self.paste_action = menu.addAction('Paste', self.paste) |
|
1036 | self.paste_action = menu.addAction('Paste', self.paste) | |
1037 | self.paste_action.setEnabled(self.can_paste()) |
|
1037 | self.paste_action.setEnabled(self.can_paste()) | |
1038 | self.paste_action.setShortcut(QtGui.QKeySequence.Paste) |
|
1038 | self.paste_action.setShortcut(QtGui.QKeySequence.Paste) | |
1039 |
|
1039 | |||
1040 | anchor = self._control.anchorAt(pos) |
|
1040 | anchor = self._control.anchorAt(pos) | |
1041 | if anchor: |
|
1041 | if anchor: | |
1042 | menu.addSeparator() |
|
1042 | menu.addSeparator() | |
1043 | self.copy_link_action = menu.addAction( |
|
1043 | self.copy_link_action = menu.addAction( | |
1044 | 'Copy Link Address', lambda: self.copy_anchor(anchor=anchor)) |
|
1044 | 'Copy Link Address', lambda: self.copy_anchor(anchor=anchor)) | |
1045 | self.open_link_action = menu.addAction( |
|
1045 | self.open_link_action = menu.addAction( | |
1046 | 'Open Link', lambda: self.open_anchor(anchor=anchor)) |
|
1046 | 'Open Link', lambda: self.open_anchor(anchor=anchor)) | |
1047 |
|
1047 | |||
1048 | menu.addSeparator() |
|
1048 | menu.addSeparator() | |
1049 | menu.addAction(self.select_all_action) |
|
1049 | menu.addAction(self.select_all_action) | |
1050 |
|
1050 | |||
1051 | menu.addSeparator() |
|
1051 | menu.addSeparator() | |
1052 | menu.addAction(self.export_action) |
|
1052 | menu.addAction(self.export_action) | |
1053 | menu.addAction(self.print_action) |
|
1053 | menu.addAction(self.print_action) | |
1054 |
|
1054 | |||
1055 | return menu |
|
1055 | return menu | |
1056 |
|
1056 | |||
1057 | def _control_key_down(self, modifiers, include_command=False): |
|
1057 | def _control_key_down(self, modifiers, include_command=False): | |
1058 | """ Given a KeyboardModifiers flags object, return whether the Control |
|
1058 | """ Given a KeyboardModifiers flags object, return whether the Control | |
1059 | key is down. |
|
1059 | key is down. | |
1060 |
|
1060 | |||
1061 | Parameters: |
|
1061 | Parameters: | |
1062 | ----------- |
|
1062 | ----------- | |
1063 | include_command : bool, optional (default True) |
|
1063 | include_command : bool, optional (default True) | |
1064 | Whether to treat the Command key as a (mutually exclusive) synonym |
|
1064 | Whether to treat the Command key as a (mutually exclusive) synonym | |
1065 | for Control when in Mac OS. |
|
1065 | for Control when in Mac OS. | |
1066 | """ |
|
1066 | """ | |
1067 | # Note that on Mac OS, ControlModifier corresponds to the Command key |
|
1067 | # Note that on Mac OS, ControlModifier corresponds to the Command key | |
1068 | # while MetaModifier corresponds to the Control key. |
|
1068 | # while MetaModifier corresponds to the Control key. | |
1069 | if sys.platform == 'darwin': |
|
1069 | if sys.platform == 'darwin': | |
1070 | down = include_command and (modifiers & QtCore.Qt.ControlModifier) |
|
1070 | down = include_command and (modifiers & QtCore.Qt.ControlModifier) | |
1071 | return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier) |
|
1071 | return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier) | |
1072 | else: |
|
1072 | else: | |
1073 | return bool(modifiers & QtCore.Qt.ControlModifier) |
|
1073 | return bool(modifiers & QtCore.Qt.ControlModifier) | |
1074 |
|
1074 | |||
1075 | def _create_control(self): |
|
1075 | def _create_control(self): | |
1076 | """ Creates and connects the underlying text widget. |
|
1076 | """ Creates and connects the underlying text widget. | |
1077 | """ |
|
1077 | """ | |
1078 | # Create the underlying control. |
|
1078 | # Create the underlying control. | |
1079 | if self.custom_control: |
|
1079 | if self.custom_control: | |
1080 | control = self.custom_control() |
|
1080 | control = self.custom_control() | |
1081 | elif self.kind == 'plain': |
|
1081 | elif self.kind == 'plain': | |
1082 | control = QtGui.QPlainTextEdit() |
|
1082 | control = QtGui.QPlainTextEdit() | |
1083 | elif self.kind == 'rich': |
|
1083 | elif self.kind == 'rich': | |
1084 | control = QtGui.QTextEdit() |
|
1084 | control = QtGui.QTextEdit() | |
1085 | control.setAcceptRichText(False) |
|
1085 | control.setAcceptRichText(False) | |
1086 | control.setMouseTracking(True) |
|
1086 | control.setMouseTracking(True) | |
1087 |
|
1087 | |||
1088 | # Prevent the widget from handling drops, as we already provide |
|
1088 | # Prevent the widget from handling drops, as we already provide | |
1089 | # the logic in this class. |
|
1089 | # the logic in this class. | |
1090 | control.setAcceptDrops(False) |
|
1090 | control.setAcceptDrops(False) | |
1091 |
|
1091 | |||
1092 | # Install event filters. The filter on the viewport is needed for |
|
1092 | # Install event filters. The filter on the viewport is needed for | |
1093 | # mouse events. |
|
1093 | # mouse events. | |
1094 | control.installEventFilter(self) |
|
1094 | control.installEventFilter(self) | |
1095 | control.viewport().installEventFilter(self) |
|
1095 | control.viewport().installEventFilter(self) | |
1096 |
|
1096 | |||
1097 | # Connect signals. |
|
1097 | # Connect signals. | |
1098 | control.customContextMenuRequested.connect( |
|
1098 | control.customContextMenuRequested.connect( | |
1099 | self._custom_context_menu_requested) |
|
1099 | self._custom_context_menu_requested) | |
1100 | control.copyAvailable.connect(self.copy_available) |
|
1100 | control.copyAvailable.connect(self.copy_available) | |
1101 | control.redoAvailable.connect(self.redo_available) |
|
1101 | control.redoAvailable.connect(self.redo_available) | |
1102 | control.undoAvailable.connect(self.undo_available) |
|
1102 | control.undoAvailable.connect(self.undo_available) | |
1103 |
|
1103 | |||
1104 | # Hijack the document size change signal to prevent Qt from adjusting |
|
1104 | # Hijack the document size change signal to prevent Qt from adjusting | |
1105 | # the viewport's scrollbar. We are relying on an implementation detail |
|
1105 | # the viewport's scrollbar. We are relying on an implementation detail | |
1106 | # of Q(Plain)TextEdit here, which is potentially dangerous, but without |
|
1106 | # of Q(Plain)TextEdit here, which is potentially dangerous, but without | |
1107 | # this functionality we cannot create a nice terminal interface. |
|
1107 | # this functionality we cannot create a nice terminal interface. | |
1108 | layout = control.document().documentLayout() |
|
1108 | layout = control.document().documentLayout() | |
1109 | layout.documentSizeChanged.disconnect() |
|
1109 | layout.documentSizeChanged.disconnect() | |
1110 | layout.documentSizeChanged.connect(self._adjust_scrollbars) |
|
1110 | layout.documentSizeChanged.connect(self._adjust_scrollbars) | |
1111 |
|
1111 | |||
1112 | # Configure the control. |
|
1112 | # Configure the control. | |
1113 | control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True) |
|
1113 | control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True) | |
1114 | control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) |
|
1114 | control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) | |
1115 | control.setReadOnly(True) |
|
1115 | control.setReadOnly(True) | |
1116 | control.setUndoRedoEnabled(False) |
|
1116 | control.setUndoRedoEnabled(False) | |
1117 | control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) |
|
1117 | control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) | |
1118 | return control |
|
1118 | return control | |
1119 |
|
1119 | |||
1120 | def _create_page_control(self): |
|
1120 | def _create_page_control(self): | |
1121 | """ Creates and connects the underlying paging widget. |
|
1121 | """ Creates and connects the underlying paging widget. | |
1122 | """ |
|
1122 | """ | |
1123 | if self.custom_page_control: |
|
1123 | if self.custom_page_control: | |
1124 | control = self.custom_page_control() |
|
1124 | control = self.custom_page_control() | |
1125 | elif self.kind == 'plain': |
|
1125 | elif self.kind == 'plain': | |
1126 | control = QtGui.QPlainTextEdit() |
|
1126 | control = QtGui.QPlainTextEdit() | |
1127 | elif self.kind == 'rich': |
|
1127 | elif self.kind == 'rich': | |
1128 | control = QtGui.QTextEdit() |
|
1128 | control = QtGui.QTextEdit() | |
1129 | control.installEventFilter(self) |
|
1129 | control.installEventFilter(self) | |
1130 | viewport = control.viewport() |
|
1130 | viewport = control.viewport() | |
1131 | viewport.installEventFilter(self) |
|
1131 | viewport.installEventFilter(self) | |
1132 | control.setReadOnly(True) |
|
1132 | control.setReadOnly(True) | |
1133 | control.setUndoRedoEnabled(False) |
|
1133 | control.setUndoRedoEnabled(False) | |
1134 | control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) |
|
1134 | control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn) | |
1135 | return control |
|
1135 | return control | |
1136 |
|
1136 | |||
1137 | def _event_filter_console_keypress(self, event): |
|
1137 | def _event_filter_console_keypress(self, event): | |
1138 | """ Filter key events for the underlying text widget to create a |
|
1138 | """ Filter key events for the underlying text widget to create a | |
1139 | console-like interface. |
|
1139 | console-like interface. | |
1140 | """ |
|
1140 | """ | |
1141 | intercepted = False |
|
1141 | intercepted = False | |
1142 | cursor = self._control.textCursor() |
|
1142 | cursor = self._control.textCursor() | |
1143 | position = cursor.position() |
|
1143 | position = cursor.position() | |
1144 | key = event.key() |
|
1144 | key = event.key() | |
1145 | ctrl_down = self._control_key_down(event.modifiers()) |
|
1145 | ctrl_down = self._control_key_down(event.modifiers()) | |
1146 | alt_down = event.modifiers() & QtCore.Qt.AltModifier |
|
1146 | alt_down = event.modifiers() & QtCore.Qt.AltModifier | |
1147 | shift_down = event.modifiers() & QtCore.Qt.ShiftModifier |
|
1147 | shift_down = event.modifiers() & QtCore.Qt.ShiftModifier | |
1148 |
|
1148 | |||
1149 | #------ Special sequences ---------------------------------------------- |
|
1149 | #------ Special sequences ---------------------------------------------- | |
1150 |
|
1150 | |||
1151 | if event.matches(QtGui.QKeySequence.Copy): |
|
1151 | if event.matches(QtGui.QKeySequence.Copy): | |
1152 | self.copy() |
|
1152 | self.copy() | |
1153 | intercepted = True |
|
1153 | intercepted = True | |
1154 |
|
1154 | |||
1155 | elif event.matches(QtGui.QKeySequence.Cut): |
|
1155 | elif event.matches(QtGui.QKeySequence.Cut): | |
1156 | self.cut() |
|
1156 | self.cut() | |
1157 | intercepted = True |
|
1157 | intercepted = True | |
1158 |
|
1158 | |||
1159 | elif event.matches(QtGui.QKeySequence.Paste): |
|
1159 | elif event.matches(QtGui.QKeySequence.Paste): | |
1160 | self.paste() |
|
1160 | self.paste() | |
1161 | intercepted = True |
|
1161 | intercepted = True | |
1162 |
|
1162 | |||
1163 | #------ Special modifier logic ----------------------------------------- |
|
1163 | #------ Special modifier logic ----------------------------------------- | |
1164 |
|
1164 | |||
1165 | elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): |
|
1165 | elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): | |
1166 | intercepted = True |
|
1166 | intercepted = True | |
1167 |
|
1167 | |||
1168 | # Special handling when tab completing in text mode. |
|
1168 | # Special handling when tab completing in text mode. | |
1169 | self._cancel_completion() |
|
1169 | self._cancel_completion() | |
1170 |
|
1170 | |||
1171 | if self._in_buffer(position): |
|
1171 | if self._in_buffer(position): | |
1172 | # Special handling when a reading a line of raw input. |
|
1172 | # Special handling when a reading a line of raw input. | |
1173 | if self._reading: |
|
1173 | if self._reading: | |
1174 | self._append_plain_text('\n') |
|
1174 | self._append_plain_text('\n') | |
1175 | self._reading = False |
|
1175 | self._reading = False | |
1176 | if self._reading_callback: |
|
1176 | if self._reading_callback: | |
1177 | self._reading_callback() |
|
1177 | self._reading_callback() | |
1178 |
|
1178 | |||
1179 | # If the input buffer is a single line or there is only |
|
1179 | # If the input buffer is a single line or there is only | |
1180 | # whitespace after the cursor, execute. Otherwise, split the |
|
1180 | # whitespace after the cursor, execute. Otherwise, split the | |
1181 | # line with a continuation prompt. |
|
1181 | # line with a continuation prompt. | |
1182 | elif not self._executing: |
|
1182 | elif not self._executing: | |
1183 | cursor.movePosition(QtGui.QTextCursor.End, |
|
1183 | cursor.movePosition(QtGui.QTextCursor.End, | |
1184 | QtGui.QTextCursor.KeepAnchor) |
|
1184 | QtGui.QTextCursor.KeepAnchor) | |
1185 | at_end = len(cursor.selectedText().strip()) == 0 |
|
1185 | at_end = len(cursor.selectedText().strip()) == 0 | |
1186 | single_line = (self._get_end_cursor().blockNumber() == |
|
1186 | single_line = (self._get_end_cursor().blockNumber() == | |
1187 | self._get_prompt_cursor().blockNumber()) |
|
1187 | self._get_prompt_cursor().blockNumber()) | |
1188 | if (at_end or shift_down or single_line) and not ctrl_down: |
|
1188 | if (at_end or shift_down or single_line) and not ctrl_down: | |
1189 | self.execute(interactive = not shift_down) |
|
1189 | self.execute(interactive = not shift_down) | |
1190 | else: |
|
1190 | else: | |
1191 | # Do this inside an edit block for clean undo/redo. |
|
1191 | # Do this inside an edit block for clean undo/redo. | |
1192 | cursor.beginEditBlock() |
|
1192 | cursor.beginEditBlock() | |
1193 | cursor.setPosition(position) |
|
1193 | cursor.setPosition(position) | |
1194 | cursor.insertText('\n') |
|
1194 | cursor.insertText('\n') | |
1195 | self._insert_continuation_prompt(cursor) |
|
1195 | self._insert_continuation_prompt(cursor) | |
1196 | cursor.endEditBlock() |
|
1196 | cursor.endEditBlock() | |
1197 |
|
1197 | |||
1198 | # Ensure that the whole input buffer is visible. |
|
1198 | # Ensure that the whole input buffer is visible. | |
1199 | # FIXME: This will not be usable if the input buffer is |
|
1199 | # FIXME: This will not be usable if the input buffer is | |
1200 | # taller than the console widget. |
|
1200 | # taller than the console widget. | |
1201 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
1201 | self._control.moveCursor(QtGui.QTextCursor.End) | |
1202 | self._control.setTextCursor(cursor) |
|
1202 | self._control.setTextCursor(cursor) | |
1203 |
|
1203 | |||
1204 | #------ Control/Cmd modifier ------------------------------------------- |
|
1204 | #------ Control/Cmd modifier ------------------------------------------- | |
1205 |
|
1205 | |||
1206 | elif ctrl_down: |
|
1206 | elif ctrl_down: | |
1207 | if key == QtCore.Qt.Key_G: |
|
1207 | if key == QtCore.Qt.Key_G: | |
1208 | self._keyboard_quit() |
|
1208 | self._keyboard_quit() | |
1209 | intercepted = True |
|
1209 | intercepted = True | |
1210 |
|
1210 | |||
1211 | elif key == QtCore.Qt.Key_K: |
|
1211 | elif key == QtCore.Qt.Key_K: | |
1212 | if self._in_buffer(position): |
|
1212 | if self._in_buffer(position): | |
1213 | cursor.clearSelection() |
|
1213 | cursor.clearSelection() | |
1214 | cursor.movePosition(QtGui.QTextCursor.EndOfLine, |
|
1214 | cursor.movePosition(QtGui.QTextCursor.EndOfLine, | |
1215 | QtGui.QTextCursor.KeepAnchor) |
|
1215 | QtGui.QTextCursor.KeepAnchor) | |
1216 | if not cursor.hasSelection(): |
|
1216 | if not cursor.hasSelection(): | |
1217 | # Line deletion (remove continuation prompt) |
|
1217 | # Line deletion (remove continuation prompt) | |
1218 | cursor.movePosition(QtGui.QTextCursor.NextBlock, |
|
1218 | cursor.movePosition(QtGui.QTextCursor.NextBlock, | |
1219 | QtGui.QTextCursor.KeepAnchor) |
|
1219 | QtGui.QTextCursor.KeepAnchor) | |
1220 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
1220 | cursor.movePosition(QtGui.QTextCursor.Right, | |
1221 | QtGui.QTextCursor.KeepAnchor, |
|
1221 | QtGui.QTextCursor.KeepAnchor, | |
1222 | len(self._continuation_prompt)) |
|
1222 | len(self._continuation_prompt)) | |
1223 | self._kill_ring.kill_cursor(cursor) |
|
1223 | self._kill_ring.kill_cursor(cursor) | |
1224 | self._set_cursor(cursor) |
|
1224 | self._set_cursor(cursor) | |
1225 | intercepted = True |
|
1225 | intercepted = True | |
1226 |
|
1226 | |||
1227 | elif key == QtCore.Qt.Key_L: |
|
1227 | elif key == QtCore.Qt.Key_L: | |
1228 | self.prompt_to_top() |
|
1228 | self.prompt_to_top() | |
1229 | intercepted = True |
|
1229 | intercepted = True | |
1230 |
|
1230 | |||
1231 | elif key == QtCore.Qt.Key_O: |
|
1231 | elif key == QtCore.Qt.Key_O: | |
1232 | if self._page_control and self._page_control.isVisible(): |
|
1232 | if self._page_control and self._page_control.isVisible(): | |
1233 | self._page_control.setFocus() |
|
1233 | self._page_control.setFocus() | |
1234 | intercepted = True |
|
1234 | intercepted = True | |
1235 |
|
1235 | |||
1236 | elif key == QtCore.Qt.Key_U: |
|
1236 | elif key == QtCore.Qt.Key_U: | |
1237 | if self._in_buffer(position): |
|
1237 | if self._in_buffer(position): | |
1238 | cursor.clearSelection() |
|
1238 | cursor.clearSelection() | |
1239 | start_line = cursor.blockNumber() |
|
1239 | start_line = cursor.blockNumber() | |
1240 | if start_line == self._get_prompt_cursor().blockNumber(): |
|
1240 | if start_line == self._get_prompt_cursor().blockNumber(): | |
1241 | offset = len(self._prompt) |
|
1241 | offset = len(self._prompt) | |
1242 | else: |
|
1242 | else: | |
1243 | offset = len(self._continuation_prompt) |
|
1243 | offset = len(self._continuation_prompt) | |
1244 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
1244 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | |
1245 | QtGui.QTextCursor.KeepAnchor) |
|
1245 | QtGui.QTextCursor.KeepAnchor) | |
1246 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
1246 | cursor.movePosition(QtGui.QTextCursor.Right, | |
1247 | QtGui.QTextCursor.KeepAnchor, offset) |
|
1247 | QtGui.QTextCursor.KeepAnchor, offset) | |
1248 | self._kill_ring.kill_cursor(cursor) |
|
1248 | self._kill_ring.kill_cursor(cursor) | |
1249 | self._set_cursor(cursor) |
|
1249 | self._set_cursor(cursor) | |
1250 | intercepted = True |
|
1250 | intercepted = True | |
1251 |
|
1251 | |||
1252 | elif key == QtCore.Qt.Key_Y: |
|
1252 | elif key == QtCore.Qt.Key_Y: | |
1253 | self._keep_cursor_in_buffer() |
|
1253 | self._keep_cursor_in_buffer() | |
1254 | self._kill_ring.yank() |
|
1254 | self._kill_ring.yank() | |
1255 | intercepted = True |
|
1255 | intercepted = True | |
1256 |
|
1256 | |||
1257 | elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete): |
|
1257 | elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete): | |
1258 | if key == QtCore.Qt.Key_Backspace: |
|
1258 | if key == QtCore.Qt.Key_Backspace: | |
1259 | cursor = self._get_word_start_cursor(position) |
|
1259 | cursor = self._get_word_start_cursor(position) | |
1260 | else: # key == QtCore.Qt.Key_Delete |
|
1260 | else: # key == QtCore.Qt.Key_Delete | |
1261 | cursor = self._get_word_end_cursor(position) |
|
1261 | cursor = self._get_word_end_cursor(position) | |
1262 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) |
|
1262 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) | |
1263 | self._kill_ring.kill_cursor(cursor) |
|
1263 | self._kill_ring.kill_cursor(cursor) | |
1264 | intercepted = True |
|
1264 | intercepted = True | |
1265 |
|
1265 | |||
1266 | elif key == QtCore.Qt.Key_D: |
|
1266 | elif key == QtCore.Qt.Key_D: | |
1267 | if len(self.input_buffer) == 0: |
|
1267 | if len(self.input_buffer) == 0: | |
1268 | self.exit_requested.emit(self) |
|
1268 | self.exit_requested.emit(self) | |
1269 | else: |
|
1269 | else: | |
1270 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, |
|
1270 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, | |
1271 | QtCore.Qt.Key_Delete, |
|
1271 | QtCore.Qt.Key_Delete, | |
1272 | QtCore.Qt.NoModifier) |
|
1272 | QtCore.Qt.NoModifier) | |
1273 | QtGui.qApp.sendEvent(self._control, new_event) |
|
1273 | QtGui.qApp.sendEvent(self._control, new_event) | |
1274 | intercepted = True |
|
1274 | intercepted = True | |
1275 |
|
1275 | |||
1276 | #------ Alt modifier --------------------------------------------------- |
|
1276 | #------ Alt modifier --------------------------------------------------- | |
1277 |
|
1277 | |||
1278 | elif alt_down: |
|
1278 | elif alt_down: | |
1279 | if key == QtCore.Qt.Key_B: |
|
1279 | if key == QtCore.Qt.Key_B: | |
1280 | self._set_cursor(self._get_word_start_cursor(position)) |
|
1280 | self._set_cursor(self._get_word_start_cursor(position)) | |
1281 | intercepted = True |
|
1281 | intercepted = True | |
1282 |
|
1282 | |||
1283 | elif key == QtCore.Qt.Key_F: |
|
1283 | elif key == QtCore.Qt.Key_F: | |
1284 | self._set_cursor(self._get_word_end_cursor(position)) |
|
1284 | self._set_cursor(self._get_word_end_cursor(position)) | |
1285 | intercepted = True |
|
1285 | intercepted = True | |
1286 |
|
1286 | |||
1287 | elif key == QtCore.Qt.Key_Y: |
|
1287 | elif key == QtCore.Qt.Key_Y: | |
1288 | self._kill_ring.rotate() |
|
1288 | self._kill_ring.rotate() | |
1289 | intercepted = True |
|
1289 | intercepted = True | |
1290 |
|
1290 | |||
1291 | elif key == QtCore.Qt.Key_Backspace: |
|
1291 | elif key == QtCore.Qt.Key_Backspace: | |
1292 | cursor = self._get_word_start_cursor(position) |
|
1292 | cursor = self._get_word_start_cursor(position) | |
1293 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) |
|
1293 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) | |
1294 | self._kill_ring.kill_cursor(cursor) |
|
1294 | self._kill_ring.kill_cursor(cursor) | |
1295 | intercepted = True |
|
1295 | intercepted = True | |
1296 |
|
1296 | |||
1297 | elif key == QtCore.Qt.Key_D: |
|
1297 | elif key == QtCore.Qt.Key_D: | |
1298 | cursor = self._get_word_end_cursor(position) |
|
1298 | cursor = self._get_word_end_cursor(position) | |
1299 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) |
|
1299 | cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor) | |
1300 | self._kill_ring.kill_cursor(cursor) |
|
1300 | self._kill_ring.kill_cursor(cursor) | |
1301 | intercepted = True |
|
1301 | intercepted = True | |
1302 |
|
1302 | |||
1303 | elif key == QtCore.Qt.Key_Delete: |
|
1303 | elif key == QtCore.Qt.Key_Delete: | |
1304 | intercepted = True |
|
1304 | intercepted = True | |
1305 |
|
1305 | |||
1306 | elif key == QtCore.Qt.Key_Greater: |
|
1306 | elif key == QtCore.Qt.Key_Greater: | |
1307 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
1307 | self._control.moveCursor(QtGui.QTextCursor.End) | |
1308 | intercepted = True |
|
1308 | intercepted = True | |
1309 |
|
1309 | |||
1310 | elif key == QtCore.Qt.Key_Less: |
|
1310 | elif key == QtCore.Qt.Key_Less: | |
1311 | self._control.setTextCursor(self._get_prompt_cursor()) |
|
1311 | self._control.setTextCursor(self._get_prompt_cursor()) | |
1312 | intercepted = True |
|
1312 | intercepted = True | |
1313 |
|
1313 | |||
1314 | #------ No modifiers --------------------------------------------------- |
|
1314 | #------ No modifiers --------------------------------------------------- | |
1315 |
|
1315 | |||
1316 | else: |
|
1316 | else: | |
1317 | if shift_down: |
|
1317 | if shift_down: | |
1318 | anchormode = QtGui.QTextCursor.KeepAnchor |
|
1318 | anchormode = QtGui.QTextCursor.KeepAnchor | |
1319 | else: |
|
1319 | else: | |
1320 | anchormode = QtGui.QTextCursor.MoveAnchor |
|
1320 | anchormode = QtGui.QTextCursor.MoveAnchor | |
1321 |
|
1321 | |||
1322 | if key == QtCore.Qt.Key_Escape: |
|
1322 | if key == QtCore.Qt.Key_Escape: | |
1323 | self._keyboard_quit() |
|
1323 | self._keyboard_quit() | |
1324 | intercepted = True |
|
1324 | intercepted = True | |
1325 |
|
1325 | |||
1326 | elif key == QtCore.Qt.Key_Up: |
|
1326 | elif key == QtCore.Qt.Key_Up: | |
1327 | if self._reading or not self._up_pressed(shift_down): |
|
1327 | if self._reading or not self._up_pressed(shift_down): | |
1328 | intercepted = True |
|
1328 | intercepted = True | |
1329 | else: |
|
1329 | else: | |
1330 | prompt_line = self._get_prompt_cursor().blockNumber() |
|
1330 | prompt_line = self._get_prompt_cursor().blockNumber() | |
1331 | intercepted = cursor.blockNumber() <= prompt_line |
|
1331 | intercepted = cursor.blockNumber() <= prompt_line | |
1332 |
|
1332 | |||
1333 | elif key == QtCore.Qt.Key_Down: |
|
1333 | elif key == QtCore.Qt.Key_Down: | |
1334 | if self._reading or not self._down_pressed(shift_down): |
|
1334 | if self._reading or not self._down_pressed(shift_down): | |
1335 | intercepted = True |
|
1335 | intercepted = True | |
1336 | else: |
|
1336 | else: | |
1337 | end_line = self._get_end_cursor().blockNumber() |
|
1337 | end_line = self._get_end_cursor().blockNumber() | |
1338 | intercepted = cursor.blockNumber() == end_line |
|
1338 | intercepted = cursor.blockNumber() == end_line | |
1339 |
|
1339 | |||
1340 | elif key == QtCore.Qt.Key_Tab: |
|
1340 | elif key == QtCore.Qt.Key_Tab: | |
1341 | if not self._reading: |
|
1341 | if not self._reading: | |
1342 | if self._tab_pressed(): |
|
1342 | if self._tab_pressed(): | |
1343 | # real tab-key, insert four spaces |
|
1343 | # real tab-key, insert four spaces | |
1344 | cursor.insertText(' '*4) |
|
1344 | cursor.insertText(' '*4) | |
1345 | intercepted = True |
|
1345 | intercepted = True | |
1346 |
|
1346 | |||
1347 | elif key == QtCore.Qt.Key_Left: |
|
1347 | elif key == QtCore.Qt.Key_Left: | |
1348 |
|
1348 | |||
1349 | # Move to the previous line |
|
1349 | # Move to the previous line | |
1350 | line, col = cursor.blockNumber(), cursor.columnNumber() |
|
1350 | line, col = cursor.blockNumber(), cursor.columnNumber() | |
1351 | if line > self._get_prompt_cursor().blockNumber() and \ |
|
1351 | if line > self._get_prompt_cursor().blockNumber() and \ | |
1352 | col == len(self._continuation_prompt): |
|
1352 | col == len(self._continuation_prompt): | |
1353 | self._control.moveCursor(QtGui.QTextCursor.PreviousBlock, |
|
1353 | self._control.moveCursor(QtGui.QTextCursor.PreviousBlock, | |
1354 | mode=anchormode) |
|
1354 | mode=anchormode) | |
1355 | self._control.moveCursor(QtGui.QTextCursor.EndOfBlock, |
|
1355 | self._control.moveCursor(QtGui.QTextCursor.EndOfBlock, | |
1356 | mode=anchormode) |
|
1356 | mode=anchormode) | |
1357 | intercepted = True |
|
1357 | intercepted = True | |
1358 |
|
1358 | |||
1359 | # Regular left movement |
|
1359 | # Regular left movement | |
1360 | else: |
|
1360 | else: | |
1361 | intercepted = not self._in_buffer(position - 1) |
|
1361 | intercepted = not self._in_buffer(position - 1) | |
1362 |
|
1362 | |||
1363 | elif key == QtCore.Qt.Key_Right: |
|
1363 | elif key == QtCore.Qt.Key_Right: | |
1364 | original_block_number = cursor.blockNumber() |
|
1364 | original_block_number = cursor.blockNumber() | |
1365 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
1365 | cursor.movePosition(QtGui.QTextCursor.Right, | |
1366 | mode=anchormode) |
|
1366 | mode=anchormode) | |
1367 | if cursor.blockNumber() != original_block_number: |
|
1367 | if cursor.blockNumber() != original_block_number: | |
1368 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
1368 | cursor.movePosition(QtGui.QTextCursor.Right, | |
1369 | n=len(self._continuation_prompt), |
|
1369 | n=len(self._continuation_prompt), | |
1370 | mode=anchormode) |
|
1370 | mode=anchormode) | |
1371 | self._set_cursor(cursor) |
|
1371 | self._set_cursor(cursor) | |
1372 | intercepted = True |
|
1372 | intercepted = True | |
1373 |
|
1373 | |||
1374 | elif key == QtCore.Qt.Key_Home: |
|
1374 | elif key == QtCore.Qt.Key_Home: | |
1375 | start_line = cursor.blockNumber() |
|
1375 | start_line = cursor.blockNumber() | |
1376 | if start_line == self._get_prompt_cursor().blockNumber(): |
|
1376 | if start_line == self._get_prompt_cursor().blockNumber(): | |
1377 | start_pos = self._prompt_pos |
|
1377 | start_pos = self._prompt_pos | |
1378 | else: |
|
1378 | else: | |
1379 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
1379 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | |
1380 | QtGui.QTextCursor.KeepAnchor) |
|
1380 | QtGui.QTextCursor.KeepAnchor) | |
1381 | start_pos = cursor.position() |
|
1381 | start_pos = cursor.position() | |
1382 | start_pos += len(self._continuation_prompt) |
|
1382 | start_pos += len(self._continuation_prompt) | |
1383 | cursor.setPosition(position) |
|
1383 | cursor.setPosition(position) | |
1384 | if shift_down and self._in_buffer(position): |
|
1384 | if shift_down and self._in_buffer(position): | |
1385 | cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor) |
|
1385 | cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor) | |
1386 | else: |
|
1386 | else: | |
1387 | cursor.setPosition(start_pos) |
|
1387 | cursor.setPosition(start_pos) | |
1388 | self._set_cursor(cursor) |
|
1388 | self._set_cursor(cursor) | |
1389 | intercepted = True |
|
1389 | intercepted = True | |
1390 |
|
1390 | |||
1391 | elif key == QtCore.Qt.Key_Backspace: |
|
1391 | elif key == QtCore.Qt.Key_Backspace: | |
1392 |
|
1392 | |||
1393 | # Line deletion (remove continuation prompt) |
|
1393 | # Line deletion (remove continuation prompt) | |
1394 | line, col = cursor.blockNumber(), cursor.columnNumber() |
|
1394 | line, col = cursor.blockNumber(), cursor.columnNumber() | |
1395 | if not self._reading and \ |
|
1395 | if not self._reading and \ | |
1396 | col == len(self._continuation_prompt) and \ |
|
1396 | col == len(self._continuation_prompt) and \ | |
1397 | line > self._get_prompt_cursor().blockNumber(): |
|
1397 | line > self._get_prompt_cursor().blockNumber(): | |
1398 | cursor.beginEditBlock() |
|
1398 | cursor.beginEditBlock() | |
1399 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, |
|
1399 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock, | |
1400 | QtGui.QTextCursor.KeepAnchor) |
|
1400 | QtGui.QTextCursor.KeepAnchor) | |
1401 | cursor.removeSelectedText() |
|
1401 | cursor.removeSelectedText() | |
1402 | cursor.deletePreviousChar() |
|
1402 | cursor.deletePreviousChar() | |
1403 | cursor.endEditBlock() |
|
1403 | cursor.endEditBlock() | |
1404 | intercepted = True |
|
1404 | intercepted = True | |
1405 |
|
1405 | |||
1406 | # Regular backwards deletion |
|
1406 | # Regular backwards deletion | |
1407 | else: |
|
1407 | else: | |
1408 | anchor = cursor.anchor() |
|
1408 | anchor = cursor.anchor() | |
1409 | if anchor == position: |
|
1409 | if anchor == position: | |
1410 | intercepted = not self._in_buffer(position - 1) |
|
1410 | intercepted = not self._in_buffer(position - 1) | |
1411 | else: |
|
1411 | else: | |
1412 | intercepted = not self._in_buffer(min(anchor, position)) |
|
1412 | intercepted = not self._in_buffer(min(anchor, position)) | |
1413 |
|
1413 | |||
1414 | elif key == QtCore.Qt.Key_Delete: |
|
1414 | elif key == QtCore.Qt.Key_Delete: | |
1415 |
|
1415 | |||
1416 | # Line deletion (remove continuation prompt) |
|
1416 | # Line deletion (remove continuation prompt) | |
1417 | if not self._reading and self._in_buffer(position) and \ |
|
1417 | if not self._reading and self._in_buffer(position) and \ | |
1418 | cursor.atBlockEnd() and not cursor.hasSelection(): |
|
1418 | cursor.atBlockEnd() and not cursor.hasSelection(): | |
1419 | cursor.movePosition(QtGui.QTextCursor.NextBlock, |
|
1419 | cursor.movePosition(QtGui.QTextCursor.NextBlock, | |
1420 | QtGui.QTextCursor.KeepAnchor) |
|
1420 | QtGui.QTextCursor.KeepAnchor) | |
1421 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
1421 | cursor.movePosition(QtGui.QTextCursor.Right, | |
1422 | QtGui.QTextCursor.KeepAnchor, |
|
1422 | QtGui.QTextCursor.KeepAnchor, | |
1423 | len(self._continuation_prompt)) |
|
1423 | len(self._continuation_prompt)) | |
1424 | cursor.removeSelectedText() |
|
1424 | cursor.removeSelectedText() | |
1425 | intercepted = True |
|
1425 | intercepted = True | |
1426 |
|
1426 | |||
1427 | # Regular forwards deletion: |
|
1427 | # Regular forwards deletion: | |
1428 | else: |
|
1428 | else: | |
1429 | anchor = cursor.anchor() |
|
1429 | anchor = cursor.anchor() | |
1430 | intercepted = (not self._in_buffer(anchor) or |
|
1430 | intercepted = (not self._in_buffer(anchor) or | |
1431 | not self._in_buffer(position)) |
|
1431 | not self._in_buffer(position)) | |
1432 |
|
1432 | |||
1433 | # Don't move the cursor if Control/Cmd is pressed to allow copy-paste |
|
1433 | # Don't move the cursor if Control/Cmd is pressed to allow copy-paste | |
1434 | # using the keyboard in any part of the buffer. Also, permit scrolling |
|
1434 | # using the keyboard in any part of the buffer. Also, permit scrolling | |
1435 | # with Page Up/Down keys. Finally, if we're executing, don't move the |
|
1435 | # with Page Up/Down keys. Finally, if we're executing, don't move the | |
1436 | # cursor (if even this made sense, we can't guarantee that the prompt |
|
1436 | # cursor (if even this made sense, we can't guarantee that the prompt | |
1437 | # position is still valid due to text truncation). |
|
1437 | # position is still valid due to text truncation). | |
1438 | if not (self._control_key_down(event.modifiers(), include_command=True) |
|
1438 | if not (self._control_key_down(event.modifiers(), include_command=True) | |
1439 | or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown) |
|
1439 | or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown) | |
1440 | or (self._executing and not self._reading)): |
|
1440 | or (self._executing and not self._reading)): | |
1441 | self._keep_cursor_in_buffer() |
|
1441 | self._keep_cursor_in_buffer() | |
1442 |
|
1442 | |||
1443 | return intercepted |
|
1443 | return intercepted | |
1444 |
|
1444 | |||
1445 | def _event_filter_page_keypress(self, event): |
|
1445 | def _event_filter_page_keypress(self, event): | |
1446 | """ Filter key events for the paging widget to create console-like |
|
1446 | """ Filter key events for the paging widget to create console-like | |
1447 | interface. |
|
1447 | interface. | |
1448 | """ |
|
1448 | """ | |
1449 | key = event.key() |
|
1449 | key = event.key() | |
1450 | ctrl_down = self._control_key_down(event.modifiers()) |
|
1450 | ctrl_down = self._control_key_down(event.modifiers()) | |
1451 | alt_down = event.modifiers() & QtCore.Qt.AltModifier |
|
1451 | alt_down = event.modifiers() & QtCore.Qt.AltModifier | |
1452 |
|
1452 | |||
1453 | if ctrl_down: |
|
1453 | if ctrl_down: | |
1454 | if key == QtCore.Qt.Key_O: |
|
1454 | if key == QtCore.Qt.Key_O: | |
1455 | self._control.setFocus() |
|
1455 | self._control.setFocus() | |
1456 | intercept = True |
|
1456 | intercept = True | |
1457 |
|
1457 | |||
1458 | elif alt_down: |
|
1458 | elif alt_down: | |
1459 | if key == QtCore.Qt.Key_Greater: |
|
1459 | if key == QtCore.Qt.Key_Greater: | |
1460 | self._page_control.moveCursor(QtGui.QTextCursor.End) |
|
1460 | self._page_control.moveCursor(QtGui.QTextCursor.End) | |
1461 | intercepted = True |
|
1461 | intercepted = True | |
1462 |
|
1462 | |||
1463 | elif key == QtCore.Qt.Key_Less: |
|
1463 | elif key == QtCore.Qt.Key_Less: | |
1464 | self._page_control.moveCursor(QtGui.QTextCursor.Start) |
|
1464 | self._page_control.moveCursor(QtGui.QTextCursor.Start) | |
1465 | intercepted = True |
|
1465 | intercepted = True | |
1466 |
|
1466 | |||
1467 | elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape): |
|
1467 | elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape): | |
1468 | if self._splitter: |
|
1468 | if self._splitter: | |
1469 | self._page_control.hide() |
|
1469 | self._page_control.hide() | |
1470 | self._control.setFocus() |
|
1470 | self._control.setFocus() | |
1471 | else: |
|
1471 | else: | |
1472 | self.layout().setCurrentWidget(self._control) |
|
1472 | self.layout().setCurrentWidget(self._control) | |
1473 | return True |
|
1473 | return True | |
1474 |
|
1474 | |||
1475 | elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, |
|
1475 | elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return, | |
1476 | QtCore.Qt.Key_Tab): |
|
1476 | QtCore.Qt.Key_Tab): | |
1477 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, |
|
1477 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, | |
1478 | QtCore.Qt.Key_PageDown, |
|
1478 | QtCore.Qt.Key_PageDown, | |
1479 | QtCore.Qt.NoModifier) |
|
1479 | QtCore.Qt.NoModifier) | |
1480 | QtGui.qApp.sendEvent(self._page_control, new_event) |
|
1480 | QtGui.qApp.sendEvent(self._page_control, new_event) | |
1481 | return True |
|
1481 | return True | |
1482 |
|
1482 | |||
1483 | elif key == QtCore.Qt.Key_Backspace: |
|
1483 | elif key == QtCore.Qt.Key_Backspace: | |
1484 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, |
|
1484 | new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, | |
1485 | QtCore.Qt.Key_PageUp, |
|
1485 | QtCore.Qt.Key_PageUp, | |
1486 | QtCore.Qt.NoModifier) |
|
1486 | QtCore.Qt.NoModifier) | |
1487 | QtGui.qApp.sendEvent(self._page_control, new_event) |
|
1487 | QtGui.qApp.sendEvent(self._page_control, new_event) | |
1488 | return True |
|
1488 | return True | |
1489 |
|
1489 | |||
1490 | return False |
|
1490 | return False | |
1491 |
|
1491 | |||
1492 | def _flush_pending_stream(self): |
|
1492 | def _flush_pending_stream(self): | |
1493 | """ Flush out pending text into the widget. """ |
|
1493 | """ Flush out pending text into the widget. """ | |
1494 | text = self._pending_insert_text |
|
1494 | text = self._pending_insert_text | |
1495 | self._pending_insert_text = [] |
|
1495 | self._pending_insert_text = [] | |
1496 | buffer_size = self._control.document().maximumBlockCount() |
|
1496 | buffer_size = self._control.document().maximumBlockCount() | |
1497 | if buffer_size > 0: |
|
1497 | if buffer_size > 0: | |
1498 | text = self._get_last_lines_from_list(text, buffer_size) |
|
1498 | text = self._get_last_lines_from_list(text, buffer_size) | |
1499 | text = ''.join(text) |
|
1499 | text = ''.join(text) | |
1500 | t = time.time() |
|
1500 | t = time.time() | |
1501 | self._insert_plain_text(self._get_end_cursor(), text, flush=True) |
|
1501 | self._insert_plain_text(self._get_end_cursor(), text, flush=True) | |
1502 | # Set the flush interval to equal the maximum time to update text. |
|
1502 | # Set the flush interval to equal the maximum time to update text. | |
1503 | self._pending_text_flush_interval.setInterval(max(100, |
|
1503 | self._pending_text_flush_interval.setInterval(max(100, | |
1504 | (time.time()-t)*1000)) |
|
1504 | (time.time()-t)*1000)) | |
1505 |
|
1505 | |||
1506 | def _format_as_columns(self, items, separator=' '): |
|
1506 | def _format_as_columns(self, items, separator=' '): | |
1507 | """ Transform a list of strings into a single string with columns. |
|
1507 | """ Transform a list of strings into a single string with columns. | |
1508 |
|
1508 | |||
1509 | Parameters |
|
1509 | Parameters | |
1510 | ---------- |
|
1510 | ---------- | |
1511 | items : sequence of strings |
|
1511 | items : sequence of strings | |
1512 | The strings to process. |
|
1512 | The strings to process. | |
1513 |
|
1513 | |||
1514 | separator : str, optional [default is two spaces] |
|
1514 | separator : str, optional [default is two spaces] | |
1515 | The string that separates columns. |
|
1515 | The string that separates columns. | |
1516 |
|
1516 | |||
1517 | Returns |
|
1517 | Returns | |
1518 | ------- |
|
1518 | ------- | |
1519 | The formatted string. |
|
1519 | The formatted string. | |
1520 | """ |
|
1520 | """ | |
1521 | # Calculate the number of characters available. |
|
1521 | # Calculate the number of characters available. | |
1522 | width = self._control.viewport().width() |
|
1522 | width = self._control.viewport().width() | |
1523 | char_width = QtGui.QFontMetrics(self.font).width(' ') |
|
1523 | char_width = QtGui.QFontMetrics(self.font).width(' ') | |
1524 | displaywidth = max(10, (width / char_width) - 1) |
|
1524 | displaywidth = max(10, (width / char_width) - 1) | |
1525 |
|
1525 | |||
1526 | return columnize(items, separator, displaywidth) |
|
1526 | return columnize(items, separator, displaywidth) | |
1527 |
|
1527 | |||
1528 | def _get_block_plain_text(self, block): |
|
1528 | def _get_block_plain_text(self, block): | |
1529 | """ Given a QTextBlock, return its unformatted text. |
|
1529 | """ Given a QTextBlock, return its unformatted text. | |
1530 | """ |
|
1530 | """ | |
1531 | cursor = QtGui.QTextCursor(block) |
|
1531 | cursor = QtGui.QTextCursor(block) | |
1532 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock) |
|
1532 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock) | |
1533 | cursor.movePosition(QtGui.QTextCursor.EndOfBlock, |
|
1533 | cursor.movePosition(QtGui.QTextCursor.EndOfBlock, | |
1534 | QtGui.QTextCursor.KeepAnchor) |
|
1534 | QtGui.QTextCursor.KeepAnchor) | |
1535 | return cursor.selection().toPlainText() |
|
1535 | return cursor.selection().toPlainText() | |
1536 |
|
1536 | |||
1537 | def _get_cursor(self): |
|
1537 | def _get_cursor(self): | |
1538 | """ Convenience method that returns a cursor for the current position. |
|
1538 | """ Convenience method that returns a cursor for the current position. | |
1539 | """ |
|
1539 | """ | |
1540 | return self._control.textCursor() |
|
1540 | return self._control.textCursor() | |
1541 |
|
1541 | |||
1542 | def _get_end_cursor(self): |
|
1542 | def _get_end_cursor(self): | |
1543 | """ Convenience method that returns a cursor for the last character. |
|
1543 | """ Convenience method that returns a cursor for the last character. | |
1544 | """ |
|
1544 | """ | |
1545 | cursor = self._control.textCursor() |
|
1545 | cursor = self._control.textCursor() | |
1546 | cursor.movePosition(QtGui.QTextCursor.End) |
|
1546 | cursor.movePosition(QtGui.QTextCursor.End) | |
1547 | return cursor |
|
1547 | return cursor | |
1548 |
|
1548 | |||
1549 | def _get_input_buffer_cursor_column(self): |
|
1549 | def _get_input_buffer_cursor_column(self): | |
1550 | """ Returns the column of the cursor in the input buffer, excluding the |
|
1550 | """ Returns the column of the cursor in the input buffer, excluding the | |
1551 | contribution by the prompt, or -1 if there is no such column. |
|
1551 | contribution by the prompt, or -1 if there is no such column. | |
1552 | """ |
|
1552 | """ | |
1553 | prompt = self._get_input_buffer_cursor_prompt() |
|
1553 | prompt = self._get_input_buffer_cursor_prompt() | |
1554 | if prompt is None: |
|
1554 | if prompt is None: | |
1555 | return -1 |
|
1555 | return -1 | |
1556 | else: |
|
1556 | else: | |
1557 | cursor = self._control.textCursor() |
|
1557 | cursor = self._control.textCursor() | |
1558 | return cursor.columnNumber() - len(prompt) |
|
1558 | return cursor.columnNumber() - len(prompt) | |
1559 |
|
1559 | |||
1560 | def _get_input_buffer_cursor_line(self): |
|
1560 | def _get_input_buffer_cursor_line(self): | |
1561 | """ Returns the text of the line of the input buffer that contains the |
|
1561 | """ Returns the text of the line of the input buffer that contains the | |
1562 | cursor, or None if there is no such line. |
|
1562 | cursor, or None if there is no such line. | |
1563 | """ |
|
1563 | """ | |
1564 | prompt = self._get_input_buffer_cursor_prompt() |
|
1564 | prompt = self._get_input_buffer_cursor_prompt() | |
1565 | if prompt is None: |
|
1565 | if prompt is None: | |
1566 | return None |
|
1566 | return None | |
1567 | else: |
|
1567 | else: | |
1568 | cursor = self._control.textCursor() |
|
1568 | cursor = self._control.textCursor() | |
1569 | text = self._get_block_plain_text(cursor.block()) |
|
1569 | text = self._get_block_plain_text(cursor.block()) | |
1570 | return text[len(prompt):] |
|
1570 | return text[len(prompt):] | |
1571 |
|
1571 | |||
1572 | def _get_input_buffer_cursor_prompt(self): |
|
1572 | def _get_input_buffer_cursor_prompt(self): | |
1573 | """ Returns the (plain text) prompt for line of the input buffer that |
|
1573 | """ Returns the (plain text) prompt for line of the input buffer that | |
1574 | contains the cursor, or None if there is no such line. |
|
1574 | contains the cursor, or None if there is no such line. | |
1575 | """ |
|
1575 | """ | |
1576 | if self._executing: |
|
1576 | if self._executing: | |
1577 | return None |
|
1577 | return None | |
1578 | cursor = self._control.textCursor() |
|
1578 | cursor = self._control.textCursor() | |
1579 | if cursor.position() >= self._prompt_pos: |
|
1579 | if cursor.position() >= self._prompt_pos: | |
1580 | if cursor.blockNumber() == self._get_prompt_cursor().blockNumber(): |
|
1580 | if cursor.blockNumber() == self._get_prompt_cursor().blockNumber(): | |
1581 | return self._prompt |
|
1581 | return self._prompt | |
1582 | else: |
|
1582 | else: | |
1583 | return self._continuation_prompt |
|
1583 | return self._continuation_prompt | |
1584 | else: |
|
1584 | else: | |
1585 | return None |
|
1585 | return None | |
1586 |
|
1586 | |||
1587 | def _get_last_lines(self, text, num_lines, return_count=False): |
|
1587 | def _get_last_lines(self, text, num_lines, return_count=False): | |
1588 | """ Return last specified number of lines of text (like `tail -n`). |
|
1588 | """ Return last specified number of lines of text (like `tail -n`). | |
1589 | If return_count is True, returns a tuple of clipped text and the |
|
1589 | If return_count is True, returns a tuple of clipped text and the | |
1590 | number of lines in the clipped text. |
|
1590 | number of lines in the clipped text. | |
1591 | """ |
|
1591 | """ | |
1592 | pos = len(text) |
|
1592 | pos = len(text) | |
1593 | if pos < num_lines: |
|
1593 | if pos < num_lines: | |
1594 | if return_count: |
|
1594 | if return_count: | |
1595 | return text, text.count('\n') if return_count else text |
|
1595 | return text, text.count('\n') if return_count else text | |
1596 | else: |
|
1596 | else: | |
1597 | return text |
|
1597 | return text | |
1598 | i = 0 |
|
1598 | i = 0 | |
1599 | while i < num_lines: |
|
1599 | while i < num_lines: | |
1600 | pos = text.rfind('\n', None, pos) |
|
1600 | pos = text.rfind('\n', None, pos) | |
1601 | if pos == -1: |
|
1601 | if pos == -1: | |
1602 | pos = None |
|
1602 | pos = None | |
1603 | break |
|
1603 | break | |
1604 | i += 1 |
|
1604 | i += 1 | |
1605 | if return_count: |
|
1605 | if return_count: | |
1606 | return text[pos:], i |
|
1606 | return text[pos:], i | |
1607 | else: |
|
1607 | else: | |
1608 | return text[pos:] |
|
1608 | return text[pos:] | |
1609 |
|
1609 | |||
1610 | def _get_last_lines_from_list(self, text_list, num_lines): |
|
1610 | def _get_last_lines_from_list(self, text_list, num_lines): | |
1611 | """ Return the list of text clipped to last specified lines. |
|
1611 | """ Return the list of text clipped to last specified lines. | |
1612 | """ |
|
1612 | """ | |
1613 | ret = [] |
|
1613 | ret = [] | |
1614 | lines_pending = num_lines |
|
1614 | lines_pending = num_lines | |
1615 | for text in reversed(text_list): |
|
1615 | for text in reversed(text_list): | |
1616 | text, lines_added = self._get_last_lines(text, lines_pending, |
|
1616 | text, lines_added = self._get_last_lines(text, lines_pending, | |
1617 | return_count=True) |
|
1617 | return_count=True) | |
1618 | ret.append(text) |
|
1618 | ret.append(text) | |
1619 | lines_pending -= lines_added |
|
1619 | lines_pending -= lines_added | |
1620 | if lines_pending <= 0: |
|
1620 | if lines_pending <= 0: | |
1621 | break |
|
1621 | break | |
1622 | return ret[::-1] |
|
1622 | return ret[::-1] | |
1623 |
|
1623 | |||
1624 | def _get_prompt_cursor(self): |
|
1624 | def _get_prompt_cursor(self): | |
1625 | """ Convenience method that returns a cursor for the prompt position. |
|
1625 | """ Convenience method that returns a cursor for the prompt position. | |
1626 | """ |
|
1626 | """ | |
1627 | cursor = self._control.textCursor() |
|
1627 | cursor = self._control.textCursor() | |
1628 | cursor.setPosition(self._prompt_pos) |
|
1628 | cursor.setPosition(self._prompt_pos) | |
1629 | return cursor |
|
1629 | return cursor | |
1630 |
|
1630 | |||
1631 | def _get_selection_cursor(self, start, end): |
|
1631 | def _get_selection_cursor(self, start, end): | |
1632 | """ Convenience method that returns a cursor with text selected between |
|
1632 | """ Convenience method that returns a cursor with text selected between | |
1633 | the positions 'start' and 'end'. |
|
1633 | the positions 'start' and 'end'. | |
1634 | """ |
|
1634 | """ | |
1635 | cursor = self._control.textCursor() |
|
1635 | cursor = self._control.textCursor() | |
1636 | cursor.setPosition(start) |
|
1636 | cursor.setPosition(start) | |
1637 | cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor) |
|
1637 | cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor) | |
1638 | return cursor |
|
1638 | return cursor | |
1639 |
|
1639 | |||
1640 | def _get_word_start_cursor(self, position): |
|
1640 | def _get_word_start_cursor(self, position): | |
1641 | """ Find the start of the word to the left the given position. If a |
|
1641 | """ Find the start of the word to the left the given position. If a | |
1642 | sequence of non-word characters precedes the first word, skip over |
|
1642 | sequence of non-word characters precedes the first word, skip over | |
1643 | them. (This emulates the behavior of bash, emacs, etc.) |
|
1643 | them. (This emulates the behavior of bash, emacs, etc.) | |
1644 | """ |
|
1644 | """ | |
1645 | document = self._control.document() |
|
1645 | document = self._control.document() | |
1646 | position -= 1 |
|
1646 | position -= 1 | |
1647 | while position >= self._prompt_pos and \ |
|
1647 | while position >= self._prompt_pos and \ | |
1648 | not is_letter_or_number(document.characterAt(position)): |
|
1648 | not is_letter_or_number(document.characterAt(position)): | |
1649 | position -= 1 |
|
1649 | position -= 1 | |
1650 | while position >= self._prompt_pos and \ |
|
1650 | while position >= self._prompt_pos and \ | |
1651 | is_letter_or_number(document.characterAt(position)): |
|
1651 | is_letter_or_number(document.characterAt(position)): | |
1652 | position -= 1 |
|
1652 | position -= 1 | |
1653 | cursor = self._control.textCursor() |
|
1653 | cursor = self._control.textCursor() | |
1654 | cursor.setPosition(position + 1) |
|
1654 | cursor.setPosition(position + 1) | |
1655 | return cursor |
|
1655 | return cursor | |
1656 |
|
1656 | |||
1657 | def _get_word_end_cursor(self, position): |
|
1657 | def _get_word_end_cursor(self, position): | |
1658 | """ Find the end of the word to the right the given position. If a |
|
1658 | """ Find the end of the word to the right the given position. If a | |
1659 | sequence of non-word characters precedes the first word, skip over |
|
1659 | sequence of non-word characters precedes the first word, skip over | |
1660 | them. (This emulates the behavior of bash, emacs, etc.) |
|
1660 | them. (This emulates the behavior of bash, emacs, etc.) | |
1661 | """ |
|
1661 | """ | |
1662 | document = self._control.document() |
|
1662 | document = self._control.document() | |
1663 | end = self._get_end_cursor().position() |
|
1663 | end = self._get_end_cursor().position() | |
1664 | while position < end and \ |
|
1664 | while position < end and \ | |
1665 | not is_letter_or_number(document.characterAt(position)): |
|
1665 | not is_letter_or_number(document.characterAt(position)): | |
1666 | position += 1 |
|
1666 | position += 1 | |
1667 | while position < end and \ |
|
1667 | while position < end and \ | |
1668 | is_letter_or_number(document.characterAt(position)): |
|
1668 | is_letter_or_number(document.characterAt(position)): | |
1669 | position += 1 |
|
1669 | position += 1 | |
1670 | cursor = self._control.textCursor() |
|
1670 | cursor = self._control.textCursor() | |
1671 | cursor.setPosition(position) |
|
1671 | cursor.setPosition(position) | |
1672 | return cursor |
|
1672 | return cursor | |
1673 |
|
1673 | |||
1674 | def _insert_continuation_prompt(self, cursor): |
|
1674 | def _insert_continuation_prompt(self, cursor): | |
1675 | """ Inserts new continuation prompt using the specified cursor. |
|
1675 | """ Inserts new continuation prompt using the specified cursor. | |
1676 | """ |
|
1676 | """ | |
1677 | if self._continuation_prompt_html is None: |
|
1677 | if self._continuation_prompt_html is None: | |
1678 | self._insert_plain_text(cursor, self._continuation_prompt) |
|
1678 | self._insert_plain_text(cursor, self._continuation_prompt) | |
1679 | else: |
|
1679 | else: | |
1680 | self._continuation_prompt = self._insert_html_fetching_plain_text( |
|
1680 | self._continuation_prompt = self._insert_html_fetching_plain_text( | |
1681 | cursor, self._continuation_prompt_html) |
|
1681 | cursor, self._continuation_prompt_html) | |
1682 |
|
1682 | |||
1683 | def _insert_block(self, cursor, block_format=None): |
|
1683 | def _insert_block(self, cursor, block_format=None): | |
1684 | """ Inserts an empty QTextBlock using the specified cursor. |
|
1684 | """ Inserts an empty QTextBlock using the specified cursor. | |
1685 | """ |
|
1685 | """ | |
1686 | if block_format is None: |
|
1686 | if block_format is None: | |
1687 | block_format = QtGui.QTextBlockFormat() |
|
1687 | block_format = QtGui.QTextBlockFormat() | |
1688 | cursor.insertBlock(block_format) |
|
1688 | cursor.insertBlock(block_format) | |
1689 |
|
1689 | |||
1690 | def _insert_html(self, cursor, html): |
|
1690 | def _insert_html(self, cursor, html): | |
1691 | """ Inserts HTML using the specified cursor in such a way that future |
|
1691 | """ Inserts HTML using the specified cursor in such a way that future | |
1692 | formatting is unaffected. |
|
1692 | formatting is unaffected. | |
1693 | """ |
|
1693 | """ | |
1694 | cursor.beginEditBlock() |
|
1694 | cursor.beginEditBlock() | |
1695 | cursor.insertHtml(html) |
|
1695 | cursor.insertHtml(html) | |
1696 |
|
1696 | |||
1697 | # After inserting HTML, the text document "remembers" it's in "html |
|
1697 | # After inserting HTML, the text document "remembers" it's in "html | |
1698 | # mode", which means that subsequent calls adding plain text will result |
|
1698 | # mode", which means that subsequent calls adding plain text will result | |
1699 | # in unwanted formatting, lost tab characters, etc. The following code |
|
1699 | # in unwanted formatting, lost tab characters, etc. The following code | |
1700 | # hacks around this behavior, which I consider to be a bug in Qt, by |
|
1700 | # hacks around this behavior, which I consider to be a bug in Qt, by | |
1701 | # (crudely) resetting the document's style state. |
|
1701 | # (crudely) resetting the document's style state. | |
1702 | cursor.movePosition(QtGui.QTextCursor.Left, |
|
1702 | cursor.movePosition(QtGui.QTextCursor.Left, | |
1703 | QtGui.QTextCursor.KeepAnchor) |
|
1703 | QtGui.QTextCursor.KeepAnchor) | |
1704 | if cursor.selection().toPlainText() == ' ': |
|
1704 | if cursor.selection().toPlainText() == ' ': | |
1705 | cursor.removeSelectedText() |
|
1705 | cursor.removeSelectedText() | |
1706 | else: |
|
1706 | else: | |
1707 | cursor.movePosition(QtGui.QTextCursor.Right) |
|
1707 | cursor.movePosition(QtGui.QTextCursor.Right) | |
1708 | cursor.insertText(' ', QtGui.QTextCharFormat()) |
|
1708 | cursor.insertText(' ', QtGui.QTextCharFormat()) | |
1709 | cursor.endEditBlock() |
|
1709 | cursor.endEditBlock() | |
1710 |
|
1710 | |||
1711 | def _insert_html_fetching_plain_text(self, cursor, html): |
|
1711 | def _insert_html_fetching_plain_text(self, cursor, html): | |
1712 | """ Inserts HTML using the specified cursor, then returns its plain text |
|
1712 | """ Inserts HTML using the specified cursor, then returns its plain text | |
1713 | version. |
|
1713 | version. | |
1714 | """ |
|
1714 | """ | |
1715 | cursor.beginEditBlock() |
|
1715 | cursor.beginEditBlock() | |
1716 | cursor.removeSelectedText() |
|
1716 | cursor.removeSelectedText() | |
1717 |
|
1717 | |||
1718 | start = cursor.position() |
|
1718 | start = cursor.position() | |
1719 | self._insert_html(cursor, html) |
|
1719 | self._insert_html(cursor, html) | |
1720 | end = cursor.position() |
|
1720 | end = cursor.position() | |
1721 | cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor) |
|
1721 | cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor) | |
1722 | text = cursor.selection().toPlainText() |
|
1722 | text = cursor.selection().toPlainText() | |
1723 |
|
1723 | |||
1724 | cursor.setPosition(end) |
|
1724 | cursor.setPosition(end) | |
1725 | cursor.endEditBlock() |
|
1725 | cursor.endEditBlock() | |
1726 | return text |
|
1726 | return text | |
1727 |
|
1727 | |||
1728 | def _insert_plain_text(self, cursor, text, flush=False): |
|
1728 | def _insert_plain_text(self, cursor, text, flush=False): | |
1729 | """ Inserts plain text using the specified cursor, processing ANSI codes |
|
1729 | """ Inserts plain text using the specified cursor, processing ANSI codes | |
1730 | if enabled. |
|
1730 | if enabled. | |
1731 | """ |
|
1731 | """ | |
1732 | # maximumBlockCount() can be different from self.buffer_size in |
|
1732 | # maximumBlockCount() can be different from self.buffer_size in | |
1733 | # case input prompt is active. |
|
1733 | # case input prompt is active. | |
1734 | buffer_size = self._control.document().maximumBlockCount() |
|
1734 | buffer_size = self._control.document().maximumBlockCount() | |
1735 |
|
1735 | |||
1736 | if self._executing and not flush and \ |
|
1736 | if self._executing and not flush and \ | |
1737 | self._pending_text_flush_interval.isActive(): |
|
1737 | self._pending_text_flush_interval.isActive(): | |
1738 | self._pending_insert_text.append(text) |
|
1738 | self._pending_insert_text.append(text) | |
1739 | if buffer_size > 0: |
|
1739 | if buffer_size > 0: | |
1740 | self._pending_insert_text = self._get_last_lines_from_list( |
|
1740 | self._pending_insert_text = self._get_last_lines_from_list( | |
1741 | self._pending_insert_text, buffer_size) |
|
1741 | self._pending_insert_text, buffer_size) | |
1742 | return |
|
1742 | return | |
1743 |
|
1743 | |||
1744 | if self._executing and not self._pending_text_flush_interval.isActive(): |
|
1744 | if self._executing and not self._pending_text_flush_interval.isActive(): | |
1745 | self._pending_text_flush_interval.start() |
|
1745 | self._pending_text_flush_interval.start() | |
1746 |
|
1746 | |||
1747 | # Clip the text to last `buffer_size` lines. |
|
1747 | # Clip the text to last `buffer_size` lines. | |
1748 | if buffer_size > 0: |
|
1748 | if buffer_size > 0: | |
1749 | text = self._get_last_lines(text, buffer_size) |
|
1749 | text = self._get_last_lines(text, buffer_size) | |
1750 |
|
1750 | |||
1751 | cursor.beginEditBlock() |
|
1751 | cursor.beginEditBlock() | |
1752 | if self.ansi_codes: |
|
1752 | if self.ansi_codes: | |
1753 | for substring in self._ansi_processor.split_string(text): |
|
1753 | for substring in self._ansi_processor.split_string(text): | |
1754 | for act in self._ansi_processor.actions: |
|
1754 | for act in self._ansi_processor.actions: | |
1755 |
|
1755 | |||
1756 | # Unlike real terminal emulators, we don't distinguish |
|
1756 | # Unlike real terminal emulators, we don't distinguish | |
1757 | # between the screen and the scrollback buffer. A screen |
|
1757 | # between the screen and the scrollback buffer. A screen | |
1758 | # erase request clears everything. |
|
1758 | # erase request clears everything. | |
1759 | if act.action == 'erase' and act.area == 'screen': |
|
1759 | if act.action == 'erase' and act.area == 'screen': | |
1760 | cursor.select(QtGui.QTextCursor.Document) |
|
1760 | cursor.select(QtGui.QTextCursor.Document) | |
1761 | cursor.removeSelectedText() |
|
1761 | cursor.removeSelectedText() | |
1762 |
|
1762 | |||
1763 | # Simulate a form feed by scrolling just past the last line. |
|
1763 | # Simulate a form feed by scrolling just past the last line. | |
1764 | elif act.action == 'scroll' and act.unit == 'page': |
|
1764 | elif act.action == 'scroll' and act.unit == 'page': | |
1765 | cursor.insertText('\n') |
|
1765 | cursor.insertText('\n') | |
1766 | cursor.endEditBlock() |
|
1766 | cursor.endEditBlock() | |
1767 | self._set_top_cursor(cursor) |
|
1767 | self._set_top_cursor(cursor) | |
1768 | cursor.joinPreviousEditBlock() |
|
1768 | cursor.joinPreviousEditBlock() | |
1769 | cursor.deletePreviousChar() |
|
1769 | cursor.deletePreviousChar() | |
1770 |
|
1770 | |||
1771 | elif act.action == 'carriage-return': |
|
1771 | elif act.action == 'carriage-return': | |
1772 | cursor.movePosition( |
|
1772 | cursor.movePosition( | |
1773 | cursor.StartOfLine, cursor.KeepAnchor) |
|
1773 | cursor.StartOfLine, cursor.KeepAnchor) | |
1774 |
|
1774 | |||
1775 | elif act.action == 'beep': |
|
1775 | elif act.action == 'beep': | |
1776 | QtGui.qApp.beep() |
|
1776 | QtGui.qApp.beep() | |
1777 |
|
1777 | |||
1778 | elif act.action == 'backspace': |
|
1778 | elif act.action == 'backspace': | |
1779 | if not cursor.atBlockStart(): |
|
1779 | if not cursor.atBlockStart(): | |
1780 | cursor.movePosition( |
|
1780 | cursor.movePosition( | |
1781 | cursor.PreviousCharacter, cursor.KeepAnchor) |
|
1781 | cursor.PreviousCharacter, cursor.KeepAnchor) | |
1782 |
|
1782 | |||
1783 | elif act.action == 'newline': |
|
1783 | elif act.action == 'newline': | |
1784 | cursor.movePosition(cursor.EndOfLine) |
|
1784 | cursor.movePosition(cursor.EndOfLine) | |
1785 |
|
1785 | |||
1786 | format = self._ansi_processor.get_format() |
|
1786 | format = self._ansi_processor.get_format() | |
1787 |
|
1787 | |||
1788 | selection = cursor.selectedText() |
|
1788 | selection = cursor.selectedText() | |
1789 | if len(selection) == 0: |
|
1789 | if len(selection) == 0: | |
1790 | cursor.insertText(substring, format) |
|
1790 | cursor.insertText(substring, format) | |
1791 | elif substring is not None: |
|
1791 | elif substring is not None: | |
1792 | # BS and CR are treated as a change in print |
|
1792 | # BS and CR are treated as a change in print | |
1793 | # position, rather than a backwards character |
|
1793 | # position, rather than a backwards character | |
1794 | # deletion for output equivalence with (I)Python |
|
1794 | # deletion for output equivalence with (I)Python | |
1795 | # terminal. |
|
1795 | # terminal. | |
1796 | if len(substring) >= len(selection): |
|
1796 | if len(substring) >= len(selection): | |
1797 | cursor.insertText(substring, format) |
|
1797 | cursor.insertText(substring, format) | |
1798 | else: |
|
1798 | else: | |
1799 | old_text = selection[len(substring):] |
|
1799 | old_text = selection[len(substring):] | |
1800 | cursor.insertText(substring + old_text, format) |
|
1800 | cursor.insertText(substring + old_text, format) | |
1801 | cursor.movePosition(cursor.PreviousCharacter, |
|
1801 | cursor.movePosition(cursor.PreviousCharacter, | |
1802 | cursor.KeepAnchor, len(old_text)) |
|
1802 | cursor.KeepAnchor, len(old_text)) | |
1803 | else: |
|
1803 | else: | |
1804 | cursor.insertText(text) |
|
1804 | cursor.insertText(text) | |
1805 | cursor.endEditBlock() |
|
1805 | cursor.endEditBlock() | |
1806 |
|
1806 | |||
1807 | def _insert_plain_text_into_buffer(self, cursor, text): |
|
1807 | def _insert_plain_text_into_buffer(self, cursor, text): | |
1808 | """ Inserts text into the input buffer using the specified cursor (which |
|
1808 | """ Inserts text into the input buffer using the specified cursor (which | |
1809 | must be in the input buffer), ensuring that continuation prompts are |
|
1809 | must be in the input buffer), ensuring that continuation prompts are | |
1810 | inserted as necessary. |
|
1810 | inserted as necessary. | |
1811 | """ |
|
1811 | """ | |
1812 | lines = text.splitlines(True) |
|
1812 | lines = text.splitlines(True) | |
1813 | if lines: |
|
1813 | if lines: | |
1814 | cursor.beginEditBlock() |
|
1814 | cursor.beginEditBlock() | |
1815 | cursor.insertText(lines[0]) |
|
1815 | cursor.insertText(lines[0]) | |
1816 | for line in lines[1:]: |
|
1816 | for line in lines[1:]: | |
1817 | if self._continuation_prompt_html is None: |
|
1817 | if self._continuation_prompt_html is None: | |
1818 | cursor.insertText(self._continuation_prompt) |
|
1818 | cursor.insertText(self._continuation_prompt) | |
1819 | else: |
|
1819 | else: | |
1820 | self._continuation_prompt = \ |
|
1820 | self._continuation_prompt = \ | |
1821 | self._insert_html_fetching_plain_text( |
|
1821 | self._insert_html_fetching_plain_text( | |
1822 | cursor, self._continuation_prompt_html) |
|
1822 | cursor, self._continuation_prompt_html) | |
1823 | cursor.insertText(line) |
|
1823 | cursor.insertText(line) | |
1824 | cursor.endEditBlock() |
|
1824 | cursor.endEditBlock() | |
1825 |
|
1825 | |||
1826 | def _in_buffer(self, position=None): |
|
1826 | def _in_buffer(self, position=None): | |
1827 | """ Returns whether the current cursor (or, if specified, a position) is |
|
1827 | """ Returns whether the current cursor (or, if specified, a position) is | |
1828 | inside the editing region. |
|
1828 | inside the editing region. | |
1829 | """ |
|
1829 | """ | |
1830 | cursor = self._control.textCursor() |
|
1830 | cursor = self._control.textCursor() | |
1831 | if position is None: |
|
1831 | if position is None: | |
1832 | position = cursor.position() |
|
1832 | position = cursor.position() | |
1833 | else: |
|
1833 | else: | |
1834 | cursor.setPosition(position) |
|
1834 | cursor.setPosition(position) | |
1835 | line = cursor.blockNumber() |
|
1835 | line = cursor.blockNumber() | |
1836 | prompt_line = self._get_prompt_cursor().blockNumber() |
|
1836 | prompt_line = self._get_prompt_cursor().blockNumber() | |
1837 | if line == prompt_line: |
|
1837 | if line == prompt_line: | |
1838 | return position >= self._prompt_pos |
|
1838 | return position >= self._prompt_pos | |
1839 | elif line > prompt_line: |
|
1839 | elif line > prompt_line: | |
1840 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock) |
|
1840 | cursor.movePosition(QtGui.QTextCursor.StartOfBlock) | |
1841 | prompt_pos = cursor.position() + len(self._continuation_prompt) |
|
1841 | prompt_pos = cursor.position() + len(self._continuation_prompt) | |
1842 | return position >= prompt_pos |
|
1842 | return position >= prompt_pos | |
1843 | return False |
|
1843 | return False | |
1844 |
|
1844 | |||
1845 | def _keep_cursor_in_buffer(self): |
|
1845 | def _keep_cursor_in_buffer(self): | |
1846 | """ Ensures that the cursor is inside the editing region. Returns |
|
1846 | """ Ensures that the cursor is inside the editing region. Returns | |
1847 | whether the cursor was moved. |
|
1847 | whether the cursor was moved. | |
1848 | """ |
|
1848 | """ | |
1849 | moved = not self._in_buffer() |
|
1849 | moved = not self._in_buffer() | |
1850 | if moved: |
|
1850 | if moved: | |
1851 | cursor = self._control.textCursor() |
|
1851 | cursor = self._control.textCursor() | |
1852 | cursor.movePosition(QtGui.QTextCursor.End) |
|
1852 | cursor.movePosition(QtGui.QTextCursor.End) | |
1853 | self._control.setTextCursor(cursor) |
|
1853 | self._control.setTextCursor(cursor) | |
1854 | return moved |
|
1854 | return moved | |
1855 |
|
1855 | |||
1856 | def _keyboard_quit(self): |
|
1856 | def _keyboard_quit(self): | |
1857 | """ Cancels the current editing task ala Ctrl-G in Emacs. |
|
1857 | """ Cancels the current editing task ala Ctrl-G in Emacs. | |
1858 | """ |
|
1858 | """ | |
1859 | if self._temp_buffer_filled : |
|
1859 | if self._temp_buffer_filled : | |
1860 | self._cancel_completion() |
|
1860 | self._cancel_completion() | |
1861 | self._clear_temporary_buffer() |
|
1861 | self._clear_temporary_buffer() | |
1862 | else: |
|
1862 | else: | |
1863 | self.input_buffer = '' |
|
1863 | self.input_buffer = '' | |
1864 |
|
1864 | |||
1865 | def _page(self, text, html=False): |
|
1865 | def _page(self, text, html=False): | |
1866 | """ Displays text using the pager if it exceeds the height of the |
|
1866 | """ Displays text using the pager if it exceeds the height of the | |
1867 | viewport. |
|
1867 | viewport. | |
1868 |
|
1868 | |||
1869 | Parameters: |
|
1869 | Parameters: | |
1870 | ----------- |
|
1870 | ----------- | |
1871 | html : bool, optional (default False) |
|
1871 | html : bool, optional (default False) | |
1872 | If set, the text will be interpreted as HTML instead of plain text. |
|
1872 | If set, the text will be interpreted as HTML instead of plain text. | |
1873 | """ |
|
1873 | """ | |
1874 | line_height = QtGui.QFontMetrics(self.font).height() |
|
1874 | line_height = QtGui.QFontMetrics(self.font).height() | |
1875 | minlines = self._control.viewport().height() / line_height |
|
1875 | minlines = self._control.viewport().height() / line_height | |
1876 | if self.paging != 'none' and \ |
|
1876 | if self.paging != 'none' and \ | |
1877 | re.match("(?:[^\n]*\n){%i}" % minlines, text): |
|
1877 | re.match("(?:[^\n]*\n){%i}" % minlines, text): | |
1878 | if self.paging == 'custom': |
|
1878 | if self.paging == 'custom': | |
1879 | self.custom_page_requested.emit(text) |
|
1879 | self.custom_page_requested.emit(text) | |
1880 | else: |
|
1880 | else: | |
1881 | self._page_control.clear() |
|
1881 | self._page_control.clear() | |
1882 | cursor = self._page_control.textCursor() |
|
1882 | cursor = self._page_control.textCursor() | |
1883 | if html: |
|
1883 | if html: | |
1884 | self._insert_html(cursor, text) |
|
1884 | self._insert_html(cursor, text) | |
1885 | else: |
|
1885 | else: | |
1886 | self._insert_plain_text(cursor, text) |
|
1886 | self._insert_plain_text(cursor, text) | |
1887 | self._page_control.moveCursor(QtGui.QTextCursor.Start) |
|
1887 | self._page_control.moveCursor(QtGui.QTextCursor.Start) | |
1888 |
|
1888 | |||
1889 | self._page_control.viewport().resize(self._control.size()) |
|
1889 | self._page_control.viewport().resize(self._control.size()) | |
1890 | if self._splitter: |
|
1890 | if self._splitter: | |
1891 | self._page_control.show() |
|
1891 | self._page_control.show() | |
1892 | self._page_control.setFocus() |
|
1892 | self._page_control.setFocus() | |
1893 | else: |
|
1893 | else: | |
1894 | self.layout().setCurrentWidget(self._page_control) |
|
1894 | self.layout().setCurrentWidget(self._page_control) | |
1895 | elif html: |
|
1895 | elif html: | |
1896 | self._append_html(text) |
|
1896 | self._append_html(text) | |
1897 | else: |
|
1897 | else: | |
1898 | self._append_plain_text(text) |
|
1898 | self._append_plain_text(text) | |
1899 |
|
1899 | |||
1900 | def _set_paging(self, paging): |
|
1900 | def _set_paging(self, paging): | |
1901 | """ |
|
1901 | """ | |
1902 | Change the pager to `paging` style. |
|
1902 | Change the pager to `paging` style. | |
1903 |
|
1903 | |||
1904 | XXX: currently, this is limited to switching between 'hsplit' and |
|
1904 | XXX: currently, this is limited to switching between 'hsplit' and | |
1905 | 'vsplit'. |
|
1905 | 'vsplit'. | |
1906 |
|
1906 | |||
1907 | Parameters: |
|
1907 | Parameters: | |
1908 | ----------- |
|
1908 | ----------- | |
1909 | paging : string |
|
1909 | paging : string | |
1910 | Either "hsplit", "vsplit", or "inside" |
|
1910 | Either "hsplit", "vsplit", or "inside" | |
1911 | """ |
|
1911 | """ | |
1912 | if self._splitter is None: |
|
1912 | if self._splitter is None: | |
1913 | raise NotImplementedError("""can only switch if --paging=hsplit or |
|
1913 | raise NotImplementedError("""can only switch if --paging=hsplit or | |
1914 | --paging=vsplit is used.""") |
|
1914 | --paging=vsplit is used.""") | |
1915 | if paging == 'hsplit': |
|
1915 | if paging == 'hsplit': | |
1916 | self._splitter.setOrientation(QtCore.Qt.Horizontal) |
|
1916 | self._splitter.setOrientation(QtCore.Qt.Horizontal) | |
1917 | elif paging == 'vsplit': |
|
1917 | elif paging == 'vsplit': | |
1918 | self._splitter.setOrientation(QtCore.Qt.Vertical) |
|
1918 | self._splitter.setOrientation(QtCore.Qt.Vertical) | |
1919 | elif paging == 'inside': |
|
1919 | elif paging == 'inside': | |
1920 | raise NotImplementedError("""switching to 'inside' paging not |
|
1920 | raise NotImplementedError("""switching to 'inside' paging not | |
1921 | supported yet.""") |
|
1921 | supported yet.""") | |
1922 | else: |
|
1922 | else: | |
1923 | raise ValueError("unknown paging method '%s'" % paging) |
|
1923 | raise ValueError("unknown paging method '%s'" % paging) | |
1924 | self.paging = paging |
|
1924 | self.paging = paging | |
1925 |
|
1925 | |||
1926 | def _prompt_finished(self): |
|
1926 | def _prompt_finished(self): | |
1927 | """ Called immediately after a prompt is finished, i.e. when some input |
|
1927 | """ Called immediately after a prompt is finished, i.e. when some input | |
1928 | will be processed and a new prompt displayed. |
|
1928 | will be processed and a new prompt displayed. | |
1929 | """ |
|
1929 | """ | |
1930 | self._control.setReadOnly(True) |
|
1930 | self._control.setReadOnly(True) | |
1931 | self._prompt_finished_hook() |
|
1931 | self._prompt_finished_hook() | |
1932 |
|
1932 | |||
1933 | def _prompt_started(self): |
|
1933 | def _prompt_started(self): | |
1934 | """ Called immediately after a new prompt is displayed. |
|
1934 | """ Called immediately after a new prompt is displayed. | |
1935 | """ |
|
1935 | """ | |
1936 | # Temporarily disable the maximum block count to permit undo/redo and |
|
1936 | # Temporarily disable the maximum block count to permit undo/redo and | |
1937 | # to ensure that the prompt position does not change due to truncation. |
|
1937 | # to ensure that the prompt position does not change due to truncation. | |
1938 | self._control.document().setMaximumBlockCount(0) |
|
1938 | self._control.document().setMaximumBlockCount(0) | |
1939 | self._control.setUndoRedoEnabled(True) |
|
1939 | self._control.setUndoRedoEnabled(True) | |
1940 |
|
1940 | |||
1941 | # Work around bug in QPlainTextEdit: input method is not re-enabled |
|
1941 | # Work around bug in QPlainTextEdit: input method is not re-enabled | |
1942 | # when read-only is disabled. |
|
1942 | # when read-only is disabled. | |
1943 | self._control.setReadOnly(False) |
|
1943 | self._control.setReadOnly(False) | |
1944 | self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True) |
|
1944 | self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True) | |
1945 |
|
1945 | |||
1946 | if not self._reading: |
|
1946 | if not self._reading: | |
1947 | self._executing = False |
|
1947 | self._executing = False | |
1948 | self._prompt_started_hook() |
|
1948 | self._prompt_started_hook() | |
1949 |
|
1949 | |||
1950 | # If the input buffer has changed while executing, load it. |
|
1950 | # If the input buffer has changed while executing, load it. | |
1951 | if self._input_buffer_pending: |
|
1951 | if self._input_buffer_pending: | |
1952 | self.input_buffer = self._input_buffer_pending |
|
1952 | self.input_buffer = self._input_buffer_pending | |
1953 | self._input_buffer_pending = '' |
|
1953 | self._input_buffer_pending = '' | |
1954 |
|
1954 | |||
1955 | self._control.moveCursor(QtGui.QTextCursor.End) |
|
1955 | self._control.moveCursor(QtGui.QTextCursor.End) | |
1956 |
|
1956 | |||
1957 | def _readline(self, prompt='', callback=None): |
|
1957 | def _readline(self, prompt='', callback=None): | |
1958 | """ Reads one line of input from the user. |
|
1958 | """ Reads one line of input from the user. | |
1959 |
|
1959 | |||
1960 | Parameters |
|
1960 | Parameters | |
1961 | ---------- |
|
1961 | ---------- | |
1962 | prompt : str, optional |
|
1962 | prompt : str, optional | |
1963 | The prompt to print before reading the line. |
|
1963 | The prompt to print before reading the line. | |
1964 |
|
1964 | |||
1965 | callback : callable, optional |
|
1965 | callback : callable, optional | |
1966 | A callback to execute with the read line. If not specified, input is |
|
1966 | A callback to execute with the read line. If not specified, input is | |
1967 | read *synchronously* and this method does not return until it has |
|
1967 | read *synchronously* and this method does not return until it has | |
1968 | been read. |
|
1968 | been read. | |
1969 |
|
1969 | |||
1970 | Returns |
|
1970 | Returns | |
1971 | ------- |
|
1971 | ------- | |
1972 | If a callback is specified, returns nothing. Otherwise, returns the |
|
1972 | If a callback is specified, returns nothing. Otherwise, returns the | |
1973 | input string with the trailing newline stripped. |
|
1973 | input string with the trailing newline stripped. | |
1974 | """ |
|
1974 | """ | |
1975 | if self._reading: |
|
1975 | if self._reading: | |
1976 | raise RuntimeError('Cannot read a line. Widget is already reading.') |
|
1976 | raise RuntimeError('Cannot read a line. Widget is already reading.') | |
1977 |
|
1977 | |||
1978 | if not callback and not self.isVisible(): |
|
1978 | if not callback and not self.isVisible(): | |
1979 | # If the user cannot see the widget, this function cannot return. |
|
1979 | # If the user cannot see the widget, this function cannot return. | |
1980 | raise RuntimeError('Cannot synchronously read a line if the widget ' |
|
1980 | raise RuntimeError('Cannot synchronously read a line if the widget ' | |
1981 | 'is not visible!') |
|
1981 | 'is not visible!') | |
1982 |
|
1982 | |||
1983 | self._reading = True |
|
1983 | self._reading = True | |
1984 | self._show_prompt(prompt, newline=False) |
|
1984 | self._show_prompt(prompt, newline=False) | |
1985 |
|
1985 | |||
1986 | if callback is None: |
|
1986 | if callback is None: | |
1987 | self._reading_callback = None |
|
1987 | self._reading_callback = None | |
1988 | while self._reading: |
|
1988 | while self._reading: | |
1989 | QtCore.QCoreApplication.processEvents() |
|
1989 | QtCore.QCoreApplication.processEvents() | |
1990 | return self._get_input_buffer(force=True).rstrip('\n') |
|
1990 | return self._get_input_buffer(force=True).rstrip('\n') | |
1991 |
|
1991 | |||
1992 | else: |
|
1992 | else: | |
1993 | self._reading_callback = lambda: \ |
|
1993 | self._reading_callback = lambda: \ | |
1994 | callback(self._get_input_buffer(force=True).rstrip('\n')) |
|
1994 | callback(self._get_input_buffer(force=True).rstrip('\n')) | |
1995 |
|
1995 | |||
1996 | def _set_continuation_prompt(self, prompt, html=False): |
|
1996 | def _set_continuation_prompt(self, prompt, html=False): | |
1997 | """ Sets the continuation prompt. |
|
1997 | """ Sets the continuation prompt. | |
1998 |
|
1998 | |||
1999 | Parameters |
|
1999 | Parameters | |
2000 | ---------- |
|
2000 | ---------- | |
2001 | prompt : str |
|
2001 | prompt : str | |
2002 | The prompt to show when more input is needed. |
|
2002 | The prompt to show when more input is needed. | |
2003 |
|
2003 | |||
2004 | html : bool, optional (default False) |
|
2004 | html : bool, optional (default False) | |
2005 | If set, the prompt will be inserted as formatted HTML. Otherwise, |
|
2005 | If set, the prompt will be inserted as formatted HTML. Otherwise, | |
2006 | the prompt will be treated as plain text, though ANSI color codes |
|
2006 | the prompt will be treated as plain text, though ANSI color codes | |
2007 | will be handled. |
|
2007 | will be handled. | |
2008 | """ |
|
2008 | """ | |
2009 | if html: |
|
2009 | if html: | |
2010 | self._continuation_prompt_html = prompt |
|
2010 | self._continuation_prompt_html = prompt | |
2011 | else: |
|
2011 | else: | |
2012 | self._continuation_prompt = prompt |
|
2012 | self._continuation_prompt = prompt | |
2013 | self._continuation_prompt_html = None |
|
2013 | self._continuation_prompt_html = None | |
2014 |
|
2014 | |||
2015 | def _set_cursor(self, cursor): |
|
2015 | def _set_cursor(self, cursor): | |
2016 | """ Convenience method to set the current cursor. |
|
2016 | """ Convenience method to set the current cursor. | |
2017 | """ |
|
2017 | """ | |
2018 | self._control.setTextCursor(cursor) |
|
2018 | self._control.setTextCursor(cursor) | |
2019 |
|
2019 | |||
2020 | def _set_top_cursor(self, cursor): |
|
2020 | def _set_top_cursor(self, cursor): | |
2021 | """ Scrolls the viewport so that the specified cursor is at the top. |
|
2021 | """ Scrolls the viewport so that the specified cursor is at the top. | |
2022 | """ |
|
2022 | """ | |
2023 | scrollbar = self._control.verticalScrollBar() |
|
2023 | scrollbar = self._control.verticalScrollBar() | |
2024 | scrollbar.setValue(scrollbar.maximum()) |
|
2024 | scrollbar.setValue(scrollbar.maximum()) | |
2025 | original_cursor = self._control.textCursor() |
|
2025 | original_cursor = self._control.textCursor() | |
2026 | self._control.setTextCursor(cursor) |
|
2026 | self._control.setTextCursor(cursor) | |
2027 | self._control.ensureCursorVisible() |
|
2027 | self._control.ensureCursorVisible() | |
2028 | self._control.setTextCursor(original_cursor) |
|
2028 | self._control.setTextCursor(original_cursor) | |
2029 |
|
2029 | |||
2030 | def _show_prompt(self, prompt=None, html=False, newline=True): |
|
2030 | def _show_prompt(self, prompt=None, html=False, newline=True): | |
2031 | """ Writes a new prompt at the end of the buffer. |
|
2031 | """ Writes a new prompt at the end of the buffer. | |
2032 |
|
2032 | |||
2033 | Parameters |
|
2033 | Parameters | |
2034 | ---------- |
|
2034 | ---------- | |
2035 | prompt : str, optional |
|
2035 | prompt : str, optional | |
2036 | The prompt to show. If not specified, the previous prompt is used. |
|
2036 | The prompt to show. If not specified, the previous prompt is used. | |
2037 |
|
2037 | |||
2038 | html : bool, optional (default False) |
|
2038 | html : bool, optional (default False) | |
2039 | Only relevant when a prompt is specified. If set, the prompt will |
|
2039 | Only relevant when a prompt is specified. If set, the prompt will | |
2040 | be inserted as formatted HTML. Otherwise, the prompt will be treated |
|
2040 | be inserted as formatted HTML. Otherwise, the prompt will be treated | |
2041 | as plain text, though ANSI color codes will be handled. |
|
2041 | as plain text, though ANSI color codes will be handled. | |
2042 |
|
2042 | |||
2043 | newline : bool, optional (default True) |
|
2043 | newline : bool, optional (default True) | |
2044 | If set, a new line will be written before showing the prompt if |
|
2044 | If set, a new line will be written before showing the prompt if | |
2045 | there is not already a newline at the end of the buffer. |
|
2045 | there is not already a newline at the end of the buffer. | |
2046 | """ |
|
2046 | """ | |
2047 | # Save the current end position to support _append*(before_prompt=True). |
|
2047 | # Save the current end position to support _append*(before_prompt=True). | |
2048 | cursor = self._get_end_cursor() |
|
2048 | cursor = self._get_end_cursor() | |
2049 | self._append_before_prompt_pos = cursor.position() |
|
2049 | self._append_before_prompt_pos = cursor.position() | |
2050 |
|
2050 | |||
2051 | # Insert a preliminary newline, if necessary. |
|
2051 | # Insert a preliminary newline, if necessary. | |
2052 | if newline and cursor.position() > 0: |
|
2052 | if newline and cursor.position() > 0: | |
2053 | cursor.movePosition(QtGui.QTextCursor.Left, |
|
2053 | cursor.movePosition(QtGui.QTextCursor.Left, | |
2054 | QtGui.QTextCursor.KeepAnchor) |
|
2054 | QtGui.QTextCursor.KeepAnchor) | |
2055 | if cursor.selection().toPlainText() != '\n': |
|
2055 | if cursor.selection().toPlainText() != '\n': | |
2056 | self._append_block() |
|
2056 | self._append_block() | |
2057 |
|
2057 | |||
2058 | # Write the prompt. |
|
2058 | # Write the prompt. | |
2059 | self._append_plain_text(self._prompt_sep) |
|
2059 | self._append_plain_text(self._prompt_sep) | |
2060 | if prompt is None: |
|
2060 | if prompt is None: | |
2061 | if self._prompt_html is None: |
|
2061 | if self._prompt_html is None: | |
2062 | self._append_plain_text(self._prompt) |
|
2062 | self._append_plain_text(self._prompt) | |
2063 | else: |
|
2063 | else: | |
2064 | self._append_html(self._prompt_html) |
|
2064 | self._append_html(self._prompt_html) | |
2065 | else: |
|
2065 | else: | |
2066 | if html: |
|
2066 | if html: | |
2067 | self._prompt = self._append_html_fetching_plain_text(prompt) |
|
2067 | self._prompt = self._append_html_fetching_plain_text(prompt) | |
2068 | self._prompt_html = prompt |
|
2068 | self._prompt_html = prompt | |
2069 | else: |
|
2069 | else: | |
2070 | self._append_plain_text(prompt) |
|
2070 | self._append_plain_text(prompt) | |
2071 | self._prompt = prompt |
|
2071 | self._prompt = prompt | |
2072 | self._prompt_html = None |
|
2072 | self._prompt_html = None | |
2073 |
|
2073 | |||
2074 | self._flush_pending_stream() |
|
2074 | self._flush_pending_stream() | |
2075 | self._prompt_pos = self._get_end_cursor().position() |
|
2075 | self._prompt_pos = self._get_end_cursor().position() | |
2076 | self._prompt_started() |
|
2076 | self._prompt_started() | |
2077 |
|
2077 | |||
2078 | #------ Signal handlers ---------------------------------------------------- |
|
2078 | #------ Signal handlers ---------------------------------------------------- | |
2079 |
|
2079 | |||
2080 | def _adjust_scrollbars(self): |
|
2080 | def _adjust_scrollbars(self): | |
2081 | """ Expands the vertical scrollbar beyond the range set by Qt. |
|
2081 | """ Expands the vertical scrollbar beyond the range set by Qt. | |
2082 | """ |
|
2082 | """ | |
2083 | # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp |
|
2083 | # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp | |
2084 | # and qtextedit.cpp. |
|
2084 | # and qtextedit.cpp. | |
2085 | document = self._control.document() |
|
2085 | document = self._control.document() | |
2086 | scrollbar = self._control.verticalScrollBar() |
|
2086 | scrollbar = self._control.verticalScrollBar() | |
2087 | viewport_height = self._control.viewport().height() |
|
2087 | viewport_height = self._control.viewport().height() | |
2088 | if isinstance(self._control, QtGui.QPlainTextEdit): |
|
2088 | if isinstance(self._control, QtGui.QPlainTextEdit): | |
2089 | maximum = max(0, document.lineCount() - 1) |
|
2089 | maximum = max(0, document.lineCount() - 1) | |
2090 | step = viewport_height / self._control.fontMetrics().lineSpacing() |
|
2090 | step = viewport_height / self._control.fontMetrics().lineSpacing() | |
2091 | else: |
|
2091 | else: | |
2092 | # QTextEdit does not do line-based layout and blocks will not in |
|
2092 | # QTextEdit does not do line-based layout and blocks will not in | |
2093 | # general have the same height. Therefore it does not make sense to |
|
2093 | # general have the same height. Therefore it does not make sense to | |
2094 | # attempt to scroll in line height increments. |
|
2094 | # attempt to scroll in line height increments. | |
2095 | maximum = document.size().height() |
|
2095 | maximum = document.size().height() | |
2096 | step = viewport_height |
|
2096 | step = viewport_height | |
2097 | diff = maximum - scrollbar.maximum() |
|
2097 | diff = maximum - scrollbar.maximum() | |
2098 | scrollbar.setRange(0, maximum) |
|
2098 | scrollbar.setRange(0, maximum) | |
2099 | scrollbar.setPageStep(step) |
|
2099 | scrollbar.setPageStep(step) | |
2100 |
|
2100 | |||
2101 | # Compensate for undesirable scrolling that occurs automatically due to |
|
2101 | # Compensate for undesirable scrolling that occurs automatically due to | |
2102 | # maximumBlockCount() text truncation. |
|
2102 | # maximumBlockCount() text truncation. | |
2103 | if diff < 0 and document.blockCount() == document.maximumBlockCount(): |
|
2103 | if diff < 0 and document.blockCount() == document.maximumBlockCount(): | |
2104 | scrollbar.setValue(scrollbar.value() + diff) |
|
2104 | scrollbar.setValue(scrollbar.value() + diff) | |
2105 |
|
2105 | |||
2106 | def _custom_context_menu_requested(self, pos): |
|
2106 | def _custom_context_menu_requested(self, pos): | |
2107 | """ Shows a context menu at the given QPoint (in widget coordinates). |
|
2107 | """ Shows a context menu at the given QPoint (in widget coordinates). | |
2108 | """ |
|
2108 | """ | |
2109 | menu = self._context_menu_make(pos) |
|
2109 | menu = self._context_menu_make(pos) | |
2110 | menu.exec_(self._control.mapToGlobal(pos)) |
|
2110 | menu.exec_(self._control.mapToGlobal(pos)) |
@@ -1,220 +1,215 b'' | |||||
1 | """ Defines a KernelManager that provides signals and slots. |
|
1 | """ Defines a KernelManager that provides signals and slots. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | # System library imports. |
|
4 | # System library imports. | |
5 | from IPython.external.qt import QtCore |
|
5 | from IPython.external.qt import QtCore | |
6 |
|
6 | |||
7 | # IPython imports. |
|
7 | # IPython imports. | |
8 | from IPython.utils.traitlets import HasTraits, Type |
|
8 | from IPython.utils.traitlets import HasTraits, Type | |
9 | from .util import MetaQObjectHasTraits, SuperQObject |
|
9 | from .util import MetaQObjectHasTraits, SuperQObject | |
10 |
|
10 | |||
11 |
|
11 | |||
12 | class ChannelQObject(SuperQObject): |
|
12 | class ChannelQObject(SuperQObject): | |
13 |
|
13 | |||
14 | # Emitted when the channel is started. |
|
14 | # Emitted when the channel is started. | |
15 | started = QtCore.Signal() |
|
15 | started = QtCore.Signal() | |
16 |
|
16 | |||
17 | # Emitted when the channel is stopped. |
|
17 | # Emitted when the channel is stopped. | |
18 | stopped = QtCore.Signal() |
|
18 | stopped = QtCore.Signal() | |
19 |
|
19 | |||
20 | #--------------------------------------------------------------------------- |
|
20 | #--------------------------------------------------------------------------- | |
21 | # Channel interface |
|
21 | # Channel interface | |
22 | #--------------------------------------------------------------------------- |
|
22 | #--------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | def start(self): |
|
24 | def start(self): | |
25 | """ Reimplemented to emit signal. |
|
25 | """ Reimplemented to emit signal. | |
26 | """ |
|
26 | """ | |
27 | super(ChannelQObject, self).start() |
|
27 | super(ChannelQObject, self).start() | |
28 | self.started.emit() |
|
28 | self.started.emit() | |
29 |
|
29 | |||
30 | def stop(self): |
|
30 | def stop(self): | |
31 | """ Reimplemented to emit signal. |
|
31 | """ Reimplemented to emit signal. | |
32 | """ |
|
32 | """ | |
33 | super(ChannelQObject, self).stop() |
|
33 | super(ChannelQObject, self).stop() | |
34 | self.stopped.emit() |
|
34 | self.stopped.emit() | |
35 |
|
35 | |||
36 | #--------------------------------------------------------------------------- |
|
36 | #--------------------------------------------------------------------------- | |
37 | # InProcessChannel interface |
|
37 | # InProcessChannel interface | |
38 | #--------------------------------------------------------------------------- |
|
38 | #--------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | def call_handlers_later(self, *args, **kwds): |
|
40 | def call_handlers_later(self, *args, **kwds): | |
41 | """ Call the message handlers later. |
|
41 | """ Call the message handlers later. | |
42 | """ |
|
42 | """ | |
43 | do_later = lambda: self.call_handlers(*args, **kwds) |
|
43 | do_later = lambda: self.call_handlers(*args, **kwds) | |
44 | QtCore.QTimer.singleShot(0, do_later) |
|
44 | QtCore.QTimer.singleShot(0, do_later) | |
45 |
|
45 | |||
46 | def process_events(self): |
|
46 | def process_events(self): | |
47 | """ Process any pending GUI events. |
|
47 | """ Process any pending GUI events. | |
48 | """ |
|
48 | """ | |
49 | QtCore.QCoreApplication.instance().processEvents() |
|
49 | QtCore.QCoreApplication.instance().processEvents() | |
50 |
|
50 | |||
51 |
|
51 | |||
52 | class QtShellChannelMixin(ChannelQObject): |
|
52 | class QtShellChannelMixin(ChannelQObject): | |
53 |
|
53 | |||
54 | # Emitted when any message is received. |
|
54 | # Emitted when any message is received. | |
55 | message_received = QtCore.Signal(object) |
|
55 | message_received = QtCore.Signal(object) | |
56 |
|
56 | |||
57 | # Emitted when a reply has been received for the corresponding request type. |
|
57 | # Emitted when a reply has been received for the corresponding request type. | |
58 | execute_reply = QtCore.Signal(object) |
|
58 | execute_reply = QtCore.Signal(object) | |
59 | complete_reply = QtCore.Signal(object) |
|
59 | complete_reply = QtCore.Signal(object) | |
60 | object_info_reply = QtCore.Signal(object) |
|
60 | object_info_reply = QtCore.Signal(object) | |
61 | history_reply = QtCore.Signal(object) |
|
61 | history_reply = QtCore.Signal(object) | |
62 |
|
62 | |||
63 | #--------------------------------------------------------------------------- |
|
63 | #--------------------------------------------------------------------------- | |
64 | # 'ShellChannel' interface |
|
64 | # 'ShellChannel' interface | |
65 | #--------------------------------------------------------------------------- |
|
65 | #--------------------------------------------------------------------------- | |
66 |
|
66 | |||
67 | def call_handlers(self, msg): |
|
67 | def call_handlers(self, msg): | |
68 | """ Reimplemented to emit signals instead of making callbacks. |
|
68 | """ Reimplemented to emit signals instead of making callbacks. | |
69 | """ |
|
69 | """ | |
70 | # Emit the generic signal. |
|
70 | # Emit the generic signal. | |
71 | self.message_received.emit(msg) |
|
71 | self.message_received.emit(msg) | |
72 |
|
72 | |||
73 | # Emit signals for specialized message types. |
|
73 | # Emit signals for specialized message types. | |
74 | msg_type = msg['header']['msg_type'] |
|
74 | msg_type = msg['header']['msg_type'] | |
75 | signal = getattr(self, msg_type, None) |
|
75 | signal = getattr(self, msg_type, None) | |
76 | if signal: |
|
76 | if signal: | |
77 | signal.emit(msg) |
|
77 | signal.emit(msg) | |
78 |
|
78 | |||
79 |
|
79 | |||
80 | class QtIOPubChannelMixin(ChannelQObject): |
|
80 | class QtIOPubChannelMixin(ChannelQObject): | |
81 |
|
81 | |||
82 | # Emitted when any message is received. |
|
82 | # Emitted when any message is received. | |
83 | message_received = QtCore.Signal(object) |
|
83 | message_received = QtCore.Signal(object) | |
84 |
|
84 | |||
85 | # Emitted when a message of type 'stream' is received. |
|
85 | # Emitted when a message of type 'stream' is received. | |
86 | stream_received = QtCore.Signal(object) |
|
86 | stream_received = QtCore.Signal(object) | |
87 |
|
87 | |||
88 | # Emitted when a message of type 'pyin' is received. |
|
88 | # Emitted when a message of type 'pyin' is received. | |
89 | pyin_received = QtCore.Signal(object) |
|
89 | pyin_received = QtCore.Signal(object) | |
90 |
|
90 | |||
91 | # Emitted when a message of type 'pyout' is received. |
|
91 | # Emitted when a message of type 'pyout' is received. | |
92 | pyout_received = QtCore.Signal(object) |
|
92 | pyout_received = QtCore.Signal(object) | |
93 |
|
93 | |||
94 | # Emitted when a message of type 'pyerr' is received. |
|
94 | # Emitted when a message of type 'pyerr' is received. | |
95 | pyerr_received = QtCore.Signal(object) |
|
95 | pyerr_received = QtCore.Signal(object) | |
96 |
|
96 | |||
97 | # Emitted when a message of type 'display_data' is received |
|
97 | # Emitted when a message of type 'display_data' is received | |
98 | display_data_received = QtCore.Signal(object) |
|
98 | display_data_received = QtCore.Signal(object) | |
99 |
|
99 | |||
100 | # Emitted when a crash report message is received from the kernel's |
|
100 | # Emitted when a crash report message is received from the kernel's | |
101 | # last-resort sys.excepthook. |
|
101 | # last-resort sys.excepthook. | |
102 | crash_received = QtCore.Signal(object) |
|
102 | crash_received = QtCore.Signal(object) | |
103 |
|
103 | |||
104 | # Emitted when a shutdown is noticed. |
|
104 | # Emitted when a shutdown is noticed. | |
105 | shutdown_reply_received = QtCore.Signal(object) |
|
105 | shutdown_reply_received = QtCore.Signal(object) | |
106 |
|
106 | |||
107 | #--------------------------------------------------------------------------- |
|
107 | #--------------------------------------------------------------------------- | |
108 | # 'IOPubChannel' interface |
|
108 | # 'IOPubChannel' interface | |
109 | #--------------------------------------------------------------------------- |
|
109 | #--------------------------------------------------------------------------- | |
110 |
|
110 | |||
111 | def call_handlers(self, msg): |
|
111 | def call_handlers(self, msg): | |
112 | """ Reimplemented to emit signals instead of making callbacks. |
|
112 | """ Reimplemented to emit signals instead of making callbacks. | |
113 | """ |
|
113 | """ | |
114 | # Emit the generic signal. |
|
114 | # Emit the generic signal. | |
115 | self.message_received.emit(msg) |
|
115 | self.message_received.emit(msg) | |
116 | # Emit signals for specialized message types. |
|
116 | # Emit signals for specialized message types. | |
117 | msg_type = msg['header']['msg_type'] |
|
117 | msg_type = msg['header']['msg_type'] | |
118 | signal = getattr(self, msg_type + '_received', None) |
|
118 | signal = getattr(self, msg_type + '_received', None) | |
119 | if signal: |
|
119 | if signal: | |
120 | signal.emit(msg) |
|
120 | signal.emit(msg) | |
121 | elif msg_type in ('stdout', 'stderr'): |
|
121 | elif msg_type in ('stdout', 'stderr'): | |
122 | self.stream_received.emit(msg) |
|
122 | self.stream_received.emit(msg) | |
123 |
|
123 | |||
124 | def flush(self): |
|
124 | def flush(self): | |
125 | """ Reimplemented to ensure that signals are dispatched immediately. |
|
125 | """ Reimplemented to ensure that signals are dispatched immediately. | |
126 | """ |
|
126 | """ | |
127 | super(QtIOPubChannelMixin, self).flush() |
|
127 | super(QtIOPubChannelMixin, self).flush() | |
128 | QtCore.QCoreApplication.instance().processEvents() |
|
128 | QtCore.QCoreApplication.instance().processEvents() | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | class QtStdInChannelMixin(ChannelQObject): |
|
131 | class QtStdInChannelMixin(ChannelQObject): | |
132 |
|
132 | |||
133 | # Emitted when any message is received. |
|
133 | # Emitted when any message is received. | |
134 | message_received = QtCore.Signal(object) |
|
134 | message_received = QtCore.Signal(object) | |
135 |
|
135 | |||
136 | # Emitted when an input request is received. |
|
136 | # Emitted when an input request is received. | |
137 | input_requested = QtCore.Signal(object) |
|
137 | input_requested = QtCore.Signal(object) | |
138 |
|
138 | |||
139 | #--------------------------------------------------------------------------- |
|
139 | #--------------------------------------------------------------------------- | |
140 | # 'StdInChannel' interface |
|
140 | # 'StdInChannel' interface | |
141 | #--------------------------------------------------------------------------- |
|
141 | #--------------------------------------------------------------------------- | |
142 |
|
142 | |||
143 | def call_handlers(self, msg): |
|
143 | def call_handlers(self, msg): | |
144 | """ Reimplemented to emit signals instead of making callbacks. |
|
144 | """ Reimplemented to emit signals instead of making callbacks. | |
145 | """ |
|
145 | """ | |
146 | # Emit the generic signal. |
|
146 | # Emit the generic signal. | |
147 | self.message_received.emit(msg) |
|
147 | self.message_received.emit(msg) | |
148 |
|
148 | |||
149 | # Emit signals for specialized message types. |
|
149 | # Emit signals for specialized message types. | |
150 | msg_type = msg['header']['msg_type'] |
|
150 | msg_type = msg['header']['msg_type'] | |
151 | if msg_type == 'input_request': |
|
151 | if msg_type == 'input_request': | |
152 | self.input_requested.emit(msg) |
|
152 | self.input_requested.emit(msg) | |
153 |
|
153 | |||
154 |
|
154 | |||
155 | class QtHBChannelMixin(ChannelQObject): |
|
155 | class QtHBChannelMixin(ChannelQObject): | |
156 |
|
156 | |||
157 | # Emitted when the kernel has died. |
|
157 | # Emitted when the kernel has died. | |
158 | kernel_died = QtCore.Signal(object) |
|
158 | kernel_died = QtCore.Signal(object) | |
159 |
|
159 | |||
160 | #--------------------------------------------------------------------------- |
|
160 | #--------------------------------------------------------------------------- | |
161 | # 'HBChannel' interface |
|
161 | # 'HBChannel' interface | |
162 | #--------------------------------------------------------------------------- |
|
162 | #--------------------------------------------------------------------------- | |
163 |
|
163 | |||
164 | def call_handlers(self, since_last_heartbeat): |
|
164 | def call_handlers(self, since_last_heartbeat): | |
165 | """ Reimplemented to emit signals instead of making callbacks. |
|
165 | """ Reimplemented to emit signals instead of making callbacks. | |
166 | """ |
|
166 | """ | |
167 | # Emit the generic signal. |
|
167 | # Emit the generic signal. | |
168 | self.kernel_died.emit(since_last_heartbeat) |
|
168 | self.kernel_died.emit(since_last_heartbeat) | |
169 |
|
169 | |||
170 |
|
170 | |||
171 | class QtKernelRestarterMixin(HasTraits, SuperQObject): |
|
171 | class QtKernelRestarterMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})): | |
172 |
|
172 | |||
173 | __metaclass__ = MetaQObjectHasTraits |
|
|||
174 | _timer = None |
|
173 | _timer = None | |
175 |
|
174 | |||
176 |
|
175 | |||
177 | class QtKernelManagerMixin(HasTraits, SuperQObject): |
|
176 | class QtKernelManagerMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})): | |
178 | """ A KernelClient that provides signals and slots. |
|
177 | """ A KernelClient that provides signals and slots. | |
179 | """ |
|
178 | """ | |
180 |
|
179 | |||
181 | __metaclass__ = MetaQObjectHasTraits |
|
|||
182 |
|
||||
183 | kernel_restarted = QtCore.Signal() |
|
180 | kernel_restarted = QtCore.Signal() | |
184 |
|
181 | |||
185 |
|
182 | |||
186 | class QtKernelClientMixin(HasTraits, SuperQObject): |
|
183 | class QtKernelClientMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})): | |
187 | """ A KernelClient that provides signals and slots. |
|
184 | """ A KernelClient that provides signals and slots. | |
188 | """ |
|
185 | """ | |
189 |
|
186 | |||
190 | __metaclass__ = MetaQObjectHasTraits |
|
|||
191 |
|
||||
192 | # Emitted when the kernel client has started listening. |
|
187 | # Emitted when the kernel client has started listening. | |
193 | started_channels = QtCore.Signal() |
|
188 | started_channels = QtCore.Signal() | |
194 |
|
189 | |||
195 | # Emitted when the kernel client has stopped listening. |
|
190 | # Emitted when the kernel client has stopped listening. | |
196 | stopped_channels = QtCore.Signal() |
|
191 | stopped_channels = QtCore.Signal() | |
197 |
|
192 | |||
198 | # Use Qt-specific channel classes that emit signals. |
|
193 | # Use Qt-specific channel classes that emit signals. | |
199 | iopub_channel_class = Type(QtIOPubChannelMixin) |
|
194 | iopub_channel_class = Type(QtIOPubChannelMixin) | |
200 | shell_channel_class = Type(QtShellChannelMixin) |
|
195 | shell_channel_class = Type(QtShellChannelMixin) | |
201 | stdin_channel_class = Type(QtStdInChannelMixin) |
|
196 | stdin_channel_class = Type(QtStdInChannelMixin) | |
202 | hb_channel_class = Type(QtHBChannelMixin) |
|
197 | hb_channel_class = Type(QtHBChannelMixin) | |
203 |
|
198 | |||
204 | #--------------------------------------------------------------------------- |
|
199 | #--------------------------------------------------------------------------- | |
205 | # 'KernelClient' interface |
|
200 | # 'KernelClient' interface | |
206 | #--------------------------------------------------------------------------- |
|
201 | #--------------------------------------------------------------------------- | |
207 |
|
202 | |||
208 | #------ Channel management ------------------------------------------------- |
|
203 | #------ Channel management ------------------------------------------------- | |
209 |
|
204 | |||
210 | def start_channels(self, *args, **kw): |
|
205 | def start_channels(self, *args, **kw): | |
211 | """ Reimplemented to emit signal. |
|
206 | """ Reimplemented to emit signal. | |
212 | """ |
|
207 | """ | |
213 | super(QtKernelClientMixin, self).start_channels(*args, **kw) |
|
208 | super(QtKernelClientMixin, self).start_channels(*args, **kw) | |
214 | self.started_channels.emit() |
|
209 | self.started_channels.emit() | |
215 |
|
210 | |||
216 | def stop_channels(self): |
|
211 | def stop_channels(self): | |
217 | """ Reimplemented to emit signal. |
|
212 | """ Reimplemented to emit signal. | |
218 | """ |
|
213 | """ | |
219 | super(QtKernelClientMixin, self).stop_channels() |
|
214 | super(QtKernelClientMixin, self).stop_channels() | |
220 | self.stopped_channels.emit() |
|
215 | self.stopped_channels.emit() |
@@ -1,210 +1,235 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" |
|
2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" | |
3 | import functools |
|
3 | import functools | |
4 | import sys |
|
4 | import sys | |
5 | import re |
|
5 | import re | |
6 | import types |
|
6 | import types | |
7 |
|
7 | |||
8 | from .encoding import DEFAULT_ENCODING |
|
8 | from .encoding import DEFAULT_ENCODING | |
9 |
|
9 | |||
10 | orig_open = open |
|
10 | orig_open = open | |
11 |
|
11 | |||
12 | def no_code(x, encoding=None): |
|
12 | def no_code(x, encoding=None): | |
13 | return x |
|
13 | return x | |
14 |
|
14 | |||
15 | def decode(s, encoding=None): |
|
15 | def decode(s, encoding=None): | |
16 | encoding = encoding or DEFAULT_ENCODING |
|
16 | encoding = encoding or DEFAULT_ENCODING | |
17 | return s.decode(encoding, "replace") |
|
17 | return s.decode(encoding, "replace") | |
18 |
|
18 | |||
19 | def encode(u, encoding=None): |
|
19 | def encode(u, encoding=None): | |
20 | encoding = encoding or DEFAULT_ENCODING |
|
20 | encoding = encoding or DEFAULT_ENCODING | |
21 | return u.encode(encoding, "replace") |
|
21 | return u.encode(encoding, "replace") | |
22 |
|
22 | |||
23 |
|
23 | |||
24 | def cast_unicode(s, encoding=None): |
|
24 | def cast_unicode(s, encoding=None): | |
25 | if isinstance(s, bytes): |
|
25 | if isinstance(s, bytes): | |
26 | return decode(s, encoding) |
|
26 | return decode(s, encoding) | |
27 | return s |
|
27 | return s | |
28 |
|
28 | |||
29 | def cast_bytes(s, encoding=None): |
|
29 | def cast_bytes(s, encoding=None): | |
30 | if not isinstance(s, bytes): |
|
30 | if not isinstance(s, bytes): | |
31 | return encode(s, encoding) |
|
31 | return encode(s, encoding) | |
32 | return s |
|
32 | return s | |
33 |
|
33 | |||
34 | def _modify_str_or_docstring(str_change_func): |
|
34 | def _modify_str_or_docstring(str_change_func): | |
35 | @functools.wraps(str_change_func) |
|
35 | @functools.wraps(str_change_func) | |
36 | def wrapper(func_or_str): |
|
36 | def wrapper(func_or_str): | |
37 | if isinstance(func_or_str, string_types): |
|
37 | if isinstance(func_or_str, string_types): | |
38 | func = None |
|
38 | func = None | |
39 | doc = func_or_str |
|
39 | doc = func_or_str | |
40 | else: |
|
40 | else: | |
41 | func = func_or_str |
|
41 | func = func_or_str | |
42 | doc = func.__doc__ |
|
42 | doc = func.__doc__ | |
43 |
|
43 | |||
44 | doc = str_change_func(doc) |
|
44 | doc = str_change_func(doc) | |
45 |
|
45 | |||
46 | if func: |
|
46 | if func: | |
47 | func.__doc__ = doc |
|
47 | func.__doc__ = doc | |
48 | return func |
|
48 | return func | |
49 | return doc |
|
49 | return doc | |
50 | return wrapper |
|
50 | return wrapper | |
51 |
|
51 | |||
52 | def safe_unicode(e): |
|
52 | def safe_unicode(e): | |
53 | """unicode(e) with various fallbacks. Used for exceptions, which may not be |
|
53 | """unicode(e) with various fallbacks. Used for exceptions, which may not be | |
54 | safe to call unicode() on. |
|
54 | safe to call unicode() on. | |
55 | """ |
|
55 | """ | |
56 | try: |
|
56 | try: | |
57 | return unicode_type(e) |
|
57 | return unicode_type(e) | |
58 | except UnicodeError: |
|
58 | except UnicodeError: | |
59 | pass |
|
59 | pass | |
60 |
|
60 | |||
61 | try: |
|
61 | try: | |
62 | return str_to_unicode(str(e)) |
|
62 | return str_to_unicode(str(e)) | |
63 | except UnicodeError: |
|
63 | except UnicodeError: | |
64 | pass |
|
64 | pass | |
65 |
|
65 | |||
66 | try: |
|
66 | try: | |
67 | return str_to_unicode(repr(e)) |
|
67 | return str_to_unicode(repr(e)) | |
68 | except UnicodeError: |
|
68 | except UnicodeError: | |
69 | pass |
|
69 | pass | |
70 |
|
70 | |||
71 | return u'Unrecoverably corrupt evalue' |
|
71 | return u'Unrecoverably corrupt evalue' | |
72 |
|
72 | |||
73 | if sys.version_info[0] >= 3: |
|
73 | if sys.version_info[0] >= 3: | |
74 | PY3 = True |
|
74 | PY3 = True | |
75 |
|
75 | |||
76 | input = input |
|
76 | input = input | |
77 | builtin_mod_name = "builtins" |
|
77 | builtin_mod_name = "builtins" | |
78 | import builtins as builtin_mod |
|
78 | import builtins as builtin_mod | |
79 |
|
79 | |||
80 | str_to_unicode = no_code |
|
80 | str_to_unicode = no_code | |
81 | unicode_to_str = no_code |
|
81 | unicode_to_str = no_code | |
82 | str_to_bytes = encode |
|
82 | str_to_bytes = encode | |
83 | bytes_to_str = decode |
|
83 | bytes_to_str = decode | |
84 | cast_bytes_py2 = no_code |
|
84 | cast_bytes_py2 = no_code | |
85 |
|
85 | |||
86 | string_types = (str,) |
|
86 | string_types = (str,) | |
87 | unicode_type = str |
|
87 | unicode_type = str | |
88 |
|
88 | |||
89 | def isidentifier(s, dotted=False): |
|
89 | def isidentifier(s, dotted=False): | |
90 | if dotted: |
|
90 | if dotted: | |
91 | return all(isidentifier(a) for a in s.split(".")) |
|
91 | return all(isidentifier(a) for a in s.split(".")) | |
92 | return s.isidentifier() |
|
92 | return s.isidentifier() | |
93 |
|
93 | |||
94 | open = orig_open |
|
94 | open = orig_open | |
95 | xrange = range |
|
95 | xrange = range | |
96 |
|
96 | |||
97 | MethodType = types.MethodType |
|
97 | MethodType = types.MethodType | |
98 |
|
98 | |||
99 | def execfile(fname, glob, loc=None): |
|
99 | def execfile(fname, glob, loc=None): | |
100 | loc = loc if (loc is not None) else glob |
|
100 | loc = loc if (loc is not None) else glob | |
101 | with open(fname, 'rb') as f: |
|
101 | with open(fname, 'rb') as f: | |
102 | exec(compile(f.read(), fname, 'exec'), glob, loc) |
|
102 | exec(compile(f.read(), fname, 'exec'), glob, loc) | |
103 |
|
103 | |||
104 | # Refactor print statements in doctests. |
|
104 | # Refactor print statements in doctests. | |
105 | _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) |
|
105 | _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE) | |
106 | def _print_statement_sub(match): |
|
106 | def _print_statement_sub(match): | |
107 | expr = match.groups('expr') |
|
107 | expr = match.groups('expr') | |
108 | return "print(%s)" % expr |
|
108 | return "print(%s)" % expr | |
109 |
|
109 | |||
110 | @_modify_str_or_docstring |
|
110 | @_modify_str_or_docstring | |
111 | def doctest_refactor_print(doc): |
|
111 | def doctest_refactor_print(doc): | |
112 | """Refactor 'print x' statements in a doctest to print(x) style. 2to3 |
|
112 | """Refactor 'print x' statements in a doctest to print(x) style. 2to3 | |
113 | unfortunately doesn't pick up on our doctests. |
|
113 | unfortunately doesn't pick up on our doctests. | |
114 |
|
114 | |||
115 | Can accept a string or a function, so it can be used as a decorator.""" |
|
115 | Can accept a string or a function, so it can be used as a decorator.""" | |
116 | return _print_statement_re.sub(_print_statement_sub, doc) |
|
116 | return _print_statement_re.sub(_print_statement_sub, doc) | |
117 |
|
117 | |||
118 | # Abstract u'abc' syntax: |
|
118 | # Abstract u'abc' syntax: | |
119 | @_modify_str_or_docstring |
|
119 | @_modify_str_or_docstring | |
120 | def u_format(s): |
|
120 | def u_format(s): | |
121 | """"{u}'abc'" --> "'abc'" (Python 3) |
|
121 | """"{u}'abc'" --> "'abc'" (Python 3) | |
122 |
|
122 | |||
123 | Accepts a string or a function, so it can be used as a decorator.""" |
|
123 | Accepts a string or a function, so it can be used as a decorator.""" | |
124 | return s.format(u='') |
|
124 | return s.format(u='') | |
125 |
|
125 | |||
126 | else: |
|
126 | else: | |
127 | PY3 = False |
|
127 | PY3 = False | |
128 |
|
128 | |||
129 | input = raw_input |
|
129 | input = raw_input | |
130 | builtin_mod_name = "__builtin__" |
|
130 | builtin_mod_name = "__builtin__" | |
131 | import __builtin__ as builtin_mod |
|
131 | import __builtin__ as builtin_mod | |
132 |
|
132 | |||
133 | str_to_unicode = decode |
|
133 | str_to_unicode = decode | |
134 | unicode_to_str = encode |
|
134 | unicode_to_str = encode | |
135 | str_to_bytes = no_code |
|
135 | str_to_bytes = no_code | |
136 | bytes_to_str = no_code |
|
136 | bytes_to_str = no_code | |
137 | cast_bytes_py2 = cast_bytes |
|
137 | cast_bytes_py2 = cast_bytes | |
138 |
|
138 | |||
139 | string_types = (str, unicode) |
|
139 | string_types = (str, unicode) | |
140 | unicode_type = unicode |
|
140 | unicode_type = unicode | |
141 |
|
141 | |||
142 | import re |
|
142 | import re | |
143 | _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") |
|
143 | _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") | |
144 | def isidentifier(s, dotted=False): |
|
144 | def isidentifier(s, dotted=False): | |
145 | if dotted: |
|
145 | if dotted: | |
146 | return all(isidentifier(a) for a in s.split(".")) |
|
146 | return all(isidentifier(a) for a in s.split(".")) | |
147 | return bool(_name_re.match(s)) |
|
147 | return bool(_name_re.match(s)) | |
148 |
|
148 | |||
149 | class open(object): |
|
149 | class open(object): | |
150 | """Wrapper providing key part of Python 3 open() interface.""" |
|
150 | """Wrapper providing key part of Python 3 open() interface.""" | |
151 | def __init__(self, fname, mode="r", encoding="utf-8"): |
|
151 | def __init__(self, fname, mode="r", encoding="utf-8"): | |
152 | self.f = orig_open(fname, mode) |
|
152 | self.f = orig_open(fname, mode) | |
153 | self.enc = encoding |
|
153 | self.enc = encoding | |
154 |
|
154 | |||
155 | def write(self, s): |
|
155 | def write(self, s): | |
156 | return self.f.write(s.encode(self.enc)) |
|
156 | return self.f.write(s.encode(self.enc)) | |
157 |
|
157 | |||
158 | def read(self, size=-1): |
|
158 | def read(self, size=-1): | |
159 | return self.f.read(size).decode(self.enc) |
|
159 | return self.f.read(size).decode(self.enc) | |
160 |
|
160 | |||
161 | def close(self): |
|
161 | def close(self): | |
162 | return self.f.close() |
|
162 | return self.f.close() | |
163 |
|
163 | |||
164 | def __enter__(self): |
|
164 | def __enter__(self): | |
165 | return self |
|
165 | return self | |
166 |
|
166 | |||
167 | def __exit__(self, etype, value, traceback): |
|
167 | def __exit__(self, etype, value, traceback): | |
168 | self.f.close() |
|
168 | self.f.close() | |
169 |
|
169 | |||
170 | xrange = xrange |
|
170 | xrange = xrange | |
171 |
|
171 | |||
172 | def MethodType(func, instance): |
|
172 | def MethodType(func, instance): | |
173 | return types.MethodType(func, instance, type(instance)) |
|
173 | return types.MethodType(func, instance, type(instance)) | |
174 |
|
174 | |||
175 | # don't override system execfile on 2.x: |
|
175 | # don't override system execfile on 2.x: | |
176 | execfile = execfile |
|
176 | execfile = execfile | |
177 |
|
177 | |||
178 | def doctest_refactor_print(func_or_str): |
|
178 | def doctest_refactor_print(func_or_str): | |
179 | return func_or_str |
|
179 | return func_or_str | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | # Abstract u'abc' syntax: |
|
182 | # Abstract u'abc' syntax: | |
183 | @_modify_str_or_docstring |
|
183 | @_modify_str_or_docstring | |
184 | def u_format(s): |
|
184 | def u_format(s): | |
185 | """"{u}'abc'" --> "u'abc'" (Python 2) |
|
185 | """"{u}'abc'" --> "u'abc'" (Python 2) | |
186 |
|
186 | |||
187 | Accepts a string or a function, so it can be used as a decorator.""" |
|
187 | Accepts a string or a function, so it can be used as a decorator.""" | |
188 | return s.format(u='u') |
|
188 | return s.format(u='u') | |
189 |
|
189 | |||
190 | if sys.platform == 'win32': |
|
190 | if sys.platform == 'win32': | |
191 | def execfile(fname, glob=None, loc=None): |
|
191 | def execfile(fname, glob=None, loc=None): | |
192 | loc = loc if (loc is not None) else glob |
|
192 | loc = loc if (loc is not None) else glob | |
193 | # The rstrip() is necessary b/c trailing whitespace in files will |
|
193 | # The rstrip() is necessary b/c trailing whitespace in files will | |
194 | # cause an IndentationError in Python 2.6 (this was fixed in 2.7, |
|
194 | # cause an IndentationError in Python 2.6 (this was fixed in 2.7, | |
195 | # but we still support 2.6). See issue 1027. |
|
195 | # but we still support 2.6). See issue 1027. | |
196 | scripttext = builtin_mod.open(fname).read().rstrip() + '\n' |
|
196 | scripttext = builtin_mod.open(fname).read().rstrip() + '\n' | |
197 | # compile converts unicode filename to str assuming |
|
197 | # compile converts unicode filename to str assuming | |
198 | # ascii. Let's do the conversion before calling compile |
|
198 | # ascii. Let's do the conversion before calling compile | |
199 | if isinstance(fname, unicode): |
|
199 | if isinstance(fname, unicode): | |
200 | filename = unicode_to_str(fname) |
|
200 | filename = unicode_to_str(fname) | |
201 | else: |
|
201 | else: | |
202 | filename = fname |
|
202 | filename = fname | |
203 | exec(compile(scripttext, filename, 'exec'), glob, loc) |
|
203 | exec(compile(scripttext, filename, 'exec'), glob, loc) | |
204 | else: |
|
204 | else: | |
205 | def execfile(fname, *where): |
|
205 | def execfile(fname, *where): | |
206 | if isinstance(fname, unicode): |
|
206 | if isinstance(fname, unicode): | |
207 | filename = fname.encode(sys.getfilesystemencoding()) |
|
207 | filename = fname.encode(sys.getfilesystemencoding()) | |
208 | else: |
|
208 | else: | |
209 | filename = fname |
|
209 | filename = fname | |
210 | builtin_mod.execfile(filename, *where) |
|
210 | builtin_mod.execfile(filename, *where) | |
|
211 | ||||
|
212 | # Parts below taken from six: | |||
|
213 | # Copyright (c) 2010-2013 Benjamin Peterson | |||
|
214 | # | |||
|
215 | # Permission is hereby granted, free of charge, to any person obtaining a copy | |||
|
216 | # of this software and associated documentation files (the "Software"), to deal | |||
|
217 | # in the Software without restriction, including without limitation the rights | |||
|
218 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |||
|
219 | # copies of the Software, and to permit persons to whom the Software is | |||
|
220 | # furnished to do so, subject to the following conditions: | |||
|
221 | # | |||
|
222 | # The above copyright notice and this permission notice shall be included in all | |||
|
223 | # copies or substantial portions of the Software. | |||
|
224 | # | |||
|
225 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |||
|
226 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |||
|
227 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |||
|
228 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |||
|
229 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |||
|
230 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |||
|
231 | # SOFTWARE. | |||
|
232 | ||||
|
233 | def with_metaclass(meta, *bases): | |||
|
234 | """Create a base class with a metaclass.""" | |||
|
235 | return meta("NewBase", bases, {}) |
@@ -1,1439 +1,1437 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """ |
|
2 | """ | |
3 | A lightweight Traits like module. |
|
3 | A lightweight Traits like module. | |
4 |
|
4 | |||
5 | This is designed to provide a lightweight, simple, pure Python version of |
|
5 | This is designed to provide a lightweight, simple, pure Python version of | |
6 | many of the capabilities of enthought.traits. This includes: |
|
6 | many of the capabilities of enthought.traits. This includes: | |
7 |
|
7 | |||
8 | * Validation |
|
8 | * Validation | |
9 | * Type specification with defaults |
|
9 | * Type specification with defaults | |
10 | * Static and dynamic notification |
|
10 | * Static and dynamic notification | |
11 | * Basic predefined types |
|
11 | * Basic predefined types | |
12 | * An API that is similar to enthought.traits |
|
12 | * An API that is similar to enthought.traits | |
13 |
|
13 | |||
14 | We don't support: |
|
14 | We don't support: | |
15 |
|
15 | |||
16 | * Delegation |
|
16 | * Delegation | |
17 | * Automatic GUI generation |
|
17 | * Automatic GUI generation | |
18 | * A full set of trait types. Most importantly, we don't provide container |
|
18 | * A full set of trait types. Most importantly, we don't provide container | |
19 | traits (list, dict, tuple) that can trigger notifications if their |
|
19 | traits (list, dict, tuple) that can trigger notifications if their | |
20 | contents change. |
|
20 | contents change. | |
21 | * API compatibility with enthought.traits |
|
21 | * API compatibility with enthought.traits | |
22 |
|
22 | |||
23 | There are also some important difference in our design: |
|
23 | There are also some important difference in our design: | |
24 |
|
24 | |||
25 | * enthought.traits does not validate default values. We do. |
|
25 | * enthought.traits does not validate default values. We do. | |
26 |
|
26 | |||
27 | We choose to create this module because we need these capabilities, but |
|
27 | We choose to create this module because we need these capabilities, but | |
28 | we need them to be pure Python so they work in all Python implementations, |
|
28 | we need them to be pure Python so they work in all Python implementations, | |
29 | including Jython and IronPython. |
|
29 | including Jython and IronPython. | |
30 |
|
30 | |||
31 | Inheritance diagram: |
|
31 | Inheritance diagram: | |
32 |
|
32 | |||
33 | .. inheritance-diagram:: IPython.utils.traitlets |
|
33 | .. inheritance-diagram:: IPython.utils.traitlets | |
34 | :parts: 3 |
|
34 | :parts: 3 | |
35 |
|
35 | |||
36 | Authors: |
|
36 | Authors: | |
37 |
|
37 | |||
38 | * Brian Granger |
|
38 | * Brian Granger | |
39 | * Enthought, Inc. Some of the code in this file comes from enthought.traits |
|
39 | * Enthought, Inc. Some of the code in this file comes from enthought.traits | |
40 | and is licensed under the BSD license. Also, many of the ideas also come |
|
40 | and is licensed under the BSD license. Also, many of the ideas also come | |
41 | from enthought.traits even though our implementation is very different. |
|
41 | from enthought.traits even though our implementation is very different. | |
42 | """ |
|
42 | """ | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # Copyright (C) 2008-2011 The IPython Development Team |
|
45 | # Copyright (C) 2008-2011 The IPython Development Team | |
46 | # |
|
46 | # | |
47 | # Distributed under the terms of the BSD License. The full license is in |
|
47 | # Distributed under the terms of the BSD License. The full license is in | |
48 | # the file COPYING, distributed as part of this software. |
|
48 | # the file COPYING, distributed as part of this software. | |
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 |
|
50 | |||
51 | #----------------------------------------------------------------------------- |
|
51 | #----------------------------------------------------------------------------- | |
52 | # Imports |
|
52 | # Imports | |
53 | #----------------------------------------------------------------------------- |
|
53 | #----------------------------------------------------------------------------- | |
54 |
|
54 | |||
55 |
|
55 | |||
56 | import inspect |
|
56 | import inspect | |
57 | import re |
|
57 | import re | |
58 | import sys |
|
58 | import sys | |
59 | import types |
|
59 | import types | |
60 | from types import FunctionType |
|
60 | from types import FunctionType | |
61 | try: |
|
61 | try: | |
62 | from types import ClassType, InstanceType |
|
62 | from types import ClassType, InstanceType | |
63 | ClassTypes = (ClassType, type) |
|
63 | ClassTypes = (ClassType, type) | |
64 | except: |
|
64 | except: | |
65 | ClassTypes = (type,) |
|
65 | ClassTypes = (type,) | |
66 |
|
66 | |||
67 | from .importstring import import_item |
|
67 | from .importstring import import_item | |
68 | from IPython.utils import py3compat |
|
68 | from IPython.utils import py3compat | |
69 |
|
69 | |||
70 | SequenceTypes = (list, tuple, set, frozenset) |
|
70 | SequenceTypes = (list, tuple, set, frozenset) | |
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Basic classes |
|
73 | # Basic classes | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | class NoDefaultSpecified ( object ): pass |
|
77 | class NoDefaultSpecified ( object ): pass | |
78 | NoDefaultSpecified = NoDefaultSpecified() |
|
78 | NoDefaultSpecified = NoDefaultSpecified() | |
79 |
|
79 | |||
80 |
|
80 | |||
81 | class Undefined ( object ): pass |
|
81 | class Undefined ( object ): pass | |
82 | Undefined = Undefined() |
|
82 | Undefined = Undefined() | |
83 |
|
83 | |||
84 | class TraitError(Exception): |
|
84 | class TraitError(Exception): | |
85 | pass |
|
85 | pass | |
86 |
|
86 | |||
87 | #----------------------------------------------------------------------------- |
|
87 | #----------------------------------------------------------------------------- | |
88 | # Utilities |
|
88 | # Utilities | |
89 | #----------------------------------------------------------------------------- |
|
89 | #----------------------------------------------------------------------------- | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | def class_of ( object ): |
|
92 | def class_of ( object ): | |
93 | """ Returns a string containing the class name of an object with the |
|
93 | """ Returns a string containing the class name of an object with the | |
94 | correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', |
|
94 | correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image', | |
95 | 'a PlotValue'). |
|
95 | 'a PlotValue'). | |
96 | """ |
|
96 | """ | |
97 | if isinstance( object, py3compat.string_types ): |
|
97 | if isinstance( object, py3compat.string_types ): | |
98 | return add_article( object ) |
|
98 | return add_article( object ) | |
99 |
|
99 | |||
100 | return add_article( object.__class__.__name__ ) |
|
100 | return add_article( object.__class__.__name__ ) | |
101 |
|
101 | |||
102 |
|
102 | |||
103 | def add_article ( name ): |
|
103 | def add_article ( name ): | |
104 | """ Returns a string containing the correct indefinite article ('a' or 'an') |
|
104 | """ Returns a string containing the correct indefinite article ('a' or 'an') | |
105 | prefixed to the specified string. |
|
105 | prefixed to the specified string. | |
106 | """ |
|
106 | """ | |
107 | if name[:1].lower() in 'aeiou': |
|
107 | if name[:1].lower() in 'aeiou': | |
108 | return 'an ' + name |
|
108 | return 'an ' + name | |
109 |
|
109 | |||
110 | return 'a ' + name |
|
110 | return 'a ' + name | |
111 |
|
111 | |||
112 |
|
112 | |||
113 | def repr_type(obj): |
|
113 | def repr_type(obj): | |
114 | """ Return a string representation of a value and its type for readable |
|
114 | """ Return a string representation of a value and its type for readable | |
115 | error messages. |
|
115 | error messages. | |
116 | """ |
|
116 | """ | |
117 | the_type = type(obj) |
|
117 | the_type = type(obj) | |
118 | if (not py3compat.PY3) and the_type is InstanceType: |
|
118 | if (not py3compat.PY3) and the_type is InstanceType: | |
119 | # Old-style class. |
|
119 | # Old-style class. | |
120 | the_type = obj.__class__ |
|
120 | the_type = obj.__class__ | |
121 | msg = '%r %r' % (obj, the_type) |
|
121 | msg = '%r %r' % (obj, the_type) | |
122 | return msg |
|
122 | return msg | |
123 |
|
123 | |||
124 |
|
124 | |||
125 | def is_trait(t): |
|
125 | def is_trait(t): | |
126 | """ Returns whether the given value is an instance or subclass of TraitType. |
|
126 | """ Returns whether the given value is an instance or subclass of TraitType. | |
127 | """ |
|
127 | """ | |
128 | return (isinstance(t, TraitType) or |
|
128 | return (isinstance(t, TraitType) or | |
129 | (isinstance(t, type) and issubclass(t, TraitType))) |
|
129 | (isinstance(t, type) and issubclass(t, TraitType))) | |
130 |
|
130 | |||
131 |
|
131 | |||
132 | def parse_notifier_name(name): |
|
132 | def parse_notifier_name(name): | |
133 | """Convert the name argument to a list of names. |
|
133 | """Convert the name argument to a list of names. | |
134 |
|
134 | |||
135 | Examples |
|
135 | Examples | |
136 | -------- |
|
136 | -------- | |
137 |
|
137 | |||
138 | >>> parse_notifier_name('a') |
|
138 | >>> parse_notifier_name('a') | |
139 | ['a'] |
|
139 | ['a'] | |
140 | >>> parse_notifier_name(['a','b']) |
|
140 | >>> parse_notifier_name(['a','b']) | |
141 | ['a', 'b'] |
|
141 | ['a', 'b'] | |
142 | >>> parse_notifier_name(None) |
|
142 | >>> parse_notifier_name(None) | |
143 | ['anytrait'] |
|
143 | ['anytrait'] | |
144 | """ |
|
144 | """ | |
145 | if isinstance(name, str): |
|
145 | if isinstance(name, str): | |
146 | return [name] |
|
146 | return [name] | |
147 | elif name is None: |
|
147 | elif name is None: | |
148 | return ['anytrait'] |
|
148 | return ['anytrait'] | |
149 | elif isinstance(name, (list, tuple)): |
|
149 | elif isinstance(name, (list, tuple)): | |
150 | for n in name: |
|
150 | for n in name: | |
151 | assert isinstance(n, str), "names must be strings" |
|
151 | assert isinstance(n, str), "names must be strings" | |
152 | return name |
|
152 | return name | |
153 |
|
153 | |||
154 |
|
154 | |||
155 | class _SimpleTest: |
|
155 | class _SimpleTest: | |
156 | def __init__ ( self, value ): self.value = value |
|
156 | def __init__ ( self, value ): self.value = value | |
157 | def __call__ ( self, test ): |
|
157 | def __call__ ( self, test ): | |
158 | return test == self.value |
|
158 | return test == self.value | |
159 | def __repr__(self): |
|
159 | def __repr__(self): | |
160 | return "<SimpleTest(%r)" % self.value |
|
160 | return "<SimpleTest(%r)" % self.value | |
161 | def __str__(self): |
|
161 | def __str__(self): | |
162 | return self.__repr__() |
|
162 | return self.__repr__() | |
163 |
|
163 | |||
164 |
|
164 | |||
165 | def getmembers(object, predicate=None): |
|
165 | def getmembers(object, predicate=None): | |
166 | """A safe version of inspect.getmembers that handles missing attributes. |
|
166 | """A safe version of inspect.getmembers that handles missing attributes. | |
167 |
|
167 | |||
168 | This is useful when there are descriptor based attributes that for |
|
168 | This is useful when there are descriptor based attributes that for | |
169 | some reason raise AttributeError even though they exist. This happens |
|
169 | some reason raise AttributeError even though they exist. This happens | |
170 | in zope.inteface with the __provides__ attribute. |
|
170 | in zope.inteface with the __provides__ attribute. | |
171 | """ |
|
171 | """ | |
172 | results = [] |
|
172 | results = [] | |
173 | for key in dir(object): |
|
173 | for key in dir(object): | |
174 | try: |
|
174 | try: | |
175 | value = getattr(object, key) |
|
175 | value = getattr(object, key) | |
176 | except AttributeError: |
|
176 | except AttributeError: | |
177 | pass |
|
177 | pass | |
178 | else: |
|
178 | else: | |
179 | if not predicate or predicate(value): |
|
179 | if not predicate or predicate(value): | |
180 | results.append((key, value)) |
|
180 | results.append((key, value)) | |
181 | results.sort() |
|
181 | results.sort() | |
182 | return results |
|
182 | return results | |
183 |
|
183 | |||
184 |
|
184 | |||
185 | #----------------------------------------------------------------------------- |
|
185 | #----------------------------------------------------------------------------- | |
186 | # Base TraitType for all traits |
|
186 | # Base TraitType for all traits | |
187 | #----------------------------------------------------------------------------- |
|
187 | #----------------------------------------------------------------------------- | |
188 |
|
188 | |||
189 |
|
189 | |||
190 | class TraitType(object): |
|
190 | class TraitType(object): | |
191 | """A base class for all trait descriptors. |
|
191 | """A base class for all trait descriptors. | |
192 |
|
192 | |||
193 | Notes |
|
193 | Notes | |
194 | ----- |
|
194 | ----- | |
195 | Our implementation of traits is based on Python's descriptor |
|
195 | Our implementation of traits is based on Python's descriptor | |
196 | prototol. This class is the base class for all such descriptors. The |
|
196 | prototol. This class is the base class for all such descriptors. The | |
197 | only magic we use is a custom metaclass for the main :class:`HasTraits` |
|
197 | only magic we use is a custom metaclass for the main :class:`HasTraits` | |
198 | class that does the following: |
|
198 | class that does the following: | |
199 |
|
199 | |||
200 | 1. Sets the :attr:`name` attribute of every :class:`TraitType` |
|
200 | 1. Sets the :attr:`name` attribute of every :class:`TraitType` | |
201 | instance in the class dict to the name of the attribute. |
|
201 | instance in the class dict to the name of the attribute. | |
202 | 2. Sets the :attr:`this_class` attribute of every :class:`TraitType` |
|
202 | 2. Sets the :attr:`this_class` attribute of every :class:`TraitType` | |
203 | instance in the class dict to the *class* that declared the trait. |
|
203 | instance in the class dict to the *class* that declared the trait. | |
204 | This is used by the :class:`This` trait to allow subclasses to |
|
204 | This is used by the :class:`This` trait to allow subclasses to | |
205 | accept superclasses for :class:`This` values. |
|
205 | accept superclasses for :class:`This` values. | |
206 | """ |
|
206 | """ | |
207 |
|
207 | |||
208 |
|
208 | |||
209 | metadata = {} |
|
209 | metadata = {} | |
210 | default_value = Undefined |
|
210 | default_value = Undefined | |
211 | info_text = 'any value' |
|
211 | info_text = 'any value' | |
212 |
|
212 | |||
213 | def __init__(self, default_value=NoDefaultSpecified, **metadata): |
|
213 | def __init__(self, default_value=NoDefaultSpecified, **metadata): | |
214 | """Create a TraitType. |
|
214 | """Create a TraitType. | |
215 | """ |
|
215 | """ | |
216 | if default_value is not NoDefaultSpecified: |
|
216 | if default_value is not NoDefaultSpecified: | |
217 | self.default_value = default_value |
|
217 | self.default_value = default_value | |
218 |
|
218 | |||
219 | if len(metadata) > 0: |
|
219 | if len(metadata) > 0: | |
220 | if len(self.metadata) > 0: |
|
220 | if len(self.metadata) > 0: | |
221 | self._metadata = self.metadata.copy() |
|
221 | self._metadata = self.metadata.copy() | |
222 | self._metadata.update(metadata) |
|
222 | self._metadata.update(metadata) | |
223 | else: |
|
223 | else: | |
224 | self._metadata = metadata |
|
224 | self._metadata = metadata | |
225 | else: |
|
225 | else: | |
226 | self._metadata = self.metadata |
|
226 | self._metadata = self.metadata | |
227 |
|
227 | |||
228 | self.init() |
|
228 | self.init() | |
229 |
|
229 | |||
230 | def init(self): |
|
230 | def init(self): | |
231 | pass |
|
231 | pass | |
232 |
|
232 | |||
233 | def get_default_value(self): |
|
233 | def get_default_value(self): | |
234 | """Create a new instance of the default value.""" |
|
234 | """Create a new instance of the default value.""" | |
235 | return self.default_value |
|
235 | return self.default_value | |
236 |
|
236 | |||
237 | def instance_init(self, obj): |
|
237 | def instance_init(self, obj): | |
238 | """This is called by :meth:`HasTraits.__new__` to finish init'ing. |
|
238 | """This is called by :meth:`HasTraits.__new__` to finish init'ing. | |
239 |
|
239 | |||
240 | Some stages of initialization must be delayed until the parent |
|
240 | Some stages of initialization must be delayed until the parent | |
241 | :class:`HasTraits` instance has been created. This method is |
|
241 | :class:`HasTraits` instance has been created. This method is | |
242 | called in :meth:`HasTraits.__new__` after the instance has been |
|
242 | called in :meth:`HasTraits.__new__` after the instance has been | |
243 | created. |
|
243 | created. | |
244 |
|
244 | |||
245 | This method trigger the creation and validation of default values |
|
245 | This method trigger the creation and validation of default values | |
246 | and also things like the resolution of str given class names in |
|
246 | and also things like the resolution of str given class names in | |
247 | :class:`Type` and :class`Instance`. |
|
247 | :class:`Type` and :class`Instance`. | |
248 |
|
248 | |||
249 | Parameters |
|
249 | Parameters | |
250 | ---------- |
|
250 | ---------- | |
251 | obj : :class:`HasTraits` instance |
|
251 | obj : :class:`HasTraits` instance | |
252 | The parent :class:`HasTraits` instance that has just been |
|
252 | The parent :class:`HasTraits` instance that has just been | |
253 | created. |
|
253 | created. | |
254 | """ |
|
254 | """ | |
255 | self.set_default_value(obj) |
|
255 | self.set_default_value(obj) | |
256 |
|
256 | |||
257 | def set_default_value(self, obj): |
|
257 | def set_default_value(self, obj): | |
258 | """Set the default value on a per instance basis. |
|
258 | """Set the default value on a per instance basis. | |
259 |
|
259 | |||
260 | This method is called by :meth:`instance_init` to create and |
|
260 | This method is called by :meth:`instance_init` to create and | |
261 | validate the default value. The creation and validation of |
|
261 | validate the default value. The creation and validation of | |
262 | default values must be delayed until the parent :class:`HasTraits` |
|
262 | default values must be delayed until the parent :class:`HasTraits` | |
263 | class has been instantiated. |
|
263 | class has been instantiated. | |
264 | """ |
|
264 | """ | |
265 | # Check for a deferred initializer defined in the same class as the |
|
265 | # Check for a deferred initializer defined in the same class as the | |
266 | # trait declaration or above. |
|
266 | # trait declaration or above. | |
267 | mro = type(obj).mro() |
|
267 | mro = type(obj).mro() | |
268 | meth_name = '_%s_default' % self.name |
|
268 | meth_name = '_%s_default' % self.name | |
269 | for cls in mro[:mro.index(self.this_class)+1]: |
|
269 | for cls in mro[:mro.index(self.this_class)+1]: | |
270 | if meth_name in cls.__dict__: |
|
270 | if meth_name in cls.__dict__: | |
271 | break |
|
271 | break | |
272 | else: |
|
272 | else: | |
273 | # We didn't find one. Do static initialization. |
|
273 | # We didn't find one. Do static initialization. | |
274 | dv = self.get_default_value() |
|
274 | dv = self.get_default_value() | |
275 | newdv = self._validate(obj, dv) |
|
275 | newdv = self._validate(obj, dv) | |
276 | obj._trait_values[self.name] = newdv |
|
276 | obj._trait_values[self.name] = newdv | |
277 | return |
|
277 | return | |
278 | # Complete the dynamic initialization. |
|
278 | # Complete the dynamic initialization. | |
279 | obj._trait_dyn_inits[self.name] = cls.__dict__[meth_name] |
|
279 | obj._trait_dyn_inits[self.name] = cls.__dict__[meth_name] | |
280 |
|
280 | |||
281 | def __get__(self, obj, cls=None): |
|
281 | def __get__(self, obj, cls=None): | |
282 | """Get the value of the trait by self.name for the instance. |
|
282 | """Get the value of the trait by self.name for the instance. | |
283 |
|
283 | |||
284 | Default values are instantiated when :meth:`HasTraits.__new__` |
|
284 | Default values are instantiated when :meth:`HasTraits.__new__` | |
285 | is called. Thus by the time this method gets called either the |
|
285 | is called. Thus by the time this method gets called either the | |
286 | default value or a user defined value (they called :meth:`__set__`) |
|
286 | default value or a user defined value (they called :meth:`__set__`) | |
287 | is in the :class:`HasTraits` instance. |
|
287 | is in the :class:`HasTraits` instance. | |
288 | """ |
|
288 | """ | |
289 | if obj is None: |
|
289 | if obj is None: | |
290 | return self |
|
290 | return self | |
291 | else: |
|
291 | else: | |
292 | try: |
|
292 | try: | |
293 | value = obj._trait_values[self.name] |
|
293 | value = obj._trait_values[self.name] | |
294 | except KeyError: |
|
294 | except KeyError: | |
295 | # Check for a dynamic initializer. |
|
295 | # Check for a dynamic initializer. | |
296 | if self.name in obj._trait_dyn_inits: |
|
296 | if self.name in obj._trait_dyn_inits: | |
297 | value = obj._trait_dyn_inits[self.name](obj) |
|
297 | value = obj._trait_dyn_inits[self.name](obj) | |
298 | # FIXME: Do we really validate here? |
|
298 | # FIXME: Do we really validate here? | |
299 | value = self._validate(obj, value) |
|
299 | value = self._validate(obj, value) | |
300 | obj._trait_values[self.name] = value |
|
300 | obj._trait_values[self.name] = value | |
301 | return value |
|
301 | return value | |
302 | else: |
|
302 | else: | |
303 | raise TraitError('Unexpected error in TraitType: ' |
|
303 | raise TraitError('Unexpected error in TraitType: ' | |
304 | 'both default value and dynamic initializer are ' |
|
304 | 'both default value and dynamic initializer are ' | |
305 | 'absent.') |
|
305 | 'absent.') | |
306 | except Exception: |
|
306 | except Exception: | |
307 | # HasTraits should call set_default_value to populate |
|
307 | # HasTraits should call set_default_value to populate | |
308 | # this. So this should never be reached. |
|
308 | # this. So this should never be reached. | |
309 | raise TraitError('Unexpected error in TraitType: ' |
|
309 | raise TraitError('Unexpected error in TraitType: ' | |
310 | 'default value not set properly') |
|
310 | 'default value not set properly') | |
311 | else: |
|
311 | else: | |
312 | return value |
|
312 | return value | |
313 |
|
313 | |||
314 | def __set__(self, obj, value): |
|
314 | def __set__(self, obj, value): | |
315 | new_value = self._validate(obj, value) |
|
315 | new_value = self._validate(obj, value) | |
316 | old_value = self.__get__(obj) |
|
316 | old_value = self.__get__(obj) | |
317 | obj._trait_values[self.name] = new_value |
|
317 | obj._trait_values[self.name] = new_value | |
318 | if old_value != new_value: |
|
318 | if old_value != new_value: | |
319 | obj._notify_trait(self.name, old_value, new_value) |
|
319 | obj._notify_trait(self.name, old_value, new_value) | |
320 |
|
320 | |||
321 | def _validate(self, obj, value): |
|
321 | def _validate(self, obj, value): | |
322 | if hasattr(self, 'validate'): |
|
322 | if hasattr(self, 'validate'): | |
323 | return self.validate(obj, value) |
|
323 | return self.validate(obj, value) | |
324 | elif hasattr(self, 'is_valid_for'): |
|
324 | elif hasattr(self, 'is_valid_for'): | |
325 | valid = self.is_valid_for(value) |
|
325 | valid = self.is_valid_for(value) | |
326 | if valid: |
|
326 | if valid: | |
327 | return value |
|
327 | return value | |
328 | else: |
|
328 | else: | |
329 | raise TraitError('invalid value for type: %r' % value) |
|
329 | raise TraitError('invalid value for type: %r' % value) | |
330 | elif hasattr(self, 'value_for'): |
|
330 | elif hasattr(self, 'value_for'): | |
331 | return self.value_for(value) |
|
331 | return self.value_for(value) | |
332 | else: |
|
332 | else: | |
333 | return value |
|
333 | return value | |
334 |
|
334 | |||
335 | def info(self): |
|
335 | def info(self): | |
336 | return self.info_text |
|
336 | return self.info_text | |
337 |
|
337 | |||
338 | def error(self, obj, value): |
|
338 | def error(self, obj, value): | |
339 | if obj is not None: |
|
339 | if obj is not None: | |
340 | e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ |
|
340 | e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ | |
341 | % (self.name, class_of(obj), |
|
341 | % (self.name, class_of(obj), | |
342 | self.info(), repr_type(value)) |
|
342 | self.info(), repr_type(value)) | |
343 | else: |
|
343 | else: | |
344 | e = "The '%s' trait must be %s, but a value of %r was specified." \ |
|
344 | e = "The '%s' trait must be %s, but a value of %r was specified." \ | |
345 | % (self.name, self.info(), repr_type(value)) |
|
345 | % (self.name, self.info(), repr_type(value)) | |
346 | raise TraitError(e) |
|
346 | raise TraitError(e) | |
347 |
|
347 | |||
348 | def get_metadata(self, key): |
|
348 | def get_metadata(self, key): | |
349 | return getattr(self, '_metadata', {}).get(key, None) |
|
349 | return getattr(self, '_metadata', {}).get(key, None) | |
350 |
|
350 | |||
351 | def set_metadata(self, key, value): |
|
351 | def set_metadata(self, key, value): | |
352 | getattr(self, '_metadata', {})[key] = value |
|
352 | getattr(self, '_metadata', {})[key] = value | |
353 |
|
353 | |||
354 |
|
354 | |||
355 | #----------------------------------------------------------------------------- |
|
355 | #----------------------------------------------------------------------------- | |
356 | # The HasTraits implementation |
|
356 | # The HasTraits implementation | |
357 | #----------------------------------------------------------------------------- |
|
357 | #----------------------------------------------------------------------------- | |
358 |
|
358 | |||
359 |
|
359 | |||
360 | class MetaHasTraits(type): |
|
360 | class MetaHasTraits(type): | |
361 | """A metaclass for HasTraits. |
|
361 | """A metaclass for HasTraits. | |
362 |
|
362 | |||
363 | This metaclass makes sure that any TraitType class attributes are |
|
363 | This metaclass makes sure that any TraitType class attributes are | |
364 | instantiated and sets their name attribute. |
|
364 | instantiated and sets their name attribute. | |
365 | """ |
|
365 | """ | |
366 |
|
366 | |||
367 | def __new__(mcls, name, bases, classdict): |
|
367 | def __new__(mcls, name, bases, classdict): | |
368 | """Create the HasTraits class. |
|
368 | """Create the HasTraits class. | |
369 |
|
369 | |||
370 | This instantiates all TraitTypes in the class dict and sets their |
|
370 | This instantiates all TraitTypes in the class dict and sets their | |
371 | :attr:`name` attribute. |
|
371 | :attr:`name` attribute. | |
372 | """ |
|
372 | """ | |
373 | # print "MetaHasTraitlets (mcls, name): ", mcls, name |
|
373 | # print "MetaHasTraitlets (mcls, name): ", mcls, name | |
374 | # print "MetaHasTraitlets (bases): ", bases |
|
374 | # print "MetaHasTraitlets (bases): ", bases | |
375 | # print "MetaHasTraitlets (classdict): ", classdict |
|
375 | # print "MetaHasTraitlets (classdict): ", classdict | |
376 | for k,v in classdict.iteritems(): |
|
376 | for k,v in classdict.iteritems(): | |
377 | if isinstance(v, TraitType): |
|
377 | if isinstance(v, TraitType): | |
378 | v.name = k |
|
378 | v.name = k | |
379 | elif inspect.isclass(v): |
|
379 | elif inspect.isclass(v): | |
380 | if issubclass(v, TraitType): |
|
380 | if issubclass(v, TraitType): | |
381 | vinst = v() |
|
381 | vinst = v() | |
382 | vinst.name = k |
|
382 | vinst.name = k | |
383 | classdict[k] = vinst |
|
383 | classdict[k] = vinst | |
384 | return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict) |
|
384 | return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict) | |
385 |
|
385 | |||
386 | def __init__(cls, name, bases, classdict): |
|
386 | def __init__(cls, name, bases, classdict): | |
387 | """Finish initializing the HasTraits class. |
|
387 | """Finish initializing the HasTraits class. | |
388 |
|
388 | |||
389 | This sets the :attr:`this_class` attribute of each TraitType in the |
|
389 | This sets the :attr:`this_class` attribute of each TraitType in the | |
390 | class dict to the newly created class ``cls``. |
|
390 | class dict to the newly created class ``cls``. | |
391 | """ |
|
391 | """ | |
392 | for k, v in classdict.iteritems(): |
|
392 | for k, v in classdict.iteritems(): | |
393 | if isinstance(v, TraitType): |
|
393 | if isinstance(v, TraitType): | |
394 | v.this_class = cls |
|
394 | v.this_class = cls | |
395 | super(MetaHasTraits, cls).__init__(name, bases, classdict) |
|
395 | super(MetaHasTraits, cls).__init__(name, bases, classdict) | |
396 |
|
396 | |||
397 | class HasTraits(object): |
|
397 | class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)): | |
398 |
|
||||
399 | __metaclass__ = MetaHasTraits |
|
|||
400 |
|
398 | |||
401 | def __new__(cls, *args, **kw): |
|
399 | def __new__(cls, *args, **kw): | |
402 | # This is needed because in Python 2.6 object.__new__ only accepts |
|
400 | # This is needed because in Python 2.6 object.__new__ only accepts | |
403 | # the cls argument. |
|
401 | # the cls argument. | |
404 | new_meth = super(HasTraits, cls).__new__ |
|
402 | new_meth = super(HasTraits, cls).__new__ | |
405 | if new_meth is object.__new__: |
|
403 | if new_meth is object.__new__: | |
406 | inst = new_meth(cls) |
|
404 | inst = new_meth(cls) | |
407 | else: |
|
405 | else: | |
408 | inst = new_meth(cls, **kw) |
|
406 | inst = new_meth(cls, **kw) | |
409 | inst._trait_values = {} |
|
407 | inst._trait_values = {} | |
410 | inst._trait_notifiers = {} |
|
408 | inst._trait_notifiers = {} | |
411 | inst._trait_dyn_inits = {} |
|
409 | inst._trait_dyn_inits = {} | |
412 | # Here we tell all the TraitType instances to set their default |
|
410 | # Here we tell all the TraitType instances to set their default | |
413 | # values on the instance. |
|
411 | # values on the instance. | |
414 | for key in dir(cls): |
|
412 | for key in dir(cls): | |
415 | # Some descriptors raise AttributeError like zope.interface's |
|
413 | # Some descriptors raise AttributeError like zope.interface's | |
416 | # __provides__ attributes even though they exist. This causes |
|
414 | # __provides__ attributes even though they exist. This causes | |
417 | # AttributeErrors even though they are listed in dir(cls). |
|
415 | # AttributeErrors even though they are listed in dir(cls). | |
418 | try: |
|
416 | try: | |
419 | value = getattr(cls, key) |
|
417 | value = getattr(cls, key) | |
420 | except AttributeError: |
|
418 | except AttributeError: | |
421 | pass |
|
419 | pass | |
422 | else: |
|
420 | else: | |
423 | if isinstance(value, TraitType): |
|
421 | if isinstance(value, TraitType): | |
424 | value.instance_init(inst) |
|
422 | value.instance_init(inst) | |
425 |
|
423 | |||
426 | return inst |
|
424 | return inst | |
427 |
|
425 | |||
428 | def __init__(self, *args, **kw): |
|
426 | def __init__(self, *args, **kw): | |
429 | # Allow trait values to be set using keyword arguments. |
|
427 | # Allow trait values to be set using keyword arguments. | |
430 | # We need to use setattr for this to trigger validation and |
|
428 | # We need to use setattr for this to trigger validation and | |
431 | # notifications. |
|
429 | # notifications. | |
432 | for key, value in kw.iteritems(): |
|
430 | for key, value in kw.iteritems(): | |
433 | setattr(self, key, value) |
|
431 | setattr(self, key, value) | |
434 |
|
432 | |||
435 | def _notify_trait(self, name, old_value, new_value): |
|
433 | def _notify_trait(self, name, old_value, new_value): | |
436 |
|
434 | |||
437 | # First dynamic ones |
|
435 | # First dynamic ones | |
438 | callables = [] |
|
436 | callables = [] | |
439 | callables.extend(self._trait_notifiers.get(name,[])) |
|
437 | callables.extend(self._trait_notifiers.get(name,[])) | |
440 | callables.extend(self._trait_notifiers.get('anytrait',[])) |
|
438 | callables.extend(self._trait_notifiers.get('anytrait',[])) | |
441 |
|
439 | |||
442 | # Now static ones |
|
440 | # Now static ones | |
443 | try: |
|
441 | try: | |
444 | cb = getattr(self, '_%s_changed' % name) |
|
442 | cb = getattr(self, '_%s_changed' % name) | |
445 | except: |
|
443 | except: | |
446 | pass |
|
444 | pass | |
447 | else: |
|
445 | else: | |
448 | callables.append(cb) |
|
446 | callables.append(cb) | |
449 |
|
447 | |||
450 | # Call them all now |
|
448 | # Call them all now | |
451 | for c in callables: |
|
449 | for c in callables: | |
452 | # Traits catches and logs errors here. I allow them to raise |
|
450 | # Traits catches and logs errors here. I allow them to raise | |
453 | if callable(c): |
|
451 | if callable(c): | |
454 | argspec = inspect.getargspec(c) |
|
452 | argspec = inspect.getargspec(c) | |
455 | nargs = len(argspec[0]) |
|
453 | nargs = len(argspec[0]) | |
456 | # Bound methods have an additional 'self' argument |
|
454 | # Bound methods have an additional 'self' argument | |
457 | # I don't know how to treat unbound methods, but they |
|
455 | # I don't know how to treat unbound methods, but they | |
458 | # can't really be used for callbacks. |
|
456 | # can't really be used for callbacks. | |
459 | if isinstance(c, types.MethodType): |
|
457 | if isinstance(c, types.MethodType): | |
460 | offset = -1 |
|
458 | offset = -1 | |
461 | else: |
|
459 | else: | |
462 | offset = 0 |
|
460 | offset = 0 | |
463 | if nargs + offset == 0: |
|
461 | if nargs + offset == 0: | |
464 | c() |
|
462 | c() | |
465 | elif nargs + offset == 1: |
|
463 | elif nargs + offset == 1: | |
466 | c(name) |
|
464 | c(name) | |
467 | elif nargs + offset == 2: |
|
465 | elif nargs + offset == 2: | |
468 | c(name, new_value) |
|
466 | c(name, new_value) | |
469 | elif nargs + offset == 3: |
|
467 | elif nargs + offset == 3: | |
470 | c(name, old_value, new_value) |
|
468 | c(name, old_value, new_value) | |
471 | else: |
|
469 | else: | |
472 | raise TraitError('a trait changed callback ' |
|
470 | raise TraitError('a trait changed callback ' | |
473 | 'must have 0-3 arguments.') |
|
471 | 'must have 0-3 arguments.') | |
474 | else: |
|
472 | else: | |
475 | raise TraitError('a trait changed callback ' |
|
473 | raise TraitError('a trait changed callback ' | |
476 | 'must be callable.') |
|
474 | 'must be callable.') | |
477 |
|
475 | |||
478 |
|
476 | |||
479 | def _add_notifiers(self, handler, name): |
|
477 | def _add_notifiers(self, handler, name): | |
480 | if name not in self._trait_notifiers: |
|
478 | if name not in self._trait_notifiers: | |
481 | nlist = [] |
|
479 | nlist = [] | |
482 | self._trait_notifiers[name] = nlist |
|
480 | self._trait_notifiers[name] = nlist | |
483 | else: |
|
481 | else: | |
484 | nlist = self._trait_notifiers[name] |
|
482 | nlist = self._trait_notifiers[name] | |
485 | if handler not in nlist: |
|
483 | if handler not in nlist: | |
486 | nlist.append(handler) |
|
484 | nlist.append(handler) | |
487 |
|
485 | |||
488 | def _remove_notifiers(self, handler, name): |
|
486 | def _remove_notifiers(self, handler, name): | |
489 | if name in self._trait_notifiers: |
|
487 | if name in self._trait_notifiers: | |
490 | nlist = self._trait_notifiers[name] |
|
488 | nlist = self._trait_notifiers[name] | |
491 | try: |
|
489 | try: | |
492 | index = nlist.index(handler) |
|
490 | index = nlist.index(handler) | |
493 | except ValueError: |
|
491 | except ValueError: | |
494 | pass |
|
492 | pass | |
495 | else: |
|
493 | else: | |
496 | del nlist[index] |
|
494 | del nlist[index] | |
497 |
|
495 | |||
498 | def on_trait_change(self, handler, name=None, remove=False): |
|
496 | def on_trait_change(self, handler, name=None, remove=False): | |
499 | """Setup a handler to be called when a trait changes. |
|
497 | """Setup a handler to be called when a trait changes. | |
500 |
|
498 | |||
501 | This is used to setup dynamic notifications of trait changes. |
|
499 | This is used to setup dynamic notifications of trait changes. | |
502 |
|
500 | |||
503 | Static handlers can be created by creating methods on a HasTraits |
|
501 | Static handlers can be created by creating methods on a HasTraits | |
504 | subclass with the naming convention '_[traitname]_changed'. Thus, |
|
502 | subclass with the naming convention '_[traitname]_changed'. Thus, | |
505 | to create static handler for the trait 'a', create the method |
|
503 | to create static handler for the trait 'a', create the method | |
506 | _a_changed(self, name, old, new) (fewer arguments can be used, see |
|
504 | _a_changed(self, name, old, new) (fewer arguments can be used, see | |
507 | below). |
|
505 | below). | |
508 |
|
506 | |||
509 | Parameters |
|
507 | Parameters | |
510 | ---------- |
|
508 | ---------- | |
511 | handler : callable |
|
509 | handler : callable | |
512 | A callable that is called when a trait changes. Its |
|
510 | A callable that is called when a trait changes. Its | |
513 | signature can be handler(), handler(name), handler(name, new) |
|
511 | signature can be handler(), handler(name), handler(name, new) | |
514 | or handler(name, old, new). |
|
512 | or handler(name, old, new). | |
515 | name : list, str, None |
|
513 | name : list, str, None | |
516 | If None, the handler will apply to all traits. If a list |
|
514 | If None, the handler will apply to all traits. If a list | |
517 | of str, handler will apply to all names in the list. If a |
|
515 | of str, handler will apply to all names in the list. If a | |
518 | str, the handler will apply just to that name. |
|
516 | str, the handler will apply just to that name. | |
519 | remove : bool |
|
517 | remove : bool | |
520 | If False (the default), then install the handler. If True |
|
518 | If False (the default), then install the handler. If True | |
521 | then unintall it. |
|
519 | then unintall it. | |
522 | """ |
|
520 | """ | |
523 | if remove: |
|
521 | if remove: | |
524 | names = parse_notifier_name(name) |
|
522 | names = parse_notifier_name(name) | |
525 | for n in names: |
|
523 | for n in names: | |
526 | self._remove_notifiers(handler, n) |
|
524 | self._remove_notifiers(handler, n) | |
527 | else: |
|
525 | else: | |
528 | names = parse_notifier_name(name) |
|
526 | names = parse_notifier_name(name) | |
529 | for n in names: |
|
527 | for n in names: | |
530 | self._add_notifiers(handler, n) |
|
528 | self._add_notifiers(handler, n) | |
531 |
|
529 | |||
532 | @classmethod |
|
530 | @classmethod | |
533 | def class_trait_names(cls, **metadata): |
|
531 | def class_trait_names(cls, **metadata): | |
534 | """Get a list of all the names of this classes traits. |
|
532 | """Get a list of all the names of this classes traits. | |
535 |
|
533 | |||
536 | This method is just like the :meth:`trait_names` method, but is unbound. |
|
534 | This method is just like the :meth:`trait_names` method, but is unbound. | |
537 | """ |
|
535 | """ | |
538 | return cls.class_traits(**metadata).keys() |
|
536 | return cls.class_traits(**metadata).keys() | |
539 |
|
537 | |||
540 | @classmethod |
|
538 | @classmethod | |
541 | def class_traits(cls, **metadata): |
|
539 | def class_traits(cls, **metadata): | |
542 | """Get a list of all the traits of this class. |
|
540 | """Get a list of all the traits of this class. | |
543 |
|
541 | |||
544 | This method is just like the :meth:`traits` method, but is unbound. |
|
542 | This method is just like the :meth:`traits` method, but is unbound. | |
545 |
|
543 | |||
546 | The TraitTypes returned don't know anything about the values |
|
544 | The TraitTypes returned don't know anything about the values | |
547 | that the various HasTrait's instances are holding. |
|
545 | that the various HasTrait's instances are holding. | |
548 |
|
546 | |||
549 | This follows the same algorithm as traits does and does not allow |
|
547 | This follows the same algorithm as traits does and does not allow | |
550 | for any simple way of specifying merely that a metadata name |
|
548 | for any simple way of specifying merely that a metadata name | |
551 | exists, but has any value. This is because get_metadata returns |
|
549 | exists, but has any value. This is because get_metadata returns | |
552 | None if a metadata key doesn't exist. |
|
550 | None if a metadata key doesn't exist. | |
553 | """ |
|
551 | """ | |
554 | traits = dict([memb for memb in getmembers(cls) if \ |
|
552 | traits = dict([memb for memb in getmembers(cls) if \ | |
555 | isinstance(memb[1], TraitType)]) |
|
553 | isinstance(memb[1], TraitType)]) | |
556 |
|
554 | |||
557 | if len(metadata) == 0: |
|
555 | if len(metadata) == 0: | |
558 | return traits |
|
556 | return traits | |
559 |
|
557 | |||
560 | for meta_name, meta_eval in metadata.items(): |
|
558 | for meta_name, meta_eval in metadata.items(): | |
561 | if type(meta_eval) is not FunctionType: |
|
559 | if type(meta_eval) is not FunctionType: | |
562 | metadata[meta_name] = _SimpleTest(meta_eval) |
|
560 | metadata[meta_name] = _SimpleTest(meta_eval) | |
563 |
|
561 | |||
564 | result = {} |
|
562 | result = {} | |
565 | for name, trait in traits.items(): |
|
563 | for name, trait in traits.items(): | |
566 | for meta_name, meta_eval in metadata.items(): |
|
564 | for meta_name, meta_eval in metadata.items(): | |
567 | if not meta_eval(trait.get_metadata(meta_name)): |
|
565 | if not meta_eval(trait.get_metadata(meta_name)): | |
568 | break |
|
566 | break | |
569 | else: |
|
567 | else: | |
570 | result[name] = trait |
|
568 | result[name] = trait | |
571 |
|
569 | |||
572 | return result |
|
570 | return result | |
573 |
|
571 | |||
574 | def trait_names(self, **metadata): |
|
572 | def trait_names(self, **metadata): | |
575 | """Get a list of all the names of this classes traits.""" |
|
573 | """Get a list of all the names of this classes traits.""" | |
576 | return self.traits(**metadata).keys() |
|
574 | return self.traits(**metadata).keys() | |
577 |
|
575 | |||
578 | def traits(self, **metadata): |
|
576 | def traits(self, **metadata): | |
579 | """Get a list of all the traits of this class. |
|
577 | """Get a list of all the traits of this class. | |
580 |
|
578 | |||
581 | The TraitTypes returned don't know anything about the values |
|
579 | The TraitTypes returned don't know anything about the values | |
582 | that the various HasTrait's instances are holding. |
|
580 | that the various HasTrait's instances are holding. | |
583 |
|
581 | |||
584 | This follows the same algorithm as traits does and does not allow |
|
582 | This follows the same algorithm as traits does and does not allow | |
585 | for any simple way of specifying merely that a metadata name |
|
583 | for any simple way of specifying merely that a metadata name | |
586 | exists, but has any value. This is because get_metadata returns |
|
584 | exists, but has any value. This is because get_metadata returns | |
587 | None if a metadata key doesn't exist. |
|
585 | None if a metadata key doesn't exist. | |
588 | """ |
|
586 | """ | |
589 | traits = dict([memb for memb in getmembers(self.__class__) if \ |
|
587 | traits = dict([memb for memb in getmembers(self.__class__) if \ | |
590 | isinstance(memb[1], TraitType)]) |
|
588 | isinstance(memb[1], TraitType)]) | |
591 |
|
589 | |||
592 | if len(metadata) == 0: |
|
590 | if len(metadata) == 0: | |
593 | return traits |
|
591 | return traits | |
594 |
|
592 | |||
595 | for meta_name, meta_eval in metadata.items(): |
|
593 | for meta_name, meta_eval in metadata.items(): | |
596 | if type(meta_eval) is not FunctionType: |
|
594 | if type(meta_eval) is not FunctionType: | |
597 | metadata[meta_name] = _SimpleTest(meta_eval) |
|
595 | metadata[meta_name] = _SimpleTest(meta_eval) | |
598 |
|
596 | |||
599 | result = {} |
|
597 | result = {} | |
600 | for name, trait in traits.items(): |
|
598 | for name, trait in traits.items(): | |
601 | for meta_name, meta_eval in metadata.items(): |
|
599 | for meta_name, meta_eval in metadata.items(): | |
602 | if not meta_eval(trait.get_metadata(meta_name)): |
|
600 | if not meta_eval(trait.get_metadata(meta_name)): | |
603 | break |
|
601 | break | |
604 | else: |
|
602 | else: | |
605 | result[name] = trait |
|
603 | result[name] = trait | |
606 |
|
604 | |||
607 | return result |
|
605 | return result | |
608 |
|
606 | |||
609 | def trait_metadata(self, traitname, key): |
|
607 | def trait_metadata(self, traitname, key): | |
610 | """Get metadata values for trait by key.""" |
|
608 | """Get metadata values for trait by key.""" | |
611 | try: |
|
609 | try: | |
612 | trait = getattr(self.__class__, traitname) |
|
610 | trait = getattr(self.__class__, traitname) | |
613 | except AttributeError: |
|
611 | except AttributeError: | |
614 | raise TraitError("Class %s does not have a trait named %s" % |
|
612 | raise TraitError("Class %s does not have a trait named %s" % | |
615 | (self.__class__.__name__, traitname)) |
|
613 | (self.__class__.__name__, traitname)) | |
616 | else: |
|
614 | else: | |
617 | return trait.get_metadata(key) |
|
615 | return trait.get_metadata(key) | |
618 |
|
616 | |||
619 | #----------------------------------------------------------------------------- |
|
617 | #----------------------------------------------------------------------------- | |
620 | # Actual TraitTypes implementations/subclasses |
|
618 | # Actual TraitTypes implementations/subclasses | |
621 | #----------------------------------------------------------------------------- |
|
619 | #----------------------------------------------------------------------------- | |
622 |
|
620 | |||
623 | #----------------------------------------------------------------------------- |
|
621 | #----------------------------------------------------------------------------- | |
624 | # TraitTypes subclasses for handling classes and instances of classes |
|
622 | # TraitTypes subclasses for handling classes and instances of classes | |
625 | #----------------------------------------------------------------------------- |
|
623 | #----------------------------------------------------------------------------- | |
626 |
|
624 | |||
627 |
|
625 | |||
628 | class ClassBasedTraitType(TraitType): |
|
626 | class ClassBasedTraitType(TraitType): | |
629 | """A trait with error reporting for Type, Instance and This.""" |
|
627 | """A trait with error reporting for Type, Instance and This.""" | |
630 |
|
628 | |||
631 | def error(self, obj, value): |
|
629 | def error(self, obj, value): | |
632 | kind = type(value) |
|
630 | kind = type(value) | |
633 | if (not py3compat.PY3) and kind is InstanceType: |
|
631 | if (not py3compat.PY3) and kind is InstanceType: | |
634 | msg = 'class %s' % value.__class__.__name__ |
|
632 | msg = 'class %s' % value.__class__.__name__ | |
635 | else: |
|
633 | else: | |
636 | msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) ) |
|
634 | msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) ) | |
637 |
|
635 | |||
638 | if obj is not None: |
|
636 | if obj is not None: | |
639 | e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ |
|
637 | e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \ | |
640 | % (self.name, class_of(obj), |
|
638 | % (self.name, class_of(obj), | |
641 | self.info(), msg) |
|
639 | self.info(), msg) | |
642 | else: |
|
640 | else: | |
643 | e = "The '%s' trait must be %s, but a value of %r was specified." \ |
|
641 | e = "The '%s' trait must be %s, but a value of %r was specified." \ | |
644 | % (self.name, self.info(), msg) |
|
642 | % (self.name, self.info(), msg) | |
645 |
|
643 | |||
646 | raise TraitError(e) |
|
644 | raise TraitError(e) | |
647 |
|
645 | |||
648 |
|
646 | |||
649 | class Type(ClassBasedTraitType): |
|
647 | class Type(ClassBasedTraitType): | |
650 | """A trait whose value must be a subclass of a specified class.""" |
|
648 | """A trait whose value must be a subclass of a specified class.""" | |
651 |
|
649 | |||
652 | def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ): |
|
650 | def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ): | |
653 | """Construct a Type trait |
|
651 | """Construct a Type trait | |
654 |
|
652 | |||
655 | A Type trait specifies that its values must be subclasses of |
|
653 | A Type trait specifies that its values must be subclasses of | |
656 | a particular class. |
|
654 | a particular class. | |
657 |
|
655 | |||
658 | If only ``default_value`` is given, it is used for the ``klass`` as |
|
656 | If only ``default_value`` is given, it is used for the ``klass`` as | |
659 | well. |
|
657 | well. | |
660 |
|
658 | |||
661 | Parameters |
|
659 | Parameters | |
662 | ---------- |
|
660 | ---------- | |
663 | default_value : class, str or None |
|
661 | default_value : class, str or None | |
664 | The default value must be a subclass of klass. If an str, |
|
662 | The default value must be a subclass of klass. If an str, | |
665 | the str must be a fully specified class name, like 'foo.bar.Bah'. |
|
663 | the str must be a fully specified class name, like 'foo.bar.Bah'. | |
666 | The string is resolved into real class, when the parent |
|
664 | The string is resolved into real class, when the parent | |
667 | :class:`HasTraits` class is instantiated. |
|
665 | :class:`HasTraits` class is instantiated. | |
668 | klass : class, str, None |
|
666 | klass : class, str, None | |
669 | Values of this trait must be a subclass of klass. The klass |
|
667 | Values of this trait must be a subclass of klass. The klass | |
670 | may be specified in a string like: 'foo.bar.MyClass'. |
|
668 | may be specified in a string like: 'foo.bar.MyClass'. | |
671 | The string is resolved into real class, when the parent |
|
669 | The string is resolved into real class, when the parent | |
672 | :class:`HasTraits` class is instantiated. |
|
670 | :class:`HasTraits` class is instantiated. | |
673 | allow_none : boolean |
|
671 | allow_none : boolean | |
674 | Indicates whether None is allowed as an assignable value. Even if |
|
672 | Indicates whether None is allowed as an assignable value. Even if | |
675 | ``False``, the default value may be ``None``. |
|
673 | ``False``, the default value may be ``None``. | |
676 | """ |
|
674 | """ | |
677 | if default_value is None: |
|
675 | if default_value is None: | |
678 | if klass is None: |
|
676 | if klass is None: | |
679 | klass = object |
|
677 | klass = object | |
680 | elif klass is None: |
|
678 | elif klass is None: | |
681 | klass = default_value |
|
679 | klass = default_value | |
682 |
|
680 | |||
683 | if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)): |
|
681 | if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)): | |
684 | raise TraitError("A Type trait must specify a class.") |
|
682 | raise TraitError("A Type trait must specify a class.") | |
685 |
|
683 | |||
686 | self.klass = klass |
|
684 | self.klass = klass | |
687 | self._allow_none = allow_none |
|
685 | self._allow_none = allow_none | |
688 |
|
686 | |||
689 | super(Type, self).__init__(default_value, **metadata) |
|
687 | super(Type, self).__init__(default_value, **metadata) | |
690 |
|
688 | |||
691 | def validate(self, obj, value): |
|
689 | def validate(self, obj, value): | |
692 | """Validates that the value is a valid object instance.""" |
|
690 | """Validates that the value is a valid object instance.""" | |
693 | try: |
|
691 | try: | |
694 | if issubclass(value, self.klass): |
|
692 | if issubclass(value, self.klass): | |
695 | return value |
|
693 | return value | |
696 | except: |
|
694 | except: | |
697 | if (value is None) and (self._allow_none): |
|
695 | if (value is None) and (self._allow_none): | |
698 | return value |
|
696 | return value | |
699 |
|
697 | |||
700 | self.error(obj, value) |
|
698 | self.error(obj, value) | |
701 |
|
699 | |||
702 | def info(self): |
|
700 | def info(self): | |
703 | """ Returns a description of the trait.""" |
|
701 | """ Returns a description of the trait.""" | |
704 | if isinstance(self.klass, py3compat.string_types): |
|
702 | if isinstance(self.klass, py3compat.string_types): | |
705 | klass = self.klass |
|
703 | klass = self.klass | |
706 | else: |
|
704 | else: | |
707 | klass = self.klass.__name__ |
|
705 | klass = self.klass.__name__ | |
708 | result = 'a subclass of ' + klass |
|
706 | result = 'a subclass of ' + klass | |
709 | if self._allow_none: |
|
707 | if self._allow_none: | |
710 | return result + ' or None' |
|
708 | return result + ' or None' | |
711 | return result |
|
709 | return result | |
712 |
|
710 | |||
713 | def instance_init(self, obj): |
|
711 | def instance_init(self, obj): | |
714 | self._resolve_classes() |
|
712 | self._resolve_classes() | |
715 | super(Type, self).instance_init(obj) |
|
713 | super(Type, self).instance_init(obj) | |
716 |
|
714 | |||
717 | def _resolve_classes(self): |
|
715 | def _resolve_classes(self): | |
718 | if isinstance(self.klass, py3compat.string_types): |
|
716 | if isinstance(self.klass, py3compat.string_types): | |
719 | self.klass = import_item(self.klass) |
|
717 | self.klass = import_item(self.klass) | |
720 | if isinstance(self.default_value, py3compat.string_types): |
|
718 | if isinstance(self.default_value, py3compat.string_types): | |
721 | self.default_value = import_item(self.default_value) |
|
719 | self.default_value = import_item(self.default_value) | |
722 |
|
720 | |||
723 | def get_default_value(self): |
|
721 | def get_default_value(self): | |
724 | return self.default_value |
|
722 | return self.default_value | |
725 |
|
723 | |||
726 |
|
724 | |||
727 | class DefaultValueGenerator(object): |
|
725 | class DefaultValueGenerator(object): | |
728 | """A class for generating new default value instances.""" |
|
726 | """A class for generating new default value instances.""" | |
729 |
|
727 | |||
730 | def __init__(self, *args, **kw): |
|
728 | def __init__(self, *args, **kw): | |
731 | self.args = args |
|
729 | self.args = args | |
732 | self.kw = kw |
|
730 | self.kw = kw | |
733 |
|
731 | |||
734 | def generate(self, klass): |
|
732 | def generate(self, klass): | |
735 | return klass(*self.args, **self.kw) |
|
733 | return klass(*self.args, **self.kw) | |
736 |
|
734 | |||
737 |
|
735 | |||
738 | class Instance(ClassBasedTraitType): |
|
736 | class Instance(ClassBasedTraitType): | |
739 | """A trait whose value must be an instance of a specified class. |
|
737 | """A trait whose value must be an instance of a specified class. | |
740 |
|
738 | |||
741 | The value can also be an instance of a subclass of the specified class. |
|
739 | The value can also be an instance of a subclass of the specified class. | |
742 | """ |
|
740 | """ | |
743 |
|
741 | |||
744 | def __init__(self, klass=None, args=None, kw=None, |
|
742 | def __init__(self, klass=None, args=None, kw=None, | |
745 | allow_none=True, **metadata ): |
|
743 | allow_none=True, **metadata ): | |
746 | """Construct an Instance trait. |
|
744 | """Construct an Instance trait. | |
747 |
|
745 | |||
748 | This trait allows values that are instances of a particular |
|
746 | This trait allows values that are instances of a particular | |
749 | class or its sublclasses. Our implementation is quite different |
|
747 | class or its sublclasses. Our implementation is quite different | |
750 | from that of enthough.traits as we don't allow instances to be used |
|
748 | from that of enthough.traits as we don't allow instances to be used | |
751 | for klass and we handle the ``args`` and ``kw`` arguments differently. |
|
749 | for klass and we handle the ``args`` and ``kw`` arguments differently. | |
752 |
|
750 | |||
753 | Parameters |
|
751 | Parameters | |
754 | ---------- |
|
752 | ---------- | |
755 | klass : class, str |
|
753 | klass : class, str | |
756 | The class that forms the basis for the trait. Class names |
|
754 | The class that forms the basis for the trait. Class names | |
757 | can also be specified as strings, like 'foo.bar.Bar'. |
|
755 | can also be specified as strings, like 'foo.bar.Bar'. | |
758 | args : tuple |
|
756 | args : tuple | |
759 | Positional arguments for generating the default value. |
|
757 | Positional arguments for generating the default value. | |
760 | kw : dict |
|
758 | kw : dict | |
761 | Keyword arguments for generating the default value. |
|
759 | Keyword arguments for generating the default value. | |
762 | allow_none : bool |
|
760 | allow_none : bool | |
763 | Indicates whether None is allowed as a value. |
|
761 | Indicates whether None is allowed as a value. | |
764 |
|
762 | |||
765 | Default Value |
|
763 | Default Value | |
766 | ------------- |
|
764 | ------------- | |
767 | If both ``args`` and ``kw`` are None, then the default value is None. |
|
765 | If both ``args`` and ``kw`` are None, then the default value is None. | |
768 | If ``args`` is a tuple and ``kw`` is a dict, then the default is |
|
766 | If ``args`` is a tuple and ``kw`` is a dict, then the default is | |
769 | created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is |
|
767 | created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is | |
770 | not (but not both), None is replace by ``()`` or ``{}``. |
|
768 | not (but not both), None is replace by ``()`` or ``{}``. | |
771 | """ |
|
769 | """ | |
772 |
|
770 | |||
773 | self._allow_none = allow_none |
|
771 | self._allow_none = allow_none | |
774 |
|
772 | |||
775 | if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types))): |
|
773 | if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types))): | |
776 | raise TraitError('The klass argument must be a class' |
|
774 | raise TraitError('The klass argument must be a class' | |
777 | ' you gave: %r' % klass) |
|
775 | ' you gave: %r' % klass) | |
778 | self.klass = klass |
|
776 | self.klass = klass | |
779 |
|
777 | |||
780 | # self.klass is a class, so handle default_value |
|
778 | # self.klass is a class, so handle default_value | |
781 | if args is None and kw is None: |
|
779 | if args is None and kw is None: | |
782 | default_value = None |
|
780 | default_value = None | |
783 | else: |
|
781 | else: | |
784 | if args is None: |
|
782 | if args is None: | |
785 | # kw is not None |
|
783 | # kw is not None | |
786 | args = () |
|
784 | args = () | |
787 | elif kw is None: |
|
785 | elif kw is None: | |
788 | # args is not None |
|
786 | # args is not None | |
789 | kw = {} |
|
787 | kw = {} | |
790 |
|
788 | |||
791 | if not isinstance(kw, dict): |
|
789 | if not isinstance(kw, dict): | |
792 | raise TraitError("The 'kw' argument must be a dict or None.") |
|
790 | raise TraitError("The 'kw' argument must be a dict or None.") | |
793 | if not isinstance(args, tuple): |
|
791 | if not isinstance(args, tuple): | |
794 | raise TraitError("The 'args' argument must be a tuple or None.") |
|
792 | raise TraitError("The 'args' argument must be a tuple or None.") | |
795 |
|
793 | |||
796 | default_value = DefaultValueGenerator(*args, **kw) |
|
794 | default_value = DefaultValueGenerator(*args, **kw) | |
797 |
|
795 | |||
798 | super(Instance, self).__init__(default_value, **metadata) |
|
796 | super(Instance, self).__init__(default_value, **metadata) | |
799 |
|
797 | |||
800 | def validate(self, obj, value): |
|
798 | def validate(self, obj, value): | |
801 | if value is None: |
|
799 | if value is None: | |
802 | if self._allow_none: |
|
800 | if self._allow_none: | |
803 | return value |
|
801 | return value | |
804 | self.error(obj, value) |
|
802 | self.error(obj, value) | |
805 |
|
803 | |||
806 | if isinstance(value, self.klass): |
|
804 | if isinstance(value, self.klass): | |
807 | return value |
|
805 | return value | |
808 | else: |
|
806 | else: | |
809 | self.error(obj, value) |
|
807 | self.error(obj, value) | |
810 |
|
808 | |||
811 | def info(self): |
|
809 | def info(self): | |
812 | if isinstance(self.klass, py3compat.string_types): |
|
810 | if isinstance(self.klass, py3compat.string_types): | |
813 | klass = self.klass |
|
811 | klass = self.klass | |
814 | else: |
|
812 | else: | |
815 | klass = self.klass.__name__ |
|
813 | klass = self.klass.__name__ | |
816 | result = class_of(klass) |
|
814 | result = class_of(klass) | |
817 | if self._allow_none: |
|
815 | if self._allow_none: | |
818 | return result + ' or None' |
|
816 | return result + ' or None' | |
819 |
|
817 | |||
820 | return result |
|
818 | return result | |
821 |
|
819 | |||
822 | def instance_init(self, obj): |
|
820 | def instance_init(self, obj): | |
823 | self._resolve_classes() |
|
821 | self._resolve_classes() | |
824 | super(Instance, self).instance_init(obj) |
|
822 | super(Instance, self).instance_init(obj) | |
825 |
|
823 | |||
826 | def _resolve_classes(self): |
|
824 | def _resolve_classes(self): | |
827 | if isinstance(self.klass, py3compat.string_types): |
|
825 | if isinstance(self.klass, py3compat.string_types): | |
828 | self.klass = import_item(self.klass) |
|
826 | self.klass = import_item(self.klass) | |
829 |
|
827 | |||
830 | def get_default_value(self): |
|
828 | def get_default_value(self): | |
831 | """Instantiate a default value instance. |
|
829 | """Instantiate a default value instance. | |
832 |
|
830 | |||
833 | This is called when the containing HasTraits classes' |
|
831 | This is called when the containing HasTraits classes' | |
834 | :meth:`__new__` method is called to ensure that a unique instance |
|
832 | :meth:`__new__` method is called to ensure that a unique instance | |
835 | is created for each HasTraits instance. |
|
833 | is created for each HasTraits instance. | |
836 | """ |
|
834 | """ | |
837 | dv = self.default_value |
|
835 | dv = self.default_value | |
838 | if isinstance(dv, DefaultValueGenerator): |
|
836 | if isinstance(dv, DefaultValueGenerator): | |
839 | return dv.generate(self.klass) |
|
837 | return dv.generate(self.klass) | |
840 | else: |
|
838 | else: | |
841 | return dv |
|
839 | return dv | |
842 |
|
840 | |||
843 |
|
841 | |||
844 | class This(ClassBasedTraitType): |
|
842 | class This(ClassBasedTraitType): | |
845 | """A trait for instances of the class containing this trait. |
|
843 | """A trait for instances of the class containing this trait. | |
846 |
|
844 | |||
847 | Because how how and when class bodies are executed, the ``This`` |
|
845 | Because how how and when class bodies are executed, the ``This`` | |
848 | trait can only have a default value of None. This, and because we |
|
846 | trait can only have a default value of None. This, and because we | |
849 | always validate default values, ``allow_none`` is *always* true. |
|
847 | always validate default values, ``allow_none`` is *always* true. | |
850 | """ |
|
848 | """ | |
851 |
|
849 | |||
852 | info_text = 'an instance of the same type as the receiver or None' |
|
850 | info_text = 'an instance of the same type as the receiver or None' | |
853 |
|
851 | |||
854 | def __init__(self, **metadata): |
|
852 | def __init__(self, **metadata): | |
855 | super(This, self).__init__(None, **metadata) |
|
853 | super(This, self).__init__(None, **metadata) | |
856 |
|
854 | |||
857 | def validate(self, obj, value): |
|
855 | def validate(self, obj, value): | |
858 | # What if value is a superclass of obj.__class__? This is |
|
856 | # What if value is a superclass of obj.__class__? This is | |
859 | # complicated if it was the superclass that defined the This |
|
857 | # complicated if it was the superclass that defined the This | |
860 | # trait. |
|
858 | # trait. | |
861 | if isinstance(value, self.this_class) or (value is None): |
|
859 | if isinstance(value, self.this_class) or (value is None): | |
862 | return value |
|
860 | return value | |
863 | else: |
|
861 | else: | |
864 | self.error(obj, value) |
|
862 | self.error(obj, value) | |
865 |
|
863 | |||
866 |
|
864 | |||
867 | #----------------------------------------------------------------------------- |
|
865 | #----------------------------------------------------------------------------- | |
868 | # Basic TraitTypes implementations/subclasses |
|
866 | # Basic TraitTypes implementations/subclasses | |
869 | #----------------------------------------------------------------------------- |
|
867 | #----------------------------------------------------------------------------- | |
870 |
|
868 | |||
871 |
|
869 | |||
872 | class Any(TraitType): |
|
870 | class Any(TraitType): | |
873 | default_value = None |
|
871 | default_value = None | |
874 | info_text = 'any value' |
|
872 | info_text = 'any value' | |
875 |
|
873 | |||
876 |
|
874 | |||
877 | class Int(TraitType): |
|
875 | class Int(TraitType): | |
878 | """An int trait.""" |
|
876 | """An int trait.""" | |
879 |
|
877 | |||
880 | default_value = 0 |
|
878 | default_value = 0 | |
881 | info_text = 'an int' |
|
879 | info_text = 'an int' | |
882 |
|
880 | |||
883 | def validate(self, obj, value): |
|
881 | def validate(self, obj, value): | |
884 | if isinstance(value, int): |
|
882 | if isinstance(value, int): | |
885 | return value |
|
883 | return value | |
886 | self.error(obj, value) |
|
884 | self.error(obj, value) | |
887 |
|
885 | |||
888 | class CInt(Int): |
|
886 | class CInt(Int): | |
889 | """A casting version of the int trait.""" |
|
887 | """A casting version of the int trait.""" | |
890 |
|
888 | |||
891 | def validate(self, obj, value): |
|
889 | def validate(self, obj, value): | |
892 | try: |
|
890 | try: | |
893 | return int(value) |
|
891 | return int(value) | |
894 | except: |
|
892 | except: | |
895 | self.error(obj, value) |
|
893 | self.error(obj, value) | |
896 |
|
894 | |||
897 | if py3compat.PY3: |
|
895 | if py3compat.PY3: | |
898 | Long, CLong = Int, CInt |
|
896 | Long, CLong = Int, CInt | |
899 | Integer = Int |
|
897 | Integer = Int | |
900 | else: |
|
898 | else: | |
901 | class Long(TraitType): |
|
899 | class Long(TraitType): | |
902 | """A long integer trait.""" |
|
900 | """A long integer trait.""" | |
903 |
|
901 | |||
904 | default_value = 0 |
|
902 | default_value = 0 | |
905 | info_text = 'a long' |
|
903 | info_text = 'a long' | |
906 |
|
904 | |||
907 | def validate(self, obj, value): |
|
905 | def validate(self, obj, value): | |
908 | if isinstance(value, long): |
|
906 | if isinstance(value, long): | |
909 | return value |
|
907 | return value | |
910 | if isinstance(value, int): |
|
908 | if isinstance(value, int): | |
911 | return long(value) |
|
909 | return long(value) | |
912 | self.error(obj, value) |
|
910 | self.error(obj, value) | |
913 |
|
911 | |||
914 |
|
912 | |||
915 | class CLong(Long): |
|
913 | class CLong(Long): | |
916 | """A casting version of the long integer trait.""" |
|
914 | """A casting version of the long integer trait.""" | |
917 |
|
915 | |||
918 | def validate(self, obj, value): |
|
916 | def validate(self, obj, value): | |
919 | try: |
|
917 | try: | |
920 | return long(value) |
|
918 | return long(value) | |
921 | except: |
|
919 | except: | |
922 | self.error(obj, value) |
|
920 | self.error(obj, value) | |
923 |
|
921 | |||
924 | class Integer(TraitType): |
|
922 | class Integer(TraitType): | |
925 | """An integer trait. |
|
923 | """An integer trait. | |
926 |
|
924 | |||
927 | Longs that are unnecessary (<= sys.maxint) are cast to ints.""" |
|
925 | Longs that are unnecessary (<= sys.maxint) are cast to ints.""" | |
928 |
|
926 | |||
929 | default_value = 0 |
|
927 | default_value = 0 | |
930 | info_text = 'an integer' |
|
928 | info_text = 'an integer' | |
931 |
|
929 | |||
932 | def validate(self, obj, value): |
|
930 | def validate(self, obj, value): | |
933 | if isinstance(value, int): |
|
931 | if isinstance(value, int): | |
934 | return value |
|
932 | return value | |
935 | if isinstance(value, long): |
|
933 | if isinstance(value, long): | |
936 | # downcast longs that fit in int: |
|
934 | # downcast longs that fit in int: | |
937 | # note that int(n > sys.maxint) returns a long, so |
|
935 | # note that int(n > sys.maxint) returns a long, so | |
938 | # we don't need a condition on this cast |
|
936 | # we don't need a condition on this cast | |
939 | return int(value) |
|
937 | return int(value) | |
940 | if sys.platform == "cli": |
|
938 | if sys.platform == "cli": | |
941 | from System import Int64 |
|
939 | from System import Int64 | |
942 | if isinstance(value, Int64): |
|
940 | if isinstance(value, Int64): | |
943 | return int(value) |
|
941 | return int(value) | |
944 | self.error(obj, value) |
|
942 | self.error(obj, value) | |
945 |
|
943 | |||
946 |
|
944 | |||
947 | class Float(TraitType): |
|
945 | class Float(TraitType): | |
948 | """A float trait.""" |
|
946 | """A float trait.""" | |
949 |
|
947 | |||
950 | default_value = 0.0 |
|
948 | default_value = 0.0 | |
951 | info_text = 'a float' |
|
949 | info_text = 'a float' | |
952 |
|
950 | |||
953 | def validate(self, obj, value): |
|
951 | def validate(self, obj, value): | |
954 | if isinstance(value, float): |
|
952 | if isinstance(value, float): | |
955 | return value |
|
953 | return value | |
956 | if isinstance(value, int): |
|
954 | if isinstance(value, int): | |
957 | return float(value) |
|
955 | return float(value) | |
958 | self.error(obj, value) |
|
956 | self.error(obj, value) | |
959 |
|
957 | |||
960 |
|
958 | |||
961 | class CFloat(Float): |
|
959 | class CFloat(Float): | |
962 | """A casting version of the float trait.""" |
|
960 | """A casting version of the float trait.""" | |
963 |
|
961 | |||
964 | def validate(self, obj, value): |
|
962 | def validate(self, obj, value): | |
965 | try: |
|
963 | try: | |
966 | return float(value) |
|
964 | return float(value) | |
967 | except: |
|
965 | except: | |
968 | self.error(obj, value) |
|
966 | self.error(obj, value) | |
969 |
|
967 | |||
970 | class Complex(TraitType): |
|
968 | class Complex(TraitType): | |
971 | """A trait for complex numbers.""" |
|
969 | """A trait for complex numbers.""" | |
972 |
|
970 | |||
973 | default_value = 0.0 + 0.0j |
|
971 | default_value = 0.0 + 0.0j | |
974 | info_text = 'a complex number' |
|
972 | info_text = 'a complex number' | |
975 |
|
973 | |||
976 | def validate(self, obj, value): |
|
974 | def validate(self, obj, value): | |
977 | if isinstance(value, complex): |
|
975 | if isinstance(value, complex): | |
978 | return value |
|
976 | return value | |
979 | if isinstance(value, (float, int)): |
|
977 | if isinstance(value, (float, int)): | |
980 | return complex(value) |
|
978 | return complex(value) | |
981 | self.error(obj, value) |
|
979 | self.error(obj, value) | |
982 |
|
980 | |||
983 |
|
981 | |||
984 | class CComplex(Complex): |
|
982 | class CComplex(Complex): | |
985 | """A casting version of the complex number trait.""" |
|
983 | """A casting version of the complex number trait.""" | |
986 |
|
984 | |||
987 | def validate (self, obj, value): |
|
985 | def validate (self, obj, value): | |
988 | try: |
|
986 | try: | |
989 | return complex(value) |
|
987 | return complex(value) | |
990 | except: |
|
988 | except: | |
991 | self.error(obj, value) |
|
989 | self.error(obj, value) | |
992 |
|
990 | |||
993 | # We should always be explicit about whether we're using bytes or unicode, both |
|
991 | # We should always be explicit about whether we're using bytes or unicode, both | |
994 | # for Python 3 conversion and for reliable unicode behaviour on Python 2. So |
|
992 | # for Python 3 conversion and for reliable unicode behaviour on Python 2. So | |
995 | # we don't have a Str type. |
|
993 | # we don't have a Str type. | |
996 | class Bytes(TraitType): |
|
994 | class Bytes(TraitType): | |
997 | """A trait for byte strings.""" |
|
995 | """A trait for byte strings.""" | |
998 |
|
996 | |||
999 | default_value = b'' |
|
997 | default_value = b'' | |
1000 | info_text = 'a string' |
|
998 | info_text = 'a string' | |
1001 |
|
999 | |||
1002 | def validate(self, obj, value): |
|
1000 | def validate(self, obj, value): | |
1003 | if isinstance(value, bytes): |
|
1001 | if isinstance(value, bytes): | |
1004 | return value |
|
1002 | return value | |
1005 | self.error(obj, value) |
|
1003 | self.error(obj, value) | |
1006 |
|
1004 | |||
1007 |
|
1005 | |||
1008 | class CBytes(Bytes): |
|
1006 | class CBytes(Bytes): | |
1009 | """A casting version of the byte string trait.""" |
|
1007 | """A casting version of the byte string trait.""" | |
1010 |
|
1008 | |||
1011 | def validate(self, obj, value): |
|
1009 | def validate(self, obj, value): | |
1012 | try: |
|
1010 | try: | |
1013 | return bytes(value) |
|
1011 | return bytes(value) | |
1014 | except: |
|
1012 | except: | |
1015 | self.error(obj, value) |
|
1013 | self.error(obj, value) | |
1016 |
|
1014 | |||
1017 |
|
1015 | |||
1018 | class Unicode(TraitType): |
|
1016 | class Unicode(TraitType): | |
1019 | """A trait for unicode strings.""" |
|
1017 | """A trait for unicode strings.""" | |
1020 |
|
1018 | |||
1021 | default_value = u'' |
|
1019 | default_value = u'' | |
1022 | info_text = 'a unicode string' |
|
1020 | info_text = 'a unicode string' | |
1023 |
|
1021 | |||
1024 | def validate(self, obj, value): |
|
1022 | def validate(self, obj, value): | |
1025 | if isinstance(value, py3compat.unicode_type): |
|
1023 | if isinstance(value, py3compat.unicode_type): | |
1026 | return value |
|
1024 | return value | |
1027 | if isinstance(value, bytes): |
|
1025 | if isinstance(value, bytes): | |
1028 | return py3compat.unicode_type(value) |
|
1026 | return py3compat.unicode_type(value) | |
1029 | self.error(obj, value) |
|
1027 | self.error(obj, value) | |
1030 |
|
1028 | |||
1031 |
|
1029 | |||
1032 | class CUnicode(Unicode): |
|
1030 | class CUnicode(Unicode): | |
1033 | """A casting version of the unicode trait.""" |
|
1031 | """A casting version of the unicode trait.""" | |
1034 |
|
1032 | |||
1035 | def validate(self, obj, value): |
|
1033 | def validate(self, obj, value): | |
1036 | try: |
|
1034 | try: | |
1037 | return py3compat.unicode_type(value) |
|
1035 | return py3compat.unicode_type(value) | |
1038 | except: |
|
1036 | except: | |
1039 | self.error(obj, value) |
|
1037 | self.error(obj, value) | |
1040 |
|
1038 | |||
1041 |
|
1039 | |||
1042 | class ObjectName(TraitType): |
|
1040 | class ObjectName(TraitType): | |
1043 | """A string holding a valid object name in this version of Python. |
|
1041 | """A string holding a valid object name in this version of Python. | |
1044 |
|
1042 | |||
1045 | This does not check that the name exists in any scope.""" |
|
1043 | This does not check that the name exists in any scope.""" | |
1046 | info_text = "a valid object identifier in Python" |
|
1044 | info_text = "a valid object identifier in Python" | |
1047 |
|
1045 | |||
1048 | if py3compat.PY3: |
|
1046 | if py3compat.PY3: | |
1049 | # Python 3: |
|
1047 | # Python 3: | |
1050 | coerce_str = staticmethod(lambda _,s: s) |
|
1048 | coerce_str = staticmethod(lambda _,s: s) | |
1051 |
|
1049 | |||
1052 | else: |
|
1050 | else: | |
1053 | # Python 2: |
|
1051 | # Python 2: | |
1054 | def coerce_str(self, obj, value): |
|
1052 | def coerce_str(self, obj, value): | |
1055 | "In Python 2, coerce ascii-only unicode to str" |
|
1053 | "In Python 2, coerce ascii-only unicode to str" | |
1056 | if isinstance(value, unicode): |
|
1054 | if isinstance(value, unicode): | |
1057 | try: |
|
1055 | try: | |
1058 | return str(value) |
|
1056 | return str(value) | |
1059 | except UnicodeEncodeError: |
|
1057 | except UnicodeEncodeError: | |
1060 | self.error(obj, value) |
|
1058 | self.error(obj, value) | |
1061 | return value |
|
1059 | return value | |
1062 |
|
1060 | |||
1063 | def validate(self, obj, value): |
|
1061 | def validate(self, obj, value): | |
1064 | value = self.coerce_str(obj, value) |
|
1062 | value = self.coerce_str(obj, value) | |
1065 |
|
1063 | |||
1066 | if isinstance(value, str) and py3compat.isidentifier(value): |
|
1064 | if isinstance(value, str) and py3compat.isidentifier(value): | |
1067 | return value |
|
1065 | return value | |
1068 | self.error(obj, value) |
|
1066 | self.error(obj, value) | |
1069 |
|
1067 | |||
1070 | class DottedObjectName(ObjectName): |
|
1068 | class DottedObjectName(ObjectName): | |
1071 | """A string holding a valid dotted object name in Python, such as A.b3._c""" |
|
1069 | """A string holding a valid dotted object name in Python, such as A.b3._c""" | |
1072 | def validate(self, obj, value): |
|
1070 | def validate(self, obj, value): | |
1073 | value = self.coerce_str(obj, value) |
|
1071 | value = self.coerce_str(obj, value) | |
1074 |
|
1072 | |||
1075 | if isinstance(value, str) and py3compat.isidentifier(value, dotted=True): |
|
1073 | if isinstance(value, str) and py3compat.isidentifier(value, dotted=True): | |
1076 | return value |
|
1074 | return value | |
1077 | self.error(obj, value) |
|
1075 | self.error(obj, value) | |
1078 |
|
1076 | |||
1079 |
|
1077 | |||
1080 | class Bool(TraitType): |
|
1078 | class Bool(TraitType): | |
1081 | """A boolean (True, False) trait.""" |
|
1079 | """A boolean (True, False) trait.""" | |
1082 |
|
1080 | |||
1083 | default_value = False |
|
1081 | default_value = False | |
1084 | info_text = 'a boolean' |
|
1082 | info_text = 'a boolean' | |
1085 |
|
1083 | |||
1086 | def validate(self, obj, value): |
|
1084 | def validate(self, obj, value): | |
1087 | if isinstance(value, bool): |
|
1085 | if isinstance(value, bool): | |
1088 | return value |
|
1086 | return value | |
1089 | self.error(obj, value) |
|
1087 | self.error(obj, value) | |
1090 |
|
1088 | |||
1091 |
|
1089 | |||
1092 | class CBool(Bool): |
|
1090 | class CBool(Bool): | |
1093 | """A casting version of the boolean trait.""" |
|
1091 | """A casting version of the boolean trait.""" | |
1094 |
|
1092 | |||
1095 | def validate(self, obj, value): |
|
1093 | def validate(self, obj, value): | |
1096 | try: |
|
1094 | try: | |
1097 | return bool(value) |
|
1095 | return bool(value) | |
1098 | except: |
|
1096 | except: | |
1099 | self.error(obj, value) |
|
1097 | self.error(obj, value) | |
1100 |
|
1098 | |||
1101 |
|
1099 | |||
1102 | class Enum(TraitType): |
|
1100 | class Enum(TraitType): | |
1103 | """An enum that whose value must be in a given sequence.""" |
|
1101 | """An enum that whose value must be in a given sequence.""" | |
1104 |
|
1102 | |||
1105 | def __init__(self, values, default_value=None, allow_none=True, **metadata): |
|
1103 | def __init__(self, values, default_value=None, allow_none=True, **metadata): | |
1106 | self.values = values |
|
1104 | self.values = values | |
1107 | self._allow_none = allow_none |
|
1105 | self._allow_none = allow_none | |
1108 | super(Enum, self).__init__(default_value, **metadata) |
|
1106 | super(Enum, self).__init__(default_value, **metadata) | |
1109 |
|
1107 | |||
1110 | def validate(self, obj, value): |
|
1108 | def validate(self, obj, value): | |
1111 | if value is None: |
|
1109 | if value is None: | |
1112 | if self._allow_none: |
|
1110 | if self._allow_none: | |
1113 | return value |
|
1111 | return value | |
1114 |
|
1112 | |||
1115 | if value in self.values: |
|
1113 | if value in self.values: | |
1116 | return value |
|
1114 | return value | |
1117 | self.error(obj, value) |
|
1115 | self.error(obj, value) | |
1118 |
|
1116 | |||
1119 | def info(self): |
|
1117 | def info(self): | |
1120 | """ Returns a description of the trait.""" |
|
1118 | """ Returns a description of the trait.""" | |
1121 | result = 'any of ' + repr(self.values) |
|
1119 | result = 'any of ' + repr(self.values) | |
1122 | if self._allow_none: |
|
1120 | if self._allow_none: | |
1123 | return result + ' or None' |
|
1121 | return result + ' or None' | |
1124 | return result |
|
1122 | return result | |
1125 |
|
1123 | |||
1126 | class CaselessStrEnum(Enum): |
|
1124 | class CaselessStrEnum(Enum): | |
1127 | """An enum of strings that are caseless in validate.""" |
|
1125 | """An enum of strings that are caseless in validate.""" | |
1128 |
|
1126 | |||
1129 | def validate(self, obj, value): |
|
1127 | def validate(self, obj, value): | |
1130 | if value is None: |
|
1128 | if value is None: | |
1131 | if self._allow_none: |
|
1129 | if self._allow_none: | |
1132 | return value |
|
1130 | return value | |
1133 |
|
1131 | |||
1134 | if not isinstance(value, py3compat.string_types): |
|
1132 | if not isinstance(value, py3compat.string_types): | |
1135 | self.error(obj, value) |
|
1133 | self.error(obj, value) | |
1136 |
|
1134 | |||
1137 | for v in self.values: |
|
1135 | for v in self.values: | |
1138 | if v.lower() == value.lower(): |
|
1136 | if v.lower() == value.lower(): | |
1139 | return v |
|
1137 | return v | |
1140 | self.error(obj, value) |
|
1138 | self.error(obj, value) | |
1141 |
|
1139 | |||
1142 | class Container(Instance): |
|
1140 | class Container(Instance): | |
1143 | """An instance of a container (list, set, etc.) |
|
1141 | """An instance of a container (list, set, etc.) | |
1144 |
|
1142 | |||
1145 | To be subclassed by overriding klass. |
|
1143 | To be subclassed by overriding klass. | |
1146 | """ |
|
1144 | """ | |
1147 | klass = None |
|
1145 | klass = None | |
1148 | _valid_defaults = SequenceTypes |
|
1146 | _valid_defaults = SequenceTypes | |
1149 | _trait = None |
|
1147 | _trait = None | |
1150 |
|
1148 | |||
1151 | def __init__(self, trait=None, default_value=None, allow_none=True, |
|
1149 | def __init__(self, trait=None, default_value=None, allow_none=True, | |
1152 | **metadata): |
|
1150 | **metadata): | |
1153 | """Create a container trait type from a list, set, or tuple. |
|
1151 | """Create a container trait type from a list, set, or tuple. | |
1154 |
|
1152 | |||
1155 | The default value is created by doing ``List(default_value)``, |
|
1153 | The default value is created by doing ``List(default_value)``, | |
1156 | which creates a copy of the ``default_value``. |
|
1154 | which creates a copy of the ``default_value``. | |
1157 |
|
1155 | |||
1158 | ``trait`` can be specified, which restricts the type of elements |
|
1156 | ``trait`` can be specified, which restricts the type of elements | |
1159 | in the container to that TraitType. |
|
1157 | in the container to that TraitType. | |
1160 |
|
1158 | |||
1161 | If only one arg is given and it is not a Trait, it is taken as |
|
1159 | If only one arg is given and it is not a Trait, it is taken as | |
1162 | ``default_value``: |
|
1160 | ``default_value``: | |
1163 |
|
1161 | |||
1164 | ``c = List([1,2,3])`` |
|
1162 | ``c = List([1,2,3])`` | |
1165 |
|
1163 | |||
1166 | Parameters |
|
1164 | Parameters | |
1167 | ---------- |
|
1165 | ---------- | |
1168 |
|
1166 | |||
1169 | trait : TraitType [ optional ] |
|
1167 | trait : TraitType [ optional ] | |
1170 | the type for restricting the contents of the Container. If unspecified, |
|
1168 | the type for restricting the contents of the Container. If unspecified, | |
1171 | types are not checked. |
|
1169 | types are not checked. | |
1172 |
|
1170 | |||
1173 | default_value : SequenceType [ optional ] |
|
1171 | default_value : SequenceType [ optional ] | |
1174 | The default value for the Trait. Must be list/tuple/set, and |
|
1172 | The default value for the Trait. Must be list/tuple/set, and | |
1175 | will be cast to the container type. |
|
1173 | will be cast to the container type. | |
1176 |
|
1174 | |||
1177 | allow_none : Bool [ default True ] |
|
1175 | allow_none : Bool [ default True ] | |
1178 | Whether to allow the value to be None |
|
1176 | Whether to allow the value to be None | |
1179 |
|
1177 | |||
1180 | **metadata : any |
|
1178 | **metadata : any | |
1181 | further keys for extensions to the Trait (e.g. config) |
|
1179 | further keys for extensions to the Trait (e.g. config) | |
1182 |
|
1180 | |||
1183 | """ |
|
1181 | """ | |
1184 | # allow List([values]): |
|
1182 | # allow List([values]): | |
1185 | if default_value is None and not is_trait(trait): |
|
1183 | if default_value is None and not is_trait(trait): | |
1186 | default_value = trait |
|
1184 | default_value = trait | |
1187 | trait = None |
|
1185 | trait = None | |
1188 |
|
1186 | |||
1189 | if default_value is None: |
|
1187 | if default_value is None: | |
1190 | args = () |
|
1188 | args = () | |
1191 | elif isinstance(default_value, self._valid_defaults): |
|
1189 | elif isinstance(default_value, self._valid_defaults): | |
1192 | args = (default_value,) |
|
1190 | args = (default_value,) | |
1193 | else: |
|
1191 | else: | |
1194 | raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) |
|
1192 | raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) | |
1195 |
|
1193 | |||
1196 | if is_trait(trait): |
|
1194 | if is_trait(trait): | |
1197 | self._trait = trait() if isinstance(trait, type) else trait |
|
1195 | self._trait = trait() if isinstance(trait, type) else trait | |
1198 | self._trait.name = 'element' |
|
1196 | self._trait.name = 'element' | |
1199 | elif trait is not None: |
|
1197 | elif trait is not None: | |
1200 | raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait)) |
|
1198 | raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait)) | |
1201 |
|
1199 | |||
1202 | super(Container,self).__init__(klass=self.klass, args=args, |
|
1200 | super(Container,self).__init__(klass=self.klass, args=args, | |
1203 | allow_none=allow_none, **metadata) |
|
1201 | allow_none=allow_none, **metadata) | |
1204 |
|
1202 | |||
1205 | def element_error(self, obj, element, validator): |
|
1203 | def element_error(self, obj, element, validator): | |
1206 | e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \ |
|
1204 | e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \ | |
1207 | % (self.name, class_of(obj), validator.info(), repr_type(element)) |
|
1205 | % (self.name, class_of(obj), validator.info(), repr_type(element)) | |
1208 | raise TraitError(e) |
|
1206 | raise TraitError(e) | |
1209 |
|
1207 | |||
1210 | def validate(self, obj, value): |
|
1208 | def validate(self, obj, value): | |
1211 | value = super(Container, self).validate(obj, value) |
|
1209 | value = super(Container, self).validate(obj, value) | |
1212 | if value is None: |
|
1210 | if value is None: | |
1213 | return value |
|
1211 | return value | |
1214 |
|
1212 | |||
1215 | value = self.validate_elements(obj, value) |
|
1213 | value = self.validate_elements(obj, value) | |
1216 |
|
1214 | |||
1217 | return value |
|
1215 | return value | |
1218 |
|
1216 | |||
1219 | def validate_elements(self, obj, value): |
|
1217 | def validate_elements(self, obj, value): | |
1220 | validated = [] |
|
1218 | validated = [] | |
1221 | if self._trait is None or isinstance(self._trait, Any): |
|
1219 | if self._trait is None or isinstance(self._trait, Any): | |
1222 | return value |
|
1220 | return value | |
1223 | for v in value: |
|
1221 | for v in value: | |
1224 | try: |
|
1222 | try: | |
1225 | v = self._trait.validate(obj, v) |
|
1223 | v = self._trait.validate(obj, v) | |
1226 | except TraitError: |
|
1224 | except TraitError: | |
1227 | self.element_error(obj, v, self._trait) |
|
1225 | self.element_error(obj, v, self._trait) | |
1228 | else: |
|
1226 | else: | |
1229 | validated.append(v) |
|
1227 | validated.append(v) | |
1230 | return self.klass(validated) |
|
1228 | return self.klass(validated) | |
1231 |
|
1229 | |||
1232 |
|
1230 | |||
1233 | class List(Container): |
|
1231 | class List(Container): | |
1234 | """An instance of a Python list.""" |
|
1232 | """An instance of a Python list.""" | |
1235 | klass = list |
|
1233 | klass = list | |
1236 |
|
1234 | |||
1237 | def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, |
|
1235 | def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, | |
1238 | allow_none=True, **metadata): |
|
1236 | allow_none=True, **metadata): | |
1239 | """Create a List trait type from a list, set, or tuple. |
|
1237 | """Create a List trait type from a list, set, or tuple. | |
1240 |
|
1238 | |||
1241 | The default value is created by doing ``List(default_value)``, |
|
1239 | The default value is created by doing ``List(default_value)``, | |
1242 | which creates a copy of the ``default_value``. |
|
1240 | which creates a copy of the ``default_value``. | |
1243 |
|
1241 | |||
1244 | ``trait`` can be specified, which restricts the type of elements |
|
1242 | ``trait`` can be specified, which restricts the type of elements | |
1245 | in the container to that TraitType. |
|
1243 | in the container to that TraitType. | |
1246 |
|
1244 | |||
1247 | If only one arg is given and it is not a Trait, it is taken as |
|
1245 | If only one arg is given and it is not a Trait, it is taken as | |
1248 | ``default_value``: |
|
1246 | ``default_value``: | |
1249 |
|
1247 | |||
1250 | ``c = List([1,2,3])`` |
|
1248 | ``c = List([1,2,3])`` | |
1251 |
|
1249 | |||
1252 | Parameters |
|
1250 | Parameters | |
1253 | ---------- |
|
1251 | ---------- | |
1254 |
|
1252 | |||
1255 | trait : TraitType [ optional ] |
|
1253 | trait : TraitType [ optional ] | |
1256 | the type for restricting the contents of the Container. If unspecified, |
|
1254 | the type for restricting the contents of the Container. If unspecified, | |
1257 | types are not checked. |
|
1255 | types are not checked. | |
1258 |
|
1256 | |||
1259 | default_value : SequenceType [ optional ] |
|
1257 | default_value : SequenceType [ optional ] | |
1260 | The default value for the Trait. Must be list/tuple/set, and |
|
1258 | The default value for the Trait. Must be list/tuple/set, and | |
1261 | will be cast to the container type. |
|
1259 | will be cast to the container type. | |
1262 |
|
1260 | |||
1263 | minlen : Int [ default 0 ] |
|
1261 | minlen : Int [ default 0 ] | |
1264 | The minimum length of the input list |
|
1262 | The minimum length of the input list | |
1265 |
|
1263 | |||
1266 | maxlen : Int [ default sys.maxsize ] |
|
1264 | maxlen : Int [ default sys.maxsize ] | |
1267 | The maximum length of the input list |
|
1265 | The maximum length of the input list | |
1268 |
|
1266 | |||
1269 | allow_none : Bool [ default True ] |
|
1267 | allow_none : Bool [ default True ] | |
1270 | Whether to allow the value to be None |
|
1268 | Whether to allow the value to be None | |
1271 |
|
1269 | |||
1272 | **metadata : any |
|
1270 | **metadata : any | |
1273 | further keys for extensions to the Trait (e.g. config) |
|
1271 | further keys for extensions to the Trait (e.g. config) | |
1274 |
|
1272 | |||
1275 | """ |
|
1273 | """ | |
1276 | self._minlen = minlen |
|
1274 | self._minlen = minlen | |
1277 | self._maxlen = maxlen |
|
1275 | self._maxlen = maxlen | |
1278 | super(List, self).__init__(trait=trait, default_value=default_value, |
|
1276 | super(List, self).__init__(trait=trait, default_value=default_value, | |
1279 | allow_none=allow_none, **metadata) |
|
1277 | allow_none=allow_none, **metadata) | |
1280 |
|
1278 | |||
1281 | def length_error(self, obj, value): |
|
1279 | def length_error(self, obj, value): | |
1282 | e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \ |
|
1280 | e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \ | |
1283 | % (self.name, class_of(obj), self._minlen, self._maxlen, value) |
|
1281 | % (self.name, class_of(obj), self._minlen, self._maxlen, value) | |
1284 | raise TraitError(e) |
|
1282 | raise TraitError(e) | |
1285 |
|
1283 | |||
1286 | def validate_elements(self, obj, value): |
|
1284 | def validate_elements(self, obj, value): | |
1287 | length = len(value) |
|
1285 | length = len(value) | |
1288 | if length < self._minlen or length > self._maxlen: |
|
1286 | if length < self._minlen or length > self._maxlen: | |
1289 | self.length_error(obj, value) |
|
1287 | self.length_error(obj, value) | |
1290 |
|
1288 | |||
1291 | return super(List, self).validate_elements(obj, value) |
|
1289 | return super(List, self).validate_elements(obj, value) | |
1292 |
|
1290 | |||
1293 |
|
1291 | |||
1294 | class Set(Container): |
|
1292 | class Set(Container): | |
1295 | """An instance of a Python set.""" |
|
1293 | """An instance of a Python set.""" | |
1296 | klass = set |
|
1294 | klass = set | |
1297 |
|
1295 | |||
1298 | class Tuple(Container): |
|
1296 | class Tuple(Container): | |
1299 | """An instance of a Python tuple.""" |
|
1297 | """An instance of a Python tuple.""" | |
1300 | klass = tuple |
|
1298 | klass = tuple | |
1301 |
|
1299 | |||
1302 | def __init__(self, *traits, **metadata): |
|
1300 | def __init__(self, *traits, **metadata): | |
1303 | """Tuple(*traits, default_value=None, allow_none=True, **medatata) |
|
1301 | """Tuple(*traits, default_value=None, allow_none=True, **medatata) | |
1304 |
|
1302 | |||
1305 | Create a tuple from a list, set, or tuple. |
|
1303 | Create a tuple from a list, set, or tuple. | |
1306 |
|
1304 | |||
1307 | Create a fixed-type tuple with Traits: |
|
1305 | Create a fixed-type tuple with Traits: | |
1308 |
|
1306 | |||
1309 | ``t = Tuple(Int, Str, CStr)`` |
|
1307 | ``t = Tuple(Int, Str, CStr)`` | |
1310 |
|
1308 | |||
1311 | would be length 3, with Int,Str,CStr for each element. |
|
1309 | would be length 3, with Int,Str,CStr for each element. | |
1312 |
|
1310 | |||
1313 | If only one arg is given and it is not a Trait, it is taken as |
|
1311 | If only one arg is given and it is not a Trait, it is taken as | |
1314 | default_value: |
|
1312 | default_value: | |
1315 |
|
1313 | |||
1316 | ``t = Tuple((1,2,3))`` |
|
1314 | ``t = Tuple((1,2,3))`` | |
1317 |
|
1315 | |||
1318 | Otherwise, ``default_value`` *must* be specified by keyword. |
|
1316 | Otherwise, ``default_value`` *must* be specified by keyword. | |
1319 |
|
1317 | |||
1320 | Parameters |
|
1318 | Parameters | |
1321 | ---------- |
|
1319 | ---------- | |
1322 |
|
1320 | |||
1323 | *traits : TraitTypes [ optional ] |
|
1321 | *traits : TraitTypes [ optional ] | |
1324 | the tsype for restricting the contents of the Tuple. If unspecified, |
|
1322 | the tsype for restricting the contents of the Tuple. If unspecified, | |
1325 | types are not checked. If specified, then each positional argument |
|
1323 | types are not checked. If specified, then each positional argument | |
1326 | corresponds to an element of the tuple. Tuples defined with traits |
|
1324 | corresponds to an element of the tuple. Tuples defined with traits | |
1327 | are of fixed length. |
|
1325 | are of fixed length. | |
1328 |
|
1326 | |||
1329 | default_value : SequenceType [ optional ] |
|
1327 | default_value : SequenceType [ optional ] | |
1330 | The default value for the Tuple. Must be list/tuple/set, and |
|
1328 | The default value for the Tuple. Must be list/tuple/set, and | |
1331 | will be cast to a tuple. If `traits` are specified, the |
|
1329 | will be cast to a tuple. If `traits` are specified, the | |
1332 | `default_value` must conform to the shape and type they specify. |
|
1330 | `default_value` must conform to the shape and type they specify. | |
1333 |
|
1331 | |||
1334 | allow_none : Bool [ default True ] |
|
1332 | allow_none : Bool [ default True ] | |
1335 | Whether to allow the value to be None |
|
1333 | Whether to allow the value to be None | |
1336 |
|
1334 | |||
1337 | **metadata : any |
|
1335 | **metadata : any | |
1338 | further keys for extensions to the Trait (e.g. config) |
|
1336 | further keys for extensions to the Trait (e.g. config) | |
1339 |
|
1337 | |||
1340 | """ |
|
1338 | """ | |
1341 | default_value = metadata.pop('default_value', None) |
|
1339 | default_value = metadata.pop('default_value', None) | |
1342 | allow_none = metadata.pop('allow_none', True) |
|
1340 | allow_none = metadata.pop('allow_none', True) | |
1343 |
|
1341 | |||
1344 | # allow Tuple((values,)): |
|
1342 | # allow Tuple((values,)): | |
1345 | if len(traits) == 1 and default_value is None and not is_trait(traits[0]): |
|
1343 | if len(traits) == 1 and default_value is None and not is_trait(traits[0]): | |
1346 | default_value = traits[0] |
|
1344 | default_value = traits[0] | |
1347 | traits = () |
|
1345 | traits = () | |
1348 |
|
1346 | |||
1349 | if default_value is None: |
|
1347 | if default_value is None: | |
1350 | args = () |
|
1348 | args = () | |
1351 | elif isinstance(default_value, self._valid_defaults): |
|
1349 | elif isinstance(default_value, self._valid_defaults): | |
1352 | args = (default_value,) |
|
1350 | args = (default_value,) | |
1353 | else: |
|
1351 | else: | |
1354 | raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) |
|
1352 | raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value)) | |
1355 |
|
1353 | |||
1356 | self._traits = [] |
|
1354 | self._traits = [] | |
1357 | for trait in traits: |
|
1355 | for trait in traits: | |
1358 | t = trait() if isinstance(trait, type) else trait |
|
1356 | t = trait() if isinstance(trait, type) else trait | |
1359 | t.name = 'element' |
|
1357 | t.name = 'element' | |
1360 | self._traits.append(t) |
|
1358 | self._traits.append(t) | |
1361 |
|
1359 | |||
1362 | if self._traits and default_value is None: |
|
1360 | if self._traits and default_value is None: | |
1363 | # don't allow default to be an empty container if length is specified |
|
1361 | # don't allow default to be an empty container if length is specified | |
1364 | args = None |
|
1362 | args = None | |
1365 | super(Container,self).__init__(klass=self.klass, args=args, |
|
1363 | super(Container,self).__init__(klass=self.klass, args=args, | |
1366 | allow_none=allow_none, **metadata) |
|
1364 | allow_none=allow_none, **metadata) | |
1367 |
|
1365 | |||
1368 | def validate_elements(self, obj, value): |
|
1366 | def validate_elements(self, obj, value): | |
1369 | if not self._traits: |
|
1367 | if not self._traits: | |
1370 | # nothing to validate |
|
1368 | # nothing to validate | |
1371 | return value |
|
1369 | return value | |
1372 | if len(value) != len(self._traits): |
|
1370 | if len(value) != len(self._traits): | |
1373 | e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \ |
|
1371 | e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \ | |
1374 | % (self.name, class_of(obj), len(self._traits), repr_type(value)) |
|
1372 | % (self.name, class_of(obj), len(self._traits), repr_type(value)) | |
1375 | raise TraitError(e) |
|
1373 | raise TraitError(e) | |
1376 |
|
1374 | |||
1377 | validated = [] |
|
1375 | validated = [] | |
1378 | for t,v in zip(self._traits, value): |
|
1376 | for t,v in zip(self._traits, value): | |
1379 | try: |
|
1377 | try: | |
1380 | v = t.validate(obj, v) |
|
1378 | v = t.validate(obj, v) | |
1381 | except TraitError: |
|
1379 | except TraitError: | |
1382 | self.element_error(obj, v, t) |
|
1380 | self.element_error(obj, v, t) | |
1383 | else: |
|
1381 | else: | |
1384 | validated.append(v) |
|
1382 | validated.append(v) | |
1385 | return tuple(validated) |
|
1383 | return tuple(validated) | |
1386 |
|
1384 | |||
1387 |
|
1385 | |||
1388 | class Dict(Instance): |
|
1386 | class Dict(Instance): | |
1389 | """An instance of a Python dict.""" |
|
1387 | """An instance of a Python dict.""" | |
1390 |
|
1388 | |||
1391 | def __init__(self, default_value=None, allow_none=True, **metadata): |
|
1389 | def __init__(self, default_value=None, allow_none=True, **metadata): | |
1392 | """Create a dict trait type from a dict. |
|
1390 | """Create a dict trait type from a dict. | |
1393 |
|
1391 | |||
1394 | The default value is created by doing ``dict(default_value)``, |
|
1392 | The default value is created by doing ``dict(default_value)``, | |
1395 | which creates a copy of the ``default_value``. |
|
1393 | which creates a copy of the ``default_value``. | |
1396 | """ |
|
1394 | """ | |
1397 | if default_value is None: |
|
1395 | if default_value is None: | |
1398 | args = ((),) |
|
1396 | args = ((),) | |
1399 | elif isinstance(default_value, dict): |
|
1397 | elif isinstance(default_value, dict): | |
1400 | args = (default_value,) |
|
1398 | args = (default_value,) | |
1401 | elif isinstance(default_value, SequenceTypes): |
|
1399 | elif isinstance(default_value, SequenceTypes): | |
1402 | args = (default_value,) |
|
1400 | args = (default_value,) | |
1403 | else: |
|
1401 | else: | |
1404 | raise TypeError('default value of Dict was %s' % default_value) |
|
1402 | raise TypeError('default value of Dict was %s' % default_value) | |
1405 |
|
1403 | |||
1406 | super(Dict,self).__init__(klass=dict, args=args, |
|
1404 | super(Dict,self).__init__(klass=dict, args=args, | |
1407 | allow_none=allow_none, **metadata) |
|
1405 | allow_none=allow_none, **metadata) | |
1408 |
|
1406 | |||
1409 | class TCPAddress(TraitType): |
|
1407 | class TCPAddress(TraitType): | |
1410 | """A trait for an (ip, port) tuple. |
|
1408 | """A trait for an (ip, port) tuple. | |
1411 |
|
1409 | |||
1412 | This allows for both IPv4 IP addresses as well as hostnames. |
|
1410 | This allows for both IPv4 IP addresses as well as hostnames. | |
1413 | """ |
|
1411 | """ | |
1414 |
|
1412 | |||
1415 | default_value = ('127.0.0.1', 0) |
|
1413 | default_value = ('127.0.0.1', 0) | |
1416 | info_text = 'an (ip, port) tuple' |
|
1414 | info_text = 'an (ip, port) tuple' | |
1417 |
|
1415 | |||
1418 | def validate(self, obj, value): |
|
1416 | def validate(self, obj, value): | |
1419 | if isinstance(value, tuple): |
|
1417 | if isinstance(value, tuple): | |
1420 | if len(value) == 2: |
|
1418 | if len(value) == 2: | |
1421 | if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int): |
|
1419 | if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int): | |
1422 | port = value[1] |
|
1420 | port = value[1] | |
1423 | if port >= 0 and port <= 65535: |
|
1421 | if port >= 0 and port <= 65535: | |
1424 | return value |
|
1422 | return value | |
1425 | self.error(obj, value) |
|
1423 | self.error(obj, value) | |
1426 |
|
1424 | |||
1427 | class CRegExp(TraitType): |
|
1425 | class CRegExp(TraitType): | |
1428 | """A casting compiled regular expression trait. |
|
1426 | """A casting compiled regular expression trait. | |
1429 |
|
1427 | |||
1430 | Accepts both strings and compiled regular expressions. The resulting |
|
1428 | Accepts both strings and compiled regular expressions. The resulting | |
1431 | attribute will be a compiled regular expression.""" |
|
1429 | attribute will be a compiled regular expression.""" | |
1432 |
|
1430 | |||
1433 | info_text = 'a regular expression' |
|
1431 | info_text = 'a regular expression' | |
1434 |
|
1432 | |||
1435 | def validate(self, obj, value): |
|
1433 | def validate(self, obj, value): | |
1436 | try: |
|
1434 | try: | |
1437 | return re.compile(value) |
|
1435 | return re.compile(value) | |
1438 | except: |
|
1436 | except: | |
1439 | self.error(obj, value) |
|
1437 | self.error(obj, value) |
General Comments 0
You need to be logged in to leave comments.
Login now