Debian Codegraph @

docs/topics/filtering.md

raw symbols SCIP
1 (querylist-filtering)=
2
3 # Filtering collections
4
5 Every collection libtmux hands you —
6 {attr}`server.sessions <libtmux.Server.sessions>`,
7 {attr}`session.windows <libtmux.Session.windows>`, and
8 {attr}`window.panes <libtmux.Window.panes>` — is a
9 {class}`~libtmux._internal.query_list.QueryList`, a list that knows how to filter
10 itself. You narrow one by calling
11 {meth}`~libtmux._internal.query_list.QueryList.filter` with keyword arguments,
12 optionally suffixed with a lookup like `__contains`, `__startswith`, or
13 `__regex`, and you get back another
14 {class}`~libtmux._internal.query_list.QueryList` you can iterate or chain
15 further. It's Django-style filtering applied to sessions, windows, and panes.
16
17 Most readers never look beyond `.filter()`. It's the common path, it works out
18 of the box on every collection, and the lookup suffixes and chaining cover
19 almost every query you'll write. The tmux-native `.search_*()` methods at the
20 end of this page are an optional escape hatch for large servers — you can skip
21 them until you measure a reason to care.
22
23 ## Basic filtering
24
25 Every collection is already a {class}`~libtmux._internal.query_list.QueryList`,
26 so you can inspect one before you narrow it. Here's the full set of sessions on
27 your server:
28
29 ```python
30 >>> server.sessions # doctest: +ELLIPSIS
31 [Session($... ...)]
32 ```
33
34 ### Exact match
35
36 When you pass a bare keyword like `session_name=...`, the default lookup is
37 `exact` — so these two calls mean the same thing:
38
39 ```python
40 >>> # These are equivalent
41 >>> server.sessions.filter(session_name=session.session_name) # doctest: +ELLIPSIS
42 [Session($... ...)]
43 >>> server.sessions.filter(session_name__exact=session.session_name) # doctest: +ELLIPSIS
44 [Session($... ...)]
45 ```
46
47 ### Contains and startswith
48
49 Add a suffix to the keyword to match part of a value instead of the whole
50 thing:
51
52 ```python
53 >>> # Create windows for this example
54 >>> w1 = session.new_window(window_name="api-server")
55 >>> w2 = session.new_window(window_name="api-worker")
56 >>> w3 = session.new_window(window_name="web-frontend")
57
58 >>> # Windows containing 'api'
59 >>> api_windows = session.windows.filter(window_name__contains='api')
60 >>> len(api_windows) >= 2
61 True
62
63 >>> # Windows starting with 'web'
64 >>> web_windows = session.windows.filter(window_name__startswith='web')
65 >>> len(web_windows) >= 1
66 True
67
68 >>> # Clean up
69 >>> w1.kill()
70 >>> w2.kill()
71 >>> w3.kill()
72 ```
73
74 ## Available lookups
75
76 Each suffix you append after the `__` selects one of these lookups. The
77 `i`-prefixed variants ignore case:
78
79 | Lookup | Description |
80 |--------|-------------|
81 | `exact` | Exact match (default) |
82 | `iexact` | Case-insensitive exact match |
83 | `contains` | Substring match |
84 | `icontains` | Case-insensitive substring |
85 | `startswith` | Prefix match |
86 | `istartswith` | Case-insensitive prefix |
87 | `endswith` | Suffix match |
88 | `iendswith` | Case-insensitive suffix |
89 | `in` | Value in list |
90 | `nin` | Value not in list |
91 | `regex` | Regular expression match |
92 | `iregex` | Case-insensitive regex |
93
94 ## Getting a single item
95
96 When you expect exactly one match and want the object itself rather than a
97 list, reach for {meth}`~libtmux._internal.query_list.QueryList.get`:
98
99 ```python
100 >>> window = session.windows.get(window_id=session.active_window.window_id)
101 >>> window # doctest: +ELLIPSIS
102 Window(@... ..., Session($... ...))
103 ```
104
105 `get()` insists on exactly one result. If the query matches the wrong number of
106 objects, it raises:
107
108 - {exc}`~libtmux._internal.query_list.ObjectDoesNotExist` - no matching object found
109 - {exc}`~libtmux._internal.query_list.MultipleObjectsReturned` - more than one object matches
110
111 Pass a `default` to get a fallback value back instead of an exception:
112
113 ```python
114 >>> session.windows.get(window_name="nonexistent", default=None) is None
115 True
116 ```
117
118 ## Chaining filters
119
120 You can stack conditions two ways, and both narrow with AND. Pass several
121 keywords to a single `.filter()` call, or chain `.filter()` calls one after
122 another:
123
124 ```python
125 >>> # Create windows for this example
126 >>> w1 = session.new_window(window_name="feature-login")
127 >>> w2 = session.new_window(window_name="feature-signup")
128 >>> w3 = session.new_window(window_name="bugfix-typo")
129
130 >>> # Multiple conditions in one filter (AND)
131 >>> session.windows.filter(
132 ... window_name__startswith='feature',
133 ... window_name__endswith='signup'
134 ... ) # doctest: +ELLIPSIS
135 [Window(@... ...:feature-signup, Session($... ...))]
136
137 >>> # Chained filters (also AND)
138 >>> session.windows.filter(
139 ... window_name__contains='feature'
140 ... ).filter(
141 ... window_name__contains='login'
142 ... ) # doctest: +ELLIPSIS
143 [Window(@... ...:feature-login, Session($... ...))]
144
145 >>> # Clean up
146 >>> w1.kill()
147 >>> w2.kill()
148 >>> w3.kill()
149 ```
150
151 ## Case-insensitive filtering
152
153 Reach for the `i`-prefixed variants when the casing of a name shouldn't matter:
154
155 ```python
156 >>> # Create windows with mixed case
157 >>> w1 = session.new_window(window_name="MyApp-Server")
158 >>> w2 = session.new_window(window_name="myapp-worker")
159
160 >>> # Case-insensitive contains
161 >>> myapp_windows = session.windows.filter(window_name__icontains='MYAPP')
162 >>> len(myapp_windows) >= 2
163 True
164
165 >>> # Case-insensitive startswith
166 >>> session.windows.filter(window_name__istartswith='myapp') # doctest: +ELLIPSIS
167 [Window(@... ...:MyApp-Server, Session($... ...)), Window(@... ...:myapp-worker, Session($... ...))]
168
169 >>> # Clean up
170 >>> w1.kill()
171 >>> w2.kill()
172 ```
173
174 ## Regex filtering
175
176 When a prefix or substring isn't expressive enough, the regex lookups match
177 against a full pattern:
178
179 ```python
180 >>> # Create windows with version-like names
181 >>> w1 = session.new_window(window_name="app-v1-0")
182 >>> w2 = session.new_window(window_name="app-v2-0")
183 >>> w3 = session.new_window(window_name="app-beta")
184
185 >>> # Match version pattern
186 >>> versioned = session.windows.filter(window_name__regex=r'v\d+-\d+$')
187 >>> len(versioned) >= 2
188 True
189
190 >>> # Case-insensitive regex
191 >>> session.windows.filter(window_name__iregex=r'BETA') # doctest: +ELLIPSIS
192 [Window(@... ...:app-beta, Session($... ...))]
193
194 >>> # Clean up
195 >>> w1.kill()
196 >>> w2.kill()
197 >>> w3.kill()
198 ```
199
200 ## Filtering by list membership
201
202 When you already have a set of names in hand, `in` keeps the matches and `nin`
203 (not in) drops them:
204
205 ```python
206 >>> # Create test windows
207 >>> w1 = session.new_window(window_name="dev")
208 >>> w2 = session.new_window(window_name="staging")
209 >>> w3 = session.new_window(window_name="prod")
210
211 >>> # Filter windows in a list of names
212 >>> target_envs = ["dev", "prod"]
213 >>> session.windows.filter(window_name__in=target_envs) # doctest: +ELLIPSIS
214 [Window(@... ...:dev, Session($... ...)), Window(@... ...:prod, Session($... ...))]
215
216 >>> # Filter windows NOT in a list
217 >>> non_prod = session.windows.filter(window_name__nin=["prod"])
218 >>> any(w.window_name == "prod" for w in non_prod)
219 False
220
221 >>> # Clean up
222 >>> w1.kill()
223 >>> w2.kill()
224 >>> w3.kill()
225 ```
226
227 ## Filtering across the hierarchy
228
229 You aren't limited to one window's panes. Every level of the hierarchy returns
230 a {class}`~libtmux._internal.query_list.QueryList`, and the server-wide
231 collections — {attr}`server.panes <libtmux.Server.panes>`,
232 {attr}`server.windows <libtmux.Server.windows>`, and
233 {attr}`server.sessions <libtmux.Server.sessions>` — flatten everything beneath
234 them into a single list. That lets you query the whole server at once, which is
235 handy when you want a pane by some attribute and don't care which session or
236 window it lives in:
237
238 ```python
239 >>> # All panes across all windows in the server
240 >>> server.panes # doctest: +ELLIPSIS
241 [Pane(%... Window(@... ..., Session($... ...)))]
242
243 >>> # Filter panes by their window's name
244 >>> pane = session.active_pane
245 >>> pane # doctest: +ELLIPSIS
246 Pane(%... Window(@... ..., Session($... ...)))
247 ```
248
249 ## Real-world examples
250
251 A couple of patterns you'll reach for in practice.
252
253 ### Find all editor windows
254
255 Match several editor names at once with a single regex lookup:
256
257 ```python
258 >>> # Create sample windows
259 >>> w1 = session.new_window(window_name="vim-main")
260 >>> w2 = session.new_window(window_name="nvim-config")
261 >>> w3 = session.new_window(window_name="shell")
262
263 >>> # Find vim/nvim windows
264 >>> editors = session.windows.filter(window_name__iregex=r'n?vim')
265 >>> len(editors) >= 2
266 True
267
268 >>> # Clean up
269 >>> w1.kill()
270 >>> w2.kill()
271 >>> w3.kill()
272 ```
273
274 ### Find windows by naming convention
275
276 If you name windows by convention, a prefix match pulls the whole group, and
277 `.get()` plucks one out by name:
278
279 ```python
280 >>> # Create windows following a naming convention
281 >>> w1 = session.new_window(window_name="project-frontend")
282 >>> w2 = session.new_window(window_name="project-backend")
283 >>> w3 = session.new_window(window_name="logs")
284
285 >>> # Find all project windows
286 >>> project_windows = session.windows.filter(window_name__startswith='project-')
287 >>> len(project_windows) >= 2
288 True
289
290 >>> # Get specific project window
291 >>> backend = session.windows.get(window_name='project-backend')
292 >>> backend.window_name
293 'project-backend'
294
295 >>> # Clean up
296 >>> w1.kill()
297 >>> w2.kill()
298 >>> w3.kill()
299 ```
300
301 (native-filtering)=
302
303 ## Filtering before object creation
304
305 Everything above runs in Python, *after* tmux has already returned every row.
306 That's fine for the handful of sessions and windows most servers carry. But on
307 a large server — hundreds or thousands of panes, where you want only a few —
308 you pay to build objects you immediately discard.
309
310 The `search_*()` methods push the filtering down to tmux itself: tmux applies a
311 format expression and hands back only the matching rows, so libtmux builds
312 objects for the matches alone. Every level of the hierarchy ships one:
313
314 | Caller | Method | Underlying tmux |
315 |--------|--------|-----------------|
316 | {class}`~libtmux.Server` | {meth}`~libtmux.Server.search_sessions` | `tmux list-sessions -f <filter>` |
317 | {class}`~libtmux.Server` | {meth}`~libtmux.Server.search_windows` | `tmux list-windows -a -f <filter>` |
318 | {class}`~libtmux.Server` | {meth}`~libtmux.Server.search_panes` | `tmux list-panes -a -f <filter>` |
319 | {class}`~libtmux.Session` | {meth}`~libtmux.Session.search_windows` | `tmux list-windows -t $sess -f <filter>` |
320 | {class}`~libtmux.Session` | {meth}`~libtmux.Session.search_panes` | `tmux list-panes -s -t $sess -f <filter>` |
321 | {class}`~libtmux.Window` | {meth}`~libtmux.Window.search_panes` | `tmux list-panes -t @win -f <filter>` |
322
323 The {meth}`~libtmux.Server.list_buffers` method also accepts a `filter=`
324 kwarg with the same semantics.
325
326 There is no `search_clients()` method; filter clients via the
327 {attr}`~libtmux.Server.clients` accessor and Python-side
328 {meth}`~libtmux._internal.query_list.QueryList.filter`. Filtering
329 clients in Python is usually enough because a server's client
330 count is bounded by attached terminals, not by session/window/pane
331 fan-out.
332
333 ### Python-side vs. tmux-native
334
335 | | `.filter()` | `.search_*()` |
336 |-|-------------|---------------|
337 | Where | Python (after fetch) | tmux server (before fetch) |
338 | Filter language | libtmux's lookup operators (`__contains`, `__regex`, etc.) | tmux's [FORMATS](https://man.openbsd.org/tmux.1#FORMATS) grammar |
339 | Round trips | one (full list, then filter in memory) | one (tmux returns only matches) |
340 | Best for | rich Python checks, set membership, post-fetch composition | exact/glob matches over many rows |
341 | Stability | every libtmux version supports it | requires tmux ≥ 3.2 |
342
343 Both are valid; pick based on data volume and the filter language you want.
344
345 ### Filter syntax
346
347 tmux's filter language is the same one used in `-F` templates. Three
348 shapes cover most use cases:
349
350 ```python
351 >>> # Match by glob
352 >>> s_alpha = server.new_session(session_name='alpha-1')
353 >>> s_beta = server.new_session(session_name='beta-1')
354 >>> alphas = server.search_sessions(filter='#{m:alpha-*,#{session_name}}')
355 >>> [s.session_name for s in alphas]
356 ['alpha-1']
357
358 >>> # Match by equality
359 >>> exact = server.search_sessions(
360 ... filter='#{==:#{session_name},alpha-1}'
361 ... )
362 >>> [s.session_name for s in exact]
363 ['alpha-1']
364
365 >>> # Clean up
366 >>> s_alpha.kill()
367 >>> s_beta.kill()
368 ```
369
370 `#{e:...}` evaluates an arithmetic expression; `#{?cond,a,b}` is the
371 conditional form. See `man tmux` for the full grammar.
372
373 ### The silent zero-match trap
374
375 A malformed filter expression is the single biggest footgun. tmux expands an
376 unclosed `#{...}` or an unknown format token to an empty string,
377 which the filter engine evaluates as "false" — every row is filtered
378 out and **no stderr is emitted**. A bad filter is indistinguishable
379 from a filter that genuinely matched nothing.
380
381 If `search_*()` returns empty unexpectedly:
382
383 1. Replace the filter with `#{m:*,#{session_name}}` (or the
384 equivalent for windows/panes). If that returns rows, the issue is
385 filter syntax, not data.
386 2. Expand the expression standalone via
387 {meth}`~libtmux.Server.display_message` to see what tmux actually
388 produced:
389
390 ```python
391 >>> result = server.display_message(
392 ... '#{m:alpha-*,alpha-1}', get_text=True
393 ... )
394 >>> result[0]
395 '1'
396 ```
397
398 A non-`1`, non-empty result tells you the expression is parsing as
399 text, not as a boolean.
400
401 3. Cross-check the token name against the FORMATS section of
402 `tmux(1)` and against the version gate (see {ref}`format-tokens`).
403
404 ### When to prefer which
405
406 Use `search_*()` when:
407
408 - you have hundreds or thousands of windows/panes and only want a few,
409 - your filter is a glob (`m:`) or equality check (`==:`),
410 - you're already in tmux-format thinking (writing `#{...}` for a
411 status-line template, for example).
412
413 Use `.filter()` when:
414
415 - your filter needs Python types you can't express in tmux format
416 (set membership, complex regex, computed values from outside tmux),
417 - you're chaining multiple filters and prefer composing in Python,
418 - you want predictable, version-independent semantics.
419
420 ## API reference
421
422 See {class}`~libtmux._internal.query_list.QueryList` for the complete
423 QueryList API, and each `search_*()` method for the tmux-native filter
424 contract.