Debian Codegraph @

docs/topics/workspace_setup.md

raw symbols SCIP
1 (workspace-setup)=
2
3 # Workspace setup
4
5 A workspace is a single window carved into panes, each running its own
6 program: an editor in one, a dev server in another, a log tail in a third.
7 With libtmux you build that layout from Python instead of arranging it by
8 hand — you open a window, split it into panes, arrange them with a layout,
9 and send commands into each.
10
11 You will reach for four methods more than any others:
12 {meth}`~libtmux.Session.new_window` to open a window,
13 {meth}`~libtmux.Window.split` to carve it into panes,
14 {meth}`~libtmux.Window.select_layout` to arrange them, and
15 {meth}`~libtmux.Pane.send_keys` to drive a command into one. The defaults
16 are sensible, so most of what you build needs nothing more — the recipes
17 near the end are ready-made patterns you can copy whole and adapt.
18
19 To follow along you need two terminals: one running a live tmux server, one
20 running a Python prompt to drive it.
21
22 In the first terminal, start tmux:
23
24 ```console
25 $ tmux
26 ```
27
28 In the second, start Python (`ptpython` if you have it):
29
30 ```console
31 $ python
32 ```
33
34 ## Creating windows
35
36 Every workspace begins with a window. {meth}`~libtmux.Session.new_window`
37 opens one inside a session and hands you back a {class}`~libtmux.Window` you
38 can split, rename, and fill with panes.
39
40 ### Basic window creation
41
42 Hand {meth}`~libtmux.Session.new_window` a name and you get a
43 {class}`~libtmux.Window` back, added to the session's window list. By
44 default the window is created in the background — it doesn't pull your
45 focus from the window you're already on:
46
47 ```python
48 >>> new_window = session.new_window(window_name='workspace')
49 >>> new_window # doctest: +ELLIPSIS
50 Window(@... ...:workspace, Session($... ...))
51
52 >>> # Window is part of the session
53 >>> new_window in session.windows
54 True
55 ```
56
57 ### Create without attaching
58
59 Because `attach=False` is the default, the windows you build stay in the
60 background while you assemble a workspace — focus never jumps to each one as
61 it appears. Pass it explicitly when you want that intent on the page, and
62 reach for `attach=True` only when a window should take focus as it's created:
63
64 ```python
65 >>> background_window = session.new_window(
66 ... window_name='background-task',
67 ... attach=False,
68 ... )
69 >>> background_window # doctest: +ELLIPSIS
70 Window(@... ...:background-task, Session($... ...))
71
72 >>> # Clean up
73 >>> background_window.kill()
74 ```
75
76 ### Create with specific shell
77
78 You can also choose what runs inside the window instead of the default shell
79 — handy when a pane should boot straight into a REPL, a server, or a one-off
80 script:
81
82 ```python
83 >>> shell_window = session.new_window(
84 ... window_name='shell-test',
85 ... attach=False,
86 ... window_shell='sh -c "echo Hello; exec sh"',
87 ... )
88 >>> shell_window # doctest: +ELLIPSIS
89 Window(@... ...:shell-test, Session($... ...))
90
91 >>> # Clean up
92 >>> shell_window.kill()
93 ```
94
95 ## Splitting panes
96
97 A window with one pane is just a terminal. Splitting is what turns it into a
98 workspace: {meth}`~libtmux.Window.split` (or the same method on a specific
99 {meth}`~libtmux.Pane.split`) divides the available space and returns the new
100 {class}`~libtmux.Pane`. Each split and {meth}`~libtmux.Window.resize` is a
101 round-trip to the tmux server; the resize calls below buy a window large
102 enough that the splits have room to land on a small terminal.
103
104 ### Vertical split (top/bottom)
105
106 Splitting top-and-bottom is the default — the new pane opens below the one
107 you split:
108
109 ```python
110 >>> import time
111 >>> from libtmux.constants import PaneDirection
112
113 >>> # Create a window with enough space
114 >>> v_split_window = session.new_window(window_name='v-split-demo', attach=False)
115 >>> v_split_window.resize(height=40, width=120) # doctest: +ELLIPSIS
116 Window(@... ...)
117
118 >>> # Default split is vertical (creates pane below)
119 >>> top_pane = v_split_window.active_pane
120 >>> bottom_pane = v_split_window.split()
121 >>> bottom_pane # doctest: +ELLIPSIS
122 Pane(%... Window(@... ..., Session($... ...)))
123
124 >>> len(v_split_window.panes)
125 2
126
127 >>> # Clean up
128 >>> v_split_window.kill()
129 ```
130
131 ### Horizontal split (left/right)
132
133 Pass a direction to split side-by-side instead.
134 {class}`~libtmux.constants.PaneDirection` names where the new pane goes —
135 here, to the right of the one you split:
136
137 ```python
138 >>> from libtmux.constants import PaneDirection
139
140 >>> # Create a fresh window for this demo
141 >>> h_split_window = session.new_window(window_name='h-split', attach=False)
142 >>> h_split_window.resize(height=40, width=120) # doctest: +ELLIPSIS
143 Window(@... ...)
144
145 >>> left_pane = h_split_window.active_pane
146 >>> right_pane = left_pane.split(direction=PaneDirection.Right)
147 >>> right_pane # doctest: +ELLIPSIS
148 Pane(%... Window(@... ..., Session($... ...)))
149
150 >>> len(h_split_window.panes)
151 2
152
153 >>> # Clean up
154 >>> h_split_window.kill()
155 ```
156
157 ### Split with specific size
158
159 By default tmux halves the space. Ask for a specific share — a percentage or
160 a cell count — when one pane should be smaller than the rest:
161
162 ```python
163 >>> # Create a fresh window for size demo
164 >>> size_window = session.new_window(window_name='size-demo', attach=False)
165 >>> size_window.resize(height=40, width=120) # doctest: +ELLIPSIS
166 Window(@... ...)
167
168 >>> main_pane = size_window.active_pane
169 >>> # Create pane with specific percentage
170 >>> small_pane = main_pane.split(size='20%')
171 >>> small_pane # doctest: +ELLIPSIS
172 Pane(%... Window(@... ..., Session($... ...)))
173
174 >>> # Clean up
175 >>> size_window.kill()
176 ```
177
178 ## Layout management
179
180 Once a window holds several panes, a layout decides how they share the
181 screen. {meth}`~libtmux.Window.select_layout` applies one of tmux's built-in
182 arrangements so you don't have to size each pane by hand.
183
184 ### Available layouts
185
186 tmux provides five built-in layouts:
187
188 | Layout | Description |
189 |--------|-------------|
190 | `even-horizontal` | Panes spread evenly left to right |
191 | `even-vertical` | Panes spread evenly top to bottom |
192 | `main-horizontal` | Large pane on top, others below |
193 | `main-vertical` | Large pane on left, others on right |
194 | `tiled` | Panes spread evenly in rows and columns |
195
196 ### Applying layouts
197
198 Pass a layout name and tmux re-tiles every pane in the window. You can switch
199 layouts as often as you like — the panes and their contents stay put, only
200 their geometry changes:
201
202 ```python
203 >>> # Create window with multiple panes
204 >>> layout_window = session.new_window(window_name='layout-demo', attach=False)
205 >>> layout_window.resize(height=60, width=120) # doctest: +ELLIPSIS
206 Window(@... ...)
207
208 >>> pane1 = layout_window.active_pane
209 >>> pane2 = layout_window.split()
210 >>> pane3 = layout_window.split()
211 >>> pane4 = layout_window.split()
212
213 >>> # Apply tiled layout
214 >>> layout_window.select_layout('tiled') # doctest: +ELLIPSIS
215 Window(@... ...)
216
217 >>> # Apply even-horizontal layout
218 >>> layout_window.select_layout('even-horizontal') # doctest: +ELLIPSIS
219 Window(@... ...)
220
221 >>> # Apply main-vertical layout
222 >>> layout_window.select_layout('main-vertical') # doctest: +ELLIPSIS
223 Window(@... ...)
224
225 >>> # Clean up
226 >>> layout_window.kill()
227 ```
228
229 ## Renaming and organizing
230
231 ### Rename windows
232
233 A window's name is how you find it later, so give each one a label that says
234 what it's for. {meth}`~libtmux.Window.rename_window` updates it in place:
235
236 ```python
237 >>> rename_window = session.new_window(window_name='old-name', attach=False)
238 >>> rename_window.rename_window('new-name') # doctest: +ELLIPSIS
239 Window(@... ...:new-name, Session($... ...))
240
241 >>> rename_window.window_name
242 'new-name'
243
244 >>> # Clean up
245 >>> rename_window.kill()
246 ```
247
248 ### Access window properties
249
250 A {class}`~libtmux.Window` object reflects tmux's state at the moment you ask:
251 its index in the session, its stable id, and the {class}`~libtmux.Session` it
252 belongs to are all available as attributes. libtmux reads them once when it
253 builds the object, so if something changes the window externally, call
254 {meth}`~libtmux.Window.refresh` to re-fetch from tmux before you read them
255 again:
256
257 ```python
258 >>> demo_window = session.new_window(window_name='props-demo', attach=False)
259
260 >>> # Window index
261 >>> demo_window.window_index # doctest: +ELLIPSIS
262 '...'
263
264 >>> # Window ID
265 >>> demo_window.window_id # doctest: +ELLIPSIS
266 '@...'
267
268 >>> # Parent session
269 >>> demo_window.session # doctest: +ELLIPSIS
270 Session($... ...)
271
272 >>> # Clean up
273 >>> demo_window.kill()
274 ```
275
276 ## Practical recipes
277
278 The methods above are enough to build any workspace. The recipes below stitch
279 them into patterns worth keeping — lift one and adapt it, or read them as
280 worked examples of how the pieces fit together.
281
282 ### Recipe: create a development workspace
283
284 A common shape: one large editing pane, a smaller terminal beneath it, and a
285 log pane beside the terminal. This helper wires that up and returns the panes
286 keyed by role, so the caller can drive each one by name:
287
288 ```python
289 >>> import time
290 >>> from libtmux.constants import PaneDirection
291
292 >>> def create_dev_workspace(session, name='dev'):
293 ... """Create a typical development workspace layout."""
294 ... window = session.new_window(window_name=name, attach=False)
295 ... window.resize(height=50, width=160)
296 ...
297 ... # Main editing pane (large, left side)
298 ... main_pane = window.active_pane
299 ...
300 ... # Terminal pane (bottom)
301 ... terminal_pane = main_pane.split(size='30%')
302 ...
303 ... # Logs pane (right side of terminal)
304 ... log_pane = terminal_pane.split(direction=PaneDirection.Right)
305 ...
306 ... return {
307 ... 'window': window,
308 ... 'main': main_pane,
309 ... 'terminal': terminal_pane,
310 ... 'logs': log_pane,
311 ... }
312
313 >>> workspace = create_dev_workspace(session, 'my-project')
314 >>> len(workspace['window'].panes)
315 3
316
317 >>> # Clean up
318 >>> workspace['window'].kill()
319 ```
320
321 ### Recipe: create a grid of panes
322
323 Need a uniform grid — four panes, nine, sixteen — for watching parallel jobs?
324 Split a row across, repeat down the rows, then let the `tiled`
325 {meth}`~libtmux.Window.select_layout` even everything out:
326
327 ```python
328 >>> from libtmux.constants import PaneDirection
329
330 >>> def create_pane_grid(session, rows=2, cols=2, name='grid'):
331 ... """Create an NxM grid of panes."""
332 ... window = session.new_window(window_name=name, attach=False)
333 ... window.resize(height=50, width=160)
334 ...
335 ... panes = []
336 ... base_pane = window.active_pane
337 ... panes.append(base_pane)
338 ...
339 ... # Create first row of panes
340 ... current = base_pane
341 ... for _ in range(cols - 1):
342 ... new_pane = current.split(direction=PaneDirection.Right)
343 ... panes.append(new_pane)
344 ... current = new_pane
345 ...
346 ... # Create additional rows
347 ... for _ in range(rows - 1):
348 ... row_start = panes[-cols]
349 ... current = row_start
350 ... for col in range(cols):
351 ... new_pane = panes[-cols + col].split(direction=PaneDirection.Below)
352 ... panes.append(new_pane)
353 ...
354 ... # Apply tiled layout for even distribution
355 ... window.select_layout('tiled')
356 ... return window, panes
357
358 >>> grid_window, grid_panes = create_pane_grid(session, rows=2, cols=2, name='test-grid')
359 >>> len(grid_panes) >= 4
360 True
361
362 >>> # Clean up
363 >>> grid_window.kill()
364 ```
365
366 ### Recipe: run commands in multiple panes
367
368 Sending keys is how you put work into a pane.
369 {meth}`~libtmux.Pane.send_keys` returns as soon as the keystrokes are
370 delivered — the command itself runs asynchronously — so when you need to read
371 its output back with {meth}`~libtmux.Pane.capture_pane`, give it a beat to
372 finish first:
373
374 ```python
375 >>> import time
376
377 >>> def run_in_panes(panes, commands):
378 ... """Run different commands in each pane."""
379 ... for pane, cmd in zip(panes, commands):
380 ... pane.send_keys(cmd)
381
382 >>> multi_window = session.new_window(window_name='multi-cmd', attach=False)
383 >>> multi_window.resize(height=40, width=120) # doctest: +ELLIPSIS
384 Window(@... ...)
385
386 >>> pane_a = multi_window.active_pane
387 >>> pane_b = multi_window.split()
388 >>> pane_c = multi_window.split()
389
390 >>> run_in_panes(
391 ... [pane_a, pane_b, pane_c],
392 ... ['echo "Task A"', 'echo "Task B"', 'echo "Task C"'],
393 ... )
394
395 >>> # Give commands time to execute
396 >>> time.sleep(0.2)
397
398 >>> # Verify all commands ran
399 >>> 'Task A' in '\\n'.join(pane_a.capture_pane())
400 True
401
402 >>> # Clean up
403 >>> multi_window.kill()
404 ```
405
406 ## Window context managers
407
408 When a window is only meant to live for the span of a task — a test run, a
409 quick capture — let a `with` block own it. The window is created on entry and
410 killed on exit, so you never leak a stray window even if something raises
411 midway through:
412
413 ```python
414 >>> with session.new_window(window_name='temp-window') as temp_win:
415 ... pane = temp_win.active_pane
416 ... pane.send_keys('echo "temporary workspace"')
417 ... temp_win in session.windows
418 True
419
420 >>> # Window is automatically killed after exiting context
421 >>> temp_win not in session.windows
422 True
423 ```
424
425 :::{seealso}
426 - {ref}`pane-interaction` for working with pane content
427 - {ref}`automation-patterns` for advanced orchestration
428 - {class}`~libtmux.Window` for all window methods
429 - {class}`~libtmux.Session` for session management
430 :::