forked from tmux-python/libtmux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpane.py
452 lines (366 loc) · 11.6 KB
/
pane.py
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
# flake8: NOQA W605
"""Pythonization of the :ref:`tmux(1)` pane.
libtmux.pane
~~~~~~~~~~~~
"""
import dataclasses
import logging
import typing as t
import warnings
from typing import overload
from libtmux.common import tmux_cmd
from libtmux.neo import Obj, fetch_obj
from . import exc, formats
from .common import PaneDict
if t.TYPE_CHECKING:
from typing_extensions import Literal
from .server import Server
from .session import Session
from .window import Window
logger = logging.getLogger(__name__)
@dataclasses.dataclass()
class Pane(Obj):
"""
A :term:`tmux(1)` :term:`Pane` [pane_manual]_.
``Pane`` instances can send commands directly to a pane, or traverse
between linked tmux objects.
Attributes
----------
window : :class:`Window`
Examples
--------
>>> pane
Pane(%1 Window(@1 1:..., Session($1 ...)))
>>> pane in window.panes
True
>>> pane.window
Window(@1 1:..., Session($1 ...))
>>> pane.session
Session($1 ...)
Notes
-----
.. versionchanged:: 0.8
Renamed from ``.tmux`` to ``.cmd``.
References
----------
.. [pane_manual] tmux pane. openbsd manpage for TMUX(1).
"Each window displayed by tmux may be split into one or more
panes; each pane takes up a certain area of the display and is
a separate terminal."
https://man.openbsd.org/tmux.1#WINDOWS_AND_PANES.
Accessed April 1st, 2018.
"""
server: "Server"
def refresh(self) -> None:
assert isinstance(self.pane_id, str)
return super()._refresh(obj_key="pane_id", obj_id=self.pane_id)
@classmethod
def from_pane_id(cls, server: "Server", pane_id: str) -> "Pane":
pane = fetch_obj(
obj_key="pane_id",
obj_id=pane_id,
server=server,
list_cmd="list-panes",
list_extra_args=("-a",),
)
return cls(server=server, **pane)
#
# Relations
#
@property
def window(self) -> "Window":
assert isinstance(self.window_id, str)
from libtmux.window import Window
return Window.from_window_id(server=self.server, window_id=self.window_id)
@property
def session(self) -> "Session":
return self.window.session
#
# Command (pane-scoped)
#
def cmd(self, cmd: str, *args: t.Any, **kwargs: t.Any) -> tmux_cmd:
"""Return :meth:`Server.cmd` defaulting to ``target_pane`` as target.
Send command to tmux with :attr:`pane_id` as ``target-pane``.
Specifying ``('-t', 'custom-target')`` or ``('-tcustom_target')`` in
``args`` will override using the object's ``pane_id`` as target.
"""
if not any(arg.startswith("-t") for arg in args):
args = ("-t", self.pane_id) + args
return self.server.cmd(cmd, *args, **kwargs)
#
# Commands (tmux-like)
#
def resize_pane(self, *args: t.Any, **kwargs: t.Any) -> "Pane":
"""
``$ tmux resize-pane`` of pane and return ``self``.
Parameters
----------
target_pane : str
``target_pane``, or ``-U``,``-D``, ``-L``, ``-R``.
Other Parameters
----------------
height : int
``resize-pane -y`` dimensions
width : int
``resize-pane -x`` dimensions
Raises
------
exc.LibTmuxException
"""
if "height" in kwargs:
proc = self.cmd("resize-pane", "-y%s" % int(kwargs["height"]))
elif "width" in kwargs:
proc = self.cmd("resize-pane", "-x%s" % int(kwargs["width"]))
else:
proc = self.cmd("resize-pane", args[0])
if proc.stderr:
raise exc.LibTmuxException(proc.stderr)
self.refresh()
return self
def capture_pane(
self,
start: t.Union["Literal['-']", t.Optional[int]] = None,
end: t.Union["Literal['-']", t.Optional[int]] = None,
) -> t.Union[str, t.List[str]]:
"""
Capture text from pane.
``$ tmux capture-pane`` to pane.
``$ tmux capture-pane -S -10`` to pane.
``$ tmux capture-pane`-E 3` to pane.
``$ tmux capture-pane`-S - -E -` to pane.
Parameters
----------
start: [str,int]
Specify the starting line number.
Zero is the first line of the visible pane.
Positive numbers are lines in the visible pane.
Negative numbers are lines in the history.
‘-’ is the start of the history.
Default: None
end: [str,int]
Specify the ending line number.
Zero is the first line of the visible pane.
Positive numbers are lines in the visible pane.
Negative numbers are lines in the history.
‘-’ is the end of the visible pane
Default: None
"""
cmd = ["capture-pane", "-p"]
if start is not None:
cmd.extend(["-S", str(start)])
if end is not None:
cmd.extend(["-E", str(end)])
return self.cmd(*cmd).stdout
def send_keys(
self,
cmd: str,
enter: t.Optional[bool] = True,
suppress_history: t.Optional[bool] = False,
literal: t.Optional[bool] = False,
) -> None:
r"""``$ tmux send-keys`` to the pane.
A leading space character is added to cmd to avoid polluting the
user's history.
Parameters
----------
cmd : str
Text or input into pane
enter : bool, optional
Send enter after sending the input, default True.
suppress_history : bool, optional
Prepend a space to command to suppress shell history, default False.
.. versionchanged:: 0.14
Default changed from True to False.
literal : bool, optional
Send keys literally, default True.
Examples
--------
>>> pane = window.split_window(shell='sh')
>>> pane.capture_pane()
['$']
>>> pane.send_keys('echo "Hello world"', enter=True)
>>> pane.capture_pane()
['$ echo "Hello world"', 'Hello world', '$']
>>> print('\n'.join(pane.capture_pane())) # doctest: +NORMALIZE_WHITESPACE
$ echo "Hello world"
Hello world
$
"""
prefix = " " if suppress_history else ""
if literal:
self.cmd("send-keys", "-l", prefix + cmd)
else:
self.cmd("send-keys", prefix + cmd)
if enter:
self.enter()
@overload
def display_message(
self, cmd: str, get_text: "Literal[True]"
) -> t.Union[str, t.List[str]]:
...
@overload
def display_message(self, cmd: str, get_text: "Literal[False]") -> None:
...
def display_message(
self, cmd: str, get_text: bool = False
) -> t.Optional[t.Union[str, t.List[str]]]:
"""
``$ tmux display-message`` to the pane.
Displays a message in target-client status line.
Parameters
----------
cmd : str
Special parameters to request from pane.
get_text : bool, optional
Returns only text without displaying a message in
target-client status line.
"""
if get_text:
return self.cmd("display-message", "-p", cmd).stdout
self.cmd("display-message", cmd)
return None
#
# Commands ("climber"-helpers)
#
# These are commands that climb to the parent scope's methods with
# additional scoped window info.
#
def select_pane(self) -> "Pane":
"""
Select pane. Return ``self``.
To select a window object asynchrously. If a ``pane`` object exists
and is no longer longer the current window, ``w.select_pane()``
will make ``p`` the current pane.
"""
assert isinstance(self.pane_id, str)
pane = self.window.select_pane(self.pane_id)
if pane is None:
raise exc.LibTmuxException(f"Pane not found: {self}")
return pane
def split_window(
self,
attach: bool = False,
vertical: bool = True,
start_directory: t.Optional[str] = None,
percent: t.Optional[int] = None,
) -> "Pane": # New Pane, not self
"""
Split window at pane and return newly created :class:`Pane`.
Parameters
----------
attach : bool, optional
Attach / select pane after creation.
vertical : bool, optional
split vertically
start_directory : str, optional
specifies the working directory in which the new pane is created.
percent: int, optional
percentage to occupy with respect to current pane
"""
return self.window.split_window(
target=self.pane_id,
start_directory=start_directory,
attach=attach,
vertical=vertical,
percent=percent,
)
#
# Commands (helpers)
#
def set_width(self, width: int) -> "Pane":
"""
Set width of pane.
Parameters
----------
width : int
pane width, in cells
"""
self.resize_pane(width=width)
return self
def set_height(self, height: int) -> "Pane":
"""
Set height of pane.
Parameters
----------
height : int
height of pain, in cells
"""
self.resize_pane(height=height)
return self
def enter(self) -> "Pane":
"""
Send carriage return to pane.
``$ tmux send-keys`` send Enter to the pane.
"""
self.cmd("send-keys", "Enter")
return self
def clear(self) -> "Pane":
"""Clear pane."""
self.send_keys("reset")
return self
def reset(self) -> "Pane":
"""Reset and clear pane history."""
self.cmd("send-keys", r"-R \; clear-history")
return self
#
# Dunder
#
def __eq__(self, other: object) -> bool:
assert isinstance(other, Pane)
return self.pane_id == other.pane_id
def __repr__(self) -> str:
return "{}({} {})".format(self.__class__.__name__, self.pane_id, self.window)
#
# Aliases
#
@property
def id(self) -> t.Optional[str]:
"""Alias of :attr:`Pane.pane_id`
>>> pane.id
'%1'
>>> pane.id == pane.pane_id
True
"""
return self.pane_id
@property
def index(self) -> t.Optional[str]:
"""Alias of :attr:`Pane.pane_index`
>>> pane.index
'0'
>>> pane.index == pane.pane_index
True
"""
return self.pane_index
@property
def height(self) -> t.Optional[str]:
"""Alias of :attr:`Pane.pane_height`
>>> pane.height.isdigit()
True
>>> pane.height == pane.pane_height
True
"""
return self.pane_height
@property
def width(self) -> t.Optional[str]:
"""Alias of :attr:`Pane.pane_width`
>>> pane.width.isdigit()
True
>>> pane.width == pane.pane_width
True
"""
return self.pane_width
#
# Legacy
#
def get(self, key: str, default: t.Optional[t.Any] = None) -> t.Any:
"""
.. deprecated:: 0.16
"""
warnings.warn("Pane.get() is deprecated")
return getattr(self, key, default)
def __getitem__(self, key: str) -> t.Any:
"""
.. deprecated:: 0.16
"""
warnings.warn(f"Item lookups, e.g. pane['{key}'] is deprecated")
return getattr(self, key)