-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtmux_wrapper.py
More file actions
executable file
·1311 lines (1169 loc) · 44.7 KB
/
Copy pathtmux_wrapper.py
File metadata and controls
executable file
·1311 lines (1169 loc) · 44.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S -u VIRTUAL_ENV uv run python
"""Keyboard-driven tmux automation helpers.
This module exposes a small wrapper around tmux plus a renderer that turns
``tmux attach`` output into a printable text snapshot. It is meant for tests
and agents that must drive tmux the same way a human would:
1) create or attach to a session,
2) send literal text or key chords,
3) inspect the whole tmux window after each action.
Public entry points:
1) ``Keys`` enumerates the supported modifier, character, navigation, and
function keys used by ``TMUXWrapper.press()``.
2) ``TMUXWrapper.type(text)`` sends literal text to the active pane without
adding a trailing newline.
3) ``TMUXWrapper.press(chords)`` sends one or more key chords, including tmux
prefix sequences such as ``(Keys.Ctrl, Keys.B)`` followed by another key.
4) ``TMUXWrapper.view()`` is the fallback inspection API. It compares the
current window against the previous capture and keeps unchanged context.
5) ``TMUXWrapper.glance()`` is the default inspection API. It shows only the incremental additions since the
previous capture.
6) ``snapshot()`` is intentionally disabled.
7) ``TMUXWrapper.scroll_up(lines=3)`` and ``scroll_down(lines=3)`` emulate
mouse-wheel scrolling by operating tmux copy mode in line increments.
Behavior notes:
1) ``TMUXWrapper`` creates the target session on demand.
2) If this wrapper created the session, object cleanup deletes it by default.
3) Common tmux prefix bindings such as pane navigation and page scrolling are
translated through tmux commands when direct key injection is unreliable.
Example:
>>> from tmux_wrapper import Keys, TMUXWrapper
>>> tmux = TMUXWrapper(session="demo")
>>> tmux.glance()
>>> tmux.type("echo hello")
>>> tmux.glance()
>>> tmux.press([(Keys.Enter,)])
>>> print(tmux.glance())
...
>>> tmux.delete()
CLI:
$ tmux-c demo glance
$ tmux-c demo type "ls"
$ tmux-c demo press Enter
$ tmux-c demo glance
$ tmux-c demo view
$ tmux-c demo press Ctrl+B Z
$ tmux-c demo scroll_up 5
"""
from enum import Enum
from functools import lru_cache
import hashlib
import json
import os
from pathlib import Path
import pty
import select
import fcntl
import struct
import subprocess
import tempfile
import time
from typing import Iterable, List, Optional, Tuple
import difflib
class literal(str):
"""String subclass whose repr is the raw text block itself."""
def __repr__(self):
return self
_EMBEDDED_SKILL_TEXT = """---
name: tmux-wrapper
description: Use when tmux must be driven strictly through `tmux_wrapper.py` / `TMUXWrapper` (`type` / `press` / `view` / `glance`), with wrapper-based inspection instead of direct tmux CLI/API control.
---
# TMUX Wrapper
## Overview
Use this skill when tmux interaction should go through `TMUXWrapper` rather than direct tmux CLI/API calls.
Treat one tmux session as a serialized device. For a given session, send one action, wait, then inspect. Do not issue overlapping wrapper actions against the same session.
Canonical Python import:
```python
from tmux_wrapper import Keys, TMUXWrapper
```
Primary actions:
- `type(text)` sends literal text only.
- `press(chords)` sends one or more key chords.
- `glance()` is the default inspection method. It returns only incremental additions, plus collapsed `...[N unchanged lines]` markers. If nothing new appeared, it returns `[Nothing Changed]`.
- `view()` is the fallback inspection method when `glance()` is too compressed and you need more context.
- `scroll_up(lines=3)` / `scroll_down(lines=3)` provide line-based history scrolling via tmux copy mode.
CLI examples assume the package exposes `tmux-c`:
```bash
tmux-c demo glance
tmux-c demo type "ls"
tmux-c demo press Enter
tmux-c demo glance
tmux-c demo view
tmux-c demo scroll_up 5
```
## Default Workflow
Use one small action at a time and inspect after it. Default to `glance()`. Use `view()` only when `glance()` does not provide enough context.
Recommended pattern:
```bash
tmux-c demo glance
tmux-c demo type "echo hello"
tmux-c demo glance
tmux-c demo press Enter
tmux-c demo glance
tmux-c demo view
```
Rules of thumb:
- Prefer `glance()` for normal “what changed?” inspection.
- Use `view()` only when you need more context than `glance()` provides.
- `type()` does not press Enter; pair it with `press Enter` when needed.
- On one session, keep `type`, `press`, `glance`, and `view` strictly sequential. Do not run them in parallel tool calls for the same session.
- Keep prefix sequences as separate chords, for example `press Ctrl+B Z`.
- If the screen is slow to refresh, wait briefly before `glance()` or `view()`.
### Command Entry Safety
- Before typing a command into an existing shell, inspect first. If the pane may still be running something, interrupt with `press Ctrl+C`, then inspect again until you see a stable prompt.
- If a shell line may already contain partial input, clear it before retyping. Prefer `press Ctrl+C` for process interruption and `press Ctrl+U` only when you specifically want to clear the current shell line.
- Do not send `type "..."` and `press Enter` in the same parallel batch. Send `type`, wait briefly or inspect, then send `press Enter`.
- For long commands, prefer: `glance` -> `type` -> `glance` or short wait -> `press Enter` -> `glance`.
- If the command text is visible at the prompt but did not execute, press `Enter` once and inspect. Do not retype until you have cleared the line.
Recommended pattern for a shared shell session:
```bash
tmux-c demo glance
tmux-c demo press Ctrl+C
tmux-c demo glance
tmux-c demo type "python tools/rjob_run.py ..."
tmux-c demo glance
tmux-c demo press Enter
tmux-c demo glance
```
## Common Patterns
- Run a command:
- `tmux-c demo type "pytest -q"`
- `tmux-c demo press Enter`
- `tmux-c demo glance`
- Interrupt:
- `tmux-c demo press Ctrl+C`
- Pane navigation:
- `tmux-c demo press Ctrl+B Left`
- `tmux-c demo press Ctrl+B Right`
- Zoom toggle:
- `tmux-c demo press Ctrl+B Z`
- Scroll through output:
- `tmux-c demo scroll_up 20`
- `tmux-c demo glance`
- `tmux-c demo scroll_down 20`
- `tmux-c demo glance`
## Behavior Notes
- `TMUXWrapper(session=...)` creates the session if it does not already exist.
- If the wrapper created the session, object cleanup deletes it by default.
- Calling `delete()` always deletes the session immediately.
- `view()` and `glance()` are stateful because they update the stored baseline.
- `view()` gives precise current-screen context; `glance()` is more of an incremental observer.
- `scroll_up()` / `scroll_down()` operate tmux history statefully; `scroll_down 9999` is a practical way to get back to the bottom and usually exits copy mode.
- For large files, the most reliable pattern is: print the whole file once, then scroll up in small steps and inspect incrementally. Large jumps can reach older terminal history instead of the output you just produced.
- The diff baseline persists per session, so always keep track of what the previous capture was.
## Pitfalls
- Do not mix this wrapper workflow with direct tmux CLI/API control in the same sequence unless explicitly required.
- Do not parallelize wrapper commands against the same session. Parallel use is only safe across different sessions.
- If focus looks wrong, inspect first before sending more keys.
- Shell prompt redraws can interleave with typed text; after interrupts or failed commands, confirm the prompt is clean before typing the next command.
- Long commands are easy to duplicate or corrupt if you retype before checking the current line. Inspect first, then clear or continue deliberately.
- Some prefix actions depend on tmux state; for example `last-pane` can fail if no previous pane exists.
- `scroll_down()` exits copy mode automatically when it reaches the bottom.
- If you zoom a pane for inspection, unzoom it before leaving a shared session.
- `tmux-wrapper` is not a screenshot reader. It is an incremental observer whose output depends on the previous capture.
"""
def _load_skill_text() -> str:
return _EMBEDDED_SKILL_TEXT
class Keys(str, Enum):
"""Keyboard keys accepted by :meth:`TMUXWrapper.press`."""
# Modifiers
Ctrl = "Ctrl"
Alt = "Alt"
Shift = "Shift"
# Letters
A = "A"
B = "B"
C = "C"
D = "D"
E = "E"
F = "F"
G = "G"
H = "H"
I = "I"
J = "J"
K = "K"
L = "L"
M = "M"
N = "N"
O = "O"
P = "P"
Q = "Q"
R = "R"
S = "S"
T = "T"
U = "U"
V = "V"
W = "W"
X = "X"
Y = "Y"
Z = "Z"
# Digits
Digit0 = "Digit0"
Digit1 = "Digit1"
Digit2 = "Digit2"
Digit3 = "Digit3"
Digit4 = "Digit4"
Digit5 = "Digit5"
Digit6 = "Digit6"
Digit7 = "Digit7"
Digit8 = "Digit8"
Digit9 = "Digit9"
# Punctuation (ANSI US)
Backtick = "Backtick"
Minus = "Minus"
Equal = "Equal"
LeftBracket = "LeftBracket"
RightBracket = "RightBracket"
Backslash = "Backslash"
Semicolon = "Semicolon"
Quote = "Quote"
Comma = "Comma"
Period = "Period"
Slash = "Slash"
Space = "Space"
# Control keys
Enter = "Enter"
Tab = "Tab"
Escape = "Escape"
Backspace = "Backspace"
CapsLock = "CapsLock"
# Navigation
Up = "Up"
Down = "Down"
Left = "Left"
Right = "Right"
Home = "Home"
End = "End"
PageUp = "PageUp"
PageDown = "PageDown"
Insert = "Insert"
Delete = "Delete"
# Function keys
F1 = "F1"
F2 = "F2"
F3 = "F3"
F4 = "F4"
F5 = "F5"
F6 = "F6"
F7 = "F7"
F8 = "F8"
F9 = "F9"
F10 = "F10"
F11 = "F11"
F12 = "F12"
# System keys
PrintScreen = "PrintScreen"
ScrollLock = "ScrollLock"
Pause = "Pause"
class TMUXRenderer:
"""Render tmux attach output into a fixed-size text buffer."""
_ALT_CHARSET_MAP = {
"q": "─",
"x": "│",
"n": "┼",
"l": "┌",
"k": "┐",
"m": "└",
"j": "┘",
"t": "├",
"u": "┤",
"w": "┬",
"v": "┴",
}
def render(
self,
text: str,
width: int,
height: int,
) -> List[str]:
"""Render a captured tmux screen and overlay the cursor position."""
lines, cursor_pos = self._render_pty(text, width, height)
if cursor_pos is not None:
row, col = cursor_pos
if 0 <= row < len(lines):
line = lines[row]
if 0 <= col < len(line):
lines[row] = line[:col] + "▁" + line[col + 1 :]
if height is not None and len(lines) != height:
if len(lines) > height:
lines = lines[-height:]
else:
lines = [" " * width for _ in range(height - len(lines))] + lines
return lines
def _render_pty(self, text: str, width: int, height: int) -> Tuple[List[str], Optional[Tuple[int, int]]]:
screen = [[" " for _ in range(width)] for _ in range(height)]
row = 0
col = 0
g0_line = False
g1_line = True
use_g1 = False
saved_row = 0
saved_col = 0
scroll_top = 0
scroll_bottom = height - 1
cursor_visible = True
i = 0
while i < len(text):
ch = text[i]
if ch == "\x0e": # SO
use_g1 = True
i += 1
continue
if ch == "\x0f": # SI
use_g1 = False
i += 1
continue
if ch == "\x1b":
i += 1
if i >= len(text):
break
if text[i] == "7":
saved_row, saved_col = row, col
i += 1
continue
if text[i] == "8":
row, col = saved_row, saved_col
i += 1
continue
if text[i] in ("(", ")"):
if i + 1 < len(text):
set_g1 = text[i] == ")"
mode = text[i + 1]
if set_g1:
g1_line = mode == "0"
else:
g0_line = mode == "0"
i += 2
continue
if text[i] == "[":
i += 1
params, final, private, i = self._parse_csi(text, i)
if private and final in ("h", "l") and (params[0] if params else 0) == 25:
cursor_visible = final == "h"
else:
row, col, saved_row, saved_col, scroll_top, scroll_bottom = self._apply_csi(
params,
final,
row,
col,
screen,
saved_row,
saved_col,
scroll_top,
scroll_bottom,
)
continue
if text[i] == "]":
i = self._skip_osc(text, i + 1)
continue
i += 1
continue
if ch == "\r":
col = 0
elif ch == "\n":
row += 1
if row > scroll_bottom:
del screen[scroll_top]
screen.insert(scroll_bottom, [" " for _ in range(width)])
row = scroll_bottom
elif ch == "\b":
col = max(0, col - 1)
elif ch == "\t":
col = min(width - 1, (col // 8 + 1) * 8)
elif ch >= " " and ch != "\x7f":
if col >= width:
row += 1
col = 0
if row >= height:
screen.pop(0)
screen.append([" " for _ in range(width)])
row = height - 1
line_drawing = (use_g1 and g1_line) or ((not use_g1) and g0_line)
if line_drawing:
ch = self._ALT_CHARSET_MAP.get(ch, ch)
if 0 <= row < height and 0 <= col < width:
screen[row][col] = ch
col += 1
i += 1
lines = [self._strip_control_chars("".join(line)) for line in screen]
if not cursor_visible:
return lines, None
return lines, (row, min(max(col, 0), max(width - 1, 0)))
@staticmethod
def _parse_csi(text: str, i: int) -> Tuple[List[int], str, bool, int]:
params: List[int] = []
current = ""
private = False
while i < len(text):
ch = text[i]
if ch.isdigit():
current += ch
elif ch == ";":
params.append(int(current) if current else 0)
current = ""
elif ch == "?":
private = True
current = ""
else:
if current or params:
params.append(int(current) if current else 0)
return params, ch, private, i + 1
i += 1
return params, "m", private, i
@staticmethod
def _skip_osc(text: str, i: int) -> int:
while i < len(text):
if text[i] == "\x07":
return i + 1
if text[i] == "\x1b" and i + 1 < len(text) and text[i + 1] == "\\":
return i + 2
i += 1
return i
def _apply_csi(
self,
params: List[int],
final: str,
row: int,
col: int,
screen: List[List[str]],
saved_row: int,
saved_col: int,
scroll_top: int,
scroll_bottom: int,
) -> Tuple[int, int, int, int, int, int]:
height = len(screen)
width = len(screen[0]) if height else 0
param = params[0] if params else 0
if final in ("H", "f"):
r = (params[0] - 1) if len(params) >= 1 and params[0] else 0
c = (params[1] - 1) if len(params) >= 2 and params[1] else 0
return max(0, min(height - 1, r)), max(0, min(width - 1, c)), saved_row, saved_col, scroll_top, scroll_bottom
if final == "A":
return max(0, row - (param or 1)), col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "B":
return min(height - 1, row + (param or 1)), col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "C":
return row, min(width - 1, col + (param or 1)), saved_row, saved_col, scroll_top, scroll_bottom
if final == "D":
return row, max(0, col - (param or 1)), saved_row, saved_col, scroll_top, scroll_bottom
if final == "G":
c = (param - 1) if param else 0
return row, max(0, min(width - 1, c)), saved_row, saved_col, scroll_top, scroll_bottom
if final == "E":
r = min(height - 1, row + (param or 1))
return r, 0, saved_row, saved_col, scroll_top, scroll_bottom
if final == "F":
r = max(0, row - (param or 1))
return r, 0, saved_row, saved_col, scroll_top, scroll_bottom
if final == "s":
return row, col, row, col, scroll_top, scroll_bottom
if final == "u":
return saved_row, saved_col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "r":
top = (params[0] - 1) if len(params) >= 1 and params[0] else 0
bottom = (params[1] - 1) if len(params) >= 2 and params[1] else height - 1
top = max(0, min(height - 1, top))
bottom = max(top, min(height - 1, bottom))
return row, col, saved_row, saved_col, top, bottom
if final == "J":
mode = param or 0
if mode == 2:
for r in range(height):
screen[r] = [" " for _ in range(width)]
elif mode == 0:
for r in range(row, height):
start = col if r == row else 0
for c in range(start, width):
screen[r][c] = " "
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "K":
mode = param or 0
if mode == 2:
for c in range(width):
screen[row][c] = " "
elif mode == 0:
for c in range(col, width):
screen[row][c] = " "
elif mode == 1:
for c in range(0, col + 1):
screen[row][c] = " "
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "L":
count = param or 1
count = min(count, scroll_bottom - row + 1)
for _ in range(count):
screen.insert(row, [" " for _ in range(width)])
del screen[scroll_bottom + 1]
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "M":
count = param or 1
count = min(count, scroll_bottom - row + 1)
for _ in range(count):
del screen[row]
screen.insert(scroll_bottom, [" " for _ in range(width)])
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "@":
count = param or 1
for _ in range(count):
screen[row].insert(col, " ")
screen[row].pop()
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
if final == "P":
count = param or 1
for _ in range(count):
if col < width:
del screen[row][col]
screen[row].append(" ")
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
return row, col, saved_row, saved_col, scroll_top, scroll_bottom
@staticmethod
def _strip_control_chars(line: str) -> str:
return "".join(ch for ch in line if ch >= " " and ch != "\x7f")
class TMUXWrapper:
"""Drive a tmux session through text entry, key chords, and window capture."""
def __init__(
self,
session: str,
tmux_bin: str = "tmux",
renderer: Optional[TMUXRenderer] = None,
) -> None:
"""Attach to ``session``, creating it if needed."""
self.session = session
self.tmux_bin = tmux_bin
self.renderer = renderer or TMUXRenderer()
self._default_size = (200, 40)
self._prefix_pending = False
self._owns_session = False
self._ensure_session()
self._afterimage = []
def __del__(self) -> None:
self._safe_delete()
def type(self, type_str: str) -> None:
"""Send literal text to the active pane without pressing Enter."""
if not type_str:
return
self._run_tmux(["send-keys", "-t", self._target(), "-l", type_str])
def press(self, keys: List[Tuple[Keys, ...]]) -> None:
"""Send key chords to tmux.
Each chord is a tuple containing zero or more modifiers plus exactly
one base key. To issue a tmux prefix binding, send ``Ctrl+B`` as one
chord and the bound key as the next chord.
"""
if not keys:
return
for chord in keys:
if not chord:
continue
if self._is_prefix_chord(chord):
self._prefix_pending = True
continue
if self._prefix_pending and self._handle_tmux_binding(chord):
self._prefix_pending = False
continue
self._prefix_pending = False
encoded = self._encode_chord(chord)
self._run_tmux(["send-keys", "-t", self._target(), encoded])
def snapshot(self) -> literal:
"""Disabled API kept only to fail explicitly for old call sites."""
raise RuntimeError("snapshot() is disabled; use glance() by default or view() when you need more context")
def glance(self) -> literal:
"""Return additions plus counted collapsed markers for unchanged regions."""
afterimage = self._afterimage
content = self._attach_capture()
self._afterimage = content
diff = self._glance_lines(afterimage, content)
if not diff:
return literal("[Nothing Changed]")
return literal("\n".join(diff))
def view(self) -> literal:
"""Return a contextual diff against the previous capture."""
afterimage = self._afterimage
content = self._attach_capture()
self._afterimage = content
diff = self._diff_lines(afterimage, content, include_context=True)
return literal("\n".join(diff))
def scroll_up(self, lines: int = 3) -> None:
"""Enter copy mode and scroll the viewport up by ``lines``."""
repeat = self._normalize_scroll_lines(lines)
if repeat == 0:
return
self._enter_copy_mode()
if not self._try_copy_mode_action(["scroll-up"], repeat=repeat):
self._run_tmux(["send-keys", "-t", self._target(), "PageUp"])
def scroll_down(self, lines: int = 3) -> None:
"""Enter copy mode and scroll down; exit copy mode at the bottom."""
repeat = self._normalize_scroll_lines(lines)
if repeat == 0:
return
self._enter_copy_mode()
if not self._try_copy_mode_action(["scroll-down"], repeat=repeat):
self._run_tmux(["send-keys", "-t", self._target(), "PageDown"])
if self._in_copy_mode() and self._scroll_position() == 0:
self._try_copy_mode_action(["cancel"])
def delete(self) -> None:
"""Delete the tmux session immediately."""
try:
self._run_tmux(["kill-session", "-t", self.session])
except RuntimeError as exc:
if "can't find session" in str(exc):
return
raise
def _target(self) -> str:
return f"{self.session}:"
def _run_tmux(self, args: Iterable[str]) -> str:
cmd = [self.tmux_bin, *args]
try:
completed = subprocess.run(
cmd,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except FileNotFoundError as exc:
raise RuntimeError(f"tmux binary not found: {self.tmux_bin}") from exc
except subprocess.CalledProcessError as exc:
message = exc.stderr.strip() or exc.stdout.strip()
raise RuntimeError(f"tmux command failed: {message}") from exc
return completed.stdout
def _window_target(self) -> str:
return self.session
def _attach_capture(self) -> List[str]:
master_fd, slave_fd = pty.openpty()
try:
width, height = self._window_size()
except RuntimeError:
width, height = self._default_size
self._set_pty_size(slave_fd, width, height)
try:
self._run_tmux(["refresh-client", "-S", "-t", self._window_target()])
except RuntimeError:
pass
env = os.environ.copy()
env.setdefault("TERM", "xterm-256color")
proc = subprocess.Popen(
[self.tmux_bin, "attach", "-t", self._window_target()],
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
close_fds=True,
env=env,
)
os.close(slave_fd)
output = b""
deadline = time.time() + 1.5
while time.time() < deadline:
readable, _, _ = select.select([master_fd], [], [], 0.05)
if master_fd in readable:
try:
chunk = os.read(master_fd, 65536)
except OSError:
break
if not chunk:
break
output += chunk
try:
os.write(master_fd, b"\x02d")
except OSError:
pass
try:
proc.wait(timeout=0.5)
except subprocess.TimeoutExpired:
proc.terminate()
os.close(master_fd)
text = output.decode("utf-8", errors="ignore")
return self.renderer.render(text, width, height)
def _window_size(self) -> Tuple[int, int]:
target = self._window_target()
output = self._run_tmux(["display-message", "-p", "-t", target, "#{window_width} #{window_height}"]).strip()
width_str, height_str = output.split()
return int(width_str), int(height_str) + 1
def _client_size(self) -> Optional[Tuple[int, int]]:
try:
output = self._run_tmux([
"list-clients",
"-t",
self.session,
"-F",
"#{client_active} #{client_width} #{client_height}",
]).splitlines()
except RuntimeError:
return None
if not output:
return None
active = None
largest = None
for line in output:
parts = line.split()
if len(parts) != 3:
continue
is_active, w, h = parts
size = (int(w), int(h))
if largest is None or (size[0] * size[1]) > (largest[0] * largest[1]):
largest = size
if is_active == "1":
active = size
break
if active is not None:
return active
return largest
@staticmethod
def _set_pty_size(fd: int, width: int, height: int) -> None:
winsize = struct.pack("HHHH", height, width, 0, 0)
fcntl.ioctl(fd, 0x5414, winsize)
@staticmethod
@lru_cache(maxsize=1)
def _tmux_version() -> Tuple[int, int, int]:
output = subprocess.run(
["tmux", "-V"],
check=True,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
).stdout.strip()
version = output.split()[-1]
digits: List[int] = []
for part in version.replace("a", "").replace("b", "").split("."):
if part.isdigit():
digits.append(int(part))
while len(digits) < 3:
digits.append(0)
return tuple(digits[:3])
def _in_copy_mode(self) -> bool:
return self._run_tmux(
["display-message", "-p", "-t", self._target(), "#{pane_in_mode}"]
).strip() == "1"
def _scroll_position(self) -> Optional[int]:
value = self._run_tmux(
["display-message", "-p", "-t", self._target(), "#{scroll_position}"]
).strip()
if not value:
return None
return int(value)
@staticmethod
def _diff_lines(
before: List[str],
after: List[str],
include_context: bool,
) -> List[str]:
diff = []
for line in difflib.ndiff(before, after):
if line.startswith(("- ", "? ")):
continue
if line.startswith("+ "):
diff.append(f"!!{line[2:]}")
continue
if include_context:
diff.append(line)
return diff
@staticmethod
def _glance_lines(before: List[str], after: List[str]) -> List[str]:
lines = []
pending_context = 0
saw_addition = False
for line in difflib.ndiff(before, after):
if line.startswith(("- ", "? ")):
continue
if line.startswith("+ "):
if pending_context:
suffix = "line" if pending_context == 1 else "lines"
lines.append(f"...[{pending_context} unchanged {suffix}]")
pending_context = 0
lines.append(f"!!{line[2:]}")
saw_addition = True
continue
pending_context += 1
if not saw_addition:
return []
if pending_context:
suffix = "line" if pending_context == 1 else "lines"
lines.append(f"...[{pending_context} unchanged {suffix}]")
return lines
def _enter_copy_mode(self) -> None:
if self._in_copy_mode():
return
self._run_tmux(["copy-mode", "-t", self._target()])
for _ in range(5):
if self._in_copy_mode():
return
def _try_copy_mode_action(self, actions: List[str], repeat: int = 1) -> bool:
for action in actions:
cmd = ["send-keys", "-X"]
if repeat != 1:
cmd.extend(["-N", str(repeat)])
cmd.extend(["-t", self._target(), action])
try:
self._run_tmux(cmd)
return True
except RuntimeError:
continue
return False
@staticmethod
def _normalize_scroll_lines(lines: int) -> int:
if lines < 0:
raise ValueError("lines must be >= 0")
return lines
def _ensure_session(self) -> None:
try:
self._run_tmux(["has-session", "-t", self.session])
self._owns_session = False
except RuntimeError:
self._run_tmux(["new-session", "-d", "-s", self.session])
self._owns_session = True
def _safe_delete(self) -> None:
try:
if self._owns_session:
self.delete()
except Exception:
return
@staticmethod
def _is_prefix_chord(chord: Tuple[Keys, ...]) -> bool:
return set(chord) == {Keys.Ctrl, Keys.B}
def _handle_tmux_binding(self, chord: Tuple[Keys, ...]) -> bool:
mods, base = self._split_chord(chord)
if base in (Keys.Up, Keys.Down, Keys.Left, Keys.Right) and not mods:
direction = {
Keys.Up: "U",
Keys.Down: "D",
Keys.Left: "L",
Keys.Right: "R",
}[base]
self._run_tmux(["select-pane", f"-{direction}", "-t", self._target()])
return True
if base is Keys.PageUp and not mods:
self._enter_copy_mode()
if not self._try_copy_mode_action(["page-up", "scroll-up"]):
self._run_tmux(["send-keys", "-t", self._target(), "PageUp"])
return True
if base is Keys.PageDown and not mods:
self._enter_copy_mode()
if not self._try_copy_mode_action(["page-down", "scroll-down"]):
self._run_tmux(["send-keys", "-t", self._target(), "PageDown"])
return True
if base is Keys.Digit5 and not mods:
self._run_tmux(["split-window", "-h", "-t", self._target()])
return True
if mods and any(mod in mods for mod in (Keys.Ctrl, Keys.Alt)):
return False
char = self._encode_character_key(mods, base)
if char is None:
return False
action = self._PREFIX_BINDINGS.get(char)
if action is None:
return False
cmd, *extra = action
self._run_tmux([cmd, *extra, "-t", self._target()])
return True
return False
@staticmethod
def _split_chord(chord: Tuple[Keys, ...]) -> Tuple[List[Keys], Keys]:
modifiers = {Keys.Ctrl, Keys.Alt, Keys.Shift}
mods = [key for key in chord if key in modifiers]
base_keys = [key for key in chord if key not in modifiers]
if len(base_keys) != 1:
raise ValueError(f"Chord must contain exactly one base key: {chord}")
return mods, base_keys[0]
@staticmethod
def _encode_chord(chord: Tuple[Keys, ...]) -> str:
mods, base = TMUXWrapper._split_chord(chord)
return TMUXWrapper._encode_key(mods, base)
@staticmethod
def _encode_key(mods: List[Keys], base: Keys) -> str:
char = TMUXWrapper._encode_character_key(mods, base)
if char is not None:
return char
return TMUXWrapper._encode_special_key(mods, base)
@staticmethod
def _encode_character_key(mods: List[Keys], base: Keys) -> Optional[str]:
shifted = Keys.Shift in mods
if base in TMUXWrapper._LETTER_KEYS:
letter = base.value.lower()
if shifted:
letter = letter.upper()
return TMUXWrapper._apply_modifiers(mods, letter)
if base in TMUXWrapper._DIGIT_KEYS:
unshifted, shifted_char = TMUXWrapper._DIGIT_KEYS[base]
char = shifted_char if shifted else unshifted
return TMUXWrapper._apply_modifiers(mods, char)
if base in TMUXWrapper._PUNCT_KEYS:
unshifted, shifted_char = TMUXWrapper._PUNCT_KEYS[base]
char = shifted_char if shifted else unshifted
return TMUXWrapper._apply_modifiers(mods, char)
if base is Keys.Space:
return TMUXWrapper._apply_modifiers(mods, " ")
return None
@staticmethod
def _encode_special_key(mods: List[Keys], base: Keys) -> str:
key_name = TMUXWrapper._SPECIAL_KEYS.get(base, base.value)
return TMUXWrapper._apply_modifiers(mods, key_name, force_named=True)
@staticmethod
def _apply_modifiers(mods: List[Keys], key: str, force_named: bool = False) -> str:
mod_prefix = []
if Keys.Ctrl in mods:
mod_prefix.append("C")