##// END OF EJS Templates
Fix typo
Tim Metzler -
Show More
@@ -1,60 +1,60 b''
1 1
2 2 .. _shell_mimerenderer:
3 3
4 4
5 5 Mime Renderer Extensions
6 6 ========================
7 7
8 8 Like it's cousins, Jupyter Notebooks and JupyterLab, Terminal IPython can be
9 9 thought to render a number of mimetypes in the shell. This can be used to either
10 10 display inline images if your terminal emulator supports it; or open some
11 11 display results with external file viewers.
12 12
13 Registering new mimetype handlers can so far only be done my extensions and
13 Registering new mimetype handlers can so far only be done by extensions and
14 14 requires 4 steps:
15 15
16 16 - Define a callable that takes 2 parameters:``data`` and ``metadata``; return
17 17 value of the callable is so far ignored. This callable is responsible for
18 18 "displaying" the given mimetype. Which can be sending the right escape
19 19 sequences and bytes to the current terminal; or open an external program. -
20 20 - Appending the right mimetype to ``ipython.display_formatter.active_types``
21 21 for IPython to know it should not ignore those mimetypes.
22 22 - Enabling the given mimetype: ``ipython.display_formatter.formatters[mime].enabled = True``
23 23 - Registering above callable with mimetype handler:
24 24 ``ipython.mime_renderers[mime] = handler``
25 25
26 26
27 27 Here is a complete IPython extension to display images inline and convert math
28 28 to png, before displaying it inline for iterm2 on macOS ::
29 29
30 30
31 31 from base64 import encodebytes
32 32 from IPython.lib.latextools import latex_to_png
33 33
34 34
35 35 def mathcat(data, meta):
36 36 png = latex_to_png(f'$${data}$$'.replace('\displaystyle', '').replace('$$$', '$$'))
37 37 imcat(png, meta)
38 38
39 39 IMAGE_CODE = '\033]1337;File=name=name;inline=true;:{}\a'
40 40
41 41 def imcat(image_data, metadata):
42 42 try:
43 43 print(IMAGE_CODE.format(encodebytes(image_data).decode()))
44 44 # bug workaround
45 45 except:
46 46 print(IMAGE_CODE.format(image_data))
47 47
48 48 def register_mimerenderer(ipython, mime, handler):
49 49 ipython.display_formatter.active_types.append(mime)
50 50 ipython.display_formatter.formatters[mime].enabled = True
51 51 ipython.mime_renderers[mime] = handler
52 52
53 53 def load_ipython_extension(ipython):
54 54 register_mimerenderer(ipython, 'image/png', imcat)
55 55 register_mimerenderer(ipython, 'image/jpeg', imcat)
56 56 register_mimerenderer(ipython, 'text/latex', mathcat)
57 57
58 58 This example only work for iterm2 on macOS and skip error handling for brevity.
59 59 One could also invoke an external viewer with ``subprocess.run()`` and a
60 60 temporary file, which is left as an exercise.
General Comments 0
You need to be logged in to leave comments. Login now