ipython-icat 0.4.0__tar.gz → 0.4.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipython-icat
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: IPython magic command for displaying images in kitty terminal
5
5
  Author-email: Tony Kabilan Okeke <tonykabilanokeke@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/Kabilan108/ipython-icat
@@ -43,6 +43,13 @@ In your IPython session, load the extension:
43
43
  %load_ext icat
44
44
  ```
45
45
 
46
+ For startup files, Neovim terminals, or other launchers that should enable the
47
+ backend immediately after loading the extension, set:
48
+
49
+ ```bash
50
+ IPYTHON_ICAT_AUTO=1
51
+ ```
52
+
46
53
  ### Displaying Matplotlib Plots
47
54
 
48
55
  To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
@@ -120,12 +127,41 @@ You can also resize the image when displaying:
120
127
 
121
128
  If you'd like to use this plugin with Ghostty, make sure to install the [static kitten binary](https://github.com/kovidgoyal/kitty/releases) which will allow you to run `kitten icat`.
122
129
 
130
+ ### Using Full-Screen Terminal Apps
131
+
132
+ `ipython-icat` can render through full-screen terminal programs, such as Neovim
133
+ terminal buffers, by asking `kitten icat` to emit Kitty unicode placeholders.
134
+ Enable that mode with:
135
+
136
+ ```bash
137
+ IPYTHON_ICAT_PLACEHOLDER=1
138
+ ```
139
+
140
+ The placeholder path is configured with environment variables:
141
+
142
+ - `IPYTHON_ICAT_CELL_PIXELS=WIDTHxHEIGHT` supplies the terminal cell size in
143
+ pixels. This lets `kitten icat` compute the window size when IPython is
144
+ running inside an embedded terminal.
145
+ - `IPYTHON_ICAT_WINDOW_SIZE=COLS,ROWS,WIDTH_PX,HEIGHT_PX` overrides the
146
+ computed window size completely.
147
+ - `IPYTHON_ICAT_TRANSFER_MODE=stream|file|memory|detect` selects the Kitty
148
+ graphics transfer mode. The default is `stream`, which works reliably through
149
+ Neovim and Ghostty.
150
+ - `IPYTHON_ICAT_PASSTHROUGH=none|tmux|detect` controls whether `kitten icat`
151
+ wraps graphics commands for tmux. The default is `none`; use this when a host
152
+ program relays the graphics request itself.
153
+
154
+ [`pyrepl.nvim`](https://github.com/Kabilan108/pyrepl.nvim) sets these variables
155
+ automatically when starting IPython and relays Kitty graphics requests from the
156
+ embedded terminal to the host terminal.
157
+
123
158
  ## Features
124
159
 
125
160
  - Display matplotlib plots directly in kitty terminal
126
161
  - Show PIL Image objects or image files
127
162
  - Resize images on display
128
163
  - Seamless integration with IPython workflow
164
+ - Kitty unicode-placeholder support for embedded terminal workflows
129
165
 
130
166
  ## Contributing
131
167
 
@@ -28,6 +28,13 @@ In your IPython session, load the extension:
28
28
  %load_ext icat
29
29
  ```
30
30
 
31
+ For startup files, Neovim terminals, or other launchers that should enable the
32
+ backend immediately after loading the extension, set:
33
+
34
+ ```bash
35
+ IPYTHON_ICAT_AUTO=1
36
+ ```
37
+
31
38
  ### Displaying Matplotlib Plots
32
39
 
33
40
  To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
@@ -105,12 +112,41 @@ You can also resize the image when displaying:
105
112
 
106
113
  If you'd like to use this plugin with Ghostty, make sure to install the [static kitten binary](https://github.com/kovidgoyal/kitty/releases) which will allow you to run `kitten icat`.
107
114
 
