Skip to content

About

Common Lisp tmux client library with captured CLOS objects, native queries, and explicit operations. SBCL/Linux; alpha.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

libtmux for Common Lisp

libtmux for Common Lisp

Native Lisp checks libtmux.org license

Drive tmux from Common Lisp: sessions, windows, window links and panes as CLOS objects, queried with plain sequences, changed through an explicit client.

Documentation · API reference · REPL tutorial

Install from source

Needs SBCL, Linux (WSL included) and tmux 3.3a or newer. Not released yet: load it from a checkout.

$ git clone https://github.com/libtmux/libtmux-lisp.git && cd libtmux-lisp

Register the checkout with ASDF, from its root:

(asdf:load-asd (truename "libtmux.asd"))

Load core and queries. Both need only ASDF/UIOP:

(asdf:load-system "libtmux/query")

To run the examples, set up the toolchain with mise, then:

$ mise run examples

The examples run on a private tmux socket, never your default server.

Start a private server

libtmux:with-daemon: a server that cleans up after itself

with-client scopes the connection; new-session creates a session.

(defun inspect-owned-workspace (&key (program "tmux"))
  "Start a private daemon and return owned pane data after closing both."
  (libtmux:with-daemon (daemon :program program)
    (let ((socket (libtmux:daemon-socket-path daemon)))
      (libtmux:with-client (client :program (libtmux:daemon-program daemon)
                                   :socket-path socket)
        (let ((outcome (libtmux:new-session client :name "demo"
                                                   :command '("/bin/cat"))))
          (when (libtmux:outcome-observation-error outcome)
            (error (libtmux:outcome-observation-error outcome))))
        (map 'list #'libtmux:entity-data
             (libtmux:panes (libtmux:fetch-snapshot client)))))))
$ mise exec -- sbcl --script examples/managed-daemon.lisp

Prints MANAGED DAEMON PASS and a pane record. To reach an existing server, use with-client alone. More: daemon scopes.

Drive a pane

libtmux:split-pane: split, send, capture and resize

send-text types into the new pane and capture-pane reads its screen. resize-window and resize-pane set sizes in cells.

(asdf:load-system "libtmux")

(defun drive-panes (&key (program "tmux"))
  "Split a pane, send text, capture its screen and resize; return sizes."
  (libtmux:with-daemon (daemon :program program)
    (let ((socket (libtmux:daemon-socket-path daemon)))
      (libtmux:with-client (client :program (libtmux:daemon-program daemon)
                                   :socket-path socket)
        (flet ((observed (outcome)
                 (when (libtmux:outcome-observation-error outcome)
                   (error (libtmux:outcome-observation-error outcome)))
                 (values (libtmux:outcome-value outcome))))
          (observed (libtmux:new-session client :name "demo"
                                                :command '("/bin/cat")))
          (let* ((left (aref (libtmux:fetch-panes client) 0))
                 (right (observed
                         (libtmux:split-pane client left
                                             :direction :horizontal
                                             :command '("/bin/cat")))))
            (libtmux:send-text client right "hello from Lisp" :enter t)
            (let* ((text (libtmux:capture-pane client right))
                   (win (observed
                         (libtmux:resize-window client (libtmux:window right)
                                                :width 100 :height 30)))
                   (narrow (observed
                            (libtmux:resize-pane client right :width 20))))
              (list :text (string-right-trim '(#\Newline) text)
                    :window-size (list (libtmux:width win)
                                       (libtmux:height win))
                    :pane-width (libtmux:width narrow)))))))))
$ mise exec -- sbcl --script examples/drive-panes.lisp

Prints PANE OPERATIONS PASS, the captured text, the window size and the pane width. A send succeeds when tmux accepts the input, not when the application reads it: wait on a signal.

More: operation contracts · decoded configuration

Find sessions, windows and panes

libtmux:fetch-snapshot: read the graph once

One call to tmux; everything after is local. The examples share one package: tm is libtmux, q is libtmux.query, j is libtmux.json and ws is libtmux.workspace.

(defpackage #:libtmux.examples
  (:use #:cl)
  (:local-nicknames (#:tm #:libtmux)
                    (#:q #:libtmux.query)
                    (#:j #:libtmux.json)
                    (#:ws #:libtmux.workspace))
  (:export #:inspect-workspace #:create-workspace #:observed-value
           #:apply-workspace-document #:workspace-description
           #:terminate-owned-server #:configuration-report))

(in-package #:libtmux.examples)
(defun inspect-workspace (socket-path &key (program "tmux"))
  "Acquire one graph from SOCKET-PATH; return owned session/window/pane data."
  (tm:with-client (client :program program :socket-path socket-path)
    (let ((snapshot (tm:fetch-snapshot client)))
      (loop for session across (tm:sessions snapshot)
            collect
            (list :session (tm:name session)
                  :windows
                  (loop for link across (tm:window-links session)
                        for window = (tm:window link)
                        collect (list :index (tm:index link)
                                      :name (tm:name window)
                                      :panes (map 'list #'tm:entity-data
                                                  (tm:panes window)))))))))

A window can be linked into several sessions:

graph LR
  work[Session: work] --> a[Window link: index 0]
  work --> b[Window link: logs]
  review[Session: review] --> c[Window link: index 7]
  review --> d[Window link: notes]
  a --> editor[Physical window: editor]
  c --> editor
  editor --> p1[Pane 1]
  editor --> p2[Pane 2]
  b --> logs[Physical window: logs]
  d --> notes[Physical window: notes]
Loading

More: identity and ownership · walkthrough.

libtmux:panes: filter with plain Lisp

(defun wide-active-panes (snapshot)
  "Select captured active panes at least 40 cells wide; no tmux commands."
  (loop for pane across (tm:panes snapshot)
        when (and (tm:active-p pane) (>= (tm:width pane) 40))
          collect (tm:entity-data pane)))

Query a snapshot

Same package nicknames as above.

libtmux.query:compile-filter: a filter compiled once

matching applies it to captured objects. No tmux calls.

(defparameter *wide-active-filter*
  (q:compile-filter
   :pane
   '(:and (:= :pane/active t)
          (:>= :pane/width 40))))

(defun wide-active-pane-data (snapshot)
  "Return owned data for captured active panes at least 40 cells wide; no I/O."
  (map 'vector #'tm:entity-data
       (q:matching *wide-active-filter* (tm:panes snapshot))))

Mistyped fields are refused at compile time. More: query guide.

libtmux.query:where: follow relations

Sessions with an active pane, through window links and windows. items returns the matches.

(defparameter *active-session-filter*
  (q:compile-filter
   :session
   '(:any :session/window-links
     (:is :link/window
      (:any :window/panes
       (:= :pane/active t))))))

(defun active-session-data (snapshot)
  "Return owned data for sessions with an active pane; no I/O."
  (map 'vector #'tm:entity-data
       (q:items
        (q:where (q:from (tm:sessions snapshot) :model :session)
                 *active-session-filter*))))

libtmux.query:explain: where a filter runs

Lists the fields a compiled filter reads. Filters always run locally; tmux filters nothing for you.

(defun filter-execution (filter)
  "Report that FILTER runs locally without I/O, and list the fields it reads."
  (let ((report (q:explain filter)))
    (list :execution (getf report :execution)
          :acquires-p (getf report :acquires-p)
          :fields (getf report :required-fields))))

For the filter above it returns:

(:EXECUTION :LOCAL :ACQUIRES-P NIL :FIELDS #(:PANE/ACTIVE :PANE/WIDTH))

More: inspecting a filter

libtmux.json:write-filter: regex and JSON documents

Optional systems add CL-PPCRE matching and a versioned JSON form. read-filter restores a filter.

(defparameter *cat-command-filter*
  (q:compile-filter
   :pane
   '(:regex-full-match :pane/current-command
     (:cl-ppcre "CAT" :case-insensitive-mode t))))

(defun cat-pane-data (snapshot)
  "Return owned data for captured panes whose command is exactly cat; no I/O."
  (map 'vector #'tm:entity-data
       (q:matching *cat-command-filter* (tm:panes snapshot))))
(defun round-trip-filter-document (snapshot)
  "Round-trip the checked regex filter and apply it to one retained snapshot."
  (let* ((document (j:write-filter *cat-command-filter*))
         (restored (j:read-filter document :allow-regex t)))
    (values document
            (map 'vector #'tm:entity-data
                 (q:matching restored (tm:panes snapshot))))))

More: query interchange.

Build a workspace

libtmux.workspace:make-workspace: declare windows and panes

Plain Lisp data, or an equivalent JSON file. Nothing touches tmux until you apply it.

(defun owned-description ()
  "Describe two windows and three panes without contacting tmux."
  (libtmux.workspace:make-workspace
   '(:schema "libtmux.lisp.workspace/2" :id "demo-workspace"
     :session
     (:id "main" :name "owned-demo"
      :environment #(("DEMO_LABEL" . "hello from Common Lisp"))
      :windows
      #((:id "code" :name "code" :index 2 :layout :tiled
         :panes #((:id "shell" :command #("/bin/cat"))
                  (:id "repl" :command #("/bin/cat"))))
        (:id "logs" :name "logs" :index 5
         :panes #((:id "tail" :command #("/bin/cat")))))))))
$ mise exec -- sbcl --script examples/owned-workspace.lisp

fetch-workspace-state reads tmux. The plan is local. apply-workspace changes tmux through the client you pass.

(asdf:load-system "libtmux/workspace")

(defpackage #:libtmux.workspace.example
  (:use #:cl)
  (:local-nicknames (#:tm #:libtmux) (#:ws #:libtmux.workspace)))
(in-package #:libtmux.workspace.example)
(defun apply-owned-description (client workspace)
  "Acquire, preview and apply explicitly; return the result and owned record."
  (let* ((state (ws:fetch-workspace-state client workspace))
         (preview (ws:plan-workspace workspace state)))
    (assert (getf (ws:plan-data preview) :publish-p))
    (let* ((result (ws:apply-workspace client workspace :total-timeout 30))
           (data (ws:result-data result)))
      (assert (eq :succeeded (getf data :publication-status)))
      (values result (getf data :record)))))
  • Changing an existing workspace needs :reconcile t.
  • A preview grants no authority to apply.

More: owned workspaces · Workspace API · legacy schema.

Stream pane output

libtmux.control:with-connection: one connection, queued commands

Needs tmux 3.8 or newer. submit-command queues a request, await-request waits for its reply and next-event reads pane output as bytes.

(asdf:load-system "libtmux/control")

(defpackage #:libtmux.control.example
  (:use #:cl)
  (:local-nicknames (#:tm #:libtmux) (#:control #:libtmux.control)))
(in-package #:libtmux.control.example)
(defun echo-through-control (client session pane)
  "Send literal text and collect pane-output bytes on one scoped connection."
  (control:with-connection (connection client session)
    (let* ((id (tm:id pane))
           (text "hello from control")
           (write (control:submit-command
                   connection (list "send-keys" "-t" id "-l" text)
                   :effect :mutation))
           (enter (control:submit-command
                   connection (list "send-keys" "-t" id "Enter")
                   :effect :mutation)))
      (dolist (request (list write enter))
        (multiple-value-bind (result delivery)
            (control:await-request request :timeout 1)
          (assert (eq :ready delivery))
          (assert (eq :completed (getf result :status)))))
      (let ((bytes (make-array 0 :element-type '(unsigned-byte 8)
                                 :adjustable t :fill-pointer 0))
            (expected (map 'vector #'char-code text))
            (deadline (+ (get-internal-real-time)
                         internal-time-units-per-second)))
        (loop repeat 64
              until (search expected bytes)
              for left = (/ (- deadline (get-internal-real-time))
                            internal-time-units-per-second)
              do (assert (plusp left))
                 (multiple-value-bind (event delivery)
                     (control:next-event connection :timeout left)
                   (assert (eq :ready delivery))
                   (case (getf event :kind)
                     (:output
                      (assert (string= id (getf event :pane)))
                      (loop for byte across (getf event :data)
                            do (vector-push-extend byte bytes)))
                     ((:gap :end)
                      (error "Output stream ended or lost data: ~S" event)))))
        (assert (search expected bytes))
        (coerce bytes '(simple-array (unsigned-byte 8) (*)))))))
$ mise exec -- sbcl --script examples/control.lisp

Prints CONTROL PASS, CONTROL NOTIFICATION PASS and CONTROL RECONNECT PASS.

  • with-reconnection reconnects on request and returns fresh observations. It never replays commands.

More: control guide · control README

Choose an ASDF system

One source distribution, one version, one changelog. Load only what you use:

System Use it for Additional dependencies API
libtmux Captures, CLOS objects and explicit tmux operations ASDF/UIOP Core
libtmux/query Native predicates, relations and eager QuerySets Core Query
libtmux/regex CL-PPCRE search and full-match filters Query, CL-PPCRE Query
libtmux/json Bounded query document interchange Query, Jzon JSON
libtmux/control Queued requests, output streams and reconnection on tmux 3.8+ Core Control
libtmux/workspace Owned declarations, drift previews and explicit reconciliation Core, Jzon Workspace
libtmux/workspace/cli Workspace validation, previews and explicit-endpoint apply Workspace CLI

Definitions are in libtmux.asd; source is in src/.

libtmux: the core library

Captures the CLOS object graph and runs explicit tmux operations through a libtmux:client, with ASDF and UIOP alone.

API reference · Guides · REPL tutorial

libtmux/query: native queries

libtmux.query:compile-filter and libtmux.query:matching filter captured objects without contacting tmux.

API reference · README

libtmux/regex: CL-PPCRE operators

Adds search and full-match operators to native queries.

Query API · README

libtmux/json: bounded filter documents

libtmux.json:write-filter and libtmux.json:read-filter exchange a compiled filter as a versioned JSON document.

API reference · README

libtmux/control: control connections on tmux 3.8+

libtmux.control:with-connection scopes a connection that queues requests and streams pane output.

API reference · README

libtmux/workspace: owned workspaces

libtmux.workspace:make-workspace declares a workspace; previews and reconciliation stay explicit.

API reference · Workspace docs · README

libtmux/workspace/cli: the workspace command line

Validates, previews and applies a workspace against an explicit endpoint.

API reference · README

What it leaves out

  • Live objects. Captured session, window, window-link and pane instances keep what tmux reported when read. Call fetch-snapshot again to observe later changes.
  • A terminal emulator or ~/.tmux.conf editor. capture-pane reads the screen tmux drew, control events deliver raw bytes, and set-option updates a running server rather than files on disk.
  • tmuxp YAML and MCP. libtmux/workspace reads its own Lisp or JSON declarations, and Model Context Protocol servers are outside this port's scope.
  • Async event loops and source pushdown. Core client calls block their caller, and libtmux.query evaluates filters locally over retained captures.

Support and status

Find the right guide

Task Start here
Load the library; inspect and build a workspace REPL tutorial
Start and stop a private empty-config daemon Daemon scopes
Filter with loop, handle false/absence, export plists Local data recipes
Compile typed filters, traverse relations and compose QuerySets Native queries · Query API
Add CL-PPCRE or exchange bounded filter documents Query interchange · JSON API
Create, inspect or explicitly reconcile an owned workspace Owned workspaces · Workspace API
Rename, resize, move, send input, capture, use buffers or terminate explicit targets Operation contracts
Read typed options, hooks and environment Decoded configuration
Inspect native option, hook and environment output Configuration inspection
Look up signatures, multiple values and conditions Public API · Captured fields
Understand deadlines, cancellation and cleanup Transport
Reconnect without replaying commands Fresh control observations
Evaluate async, streaming and performance support Capabilities and limits
Rerun FiveAM tests at the REPL or inspect CI coverage Testing · Verification
Navigate all documentation Guide index

For changes, read Contributing and Writing.

Part of the libtmux.org family alongside Python libtmux, sibling language ports, and tmux. Artwork · MIT License.

About

Common Lisp tmux client library with captured CLOS objects, native queries, and explicit operations. SBCL/Linux; alpha.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages