Core Library0.xGuides

Choose documentation 1

latest

Current version

latest
English

Early release libtmux is released, and its APIs may still change between releases. This site's structure and URLs may change too.

MoreLess about this notice

Quick start

Needs libtmux for F# 0.x Install

LibTmux.FSharp libtmux.org

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.

license

Add it to an F# project:

Terminal window
$ dotnet add package LibTmux.FSharp

Contents — 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 System
open System.IO
open System.Threading
open LibTmux
open 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:

Terminal window
$ dotnet new console --language F# --framework net8.0 --output tmux-demo && \
cd tmux-demo && \
dotnet add package LibTmux.FSharp && \
dotnet run

It prints:

wait found: true
run: exit 3, output ["ok"]
sessions: build
  • Server.createOwned starts a server on a unique socket with the tmux on PATH; set ServerConnectionOptions.TmuxBinaryPath to 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.Threading
open LibTmux
open LibTmux.FSharp
let shellPanesAsync (cancellationToken: CancellationToken) (server: Server) =
server
|> Server.panes
|> Query.where (PaneFields.currentCommand |> Filter.oneOf [ "bash"; "sh"; "zsh" ])
|> Query.list cancellationToken

Run 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 System
open System.Threading
open LibTmux
open 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.waitFor waits for output you did not type, and Pane.sendAndWaitFor takes keys and patterns.
  • Every wait ends early when the program exits, and raises TmuxPaneException if 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 System
open System.Threading
open LibTmux
open 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

NeedF# callReturns
Start a server you ownoptions |> Server.createOwned ctOwnedServerScope to use!
Attach to a running serveroptions |> Server.connect ctServer
Bound every command’s timeServer.within timeout serverServer

Find

NeedF# callReturns
List and filterServer.panes server |> Query.where filter |> Query.list ctIReadOnlyList<Pane>
One session’s or window’s panesSession.panes session |> Query.list ct; Window.panes alikeIReadOnlyList<Pane>
Panes showing some textServer.panes server |> Query.showing search |> Query.list ctIReadOnlyList<Pane>
Exactly one matchQuery.exactlyOne ct query; Query.tryExactlyOne under NativeAOTResult<'T, CardinalityError>; 'T option
Find, or create when absentQuery.atMostOne ct query'T option; several raise
One object by IDServer.tryFindPane ct id serverPane option
The pane a session or window showsSession.activePane ct session, Window.activePane ct windowPane

Type, wait and run

NeedF# callReturns
Type a line, or press a keyPane.sendLine ct line pane; Pane.pressKey ct "C-c" paneTask
Type a line, wait for its outputPane.sendAndWait ct timeout line text pane; Pane.sendAndWaitFor for keys and patternsPaneWaitResult; .Found, or match PaneWait
Wait for output you did not typePane.waitForText ct timeout text pane; Pane.waitFor for patternsPaneWaitResult
Wait for a screen conditionPane.waitUntil ct timeout condition panePaneWaitResult
Many waits on one sessionuse! _ = Session.holdWaitClient ct sessionIAsyncDisposable; each wait skips attaching a client, about 5 ms
Run a command to its exit statusPane.run ct timeout command panePaneRunResult; match PaneRun
Read the screenPane.capture ct request paneIReadOnlyList<string>
What a pane printed since last timePane.readSince ct position panePaneOutputSince; pass its Position next time
Find text on one screenPane.findOnScreen ct search panerow int option

Build

NeedF# callReturns
Split a panePane.split ct request panethe new Pane
Rename a session or windowWindow.rename ct name windowa handle with the new name
Make a window or pane currentWindow.select ct window, Pane.select ct panea handle with the state afterwards
Kill a session, window or panePane.kill ct paneTask
Arrange, resize or move a windowWindow.selectLayout ct layout window, Window.resize ct request window, Window.move ct request windowa handle with the state afterwards
Title, resize, swap, respawn or clear a panePane.setTitle ct title pane, Pane.resize, Pane.swap, Pane.respawn, Pane.clearHistorythe handle, or Task
Add a window to a sessionSession.newWindow ct request sessionthe new Window
Create a session running one commandServer.newSession ct (SessionSpec.running name command) serverSession
Create a session with windowsServer.newSession ct spec serverSession
Several commands, one tmux callChain.start server |> … |> Chain.run ctTmuxCommandResult
Read or set a typed optionOptions.get ct key optionsthe key’s value type

Observe

NeedF# callReturns
A whole object graphServer.capture ct depth serversnapshot Server
Live server stateMirror.start ct sessionServerMirror
Events as they happenControl.withSession ct work servercold IAsyncEnumerable streams
One pane’s output as it printsControl.watchPane pane client; Control.watchPanes for severalevents; match PaneWatch

Recover

NeedF# callReturns
Tell failures apartTmuxFailure.NotSent, Ran, MayHaveRunactive patterns
Retry only unsent workRetry.ifNotSent ct retries operation, or Retry.ifNotSentAfter ct delays operationthe operation’s result
Await a call in an async workflowTmuxAsync.awaitTask task, TmuxAsync.awaitUnitTask taskAsync; keeps what MayHaveRun matches

Caveats

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.connect never starts tmux; Server.createOwned does, 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 LibTmux package 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.exactlyOne and Query.exactlyOne cannot be published, because their Result formats through printf, which NativeAOT rejects.
  • The NativeAOT alternatives are Query.atMostOne, or Query.tryExactlyOne where none and several can be treated alike.

Documentation

Esc
Search in

Type to search.

Reference previewOpen reference