115
+ ### Using Full-Screen Terminal Apps
116
+
117
+ `ipython-icat` can render through full-screen terminal programs, such as Neovim
118
+ terminal buffers, by asking `kitten icat` to emit Kitty unicode placeholders.
119
+ Enable that mode with:
120
+
121
+ ```bash
122
+ IPYTHON_ICAT_PLACEHOLDER=1
123
+ ```
124
+
125
+ The placeholder path is configured with environment variables:
126
+
127
+ - `IPYTHON_ICAT_CELL_PIXELS=WIDTHxHEIGHT` supplies the terminal cell size in
128
+ pixels. This lets `kitten icat` compute the window size when IPython is
129
+ running inside an embedded terminal.
130
+ - `IPYTHON_ICAT_WINDOW_SIZE=COLS,ROWS,WIDTH_PX,HEIGHT_PX` overrides the
131
+ computed window size completely.
132
+ - `IPYTHON_ICAT_TRANSFER_MODE=stream|file|memory|detect` selects the Kitty
133
+ graphics transfer mode. The default is `stream`, which works reliably through
134
+ Neovim and Ghostty.
135
+ - `IPYTHON_ICAT_PASSTHROUGH=none|tmux|detect` controls whether `kitten icat`
136
+ wraps graphics commands for tmux. The default is `none`; use this when a host
137
+ program relays the graphics request itself.
138
+
139
+ [`pyrepl.nvim`](https://github.com/Kabilan108/pyrepl.nvim) sets these variables
140
+ automatically when starting IPython and relays Kitty graphics requests from the
141
+ embedded terminal to the host terminal.
142
+
108
143
  ## Features
109
144
 
110
145
  - Display matplotlib plots directly in kitty terminal
111
146
  - Show PIL Image objects or image files
112
147
  - Resize images on display
113
148
  - Seamless integration with IPython workflow
149
+ - Kitty unicode-placeholder support for embedded terminal workflows
114
150
 
115
151
  ## Contributing
116
152
 
@@ -2,43 +2,123 @@ import sys
2
2
  from io import BytesIO
3
3
  from os import getenv
4
4
  from pathlib import Path
5
+ from shutil import get_terminal_size
5
6
  from subprocess import run
7
+ from typing import Any, List, Optional, Set, Tuple
6
8
 
7
9
  import matplotlib
10
+ from IPython.core.getipython import get_ipython
8
11
  from IPython.core.magic import Magics, line_magic, magics_class
9
12
  from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring
10
- from IPython.core.getipython import get_ipython
11
13
  from matplotlib import interactive, is_interactive
12
14
  from matplotlib._pylab_helpers import Gcf
13
15
  from matplotlib.backend_bases import FigureManagerBase, _Backend
14
16
  from matplotlib.backends.backend_agg import FigureCanvasAgg
15
17
  from PIL import Image
16
18
 
17
-
18
19
  if hasattr(sys, "ps1") or sys.flags.interactive:
19
20
  interactive(True)
20
21
 
21
22
 
22
- def _run(*cmd):
23
- def f(*args, output=True, **kwargs):
24
- if output:
25
- kwargs["capture_output"] = True
26
- kwargs["text"] = True
27
- r = run(cmd + args, **kwargs)
28
- if output:
29
- return r.stdout.rstrip()
23
+ def _env_flag(name: str) -> bool:
24
+ return getenv(name, "").strip().lower() in {"1", "true", "yes", "on"}
25
+
26
+
27
+ def _cell_pixels() -> Optional[Tuple[int, int]]:
28
+ value = getenv("IPYTHON_ICAT_CELL_PIXELS", "").strip()
29
+ if not value:
30
+ return None
31
+
32
+ normalized = value.lower().replace(",", "x")
33
+ width, _, height = normalized.partition("x")
34
+ if not width or not height:
35
+ return None
36
+
37
+ try:
38
+ cell_width = int(width)
39
+ cell_height = int(height)
40
+ except ValueError:
41
+ return None
42
+
43
+ if cell_width <= 0 or cell_height <= 0:
44
+ return None
45
+
46
+ return cell_width, cell_height
47
+
48
+
49
+ def _choice(name: str, default: str, allowed: Set[str]) -> str:
50
+ value = getenv(name, "").strip().lower()
51
+ if value in allowed:
52
+ return value
53
+ return default
54
+
55
+
56
+ def _transfer_mode() -> str:
57
+ return _choice(
58
+ "IPYTHON_ICAT_TRANSFER_MODE",
59
+ "stream",
60
+ {"detect", "file", "memory", "stream"},
61
+ )
62
+
63
+
64
+ def _passthrough_mode() -> str:
65
+ return _choice("IPYTHON_ICAT_PASSTHROUGH", "none", {"detect", "none", "tmux"})
66
+
67
+
68
+ def _window_size() -> Optional[str]:
69
+ explicit = getenv("IPYTHON_ICAT_WINDOW_SIZE", "").strip()
70
+ if explicit:
71
+ return explicit
72
+
73
+ cell_pixels = _cell_pixels()
74
+ if cell_pixels is None:
75
+ return None
30
76
 
31
- return f
77
+ terminal_size = get_terminal_size((80, 24))
78
+ cell_width, cell_height = cell_pixels
79
+ return (
80
+ f"{terminal_size.columns},{terminal_size.lines},"
81
+ f"{terminal_size.columns * cell_width},{terminal_size.lines * cell_height}"
82
+ )
83
+
84
+
85
+ def _icat_command() -> List[str]:
86
+ command = ["kitten", "icat", "--align", "left"]
87
+ if not _env_flag("IPYTHON_ICAT_PLACEHOLDER"):
88
+ return command
89
+
90
+ command.extend(
91
+ [
92
+ "--unicode-placeholder",
93
+ f"--transfer-mode={_transfer_mode()}",
94
+ f"--passthrough={_passthrough_mode()}",
95
+ "--stdin=yes",
96
+ ]
97
+ )
32
98
 
99
+ window_size = _window_size()
100
+ if window_size:
101
+ command.append(f"--use-window-size={window_size}")
33
102
 
34
- _icat = _run("kitten", "icat", "--align", "left")
103
+ return command
104
+
105
+
106
+ def _display_image(
107
+ img: Image.Image, width: Optional[int] = None, height: Optional[int] = None
108
+ ) -> None:
109
+ img_ = img.copy()
110
+ with BytesIO() as buf:
111
+ if width or height:
112
+ img_.thumbnail((width or img.width, height or img.height))
113
+ img_.save(buf, format="PNG")
114
+ run(_icat_command(), input=buf.getbuffer(), check=False)
35
115
 
36
116
 
37
117
  class FigureManagerICat(FigureManagerBase):
38
- def show(self):
118
+ def show(self) -> None:
39
119
  with BytesIO() as buf:
40
120
  self.canvas.figure.savefig(buf, format="png")
41
- _icat(output=False, input=buf.getbuffer())
121
+ run(_icat_command(), input=buf.getbuffer(), check=False)
42
122
 
43
123
 
44
124
  class FigureCanvasICat(FigureCanvasAgg):
@@ -52,13 +132,13 @@ class _BackendICatAgg(_Backend):
52
132
  mainloop = lambda: None
53
133
 
54
134
  @classmethod
55
- def draw_if_interactive(cls):
135
+ def draw_if_interactive(cls) -> None:
56
136
  manager = Gcf.get_active()
57
137
  if is_interactive() and manager.canvas.figure.get_axes():
58
138
  cls.show()
59
139
 
60
140
  @classmethod
61
- def show(cls, *args, **kwargs):
141
+ def show(cls, *args, **kwargs) -> None:
62
142
  _Backend.show(*args, **kwargs)
63
143
  Gcf.destroy_all()
64
144
 
@@ -74,7 +154,7 @@ class ICatMagics(Magics):
74
154
  @argument("-W", "--width", type=int, help="Width to resize the image")
75
155
  @argument("-H", "--height", type=int, help="Height to resize the image")
76
156
  @line_magic
77
- def icat(self, line):
157
+ def icat(self, line: str) -> None:
78
158
  args = parse_argstring(self.icat, line)
79
159
  target = (args.target or "").strip()
80
160
 
@@ -90,34 +170,28 @@ class ICatMagics(Magics):
90
170
 
91
171
  obj = _resolve_target(self.shell, target)
92
172
  if obj is None:
93
- print(f"Error: could not resolve '{target}' as an image expression or file path.")
173
+ print(
174
+ f"Error: could not resolve '{target}' as an image expression or file path."
175
+ )
94
176
  return
95
177
 
96
178
  img = _coerce_to_image(obj)
97
179
  if img is None:
98
- print(f"Error: '{target}' did not evaluate to a PIL Image or readable image path.")
180
+ print(
181
+ f"Error: '{target}' did not evaluate to a PIL Image or readable image path."
182
+ )
99
183
  return
100
184
 
101
- # resize the image if width or height is specified
102
- if args.width or args.height:
103
- img.thumbnail((args.width or img.width, args.height or img.height))
185
+ _display_image(img, args.width, args.height)
104
186
 
105
- # display image
106
- with BytesIO() as buf:
107
- img.save(buf, format="PNG")
108
- _icat(output=False, input=buf.getbuffer())
109
187
 
110
-
111
- def icat(img: Image.Image, width: int = None, height: int = None):
112
- img_ = img.copy()
113
- with BytesIO() as buf:
114
- if width or height:
115
- img_.thumbnail((width or img.width, height or img.height))
116
- img_.save(buf, format="PNG")
117
- _icat(output=False, input=buf.getbuffer())
188
+ def icat(
189
+ img: Image.Image, width: Optional[int] = None, height: Optional[int] = None
190
+ ) -> None:
191
+ _display_image(img, width, height)
118
192
 
119
193
 
120
- def load_ipython_extension(ipython):
194
+ def load_ipython_extension(ipython: Any) -> None:
121
195
  ipython.register_magics(ICatMagics)
122
196
 
123
197
  auto = getenv("IPYTHON_ICAT_AUTO", "").strip().lower()
@@ -125,11 +199,11 @@ def load_ipython_extension(ipython):
125
199
  _enable_session(ipython)
126
200
 
127
201
 
128
- def _session_state(shell) -> dict:
202
+ def _session_state(shell: Any) -> dict:
129
203
  return shell.user_ns.setdefault("_icat_state", {})
130
204
 
131
205
 
132
- def _enable_session(shell) -> None:
206
+ def _enable_session(shell: Any) -> None:
133
207
  state = _session_state(shell)
134
208
  if state.get("enabled"):
135
209
  return
@@ -153,7 +227,7 @@ def _enable_session(shell) -> None:
153
227
  state["enabled"] = True
154
228
 
155
229
 
156
- def _disable_session(shell) -> None:
230
+ def _disable_session(shell: Any) -> None:
157
231
  state = _session_state(shell)
158
232
  if not state.get("enabled"):
159
233
  return
@@ -174,7 +248,7 @@ def _disable_session(shell) -> None:
174
248
  state.clear()
175
249
 
176
250
 
177
- def _print_status(shell) -> None:
251
+ def _print_status(shell: Any) -> None:
178
252
  state = _session_state(shell)
179
253
  enabled = bool(state.get("enabled"))
180
254
  prev = state.get("prev_mpl_backend")
@@ -183,10 +257,12 @@ def _print_status(shell) -> None:
183
257
  current = matplotlib.get_backend()
184
258
  except Exception:
185
259
  pass
186
- print(f"icat: enabled={enabled}, matplotlib_backend={current!r}, prev_backend={prev!r}")
260
+ print(
261
+ f"icat: enabled={enabled}, matplotlib_backend={current!r}, prev_backend={prev!r}"
262
+ )
187
263
 
188
264
 
189
- def _resolve_target(shell, target: str):
265
+ def _resolve_target(shell: Any, target: str) -> Optional[object]:
190
266
  try:
191
267
  return shell.ev(target)
192
268
  except Exception:
@@ -202,9 +278,9 @@ def _resolve_target(shell, target: str):
202
278
  return None
203
279
 
204
280
 
205
- def _coerce_to_image(obj):
281
+ def _coerce_to_image(obj: object) -> Optional[Image.Image]:
206
282
  if isinstance(obj, Image.Image):
207
- return obj
283
+ return obj.copy()
208
284
 
209
285
  if isinstance(obj, (str, Path)):
210
286
  path = Path(obj).expanduser()
@@ -214,7 +290,7 @@ def _coerce_to_image(obj):
214
290
  return None
215
291
 
216
292
 
217
- def _enable_pil_autorender(shell) -> None:
293
+ def _enable_pil_autorender(shell: Any) -> None:
218
294
  ip = get_ipython()
219
295
  if ip is None:
220
296
  ip = shell
@@ -233,7 +309,7 @@ def _enable_pil_autorender(shell) -> None:
233
309
  fmt.for_type(Image.Image, _pil_printer)
234
310
 
235
311
 
236
- def _disable_pil_autorender(shell) -> None:
312
+ def _disable_pil_autorender(shell: Any) -> None:
237
313
  ip = get_ipython()
238
314
  if ip is None:
239
315
  ip = shell
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ipython-icat
3
- Version: 0.4.0
3
+ Version: 0.4.2
4
4
  Summary: IPython magic command for displaying images in kitty terminal
5
5
  Author-email: Tony Kabilan Okeke <tonykabilanokeke@gmail.com>
6
6
  Project-URL: Homepage, https://github.com/Kabilan108/ipython-icat
@@ -43,6 +43,13 @@ In your IPython session, load the extension:
43
43
  %load_ext icat
44
44
  ```
45
45
 
46
+ For startup files, Neovim terminals, or other launchers that should enable the
47
+ backend immediately after loading the extension, set:
48
+
49
+ ```bash
50
+ IPYTHON_ICAT_AUTO=1
51
+ ```
52
+
46
53
  ### Displaying Matplotlib Plots
47
54
 
48
55
  To enable `icat` integration for both matplotlib plots and automatic PIL image rendering:
@@ -120,12 +127,41 @@ You can also resize the image when displaying:
120
127
 
121
128
  If you'd like to use this plugin with Ghostty, make sure to install the [static kitten binary](https://github.com/kovidgoyal/kitty/releases) which will allow you to run `kitten icat`.
122
129
 
130
+ ### Using Full-Screen Terminal Apps
131
+
132
+ `ipython-icat` can render through full-screen terminal programs, such as Neovim
133
+ terminal buffers, by asking `kitten icat` to emit Kitty unicode placeholders.
134
+ Enable that mode with:
135
+
136
+ ```bash
137
+ IPYTHON_ICAT_PLACEHOLDER=1
138
+ ```
139
+
140
+ The placeholder path is configured with environment variables:
141
+
142
+ - `IPYTHON_ICAT_CELL_PIXELS=WIDTHxHEIGHT` supplies the terminal cell size in
143
+ pixels. This lets `kitten icat` compute the window size when IPython is
144
+ running inside an embedded terminal.
145
+ - `IPYTHON_ICAT_WINDOW_SIZE=COLS,ROWS,WIDTH_PX,HEIGHT_PX` overrides the
146
+ computed window size completely.
147
+ - `IPYTHON_ICAT_TRANSFER_MODE=stream|file|memory|detect` selects the Kitty
148
+ graphics transfer mode. The default is `stream`, which works reliably through
149
+ Neovim and Ghostty.
150
+ - `IPYTHON_ICAT_PASSTHROUGH=none|tmux|detect` controls whether `kitten icat`
151
+ wraps graphics commands for tmux. The default is `none`; use this when a host
152
+ program relays the graphics request itself.
153
+
154
+ [`pyrepl.nvim`](https://github.com/Kabilan108/pyrepl.nvim) sets these variables
155
+ automatically when starting IPython and relays Kitty graphics requests from the
156
+ embedded terminal to the host terminal.
157
+
123
158
  ## Features
124
159
 
125
160
  - Display matplotlib plots directly in kitty terminal
126
161
  - Show PIL Image objects or image files
127
162
  - Resize images on display
128
163
  - Seamless integration with IPython workflow
164
+ - Kitty unicode-placeholder support for embedded terminal workflows
129
165
 
130
166
  ## Contributing
131
167
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "ipython-icat"
3
- version = "0.4.0"
3
+ version = "0.4.2"
4
4
  description = "IPython magic command for displaying images in kitty terminal"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.8"
File without changes
File without changes