Quick start
Needs libtmux for F# 0.x Install
Drive tmux from F#: list and filter sessions, windows, panes and clients with typed filters, type and wait for what a pane prints, and run a command to its exit status. Every function works on the LibTmux core objects.
Add it to an F# project:
$ dotnet add package LibTmux.FSharpContents — Quick start · Find · Type and wait · Run · Choose a call · Existing tmux · Leaves out · Support
Quick start
Start a server of its own, type a command, wait for its output, run another command to its exit status, and list sessions with a filter. This is the whole program:
open Systemopen System.IOopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runAsync () = task { use deadline = new CancellationTokenSource(TimeSpan.FromSeconds 30.) let token = deadline.Token
// A server of its own on a private socket, without user configuration. let socketRoot = Directory.CreateTempSubdirectory "libtmux-example-"
use _cleanup = { new IDisposable with member _.Dispose() = socketRoot.Delete true }
let options = ServerConnectionOptions( SocketPath = Path.Combine(socketRoot.FullName, "tmux.sock"), ConfigurationFile = "/dev/null" )
use! owned = options |> Server.createOwned token
// One session whose window runs a plain shell, whatever the user's login shell is. let! session = owned.Value |> Server.newSession token (SessionSpec.running "build" "/bin/sh")
let! pane = session |> Session.activePane token
// Type a command and wait for what it prints, not for its echo. let! started = pane |> Pane.sendAndWait token (TimeSpan.FromSeconds 10.) "echo build started" "build started"
printfn "wait found: %b" started.Found
// Run a command to its exit status and read what it printed. let! result = pane |> Pane.run token (TimeSpan.FromSeconds 10.) "printf 'ok\\n'; exit 3"
match result with | PaneRun.Exited status -> printfn "run: exit %d, output %A" status (List.ofSeq result.Output) | PaneRun.Ended -> printfn "run: the shell exited first" | PaneRun.NotStarted -> printfn "run: the shell was not at a prompt" | PaneRun.TimedOut -> printfn "run: still running"
// List and filter: tmux narrows the listing, then every row is rechecked. let! found = owned.Value |> Server.sessions |> Query.where (SessionFields.name |> Filter.startsWith "bu") |> Query.list token
printfn "sessions: %s" (String.Join(", ", [ for listed in found -> listed.Name ])) }
runAsync().GetAwaiter().GetResult()To run it, make an F# console project and replace Program.fs with the program,
with tmux on PATH:
$ dotnet new console --language F# --framework net8.0 --output tmux-demo && \ cd tmux-demo && \ dotnet add package LibTmux.FSharp && \ dotnet runIt prints:
wait found: truerun: exit 3, output ["ok"]sessions: buildServer.createOwnedstarts a server on a unique socket with thetmuxonPATH; setServerConnectionOptions.TmuxBinaryPathto use another.use!stops it when the task ends.- The wait succeeds whether the line appeared before or after it began.
- The run’s exit status comes from the shell, so it does not depend on reading the screen.
- The listing reaches tmux as a filter, so tmux returns only the sessions that match.
The program is
published from a checkout:
dotnet run --project examples/LibTmux.FSharp.Quickstart runs it against the
source.
Find sessions, windows, and panes
Query.list: the panes that match a filter
Describe the listing with Server.panes and
Query.where, then read it. Building a query reads
nothing; tmux narrows the listing where it can, and every row it returns is
rechecked:
open System.Threadingopen LibTmuxopen LibTmux.FSharp
let shellPanesAsync (cancellationToken: CancellationToken) (server: Server) = server |> Server.panes |> Query.where (PaneFields.currentCommand |> Filter.oneOf [ "bash"; "sh"; "zsh" ]) |> Query.list cancellationTokenRun it with a server from Server.createOwned; it
returns the panes whose command is one of the three shells.
Query.exactlyOne returns a Result for the case
where exactly one match is expected, and
Query.atMostOne returns an option and raises on
several matches. Query.tryExactlyOne is the form
to use under NativeAOT.
Type into a pane and wait
Pane.sendAndWait: type a line, wait for its answer
It types the line, then waits for a later line to contain the text. The screen before it and the line’s own echo do not count.
From tmux 3.7 it sleeps on the pane’s output; earlier releases poll. It ends early if the program exits while it waits. This example finds a shell, types into it, and waits:
open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let runInShellAsync (cancellationToken: CancellationToken) (server: Server) = task { // List and filter: tmux narrows the listing, then every row is rechecked. let! shells = server |> Server.panes |> Query.where (PaneFields.currentCommand |> Filter.oneOf [ "bash"; "sh"; "zsh" ]) |> Query.list cancellationToken
match shells |> Seq.tryHead with | None -> return None | Some pane -> // Type a command and wait for what it prints, not for its echo. let! ready = pane |> Pane.sendAndWait cancellationToken (TimeSpan.FromSeconds 10.) "echo ready" "ready"
// Run a command to its exit status and read what it printed. let! listing = pane |> Pane.run cancellationToken (TimeSpan.FromSeconds 30.) "ls /"
match listing with | PaneRun.Exited status -> return Some(ready.Found, status, listing.Output) | PaneRun.Ended | PaneRun.NotStarted | PaneRun.TimedOut -> return None }It returns Some (true, 0, lines) for the ls / listing, or None when no
shell pane exists or the shell was not at a prompt.
Pane.waitForwaits for output you did not type, andPane.sendAndWaitFortakes keys and patterns.- Every wait ends early when the program exits, and raises
TmuxPaneExceptionif it already had. Which wait compares them. - The sample types into the first shell it finds. On a tmux that is already running, that may be the terminal you are reading.
Run a command and read its status
Pane.run: the exit status and what it printed
It returns the lines the command printed, and the PaneRun case says how it
ended: the command exited with a status, its shell exited first, it never
started, or it ran out of time:
open Systemopen System.Threadingopen LibTmuxopen LibTmux.FSharp
let exitStatusAsync (cancellationToken: CancellationToken) (pane: Pane) = task { // Run a command to its exit status and read what it printed. let! run = pane |> Pane.run cancellationToken (TimeSpan.FromSeconds 10.) "printf 'ok\\n'; exit 3"
match run with | PaneRun.Exited status -> return Some(status, List.ofSeq run.Output) | PaneRun.Ended | PaneRun.NotStarted | PaneRun.TimedOut -> return None }Against the quick-start server it returns Some (3, ["ok"]).
Pane.run needs a POSIX shell prompt and refuses fish,
PowerShell, and a REPL.
Choose a call
Connect
| Need | F# call | Returns |
|---|---|---|
| Start a server you own¶ | options |> Server.createOwned ct | OwnedServerScope to use! |
| Attach to a running server¶ | options |> Server.connect ct | Server |
| Bound every command’s time¶ | Server.within timeout server | Server |
Find
| Need | F# call | Returns |
|---|---|---|
| List and filter¶ | Server.panes server |> Query.where filter |> Query.list ct | IReadOnlyList<Pane> |
| One session’s or window’s panes¶ | Session.panes session |> Query.list ct; Window.panes alike | IReadOnlyList<Pane> |
| Panes showing some text¶ | Server.panes server |> Query.showing search |> Query.list ct | IReadOnlyList<Pane> |
| Exactly one match¶ | Query.exactlyOne ct query; Query.tryExactlyOne under NativeAOT | Result<'T, CardinalityError>; 'T option |
| Find, or create when absent¶ | Query.atMostOne ct query | 'T option; several raise |
| One object by ID¶ | Server.tryFindPane ct id server | Pane option |
| The pane a session or window shows¶ | Session.activePane ct session, Window.activePane ct window | Pane |
Type, wait and run
| Need | F# call | Returns |
|---|---|---|
| Type a line, or press a key¶ | Pane.sendLine ct line pane; Pane.pressKey ct "C-c" pane | Task |
| Type a line, wait for its output¶ | Pane.sendAndWait ct timeout line text pane; Pane.sendAndWaitFor for keys and patterns | PaneWaitResult; .Found, or match PaneWait |
| Wait for output you did not type¶ | Pane.waitForText ct timeout text pane; Pane.waitFor for patterns | PaneWaitResult |
| Wait for a screen condition¶ | Pane.waitUntil ct timeout condition pane | PaneWaitResult |
| Many waits on one session¶ | use! _ = Session.holdWaitClient ct session | IAsyncDisposable; each wait skips attaching a client, about 5 ms |
| Run a command to its exit status¶ | Pane.run ct timeout command pane | PaneRunResult; match PaneRun |
| Read the screen¶ | Pane.capture ct request pane | IReadOnlyList<string> |
| What a pane printed since last time¶ | Pane.readSince ct position pane | PaneOutputSince; pass its Position next time |
| Find text on one screen¶ | Pane.findOnScreen ct search pane | row int option |
Build
| Need | F# call | Returns |
|---|---|---|
| Split a pane¶ | Pane.split ct request pane | the new Pane |
| Rename a session or window¶ | Window.rename ct name window | a handle with the new name |
| Make a window or pane current¶ | Window.select ct window, Pane.select ct pane | a handle with the state afterwards |
| Kill a session, window or pane¶ | Pane.kill ct pane | Task |
| Arrange, resize or move a window¶ | Window.selectLayout ct layout window, Window.resize ct request window, Window.move ct request window | a handle with the state afterwards |
| Title, resize, swap, respawn or clear a pane¶ | Pane.setTitle ct title pane, Pane.resize, Pane.swap, Pane.respawn, Pane.clearHistory | the handle, or Task |
| Add a window to a session¶ | Session.newWindow ct request session | the new Window |
| Create a session running one command¶ | Server.newSession ct (SessionSpec.running name command) server | Session |
| Create a session with windows¶ | Server.newSession ct spec server | Session |
| Several commands, one tmux call¶ | Chain.start server |> … |> Chain.run ct | TmuxCommandResult |
| Read or set a typed option¶ | Options.get ct key options | the key’s value type |
Observe
| Need | F# call | Returns |
|---|---|---|
| A whole object graph¶ | Server.capture ct depth server | snapshot Server |
| Live server state¶ | Mirror.start ct session | ServerMirror |
| Events as they happen¶ | Control.withSession ct work server | cold IAsyncEnumerable streams |
| One pane’s output as it prints¶ | Control.watchPane pane client; Control.watchPanes for several | events; match PaneWatch |
Recover
| Need | F# call | Returns |
|---|---|---|
| Tell failures apart¶ | TmuxFailure.NotSent, Ran, MayHaveRun | active patterns |
| Retry only unsent work¶ | Retry.ifNotSent ct retries operation, or Retry.ifNotSentAfter ct delays operation | the operation’s result |
Await a call in an async workflow¶ | TmuxAsync.awaitTask task, TmuxAsync.awaitUnitTask task | Async; keeps what MayHaveRun matches |
Caveats
- Queries: tmux narrows each listing where it can, and every row is rechecked.
- Bounds: a handle from
Server.withinshares its bound with the sessions, windows and panes taken from it. - Live state:
Mirror.startreturns a mirror touse!.Mirror.waitUntilraises when no view matches in time;Mirror.tryWaitUntilreturnsNone. - Events: inside
Control.withSession,Control.events,Control.watchPaneandControl.watchPanesread the client it opens, one reader at a time.
Connect to a running tmux
Server.connect: a server your program did not start
options |> Server.connect ct attaches to the server already running on the
socket the options name. It never starts tmux.
Default options choose no socket, so tmux picks the server;
socket selection
gives the order. Code running inside a tmux pane can use
Server.FromEnvironment() to find that pane’s server.
What it leaves out
- Its own handle types. Captured sessions, windows, panes, and IDs are the core .NET types. A window linked into more than one session has a placement in each; filtering keeps their order and multiplicity.
- Implicit starts.
Server.connectnever starts tmux;Server.createOwneddoes, and stops it. - Control-mode waits on older releases. Waits use pane output from tmux 3.7; earlier releases poll.
- Other shells for
Pane.run. It needs a POSIX shell prompt. - Empty answers for missing data. An uncaptured relationship raises
IncompleteSnapshotException.
Support and status
- Pre-1.0. Any release may change or remove an exported identifier. The changelog marks each break, so pin an exact version.
- .NET. .NET 8 and .NET 10, using the matching
LibTmuxpackage version. - F#. FSharp.Core 8.0.100 or newer, so an application keeps its SDK’s FSharp.Core.
- tmux. 3.3a or newer, tested through 3.8.
- Systems. Linux, including WSL. macOS is best effort. Native Windows is
unsupported: the core marks its tmux calls
[UnsupportedOSPlatform("windows")]. - NativeAOT and trimming. Portable filters bind fields without reflection. A Linux consumer publishes and runs snapshots, tmux queries, and portable filters under both, on both frameworks.
- Under NativeAOT,
Selection.exactlyOneandQuery.exactlyOnecannot be published, because theirResultformats throughprintf, which NativeAOT rejects. - The NativeAOT alternatives are
Query.atMostOne, orQuery.tryExactlyOnewhere none and several can be treated alike.
Documentation
- API reference and guides on libtmux.org: every public symbol, and task-oriented walkthroughs.
- Source: the package directory on GitHub.
- Send, wait and read; split panes: owned scopes, waits, runs and live mutation.
- Query tmux, filter captured objects and supported fields: every level, pushdown, screen search, relations and capture depth.
- Choose an execution mode and stream events: scoped clients, cold streams, pane watches, cancellation, and command chains.
- Test code that drives tmux: a private server per test, waits on state, and CI setup.
- Share one server across tasks: what handles, waits, runs, control clients and mirrors share.
- Run tmux work in a service: one bounded handle, stopping, retries, one writer per pane, and telemetry.
- Call the core from F# and browse signatures.
- Read benchmark records: measured core execution modes and benchmark methods.
- Changelog: what each release of this package changed