##// END OF EJS Templates
Misc updates the display system....
Brian Granger -
Show More
@@ -1,576 +1,593 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4
4
5 Authors:
5 Authors:
6
6
7 * Robert Kern
7 * Robert Kern
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (c) 2010, IPython Development Team.
11 # Copyright (c) 2010, IPython Development Team.
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # Stdlib imports
22 # Stdlib imports
23 import abc
23 import abc
24 import sys
24 import sys
25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
25 # We must use StringIO, as cStringIO doesn't handle unicode properly.
26 from StringIO import StringIO
26 from StringIO import StringIO
27
27
28 # Our own imports
28 # Our own imports
29 from IPython.config.configurable import Configurable
29 from IPython.config.configurable import Configurable
30 from IPython.lib import pretty
30 from IPython.lib import pretty
31 from IPython.utils.traitlets import Bool, Dict, Int, Str, CStr
31 from IPython.utils.traitlets import Bool, Dict, Int, Str, CStr
32
32
33
33
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35 # The main DisplayFormatter class
35 # The main DisplayFormatter class
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37
37
38
38
39 class DisplayFormatter(Configurable):
39 class DisplayFormatter(Configurable):
40
40
41 # When set to true only the default plain text formatter will be used.
41 # When set to true only the default plain text formatter will be used.
42 plain_text_only = Bool(False, config=True)
42 plain_text_only = Bool(False, config=True)
43
43
44 # A dict of formatter whose keys are format types (MIME types) and whose
44 # A dict of formatter whose keys are format types (MIME types) and whose
45 # values are subclasses of BaseFormatter.
45 # values are subclasses of BaseFormatter.
46 formatters = Dict(config=True)
46 formatters = Dict(config=True)
47 def _formatters_default(self):
47 def _formatters_default(self):
48 """Activate the default formatters."""
48 """Activate the default formatters."""
49 formatter_classes = [
49 formatter_classes = [
50 PlainTextFormatter,
50 PlainTextFormatter,
51 HTMLFormatter,
51 HTMLFormatter,
52 SVGFormatter,
52 SVGFormatter,
53 PNGFormatter,
53 PNGFormatter,
54 LatexFormatter,
54 LatexFormatter,
55 JSONFormatter,
55 JSONFormatter,
56 JavascriptFormatter
56 JavascriptFormatter
57 ]
57 ]
58 d = {}
58 d = {}
59 for cls in formatter_classes:
59 for cls in formatter_classes:
60 f = cls(config=self.config)
60 f = cls(config=self.config)
61 d[f.format_type] = f
61 d[f.format_type] = f
62 return d
62 return d
63
63
64 def format(self, obj, include=None, exclude=None):
64 def format(self, obj, include=None, exclude=None):
65 """Return a format data dict for an object.
65 """Return a format data dict for an object.
66
66
67 By default all format types will be computed.
67 By default all format types will be computed.
68
68
69 The following MIME types are currently implemented:
69 The following MIME types are currently implemented:
70
70
71 * text/plain
71 * text/plain
72 * text/html
72 * text/html
73 * text/latex
73 * text/latex
74 * application/json
74 * application/json
75 * image/png
75 * image/png
76 * immage/svg+xml
76 * immage/svg+xml
77
77
78 Parameters
78 Parameters
79 ----------
79 ----------
80 obj : object
80 obj : object
81 The Python object whose format data will be computed.
81 The Python object whose format data will be computed.
82 include : list or tuple, optional
82 include : list or tuple, optional
83 A list of format type strings (MIME types) to include in the
83 A list of format type strings (MIME types) to include in the
84 format data dict. If this is set *only* the format types included
84 format data dict. If this is set *only* the format types included
85 in this list will be computed.
85 in this list will be computed.
86 exclude : list or tuple, optional
86 exclude : list or tuple, optional
87 A list of format type string (MIME types) to exclue in the format
87 A list of format type string (MIME types) to exclue in the format
88 data dict. If this is set all format types will be computed,
88 data dict. If this is set all format types will be computed,
89 except for those included in this argument.
89 except for those included in this argument.
90
90
91 Returns
91 Returns
92 -------
92 -------
93 format_dict : dict
93 format_dict : dict
94 A dictionary of key/value pairs, one or each format that was
94 A dictionary of key/value pairs, one or each format that was
95 generated for the object. The keys are the format types, which
95 generated for the object. The keys are the format types, which
96 will usually be MIME type strings and the values and JSON'able
96 will usually be MIME type strings and the values and JSON'able
97 data structure containing the raw data for the representation in
97 data structure containing the raw data for the representation in
98 that format.
98 that format.
99 """
99 """
100 format_dict = {}
100 format_dict = {}
101
101
102 # If plain text only is active
102 # If plain text only is active
103 if self.plain_text_only:
103 if self.plain_text_only:
104 formatter = self.formatters['text/plain']
104 formatter = self.formatters['text/plain']
105 try:
105 try:
106 data = formatter(obj)
106 data = formatter(obj)
107 except:
107 except:
108 # FIXME: log the exception
108 # FIXME: log the exception
109 raise
109 raise
110 if data is not None:
110 if data is not None:
111 format_dict['text/plain'] = data
111 format_dict['text/plain'] = data
112 return format_dict
112 return format_dict
113
113
114 for format_type, formatter in self.formatters.items():
114 for format_type, formatter in self.formatters.items():
115 if include is not None:
115 if include is not None:
116 if format_type not in include:
116 if format_type not in include:
117 continue
117 continue
118 if exclude is not None:
118 if exclude is not None:
119 if format_type in exclude:
119 if format_type in exclude:
120 continue
120 continue
121 try:
121 try:
122 data = formatter(obj)
122 data = formatter(obj)
123 except:
123 except:
124 # FIXME: log the exception
124 # FIXME: log the exception
125 raise
125 raise
126 if data is not None:
126 if data is not None:
127 format_dict[format_type] = data
127 format_dict[format_type] = data
128 return format_dict
128 return format_dict
129
129
130 @property
130 @property
131 def format_types(self):
131 def format_types(self):
132 """Return the format types (MIME types) of the active formatters."""
132 """Return the format types (MIME types) of the active formatters."""
133 return self.formatters.keys()
133 return self.formatters.keys()
134
134
135
135
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137 # Formatters for specific format types (text, html, svg, etc.)
137 # Formatters for specific format types (text, html, svg, etc.)
138 #-----------------------------------------------------------------------------
138 #-----------------------------------------------------------------------------
139
139
140
140
141 class FormatterABC(object):
141 class FormatterABC(object):
142 """ Abstract base class for Formatters.
142 """ Abstract base class for Formatters.
143
143
144 A formatter is a callable class that is responsible for computing the
144 A formatter is a callable class that is responsible for computing the
145 raw format data for a particular format type (MIME type). For example,
145 raw format data for a particular format type (MIME type). For example,
146 an HTML formatter would have a format type of `text/html` and would return
146 an HTML formatter would have a format type of `text/html` and would return
147 the HTML representation of the object when called.
147 the HTML representation of the object when called.
148 """
148 """
149 __metaclass__ = abc.ABCMeta
149 __metaclass__ = abc.ABCMeta
150
150
151 # The format type of the data returned, usually a MIME type.
151 # The format type of the data returned, usually a MIME type.
152 format_type = 'text/plain'
152 format_type = 'text/plain'
153
153
154 # Is the formatter enabled...
154 # Is the formatter enabled...
155 enabled = True
155 enabled = True
156
156
157 @abc.abstractmethod
157 @abc.abstractmethod
158 def __call__(self, obj):
158 def __call__(self, obj):
159 """Return a JSON'able representation of the object.
159 """Return a JSON'able representation of the object.
160
160
161 If the object cannot be formatted by this formatter, then return None
161 If the object cannot be formatted by this formatter, then return None
162 """
162 """
163 try:
163 try:
164 return repr(obj)
164 return repr(obj)
165 except TypeError:
165 except TypeError:
166 return None
166 return None
167
167
168
168
169 class BaseFormatter(Configurable):
169 class BaseFormatter(Configurable):
170 """A base formatter class that is configurable.
170 """A base formatter class that is configurable.
171
171
172 This formatter should usually be used as the base class of all formatters.
172 This formatter should usually be used as the base class of all formatters.
173 It is a traited :class:`Configurable` class and includes an extensible
173 It is a traited :class:`Configurable` class and includes an extensible
174 API for users to determine how their objects are formatted. The following
174 API for users to determine how their objects are formatted. The following
175 logic is used to find a function to format an given object.
175 logic is used to find a function to format an given object.
176
176
177 1. The object is introspected to see if it has a method with the name
177 1. The object is introspected to see if it has a method with the name
178 :attr:`print_method`. If is does, that object is passed to that method
178 :attr:`print_method`. If is does, that object is passed to that method
179 for formatting.
179 for formatting.
180 2. If no print method is found, three internal dictionaries are consulted
180 2. If no print method is found, three internal dictionaries are consulted
181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
181 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
182 and :attr:`deferred_printers`.
182 and :attr:`deferred_printers`.
183
183
184 Users should use these dictionaries to register functions that will be
184 Users should use these dictionaries to register functions that will be
185 used to compute the format data for their objects (if those objects don't
185 used to compute the format data for their objects (if those objects don't
186 have the special print methods). The easiest way of using these
186 have the special print methods). The easiest way of using these
187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
187 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
188 methods.
188 methods.
189
189
190 If no function/callable is found to compute the format data, ``None`` is
190 If no function/callable is found to compute the format data, ``None`` is
191 returned and this format type is not used.
191 returned and this format type is not used.
192 """
192 """
193
193
194 format_type = Str('text/plain')
194 format_type = Str('text/plain')
195
195
196 enabled = Bool(True, config=True)
196 enabled = Bool(True, config=True)
197
197
198 print_method = Str('__repr__')
198 print_method = Str('__repr__')
199
199
200 # The singleton printers.
200 # The singleton printers.
201 # Maps the IDs of the builtin singleton objects to the format functions.
201 # Maps the IDs of the builtin singleton objects to the format functions.
202 singleton_printers = Dict(config=True)
202 singleton_printers = Dict(config=True)
203 def _singleton_printers_default(self):
203 def _singleton_printers_default(self):
204 return {}
204 return {}
205
205
206 # The type-specific printers.
206 # The type-specific printers.
207 # Map type objects to the format functions.
207 # Map type objects to the format functions.
208 type_printers = Dict(config=True)
208 type_printers = Dict(config=True)
209 def _type_printers_default(self):
209 def _type_printers_default(self):
210 return {}
210 return {}
211
211
212 # The deferred-import type-specific printers.
212 # The deferred-import type-specific printers.
213 # Map (modulename, classname) pairs to the format functions.
213 # Map (modulename, classname) pairs to the format functions.
214 deferred_printers = Dict(config=True)
214 deferred_printers = Dict(config=True)
215 def _deferred_printers_default(self):
215 def _deferred_printers_default(self):
216 return {}
216 return {}
217
217
218 def __call__(self, obj):
218 def __call__(self, obj):
219 """Compute the format for an object."""
219 """Compute the format for an object."""
220 if self.enabled:
220 if self.enabled:
221 obj_id = id(obj)
221 obj_id = id(obj)
222 try:
222 try:
223 obj_class = getattr(obj, '__class__', None) or type(obj)
223 obj_class = getattr(obj, '__class__', None) or type(obj)
224 # First try to find registered singleton printers for the type.
224 # First try to find registered singleton printers for the type.
225 try:
225 try:
226 printer = self.singleton_printers[obj_id]
226 printer = self.singleton_printers[obj_id]
227 except (TypeError, KeyError):
227 except (TypeError, KeyError):
228 pass
228 pass
229 else:
229 else:
230 return printer(obj)
230 return printer(obj)
231 # Next look for type_printers.
231 # Next look for type_printers.
232 for cls in pretty._get_mro(obj_class):
232 for cls in pretty._get_mro(obj_class):
233 if cls in self.type_printers:
233 if cls in self.type_printers:
234 return self.type_printers[cls](obj)
234 return self.type_printers[cls](obj)
235 else:
235 else:
236 printer = self._in_deferred_types(cls)
236 printer = self._in_deferred_types(cls)
237 if printer is not None:
237 if printer is not None:
238 return printer(obj)
238 return printer(obj)
239 # Finally look for special method names.
239 # Finally look for special method names.
240 if hasattr(obj_class, self.print_method):
240 if hasattr(obj_class, self.print_method):
241 printer = getattr(obj_class, self.print_method)
241 printer = getattr(obj_class, self.print_method)
242 return printer(obj)
242 return printer(obj)
243 return None
243 return None
244 except Exception:
244 except Exception:
245 pass
245 pass
246 else:
246 else:
247 return None
247 return None
248
248
249 def for_type(self, typ, func):
249 def for_type(self, typ, func):
250 """Add a format function for a given type.
250 """Add a format function for a given type.
251
251
252 Parameters
252 Parameters
253 -----------
253 -----------
254 typ : class
254 typ : class
255 The class of the object that will be formatted using `func`.
255 The class of the object that will be formatted using `func`.
256 func : callable
256 func : callable
257 The callable that will be called to compute the format data. The
257 The callable that will be called to compute the format data. The
258 call signature of this function is simple, it must take the
258 call signature of this function is simple, it must take the
259 object to be formatted and return the raw data for the given
259 object to be formatted and return the raw data for the given
260 format. Subclasses may use a different call signature for the
260 format. Subclasses may use a different call signature for the
261 `func` argument.
261 `func` argument.
262 """
262 """
263 oldfunc = self.type_printers.get(typ, None)
263 oldfunc = self.type_printers.get(typ, None)
264 if func is not None:
264 if func is not None:
265 # To support easy restoration of old printers, we need to ignore
265 # To support easy restoration of old printers, we need to ignore
266 # Nones.
266 # Nones.
267 self.type_printers[typ] = func
267 self.type_printers[typ] = func
268 return oldfunc
268 return oldfunc
269
269
270 def for_type_by_name(self, type_module, type_name, func):
270 def for_type_by_name(self, type_module, type_name, func):
271 """Add a format function for a type specified by the full dotted
271 """Add a format function for a type specified by the full dotted
272 module and name of the type, rather than the type of the object.
272 module and name of the type, rather than the type of the object.
273
273
274 Parameters
274 Parameters
275 ----------
275 ----------
276 type_module : str
276 type_module : str
277 The full dotted name of the module the type is defined in, like
277 The full dotted name of the module the type is defined in, like
278 ``numpy``.
278 ``numpy``.
279 type_name : str
279 type_name : str
280 The name of the type (the class name), like ``dtype``
280 The name of the type (the class name), like ``dtype``
281 func : callable
281 func : callable
282 The callable that will be called to compute the format data. The
282 The callable that will be called to compute the format data. The
283 call signature of this function is simple, it must take the
283 call signature of this function is simple, it must take the
284 object to be formatted and return the raw data for the given
284 object to be formatted and return the raw data for the given
285 format. Subclasses may use a different call signature for the
285 format. Subclasses may use a different call signature for the
286 `func` argument.
286 `func` argument.
287 """
287 """
288 key = (type_module, type_name)
288 key = (type_module, type_name)
289 oldfunc = self.deferred_printers.get(key, None)
289 oldfunc = self.deferred_printers.get(key, None)
290 if func is not None:
290 if func is not None:
291 # To support easy restoration of old printers, we need to ignore
291 # To support easy restoration of old printers, we need to ignore
292 # Nones.
292 # Nones.
293 self.deferred_printers[key] = func
293 self.deferred_printers[key] = func
294 return oldfunc
294 return oldfunc
295
295
296 def _in_deferred_types(self, cls):
296 def _in_deferred_types(self, cls):
297 """
297 """
298 Check if the given class is specified in the deferred type registry.
298 Check if the given class is specified in the deferred type registry.
299
299
300 Returns the printer from the registry if it exists, and None if the
300 Returns the printer from the registry if it exists, and None if the
301 class is not in the registry. Successful matches will be moved to the
301 class is not in the registry. Successful matches will be moved to the
302 regular type registry for future use.
302 regular type registry for future use.
303 """
303 """
304 mod = getattr(cls, '__module__', None)
304 mod = getattr(cls, '__module__', None)
305 name = getattr(cls, '__name__', None)
305 name = getattr(cls, '__name__', None)
306 key = (mod, name)
306 key = (mod, name)
307 printer = None
307 printer = None
308 if key in self.deferred_printers:
308 if key in self.deferred_printers:
309 # Move the printer over to the regular registry.
309 # Move the printer over to the regular registry.
310 printer = self.deferred_printers.pop(key)
310 printer = self.deferred_printers.pop(key)
311 self.type_printers[cls] = printer
311 self.type_printers[cls] = printer
312 return printer
312 return printer
313
313
314
314
315 class PlainTextFormatter(BaseFormatter):
315 class PlainTextFormatter(BaseFormatter):
316 """The default pretty-printer.
316 """The default pretty-printer.
317
317
318 This uses :mod:`IPython.external.pretty` to compute the format data of
318 This uses :mod:`IPython.external.pretty` to compute the format data of
319 the object. If the object cannot be pretty printed, :func:`repr` is used.
319 the object. If the object cannot be pretty printed, :func:`repr` is used.
320 See the documentation of :mod:`IPython.external.pretty` for details on
320 See the documentation of :mod:`IPython.external.pretty` for details on
321 how to write pretty printers. Here is a simple example::
321 how to write pretty printers. Here is a simple example::
322
322
323 def dtype_pprinter(obj, p, cycle):
323 def dtype_pprinter(obj, p, cycle):
324 if cycle:
324 if cycle:
325 return p.text('dtype(...)')
325 return p.text('dtype(...)')
326 if hasattr(obj, 'fields'):
326 if hasattr(obj, 'fields'):
327 if obj.fields is None:
327 if obj.fields is None:
328 p.text(repr(obj))
328 p.text(repr(obj))
329 else:
329 else:
330 p.begin_group(7, 'dtype([')
330 p.begin_group(7, 'dtype([')
331 for i, field in enumerate(obj.descr):
331 for i, field in enumerate(obj.descr):
332 if i > 0:
332 if i > 0:
333 p.text(',')
333 p.text(',')
334 p.breakable()
334 p.breakable()
335 p.pretty(field)
335 p.pretty(field)
336 p.end_group(7, '])')
336 p.end_group(7, '])')
337 """
337 """
338
338
339 # The format type of data returned.
339 # The format type of data returned.
340 format_type = Str('text/plain')
340 format_type = Str('text/plain')
341
341
342 # This subclass ignores this attribute as it always need to return
342 # This subclass ignores this attribute as it always need to return
343 # something.
343 # something.
344 enabled = Bool(True, config=False)
344 enabled = Bool(True, config=False)
345
345
346 # Look for a _repr_pretty_ methods to use for pretty printing.
346 # Look for a _repr_pretty_ methods to use for pretty printing.
347 print_method = Str('_repr_pretty_')
347 print_method = Str('_repr_pretty_')
348
348
349 # Whether to pretty-print or not.
349 # Whether to pretty-print or not.
350 pprint = Bool(True, config=True)
350 pprint = Bool(True, config=True)
351
351
352 # Whether to be verbose or not.
352 # Whether to be verbose or not.
353 verbose = Bool(False, config=True)
353 verbose = Bool(False, config=True)
354
354
355 # The maximum width.
355 # The maximum width.
356 max_width = Int(79, config=True)
356 max_width = Int(79, config=True)
357
357
358 # The newline character.
358 # The newline character.
359 newline = Str('\n', config=True)
359 newline = Str('\n', config=True)
360
360
361 # format-string for pprinting floats
361 # format-string for pprinting floats
362 float_format = Str('%r')
362 float_format = Str('%r')
363 # setter for float precision, either int or direct format-string
363 # setter for float precision, either int or direct format-string
364 float_precision = CStr('', config=True)
364 float_precision = CStr('', config=True)
365
365
366 def _float_precision_changed(self, name, old, new):
366 def _float_precision_changed(self, name, old, new):
367 """float_precision changed, set float_format accordingly.
367 """float_precision changed, set float_format accordingly.
368
368
369 float_precision can be set by int or str.
369 float_precision can be set by int or str.
370 This will set float_format, after interpreting input.
370 This will set float_format, after interpreting input.
371 If numpy has been imported, numpy print precision will also be set.
371 If numpy has been imported, numpy print precision will also be set.
372
372
373 integer `n` sets format to '%.nf', otherwise, format set directly.
373 integer `n` sets format to '%.nf', otherwise, format set directly.
374
374
375 An empty string returns to defaults (repr for float, 8 for numpy).
375 An empty string returns to defaults (repr for float, 8 for numpy).
376
376
377 This parameter can be set via the '%precision' magic.
377 This parameter can be set via the '%precision' magic.
378 """
378 """
379
379
380 if '%' in new:
380 if '%' in new:
381 # got explicit format string
381 # got explicit format string
382 fmt = new
382 fmt = new
383 try:
383 try:
384 fmt%3.14159
384 fmt%3.14159
385 except Exception:
385 except Exception:
386 raise ValueError("Precision must be int or format string, not %r"%new)
386 raise ValueError("Precision must be int or format string, not %r"%new)
387 elif new:
387 elif new:
388 # otherwise, should be an int
388 # otherwise, should be an int
389 try:
389 try:
390 i = int(new)
390 i = int(new)
391 assert i >= 0
391 assert i >= 0
392 except ValueError:
392 except ValueError:
393 raise ValueError("Precision must be int or format string, not %r"%new)
393 raise ValueError("Precision must be int or format string, not %r"%new)
394 except AssertionError:
394 except AssertionError:
395 raise ValueError("int precision must be non-negative, not %r"%i)
395 raise ValueError("int precision must be non-negative, not %r"%i)
396
396
397 fmt = '%%.%if'%i
397 fmt = '%%.%if'%i
398 if 'numpy' in sys.modules:
398 if 'numpy' in sys.modules:
399 # set numpy precision if it has been imported
399 # set numpy precision if it has been imported
400 import numpy
400 import numpy
401 numpy.set_printoptions(precision=i)
401 numpy.set_printoptions(precision=i)
402 else:
402 else:
403 # default back to repr
403 # default back to repr
404 fmt = '%r'
404 fmt = '%r'
405 if 'numpy' in sys.modules:
405 if 'numpy' in sys.modules:
406 import numpy
406 import numpy
407 # numpy default is 8
407 # numpy default is 8
408 numpy.set_printoptions(precision=8)
408 numpy.set_printoptions(precision=8)
409 self.float_format = fmt
409 self.float_format = fmt
410
410
411 # Use the default pretty printers from IPython.external.pretty.
411 # Use the default pretty printers from IPython.external.pretty.
412 def _singleton_printers_default(self):
412 def _singleton_printers_default(self):
413 return pretty._singleton_pprinters.copy()
413 return pretty._singleton_pprinters.copy()
414
414
415 def _type_printers_default(self):
415 def _type_printers_default(self):
416 d = pretty._type_pprinters.copy()
416 d = pretty._type_pprinters.copy()
417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
417 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
418 return d
418 return d
419
419
420 def _deferred_printers_default(self):
420 def _deferred_printers_default(self):
421 return pretty._deferred_type_pprinters.copy()
421 return pretty._deferred_type_pprinters.copy()
422
422
423 #### FormatterABC interface ####
423 #### FormatterABC interface ####
424
424
425 def __call__(self, obj):
425 def __call__(self, obj):
426 """Compute the pretty representation of the object."""
426 """Compute the pretty representation of the object."""
427 if not self.pprint:
427 if not self.pprint:
428 try:
428 try:
429 return repr(obj)
429 return repr(obj)
430 except TypeError:
430 except TypeError:
431 return ''
431 return ''
432 else:
432 else:
433 # This uses use StringIO, as cStringIO doesn't handle unicode.
433 # This uses use StringIO, as cStringIO doesn't handle unicode.
434 stream = StringIO()
434 stream = StringIO()
435 printer = pretty.RepresentationPrinter(stream, self.verbose,
435 printer = pretty.RepresentationPrinter(stream, self.verbose,
436 self.max_width, self.newline,
436 self.max_width, self.newline,
437 singleton_pprinters=self.singleton_printers,
437 singleton_pprinters=self.singleton_printers,
438 type_pprinters=self.type_printers,
438 type_pprinters=self.type_printers,
439 deferred_pprinters=self.deferred_printers)
439 deferred_pprinters=self.deferred_printers)
440 printer.pretty(obj)
440 printer.pretty(obj)
441 printer.flush()
441 printer.flush()
442 return stream.getvalue()
442 return stream.getvalue()
443
443
444
444
445 class HTMLFormatter(BaseFormatter):
445 class HTMLFormatter(BaseFormatter):
446 """An HTML formatter.
446 """An HTML formatter.
447
447
448 To define the callables that compute the HTML representation of your
448 To define the callables that compute the HTML representation of your
449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
449 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
450 or :meth:`for_type_by_name` methods to register functions that handle
450 or :meth:`for_type_by_name` methods to register functions that handle
451 this.
451 this.
452
453 The return value of this formatter should be a valid HTML snippet that
454 could be injected into an existing DOM. It should *not* include the
455 ```<html>`` or ```<body>`` tags.
452 """
456 """
453 format_type = Str('text/html')
457 format_type = Str('text/html')
454
458
455 print_method = Str('_repr_html_')
459 print_method = Str('_repr_html_')
456
460
457
461
458 class SVGFormatter(BaseFormatter):
462 class SVGFormatter(BaseFormatter):
459 """An SVG formatter.
463 """An SVG formatter.
460
464
461 To define the callables that compute the SVG representation of your
465 To define the callables that compute the SVG representation of your
462 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
466 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
463 or :meth:`for_type_by_name` methods to register functions that handle
467 or :meth:`for_type_by_name` methods to register functions that handle
464 this.
468 this.
469
470 The return value of this formatter should be valid SVG enclosed in
471 ```<svg>``` tags, that could be injected into an existing DOM. It should
472 *not* include the ```<html>`` or ```<body>`` tags.
465 """
473 """
466 format_type = Str('image/svg+xml')
474 format_type = Str('image/svg+xml')
467
475
468 print_method = Str('_repr_svg_')
476 print_method = Str('_repr_svg_')
469
477
470
478
471 class PNGFormatter(BaseFormatter):
479 class PNGFormatter(BaseFormatter):
472 """A PNG formatter.
480 """A PNG formatter.
473
481
474 To define the callables that compute the PNG representation of your
482 To define the callables that compute the PNG representation of your
475 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
483 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
476 or :meth:`for_type_by_name` methods to register functions that handle
484 or :meth:`for_type_by_name` methods to register functions that handle
477 this.
485 this.
478
486
479 The raw data should be the base64 encoded raw png data.
487 The return value of this formatter should be raw PNG data, *not*
488 base64 encoded.
480 """
489 """
481 format_type = Str('image/png')
490 format_type = Str('image/png')
482
491
483 print_method = Str('_repr_png_')
492 print_method = Str('_repr_png_')
484
493
485
494
486 class LatexFormatter(BaseFormatter):
495 class LatexFormatter(BaseFormatter):
487 """A LaTeX formatter.
496 """A LaTeX formatter.
488
497
489 To define the callables that compute the LaTeX representation of your
498 To define the callables that compute the LaTeX representation of your
490 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
499 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
491 or :meth:`for_type_by_name` methods to register functions that handle
500 or :meth:`for_type_by_name` methods to register functions that handle
492 this.
501 this.
502
503 The return value of this formatter should be a valid LaTeX equation,
504 enclosed in either ```$``` or ```$$```.
493 """
505 """
494 format_type = Str('text/latex')
506 format_type = Str('text/latex')
495
507
496 print_method = Str('_repr_latex_')
508 print_method = Str('_repr_latex_')
497
509
498
510
499 class JSONFormatter(BaseFormatter):
511 class JSONFormatter(BaseFormatter):
500 """A JSON string formatter.
512 """A JSON string formatter.
501
513
502 To define the callables that compute the JSON string representation of
514 To define the callables that compute the JSON string representation of
503 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
515 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
504 or :meth:`for_type_by_name` methods to register functions that handle
516 or :meth:`for_type_by_name` methods to register functions that handle
505 this.
517 this.
518
519 The return value of this formatter should be a valid JSON string.
506 """
520 """
507 format_type = Str('application/json')
521 format_type = Str('application/json')
508
522
509 print_method = Str('_repr_json_')
523 print_method = Str('_repr_json_')
510
524
511
525
512 class JavascriptFormatter(BaseFormatter):
526 class JavascriptFormatter(BaseFormatter):
513 """A Javascript formatter.
527 """A Javascript formatter.
514
528
515 To define the callables that compute the Javascript representation of
529 To define the callables that compute the Javascript representation of
516 your objects, define a :meth:`_repr_javascript_` method or use the
530 your objects, define a :meth:`_repr_javascript_` method or use the
517 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
531 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
518 that handle this.
532 that handle this.
533
534 The return value of this formatter should be valid Javascript code and
535 should *not* be enclosed in ```<script>``` tags.
519 """
536 """
520 format_type = Str('application/javascript')
537 format_type = Str('application/javascript')
521
538
522 print_method = Str('_repr_javascript_')
539 print_method = Str('_repr_javascript_')
523
540
524 FormatterABC.register(BaseFormatter)
541 FormatterABC.register(BaseFormatter)
525 FormatterABC.register(PlainTextFormatter)
542 FormatterABC.register(PlainTextFormatter)
526 FormatterABC.register(HTMLFormatter)
543 FormatterABC.register(HTMLFormatter)
527 FormatterABC.register(SVGFormatter)
544 FormatterABC.register(SVGFormatter)
528 FormatterABC.register(PNGFormatter)
545 FormatterABC.register(PNGFormatter)
529 FormatterABC.register(LatexFormatter)
546 FormatterABC.register(LatexFormatter)
530 FormatterABC.register(JSONFormatter)
547 FormatterABC.register(JSONFormatter)
531 FormatterABC.register(JavascriptFormatter)
548 FormatterABC.register(JavascriptFormatter)
532
549
533
550
534 def format_display_data(obj, include=None, exclude=None):
551 def format_display_data(obj, include=None, exclude=None):
535 """Return a format data dict for an object.
552 """Return a format data dict for an object.
536
553
537 By default all format types will be computed.
554 By default all format types will be computed.
538
555
539 The following MIME types are currently implemented:
556 The following MIME types are currently implemented:
540
557
541 * text/plain
558 * text/plain
542 * text/html
559 * text/html
543 * text/latex
560 * text/latex
544 * application/json
561 * application/json
545 * image/png
562 * image/png
546 * immage/svg+xml
563 * immage/svg+xml
547
564
548 Parameters
565 Parameters
549 ----------
566 ----------
550 obj : object
567 obj : object
551 The Python object whose format data will be computed.
568 The Python object whose format data will be computed.
552
569
553 Returns
570 Returns
554 -------
571 -------
555 format_dict : dict
572 format_dict : dict
556 A dictionary of key/value pairs, one or each format that was
573 A dictionary of key/value pairs, one or each format that was
557 generated for the object. The keys are the format types, which
574 generated for the object. The keys are the format types, which
558 will usually be MIME type strings and the values and JSON'able
575 will usually be MIME type strings and the values and JSON'able
559 data structure containing the raw data for the representation in
576 data structure containing the raw data for the representation in
560 that format.
577 that format.
561 include : list or tuple, optional
578 include : list or tuple, optional
562 A list of format type strings (MIME types) to include in the
579 A list of format type strings (MIME types) to include in the
563 format data dict. If this is set *only* the format types included
580 format data dict. If this is set *only* the format types included
564 in this list will be computed.
581 in this list will be computed.
565 exclude : list or tuple, optional
582 exclude : list or tuple, optional
566 A list of format type string (MIME types) to exclue in the format
583 A list of format type string (MIME types) to exclue in the format
567 data dict. If this is set all format types will be computed,
584 data dict. If this is set all format types will be computed,
568 except for those included in this argument.
585 except for those included in this argument.
569 """
586 """
570 from IPython.core.interactiveshell import InteractiveShell
587 from IPython.core.interactiveshell import InteractiveShell
571
588
572 InteractiveShell.instance().display_formatter.format(
589 InteractiveShell.instance().display_formatter.format(
573 obj,
590 obj,
574 include,
591 include,
575 exclude
592 exclude
576 )
593 )
@@ -1,70 +1,70 b''
1 """A print function that pretty prints sympy Basic objects.
1 """A print function that pretty prints sympy Basic objects.
2
2
3 Authors:
3 Authors:
4 * Brian Granger
4 * Brian Granger
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
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 IPython.lib.latextools import latex_to_png
17 from IPython.lib.latextools import latex_to_png
18 from IPython.testing import decorators as dec
18 from IPython.testing import decorators as dec
19 # use @dec.skipif_not_sympy to skip tests requiring sympy
19 # use @dec.skipif_not_sympy to skip tests requiring sympy
20
20
21 try:
21 try:
22 from sympy import pretty, latex
22 from sympy import pretty, latex
23 except ImportError:
23 except ImportError:
24 pass
24 pass
25
25
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Definitions of magic functions for use with IPython
28 # Definitions of magic functions for use with IPython
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 def print_basic_unicode(o, p, cycle):
31 def print_basic_unicode(o, p, cycle):
32 """A function to pretty print sympy Basic objects."""
32 """A function to pretty print sympy Basic objects."""
33 if cycle:
33 if cycle:
34 return p.text('Basic(...)')
34 return p.text('Basic(...)')
35 out = pretty(o, use_unicode=True)
35 out = pretty(o, use_unicode=True)
36 if '\n' in out:
36 if '\n' in out:
37 p.text(u'\n')
37 p.text(u'\n')
38 p.text(out)
38 p.text(out)
39
39
40
40
41 def print_png(o):
41 def print_png(o):
42 """A function to display sympy expression using LaTex -> PNG."""
42 """A function to display sympy expression using LaTex -> PNG."""
43 s = latex(o, mode='inline')
43 s = latex(o, mode='inline')
44 # mathtext does not understand certain latex flags, so we try to replace
44 # mathtext does not understand certain latex flags, so we try to replace
45 # them with suitable subs.
45 # them with suitable subs.
46 s = s.replace('\\operatorname','')
46 s = s.replace('\\operatorname','')
47 s = s.replace('\\overline', '\\bar')
47 s = s.replace('\\overline', '\\bar')
48 png = latex_to_png(s, encode=True)
48 png = latex_to_png(s)
49 return png
49 return png
50
50
51 _loaded = False
51 _loaded = False
52
52
53 def load_ipython_extension(ip):
53 def load_ipython_extension(ip):
54 """Load the extension in IPython."""
54 """Load the extension in IPython."""
55 global _loaded
55 global _loaded
56 if not _loaded:
56 if not _loaded:
57 plaintext_formatter = ip.display_formatter.formatters['text/plain']
57 plaintext_formatter = ip.display_formatter.formatters['text/plain']
58 plaintext_formatter.for_type_by_name(
58 plaintext_formatter.for_type_by_name(
59 'sympy.core.basic', 'Basic', print_basic_unicode
59 'sympy.core.basic', 'Basic', print_basic_unicode
60 )
60 )
61 plaintext_formatter.for_type_by_name(
61 plaintext_formatter.for_type_by_name(
62 'sympy.matrices.matrices', 'Matrix', print_basic_unicode
62 'sympy.matrices.matrices', 'Matrix', print_basic_unicode
63 )
63 )
64
64
65 png_formatter = ip.display_formatter.formatters['image/png']
65 png_formatter = ip.display_formatter.formatters['image/png']
66 png_formatter.for_type_by_name(
66 png_formatter.for_type_by_name(
67 'sympy.core.basic', 'Basic', print_png
67 'sympy.core.basic', 'Basic', print_png
68 )
68 )
69 _loaded = True
69 _loaded = True
70
70
@@ -1,62 +1,62 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tools for handling LaTeX.
2 """Tools for handling LaTeX.
3
3
4 Authors:
4 Authors:
5
5
6 * Brian Granger
6 * Brian Granger
7 """
7 """
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (c) 2010, IPython Development Team.
9 # Copyright (c) 2010, IPython Development Team.
10 #
10 #
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12 #
12 #
13 # The full license is in the file COPYING.txt, distributed with this software.
13 # The full license is in the file COPYING.txt, distributed with this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from StringIO import StringIO
20 from StringIO import StringIO
21 from base64 import encodestring
21 from base64 import encodestring
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Tools
24 # Tools
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27
27
28 def latex_to_png(s, encode=True):
28 def latex_to_png(s, encode=False):
29 """Render a LaTeX string to PNG using matplotlib.mathtext.
29 """Render a LaTeX string to PNG using matplotlib.mathtext.
30
30
31 Parameters
31 Parameters
32 ----------
32 ----------
33 s : str
33 s : str
34 The raw string containing valid inline LaTeX.
34 The raw string containing valid inline LaTeX.
35 encode : bool, optional
35 encode : bool, optional
36 Should the PNG data bebase64 encoded to make it JSON'able.
36 Should the PNG data bebase64 encoded to make it JSON'able.
37 """
37 """
38 from matplotlib import mathtext
38 from matplotlib import mathtext
39
39
40 mt = mathtext.MathTextParser('bitmap')
40 mt = mathtext.MathTextParser('bitmap')
41 f = StringIO()
41 f = StringIO()
42 mt.to_png(f, s, fontsize=12)
42 mt.to_png(f, s, fontsize=12)
43 bin_data = f.getvalue()
43 bin_data = f.getvalue()
44 if encode:
44 if encode:
45 bin_data = encodestring(bin_data)
45 bin_data = encodestring(bin_data)
46 return bin_data
46 return bin_data
47
47
48 _data_uri_template_png = """<img src="data:image/png;base64,%s" alt=%s />"""
48 _data_uri_template_png = """<img src="data:image/png;base64,%s" alt=%s />"""
49
49
50 def latex_to_html(s, alt='image'):
50 def latex_to_html(s, alt='image'):
51 """Render LaTeX to HTML with embedded PNG data using data URIs.
51 """Render LaTeX to HTML with embedded PNG data using data URIs.
52
52
53 Parameters
53 Parameters
54 ----------
54 ----------
55 s : str
55 s : str
56 The raw string containing valid inline LateX.
56 The raw string containing valid inline LateX.
57 alt : str
57 alt : str
58 The alt text to use for the HTML.
58 The alt text to use for the HTML.
59 """
59 """
60 base64_data = latex_to_png(s, encode=True)
60 base64_data = latex_to_png(s, encode=True)
61 return _data_uri_template_png % (base64_data, alt)
61 return _data_uri_template_png % (base64_data, alt)
62
62
@@ -1,588 +1,592 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 from base64 import encodestring
19 import inspect
20 import inspect
20 import os
21 import os
21
22
22 # Our own
23 # Our own
23 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
24 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
25 )
26 )
26 from IPython.core import page
27 from IPython.core import page
27 from IPython.core.autocall import ZMQExitAutocall
28 from IPython.core.autocall import ZMQExitAutocall
28 from IPython.core.displayhook import DisplayHook
29 from IPython.core.displayhook import DisplayHook
29 from IPython.core.displaypub import DisplayPublisher
30 from IPython.core.displaypub import DisplayPublisher
30 from IPython.core.macro import Macro
31 from IPython.core.macro import Macro
31 from IPython.core.payloadpage import install_payload_page
32 from IPython.core.payloadpage import install_payload_page
32 from IPython.utils import io
33 from IPython.utils import io
33 from IPython.utils.path import get_py_filename
34 from IPython.utils.path import get_py_filename
34 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.warn import warn
36 from IPython.utils.warn import warn
36 from IPython.zmq.session import extract_header
37 from IPython.zmq.session import extract_header
37 from session import Session
38 from session import Session
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Globals and side-effects
41 # Globals and side-effects
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42
43
43 # Install the payload version of page.
44 # Install the payload version of page.
44 install_payload_page()
45 install_payload_page()
45
46
46 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
47 # Functions and classes
48 # Functions and classes
48 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
49
50
50 class ZMQDisplayHook(DisplayHook):
51 class ZMQDisplayHook(DisplayHook):
51 """A displayhook subclass that publishes data using ZeroMQ."""
52 """A displayhook subclass that publishes data using ZeroMQ."""
52
53
53 session = Instance(Session)
54 session = Instance(Session)
54 pub_socket = Instance('zmq.Socket')
55 pub_socket = Instance('zmq.Socket')
55 parent_header = Dict({})
56 parent_header = Dict({})
56
57
57 def set_parent(self, parent):
58 def set_parent(self, parent):
58 """Set the parent for outbound messages."""
59 """Set the parent for outbound messages."""
59 self.parent_header = extract_header(parent)
60 self.parent_header = extract_header(parent)
60
61
61 def start_displayhook(self):
62 def start_displayhook(self):
62 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
63 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
63
64
64 def write_output_prompt(self):
65 def write_output_prompt(self):
65 """Write the output prompt."""
66 """Write the output prompt."""
66 if self.do_full_cache:
67 if self.do_full_cache:
67 self.msg['content']['execution_count'] = self.prompt_count
68 self.msg['content']['execution_count'] = self.prompt_count
68
69
69 def write_format_data(self, format_dict):
70 def write_format_data(self, format_dict):
71 pngdata = format_dict.get('image/png')
72 if pngdata is not None:
73 format_dict['image/png'] = encodestring(pngdata)
70 self.msg['content']['data'] = format_dict
74 self.msg['content']['data'] = format_dict
71
75
72 def finish_displayhook(self):
76 def finish_displayhook(self):
73 """Finish up all displayhook activities."""
77 """Finish up all displayhook activities."""
74 self.session.send(self.pub_socket, self.msg)
78 self.session.send(self.pub_socket, self.msg)
75 self.msg = None
79 self.msg = None
76
80
77
81
78 class ZMQDisplayPublisher(DisplayPublisher):
82 class ZMQDisplayPublisher(DisplayPublisher):
79 """A display publisher that publishes data using a ZeroMQ PUB socket."""
83 """A display publisher that publishes data using a ZeroMQ PUB socket."""
80
84
81 session = Instance(Session)
85 session = Instance(Session)
82 pub_socket = Instance('zmq.Socket')
86 pub_socket = Instance('zmq.Socket')
83 parent_header = Dict({})
87 parent_header = Dict({})
84
88
85 def set_parent(self, parent):
89 def set_parent(self, parent):
86 """Set the parent for outbound messages."""
90 """Set the parent for outbound messages."""
87 self.parent_header = extract_header(parent)
91 self.parent_header = extract_header(parent)
88
92
89 def publish(self, source, data, metadata=None):
93 def publish(self, source, data, metadata=None):
90 if metadata is None:
94 if metadata is None:
91 metadata = {}
95 metadata = {}
92 self._validate_data(source, data, metadata)
96 self._validate_data(source, data, metadata)
93 content = {}
97 content = {}
94 content['source'] = source
98 content['source'] = source
95 content['data'] = data
99 content['data'] = data
96 content['metadata'] = metadata
100 content['metadata'] = metadata
97 self.session.send(
101 self.session.send(
98 self.pub_socket, u'display_data', content,
102 self.pub_socket, u'display_data', content,
99 parent=self.parent_header
103 parent=self.parent_header
100 )
104 )
101
105
102
106
103 class ZMQInteractiveShell(InteractiveShell):
107 class ZMQInteractiveShell(InteractiveShell):
104 """A subclass of InteractiveShell for ZMQ."""
108 """A subclass of InteractiveShell for ZMQ."""
105
109
106 displayhook_class = Type(ZMQDisplayHook)
110 displayhook_class = Type(ZMQDisplayHook)
107 display_pub_class = Type(ZMQDisplayPublisher)
111 display_pub_class = Type(ZMQDisplayPublisher)
108
112
109 exiter = Instance(ZMQExitAutocall)
113 exiter = Instance(ZMQExitAutocall)
110 def _exiter_default(self):
114 def _exiter_default(self):
111 return ZMQExitAutocall(self)
115 return ZMQExitAutocall(self)
112
116
113 keepkernel_on_exit = None
117 keepkernel_on_exit = None
114
118
115 def init_environment(self):
119 def init_environment(self):
116 """Configure the user's environment.
120 """Configure the user's environment.
117
121
118 """
122 """
119 env = os.environ
123 env = os.environ
120 # These two ensure 'ls' produces nice coloring on BSD-derived systems
124 # These two ensure 'ls' produces nice coloring on BSD-derived systems
121 env['TERM'] = 'xterm-color'
125 env['TERM'] = 'xterm-color'
122 env['CLICOLOR'] = '1'
126 env['CLICOLOR'] = '1'
123 # Since normal pagers don't work at all (over pexpect we don't have
127 # Since normal pagers don't work at all (over pexpect we don't have
124 # single-key control of the subprocess), try to disable paging in
128 # single-key control of the subprocess), try to disable paging in
125 # subprocesses as much as possible.
129 # subprocesses as much as possible.
126 env['PAGER'] = 'cat'
130 env['PAGER'] = 'cat'
127 env['GIT_PAGER'] = 'cat'
131 env['GIT_PAGER'] = 'cat'
128
132
129 def auto_rewrite_input(self, cmd):
133 def auto_rewrite_input(self, cmd):
130 """Called to show the auto-rewritten input for autocall and friends.
134 """Called to show the auto-rewritten input for autocall and friends.
131
135
132 FIXME: this payload is currently not correctly processed by the
136 FIXME: this payload is currently not correctly processed by the
133 frontend.
137 frontend.
134 """
138 """
135 new = self.displayhook.prompt1.auto_rewrite() + cmd
139 new = self.displayhook.prompt1.auto_rewrite() + cmd
136 payload = dict(
140 payload = dict(
137 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
141 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
138 transformed_input=new,
142 transformed_input=new,
139 )
143 )
140 self.payload_manager.write_payload(payload)
144 self.payload_manager.write_payload(payload)
141
145
142 def ask_exit(self):
146 def ask_exit(self):
143 """Engage the exit actions."""
147 """Engage the exit actions."""
144 payload = dict(
148 payload = dict(
145 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
149 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
146 exit=True,
150 exit=True,
147 keepkernel=self.keepkernel_on_exit,
151 keepkernel=self.keepkernel_on_exit,
148 )
152 )
149 self.payload_manager.write_payload(payload)
153 self.payload_manager.write_payload(payload)
150
154
151 def _showtraceback(self, etype, evalue, stb):
155 def _showtraceback(self, etype, evalue, stb):
152
156
153 exc_content = {
157 exc_content = {
154 u'traceback' : stb,
158 u'traceback' : stb,
155 u'ename' : unicode(etype.__name__),
159 u'ename' : unicode(etype.__name__),
156 u'evalue' : unicode(evalue)
160 u'evalue' : unicode(evalue)
157 }
161 }
158
162
159 dh = self.displayhook
163 dh = self.displayhook
160 # Send exception info over pub socket for other clients than the caller
164 # Send exception info over pub socket for other clients than the caller
161 # to pick up
165 # to pick up
162 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
166 exc_msg = dh.session.send(dh.pub_socket, u'pyerr', exc_content, dh.parent_header)
163
167
164 # FIXME - Hack: store exception info in shell object. Right now, the
168 # FIXME - Hack: store exception info in shell object. Right now, the
165 # caller is reading this info after the fact, we need to fix this logic
169 # caller is reading this info after the fact, we need to fix this logic
166 # to remove this hack. Even uglier, we need to store the error status
170 # to remove this hack. Even uglier, we need to store the error status
167 # here, because in the main loop, the logic that sets it is being
171 # here, because in the main loop, the logic that sets it is being
168 # skipped because runlines swallows the exceptions.
172 # skipped because runlines swallows the exceptions.
169 exc_content[u'status'] = u'error'
173 exc_content[u'status'] = u'error'
170 self._reply_content = exc_content
174 self._reply_content = exc_content
171 # /FIXME
175 # /FIXME
172
176
173 return exc_content
177 return exc_content
174
178
175 #------------------------------------------------------------------------
179 #------------------------------------------------------------------------
176 # Magic overrides
180 # Magic overrides
177 #------------------------------------------------------------------------
181 #------------------------------------------------------------------------
178 # Once the base class stops inheriting from magic, this code needs to be
182 # Once the base class stops inheriting from magic, this code needs to be
179 # moved into a separate machinery as well. For now, at least isolate here
183 # moved into a separate machinery as well. For now, at least isolate here
180 # the magics which this class needs to implement differently from the base
184 # the magics which this class needs to implement differently from the base
181 # class, or that are unique to it.
185 # class, or that are unique to it.
182
186
183 def magic_doctest_mode(self,parameter_s=''):
187 def magic_doctest_mode(self,parameter_s=''):
184 """Toggle doctest mode on and off.
188 """Toggle doctest mode on and off.
185
189
186 This mode is intended to make IPython behave as much as possible like a
190 This mode is intended to make IPython behave as much as possible like a
187 plain Python shell, from the perspective of how its prompts, exceptions
191 plain Python shell, from the perspective of how its prompts, exceptions
188 and output look. This makes it easy to copy and paste parts of a
192 and output look. This makes it easy to copy and paste parts of a
189 session into doctests. It does so by:
193 session into doctests. It does so by:
190
194
191 - Changing the prompts to the classic ``>>>`` ones.
195 - Changing the prompts to the classic ``>>>`` ones.
192 - Changing the exception reporting mode to 'Plain'.
196 - Changing the exception reporting mode to 'Plain'.
193 - Disabling pretty-printing of output.
197 - Disabling pretty-printing of output.
194
198
195 Note that IPython also supports the pasting of code snippets that have
199 Note that IPython also supports the pasting of code snippets that have
196 leading '>>>' and '...' prompts in them. This means that you can paste
200 leading '>>>' and '...' prompts in them. This means that you can paste
197 doctests from files or docstrings (even if they have leading
201 doctests from files or docstrings (even if they have leading
198 whitespace), and the code will execute correctly. You can then use
202 whitespace), and the code will execute correctly. You can then use
199 '%history -t' to see the translated history; this will give you the
203 '%history -t' to see the translated history; this will give you the
200 input after removal of all the leading prompts and whitespace, which
204 input after removal of all the leading prompts and whitespace, which
201 can be pasted back into an editor.
205 can be pasted back into an editor.
202
206
203 With these features, you can switch into this mode easily whenever you
207 With these features, you can switch into this mode easily whenever you
204 need to do testing and changes to doctests, without having to leave
208 need to do testing and changes to doctests, without having to leave
205 your existing IPython session.
209 your existing IPython session.
206 """
210 """
207
211
208 from IPython.utils.ipstruct import Struct
212 from IPython.utils.ipstruct import Struct
209
213
210 # Shorthands
214 # Shorthands
211 shell = self.shell
215 shell = self.shell
212 disp_formatter = self.shell.display_formatter
216 disp_formatter = self.shell.display_formatter
213 ptformatter = disp_formatter.formatters['text/plain']
217 ptformatter = disp_formatter.formatters['text/plain']
214 # dstore is a data store kept in the instance metadata bag to track any
218 # dstore is a data store kept in the instance metadata bag to track any
215 # changes we make, so we can undo them later.
219 # changes we make, so we can undo them later.
216 dstore = shell.meta.setdefault('doctest_mode', Struct())
220 dstore = shell.meta.setdefault('doctest_mode', Struct())
217 save_dstore = dstore.setdefault
221 save_dstore = dstore.setdefault
218
222
219 # save a few values we'll need to recover later
223 # save a few values we'll need to recover later
220 mode = save_dstore('mode', False)
224 mode = save_dstore('mode', False)
221 save_dstore('rc_pprint', ptformatter.pprint)
225 save_dstore('rc_pprint', ptformatter.pprint)
222 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
226 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
223 save_dstore('xmode', shell.InteractiveTB.mode)
227 save_dstore('xmode', shell.InteractiveTB.mode)
224
228
225 if mode == False:
229 if mode == False:
226 # turn on
230 # turn on
227 ptformatter.pprint = False
231 ptformatter.pprint = False
228 disp_formatter.plain_text_only = True
232 disp_formatter.plain_text_only = True
229 shell.magic_xmode('Plain')
233 shell.magic_xmode('Plain')
230 else:
234 else:
231 # turn off
235 # turn off
232 ptformatter.pprint = dstore.rc_pprint
236 ptformatter.pprint = dstore.rc_pprint
233 disp_formatter.plain_text_only = dstore.rc_plain_text_only
237 disp_formatter.plain_text_only = dstore.rc_plain_text_only
234 shell.magic_xmode(dstore.xmode)
238 shell.magic_xmode(dstore.xmode)
235
239
236 # Store new mode and inform on console
240 # Store new mode and inform on console
237 dstore.mode = bool(1-int(mode))
241 dstore.mode = bool(1-int(mode))
238 mode_label = ['OFF','ON'][dstore.mode]
242 mode_label = ['OFF','ON'][dstore.mode]
239 print('Doctest mode is:', mode_label)
243 print('Doctest mode is:', mode_label)
240
244
241 # Send the payload back so that clients can modify their prompt display
245 # Send the payload back so that clients can modify their prompt display
242 payload = dict(
246 payload = dict(
243 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
247 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
244 mode=dstore.mode)
248 mode=dstore.mode)
245 self.payload_manager.write_payload(payload)
249 self.payload_manager.write_payload(payload)
246
250
247 def magic_edit(self,parameter_s='',last_call=['','']):
251 def magic_edit(self,parameter_s='',last_call=['','']):
248 """Bring up an editor and execute the resulting code.
252 """Bring up an editor and execute the resulting code.
249
253
250 Usage:
254 Usage:
251 %edit [options] [args]
255 %edit [options] [args]
252
256
253 %edit runs IPython's editor hook. The default version of this hook is
257 %edit runs IPython's editor hook. The default version of this hook is
254 set to call the __IPYTHON__.rc.editor command. This is read from your
258 set to call the __IPYTHON__.rc.editor command. This is read from your
255 environment variable $EDITOR. If this isn't found, it will default to
259 environment variable $EDITOR. If this isn't found, it will default to
256 vi under Linux/Unix and to notepad under Windows. See the end of this
260 vi under Linux/Unix and to notepad under Windows. See the end of this
257 docstring for how to change the editor hook.
261 docstring for how to change the editor hook.
258
262
259 You can also set the value of this editor via the command line option
263 You can also set the value of this editor via the command line option
260 '-editor' or in your ipythonrc file. This is useful if you wish to use
264 '-editor' or in your ipythonrc file. This is useful if you wish to use
261 specifically for IPython an editor different from your typical default
265 specifically for IPython an editor different from your typical default
262 (and for Windows users who typically don't set environment variables).
266 (and for Windows users who typically don't set environment variables).
263
267
264 This command allows you to conveniently edit multi-line code right in
268 This command allows you to conveniently edit multi-line code right in
265 your IPython session.
269 your IPython session.
266
270
267 If called without arguments, %edit opens up an empty editor with a
271 If called without arguments, %edit opens up an empty editor with a
268 temporary file and will execute the contents of this file when you
272 temporary file and will execute the contents of this file when you
269 close it (don't forget to save it!).
273 close it (don't forget to save it!).
270
274
271
275
272 Options:
276 Options:
273
277
274 -n <number>: open the editor at a specified line number. By default,
278 -n <number>: open the editor at a specified line number. By default,
275 the IPython editor hook uses the unix syntax 'editor +N filename', but
279 the IPython editor hook uses the unix syntax 'editor +N filename', but
276 you can configure this by providing your own modified hook if your
280 you can configure this by providing your own modified hook if your
277 favorite editor supports line-number specifications with a different
281 favorite editor supports line-number specifications with a different
278 syntax.
282 syntax.
279
283
280 -p: this will call the editor with the same data as the previous time
284 -p: this will call the editor with the same data as the previous time
281 it was used, regardless of how long ago (in your current session) it
285 it was used, regardless of how long ago (in your current session) it
282 was.
286 was.
283
287
284 -r: use 'raw' input. This option only applies to input taken from the
288 -r: use 'raw' input. This option only applies to input taken from the
285 user's history. By default, the 'processed' history is used, so that
289 user's history. By default, the 'processed' history is used, so that
286 magics are loaded in their transformed version to valid Python. If
290 magics are loaded in their transformed version to valid Python. If
287 this option is given, the raw input as typed as the command line is
291 this option is given, the raw input as typed as the command line is
288 used instead. When you exit the editor, it will be executed by
292 used instead. When you exit the editor, it will be executed by
289 IPython's own processor.
293 IPython's own processor.
290
294
291 -x: do not execute the edited code immediately upon exit. This is
295 -x: do not execute the edited code immediately upon exit. This is
292 mainly useful if you are editing programs which need to be called with
296 mainly useful if you are editing programs which need to be called with
293 command line arguments, which you can then do using %run.
297 command line arguments, which you can then do using %run.
294
298
295
299
296 Arguments:
300 Arguments:
297
301
298 If arguments are given, the following possibilites exist:
302 If arguments are given, the following possibilites exist:
299
303
300 - The arguments are numbers or pairs of colon-separated numbers (like
304 - The arguments are numbers or pairs of colon-separated numbers (like
301 1 4:8 9). These are interpreted as lines of previous input to be
305 1 4:8 9). These are interpreted as lines of previous input to be
302 loaded into the editor. The syntax is the same of the %macro command.
306 loaded into the editor. The syntax is the same of the %macro command.
303
307
304 - If the argument doesn't start with a number, it is evaluated as a
308 - If the argument doesn't start with a number, it is evaluated as a
305 variable and its contents loaded into the editor. You can thus edit
309 variable and its contents loaded into the editor. You can thus edit
306 any string which contains python code (including the result of
310 any string which contains python code (including the result of
307 previous edits).
311 previous edits).
308
312
309 - If the argument is the name of an object (other than a string),
313 - If the argument is the name of an object (other than a string),
310 IPython will try to locate the file where it was defined and open the
314 IPython will try to locate the file where it was defined and open the
311 editor at the point where it is defined. You can use `%edit function`
315 editor at the point where it is defined. You can use `%edit function`
312 to load an editor exactly at the point where 'function' is defined,
316 to load an editor exactly at the point where 'function' is defined,
313 edit it and have the file be executed automatically.
317 edit it and have the file be executed automatically.
314
318
315 If the object is a macro (see %macro for details), this opens up your
319 If the object is a macro (see %macro for details), this opens up your
316 specified editor with a temporary file containing the macro's data.
320 specified editor with a temporary file containing the macro's data.
317 Upon exit, the macro is reloaded with the contents of the file.
321 Upon exit, the macro is reloaded with the contents of the file.
318
322
319 Note: opening at an exact line is only supported under Unix, and some
323 Note: opening at an exact line is only supported under Unix, and some
320 editors (like kedit and gedit up to Gnome 2.8) do not understand the
324 editors (like kedit and gedit up to Gnome 2.8) do not understand the
321 '+NUMBER' parameter necessary for this feature. Good editors like
325 '+NUMBER' parameter necessary for this feature. Good editors like
322 (X)Emacs, vi, jed, pico and joe all do.
326 (X)Emacs, vi, jed, pico and joe all do.
323
327
324 - If the argument is not found as a variable, IPython will look for a
328 - If the argument is not found as a variable, IPython will look for a
325 file with that name (adding .py if necessary) and load it into the
329 file with that name (adding .py if necessary) and load it into the
326 editor. It will execute its contents with execfile() when you exit,
330 editor. It will execute its contents with execfile() when you exit,
327 loading any code in the file into your interactive namespace.
331 loading any code in the file into your interactive namespace.
328
332
329 After executing your code, %edit will return as output the code you
333 After executing your code, %edit will return as output the code you
330 typed in the editor (except when it was an existing file). This way
334 typed in the editor (except when it was an existing file). This way
331 you can reload the code in further invocations of %edit as a variable,
335 you can reload the code in further invocations of %edit as a variable,
332 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
336 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
333 the output.
337 the output.
334
338
335 Note that %edit is also available through the alias %ed.
339 Note that %edit is also available through the alias %ed.
336
340
337 This is an example of creating a simple function inside the editor and
341 This is an example of creating a simple function inside the editor and
338 then modifying it. First, start up the editor:
342 then modifying it. First, start up the editor:
339
343
340 In [1]: ed
344 In [1]: ed
341 Editing... done. Executing edited code...
345 Editing... done. Executing edited code...
342 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
346 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
343
347
344 We can then call the function foo():
348 We can then call the function foo():
345
349
346 In [2]: foo()
350 In [2]: foo()
347 foo() was defined in an editing session
351 foo() was defined in an editing session
348
352
349 Now we edit foo. IPython automatically loads the editor with the
353 Now we edit foo. IPython automatically loads the editor with the
350 (temporary) file where foo() was previously defined:
354 (temporary) file where foo() was previously defined:
351
355
352 In [3]: ed foo
356 In [3]: ed foo
353 Editing... done. Executing edited code...
357 Editing... done. Executing edited code...
354
358
355 And if we call foo() again we get the modified version:
359 And if we call foo() again we get the modified version:
356
360
357 In [4]: foo()
361 In [4]: foo()
358 foo() has now been changed!
362 foo() has now been changed!
359
363
360 Here is an example of how to edit a code snippet successive
364 Here is an example of how to edit a code snippet successive
361 times. First we call the editor:
365 times. First we call the editor:
362
366
363 In [5]: ed
367 In [5]: ed
364 Editing... done. Executing edited code...
368 Editing... done. Executing edited code...
365 hello
369 hello
366 Out[5]: "print 'hello'n"
370 Out[5]: "print 'hello'n"
367
371
368 Now we call it again with the previous output (stored in _):
372 Now we call it again with the previous output (stored in _):
369
373
370 In [6]: ed _
374 In [6]: ed _
371 Editing... done. Executing edited code...
375 Editing... done. Executing edited code...
372 hello world
376 hello world
373 Out[6]: "print 'hello world'n"
377 Out[6]: "print 'hello world'n"
374
378
375 Now we call it with the output #8 (stored in _8, also as Out[8]):
379 Now we call it with the output #8 (stored in _8, also as Out[8]):
376
380
377 In [7]: ed _8
381 In [7]: ed _8
378 Editing... done. Executing edited code...
382 Editing... done. Executing edited code...
379 hello again
383 hello again
380 Out[7]: "print 'hello again'n"
384 Out[7]: "print 'hello again'n"
381
385
382
386
383 Changing the default editor hook:
387 Changing the default editor hook:
384
388
385 If you wish to write your own editor hook, you can put it in a
389 If you wish to write your own editor hook, you can put it in a
386 configuration file which you load at startup time. The default hook
390 configuration file which you load at startup time. The default hook
387 is defined in the IPython.core.hooks module, and you can use that as a
391 is defined in the IPython.core.hooks module, and you can use that as a
388 starting example for further modifications. That file also has
392 starting example for further modifications. That file also has
389 general instructions on how to set a new hook for use once you've
393 general instructions on how to set a new hook for use once you've
390 defined it."""
394 defined it."""
391
395
392 # FIXME: This function has become a convoluted mess. It needs a
396 # FIXME: This function has become a convoluted mess. It needs a
393 # ground-up rewrite with clean, simple logic.
397 # ground-up rewrite with clean, simple logic.
394
398
395 def make_filename(arg):
399 def make_filename(arg):
396 "Make a filename from the given args"
400 "Make a filename from the given args"
397 try:
401 try:
398 filename = get_py_filename(arg)
402 filename = get_py_filename(arg)
399 except IOError:
403 except IOError:
400 if args.endswith('.py'):
404 if args.endswith('.py'):
401 filename = arg
405 filename = arg
402 else:
406 else:
403 filename = None
407 filename = None
404 return filename
408 return filename
405
409
406 # custom exceptions
410 # custom exceptions
407 class DataIsObject(Exception): pass
411 class DataIsObject(Exception): pass
408
412
409 opts,args = self.parse_options(parameter_s,'prn:')
413 opts,args = self.parse_options(parameter_s,'prn:')
410 # Set a few locals from the options for convenience:
414 # Set a few locals from the options for convenience:
411 opts_p = opts.has_key('p')
415 opts_p = opts.has_key('p')
412 opts_r = opts.has_key('r')
416 opts_r = opts.has_key('r')
413
417
414 # Default line number value
418 # Default line number value
415 lineno = opts.get('n',None)
419 lineno = opts.get('n',None)
416 if lineno is not None:
420 if lineno is not None:
417 try:
421 try:
418 lineno = int(lineno)
422 lineno = int(lineno)
419 except:
423 except:
420 warn("The -n argument must be an integer.")
424 warn("The -n argument must be an integer.")
421 return
425 return
422
426
423 if opts_p:
427 if opts_p:
424 args = '_%s' % last_call[0]
428 args = '_%s' % last_call[0]
425 if not self.shell.user_ns.has_key(args):
429 if not self.shell.user_ns.has_key(args):
426 args = last_call[1]
430 args = last_call[1]
427
431
428 # use last_call to remember the state of the previous call, but don't
432 # use last_call to remember the state of the previous call, but don't
429 # let it be clobbered by successive '-p' calls.
433 # let it be clobbered by successive '-p' calls.
430 try:
434 try:
431 last_call[0] = self.shell.displayhook.prompt_count
435 last_call[0] = self.shell.displayhook.prompt_count
432 if not opts_p:
436 if not opts_p:
433 last_call[1] = parameter_s
437 last_call[1] = parameter_s
434 except:
438 except:
435 pass
439 pass
436
440
437 # by default this is done with temp files, except when the given
441 # by default this is done with temp files, except when the given
438 # arg is a filename
442 # arg is a filename
439 use_temp = True
443 use_temp = True
440
444
441 data = ''
445 data = ''
442 if args[0].isdigit():
446 if args[0].isdigit():
443 # Mode where user specifies ranges of lines, like in %macro.
447 # Mode where user specifies ranges of lines, like in %macro.
444 # This means that you can't edit files whose names begin with
448 # This means that you can't edit files whose names begin with
445 # numbers this way. Tough.
449 # numbers this way. Tough.
446 ranges = args.split()
450 ranges = args.split()
447 data = ''.join(self.extract_input_slices(ranges,opts_r))
451 data = ''.join(self.extract_input_slices(ranges,opts_r))
448 elif args.endswith('.py'):
452 elif args.endswith('.py'):
449 filename = make_filename(args)
453 filename = make_filename(args)
450 use_temp = False
454 use_temp = False
451 elif args:
455 elif args:
452 try:
456 try:
453 # Load the parameter given as a variable. If not a string,
457 # Load the parameter given as a variable. If not a string,
454 # process it as an object instead (below)
458 # process it as an object instead (below)
455
459
456 #print '*** args',args,'type',type(args) # dbg
460 #print '*** args',args,'type',type(args) # dbg
457 data = eval(args, self.shell.user_ns)
461 data = eval(args, self.shell.user_ns)
458 if not isinstance(data, basestring):
462 if not isinstance(data, basestring):
459 raise DataIsObject
463 raise DataIsObject
460
464
461 except (NameError,SyntaxError):
465 except (NameError,SyntaxError):
462 # given argument is not a variable, try as a filename
466 # given argument is not a variable, try as a filename
463 filename = make_filename(args)
467 filename = make_filename(args)
464 if filename is None:
468 if filename is None:
465 warn("Argument given (%s) can't be found as a variable "
469 warn("Argument given (%s) can't be found as a variable "
466 "or as a filename." % args)
470 "or as a filename." % args)
467 return
471 return
468 use_temp = False
472 use_temp = False
469
473
470 except DataIsObject:
474 except DataIsObject:
471 # macros have a special edit function
475 # macros have a special edit function
472 if isinstance(data, Macro):
476 if isinstance(data, Macro):
473 self._edit_macro(args,data)
477 self._edit_macro(args,data)
474 return
478 return
475
479
476 # For objects, try to edit the file where they are defined
480 # For objects, try to edit the file where they are defined
477 try:
481 try:
478 filename = inspect.getabsfile(data)
482 filename = inspect.getabsfile(data)
479 if 'fakemodule' in filename.lower() and inspect.isclass(data):
483 if 'fakemodule' in filename.lower() and inspect.isclass(data):
480 # class created by %edit? Try to find source
484 # class created by %edit? Try to find source
481 # by looking for method definitions instead, the
485 # by looking for method definitions instead, the
482 # __module__ in those classes is FakeModule.
486 # __module__ in those classes is FakeModule.
483 attrs = [getattr(data, aname) for aname in dir(data)]
487 attrs = [getattr(data, aname) for aname in dir(data)]
484 for attr in attrs:
488 for attr in attrs:
485 if not inspect.ismethod(attr):
489 if not inspect.ismethod(attr):
486 continue
490 continue
487 filename = inspect.getabsfile(attr)
491 filename = inspect.getabsfile(attr)
488 if filename and 'fakemodule' not in filename.lower():
492 if filename and 'fakemodule' not in filename.lower():
489 # change the attribute to be the edit target instead
493 # change the attribute to be the edit target instead
490 data = attr
494 data = attr
491 break
495 break
492
496
493 datafile = 1
497 datafile = 1
494 except TypeError:
498 except TypeError:
495 filename = make_filename(args)
499 filename = make_filename(args)
496 datafile = 1
500 datafile = 1
497 warn('Could not find file where `%s` is defined.\n'
501 warn('Could not find file where `%s` is defined.\n'
498 'Opening a file named `%s`' % (args,filename))
502 'Opening a file named `%s`' % (args,filename))
499 # Now, make sure we can actually read the source (if it was in
503 # Now, make sure we can actually read the source (if it was in
500 # a temp file it's gone by now).
504 # a temp file it's gone by now).
501 if datafile:
505 if datafile:
502 try:
506 try:
503 if lineno is None:
507 if lineno is None:
504 lineno = inspect.getsourcelines(data)[1]
508 lineno = inspect.getsourcelines(data)[1]
505 except IOError:
509 except IOError:
506 filename = make_filename(args)
510 filename = make_filename(args)
507 if filename is None:
511 if filename is None:
508 warn('The file `%s` where `%s` was defined cannot '
512 warn('The file `%s` where `%s` was defined cannot '
509 'be read.' % (filename,data))
513 'be read.' % (filename,data))
510 return
514 return
511 use_temp = False
515 use_temp = False
512
516
513 if use_temp:
517 if use_temp:
514 filename = self.shell.mktempfile(data)
518 filename = self.shell.mktempfile(data)
515 print('IPython will make a temporary file named:', filename)
519 print('IPython will make a temporary file named:', filename)
516
520
517 # Make sure we send to the client an absolute path, in case the working
521 # Make sure we send to the client an absolute path, in case the working
518 # directory of client and kernel don't match
522 # directory of client and kernel don't match
519 filename = os.path.abspath(filename)
523 filename = os.path.abspath(filename)
520
524
521 payload = {
525 payload = {
522 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
526 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
523 'filename' : filename,
527 'filename' : filename,
524 'line_number' : lineno
528 'line_number' : lineno
525 }
529 }
526 self.payload_manager.write_payload(payload)
530 self.payload_manager.write_payload(payload)
527
531
528 def magic_gui(self, *args, **kwargs):
532 def magic_gui(self, *args, **kwargs):
529 raise NotImplementedError(
533 raise NotImplementedError(
530 'GUI support must be enabled in command line options.')
534 'GUI support must be enabled in command line options.')
531
535
532 def magic_pylab(self, *args, **kwargs):
536 def magic_pylab(self, *args, **kwargs):
533 raise NotImplementedError(
537 raise NotImplementedError(
534 'pylab support must be enabled in command line options.')
538 'pylab support must be enabled in command line options.')
535
539
536 # A few magics that are adapted to the specifics of using pexpect and a
540 # A few magics that are adapted to the specifics of using pexpect and a
537 # remote terminal
541 # remote terminal
538
542
539 def magic_clear(self, arg_s):
543 def magic_clear(self, arg_s):
540 """Clear the terminal."""
544 """Clear the terminal."""
541 if os.name == 'posix':
545 if os.name == 'posix':
542 self.shell.system("clear")
546 self.shell.system("clear")
543 else:
547 else:
544 self.shell.system("cls")
548 self.shell.system("cls")
545
549
546 if os.name == 'nt':
550 if os.name == 'nt':
547 # This is the usual name in windows
551 # This is the usual name in windows
548 magic_cls = magic_clear
552 magic_cls = magic_clear
549
553
550 # Terminal pagers won't work over pexpect, but we do have our own pager
554 # Terminal pagers won't work over pexpect, but we do have our own pager
551
555
552 def magic_less(self, arg_s):
556 def magic_less(self, arg_s):
553 """Show a file through the pager.
557 """Show a file through the pager.
554
558
555 Files ending in .py are syntax-highlighted."""
559 Files ending in .py are syntax-highlighted."""
556 cont = open(arg_s).read()
560 cont = open(arg_s).read()
557 if arg_s.endswith('.py'):
561 if arg_s.endswith('.py'):
558 cont = self.shell.pycolorize(cont)
562 cont = self.shell.pycolorize(cont)
559 page.page(cont)
563 page.page(cont)
560
564
561 magic_more = magic_less
565 magic_more = magic_less
562
566
563 # Man calls a pager, so we also need to redefine it
567 # Man calls a pager, so we also need to redefine it
564 if os.name == 'posix':
568 if os.name == 'posix':
565 def magic_man(self, arg_s):
569 def magic_man(self, arg_s):
566 """Find the man page for the given command and display in pager."""
570 """Find the man page for the given command and display in pager."""
567 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
571 page.page(self.shell.getoutput('man %s | col -b' % arg_s,
568 split=False))
572 split=False))
569
573
570 # FIXME: this is specific to the GUI, so we should let the gui app load
574 # FIXME: this is specific to the GUI, so we should let the gui app load
571 # magics at startup that are only for the gui. Once the gui app has proper
575 # magics at startup that are only for the gui. Once the gui app has proper
572 # profile and configuration management, we can have it initialize a kernel
576 # profile and configuration management, we can have it initialize a kernel
573 # with a special config file that provides these.
577 # with a special config file that provides these.
574 def magic_guiref(self, arg_s):
578 def magic_guiref(self, arg_s):
575 """Show a basic reference about the GUI console."""
579 """Show a basic reference about the GUI console."""
576 from IPython.core.usage import gui_reference
580 from IPython.core.usage import gui_reference
577 page.page(gui_reference, auto_html=True)
581 page.page(gui_reference, auto_html=True)
578
582
579 def set_next_input(self, text):
583 def set_next_input(self, text):
580 """Send the specified text to the frontend to be presented at the next
584 """Send the specified text to the frontend to be presented at the next
581 input cell."""
585 input cell."""
582 payload = dict(
586 payload = dict(
583 source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
587 source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input',
584 text=text
588 text=text
585 )
589 )
586 self.payload_manager.write_payload(payload)
590 self.payload_manager.write_payload(payload)
587
591
588 InteractiveShellABC.register(ZMQInteractiveShell)
592 InteractiveShellABC.register(ZMQInteractiveShell)
@@ -1,24 +1,27 b''
1 """Code that shows off the IPython display logic.
1 """Code that shows off the IPython display logic.
2 """
2 """
3
3
4 from IPython.lib.latextools import latex_to_png
4 from IPython.core.display import (
5 from IPython.core.display import (
5 display, display_pretty, display_html,
6 display, display_pretty, display_html,
6 display_svg, display_json
7 display_svg, display_json, display_png
7 )
8 )
8
9
9 class Circle(object):
10 class Circle(object):
10
11
11 def __init__(self, radius):
12 def __init__(self, radius):
12 self.radius = radius
13 self.radius = radius
13
14
14 def _repr_pretty_(self, p, cycle):
15 def _repr_pretty_(self, p, cycle):
15 p.text(u"\u25CB")
16 p.text(u"\u25CB")
16
17
17 def _repr_html_(self):
18 def _repr_html_(self):
18 return "<h1>Cirle: radius=%s</h1>" % self.radius
19 return "<h1>Cirle: radius=%s</h1>" % self.radius
19
20
20 def _repr_svg_(self):
21 def _repr_svg_(self):
21 return """<svg>
22 return """<svg>
22 <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
23 <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
23 </svg>"""
24 </svg>"""
24
25
26 def _repr_png_(self):
27 return latex_to_png('$\circle$')
General Comments 0
You need to be logged in to leave comments. Login now