Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ Notable changes to `libtmux`.

## Unreleased

- Docs: the README starts with a calculator in a private tmux pane. Run it
from standalone Lua or Neovim and read the reply over control mode.

- Runtime: `Runtime:start_server` starts a private tmux server and resolves to
an `OwnedServer` with its `server` handle, its `socket_path` and `stop()`.
The server lives in a new directory under `root` (the system temporary
Expand Down
181 changes: 81 additions & 100 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,92 +28,85 @@ release may change an API: pin an exact version and read the

## Quick start

Standalone scripts run on `luv`, the event loop. It builds with a C compiler,
make and CMake:
Send `19 + 23` to a calculator in a private tmux pane and read back `42`.
The example runs `awk` in its own tmux server and stops the server afterward.
It reads the reply over control mode, which needs tmux 3.7 or newer.

- Debian and Ubuntu: `build-essential` and `cmake`.
- Fedora: `gcc`, `make` and `cmake`.
- macOS: the Xcode command line tools and `cmake`.
Clone the repository for `Runtime:start_server`. The published `0.1.1-1`
rock can run the [local query example](#packages).

If the build fails, install `lua-luv` on Debian or Ubuntu instead. It serves
only the distribution's own Lua.
```console
$ git clone https://github.com/libtmux/libtmux-lua.git && cd libtmux-lua
```

`Runtime:start_server`, which the programs below call, is not in the published
`0.1.1-1` rock. It ships in the release after it. Until then, put this
repository's `lua/` directory ahead of the installed rock on `LUA_PATH`.
**From a shell.** Use LuaRocks configured for the Lua you run. To build
`luv`, install `build-essential` and `cmake` on Debian or Ubuntu, `gcc`,
`make` and `cmake` on Fedora, or the Xcode command line tools and `cmake`
on macOS.

Install the rock, then `luv` (skip it if you installed `lua-luv`):
On Debian or Ubuntu, you can install `lua-luv` for the distribution's Lua
and skip the `luv` command below.

```console
$ luarocks --local install libtmux
```
If you switch to that Lua, open a new terminal in the same directory. Run
this guide's libtmux installation and LuaRocks path setup with LuaRocks
configured for the distribution's Lua.

```console
$ luarocks --local install luv 1.52.1-0
```

Add the local rocks tree to Lua's module paths:
Build the checkout's rock and add the local rocks to Lua's search paths.

```console
$ eval "$(luarocks --local path)"
$ luarocks --local make rockspecs/libtmux-scm-1.rockspec && \
eval "$(luarocks --local path)"
```

Create a session and read it back. This is the whole program:
Put tmux on your `PATH`. To select a particular build, set `TMUX_BIN` to
its absolute path.

<!-- example: examples/api/new_session.lua -->
On tmux 3.3a through 3.6b, try [typing into a pane and reading its
screen][read-screen]. On tmux 3.7 or newer, run the calculator. Change the
numbers by passing a sum such as `"7 + 8"` after the filename.

```lua
local adapter = require("libtmux.runtime.luv")
```console
$ lua examples/api/watch_pane.lua
19 + 23 = 42
```

local function must(value, err)
if err ~= nil then
error(tostring(err), 0)
end
return value
end
**From Neovim 0.10 or newer.** Neovim supplies the Lua runtime and event loop.
Put tmux on its `PATH` and run the example from the checkout.

must(adapter.run(function(runtime)
local owned = must(runtime:start_server():await())
local created = must(owned.server
:new_session({
name = "demo",
window_name = "main",
argv = { "/bin/cat" },
})
:await())
local handles = created.session and created.window and created.pane
assert(handles, "creation handles are missing")
local snapshot = must(created.session:snapshot():await())
assert(snapshot.name == "demo", "created session has the wrong name")
print("session: " .. snapshot.name)

must(owned:stop():await())
return true
end))
```console
$ nvim --clean --cmd 'set runtimepath^=.' -c 'luafile examples/api/watch_pane.lua'
```

[`Runtime:start_server`][guide-start-server] starts a private tmux server and
`owned:stop()` ends it. [`Server:new_session`][ref-server-new-session] creates
the session and [`Session:snapshot`][ref-session-snapshot] reads it back.
After `19 + 23 = 42` appears in Neovim, you can see it again in `:messages`
or enter a different sum.

Live calls return [Requests][ref-request]. [`:await()`][ref-request-await]
yields inside the [runtime][ref-runtime] body and returns `value, err`; `must`
raises the error.
```text
:lua assert(loadfile("examples/api/watch_pane.lua"))("7 + 8")
```

Put tmux on `PATH` and run one of the programs from a checkout:
The [example program](examples/api/watch_pane.lua) starts looking for new
output before typing. Sending the expression and Enter and reading the reply
share a five-second deadline.

```console
$ git clone https://github.com/libtmux/libtmux-lua.git && cd libtmux-lua
```
<!-- excerpt: examples/api/watch_pane.lua -->

```console
$ lua examples/api/new_session.lua
session: demo
```lua
local observation = must(owned.server:observe(created.session):await())
local watch = must(observation:watch_pane(pane):await())

local deadline = uv.hrtime() / 1e6 + 5000
local send = { process = { deadline = deadline } }
must(pane:send_text(question, send):await())
must(pane:send_keys({ "Enter" }, send):await())
local answer = read_answer(watch, deadline)
```

Every Lua block here comes from a program under [`examples/`](examples/).
Excerpts continue inside the same runtime body, with `server` and `must` in
hand.
The terminal may echo `19 + 23`. The example waits for a complete
`answer:` line from the calculator and checks the value before printing it.

## Start and stop a private server

Expand Down Expand Up @@ -679,49 +672,29 @@ session (tmux 3.7 or newer).

[`Observation:watch_pane`][ref-observation-watch-pane] streams pane output,
[`Observation:watch_notifications`][ref-observation-watch-notifications]
streams tmux events, and [`watch:next`][ref-watch-next] reads the next event:

<!-- example: examples/api/watch_pane.lua -->
streams tmux events, and [`watch:next`][ref-watch-next] reads the next event.

```lua
local adapter = require("libtmux.runtime.luv")
The [calculator](#quick-start) reads bytes until it has a complete reply.
Events can split a line, so each read uses the same deadline and the example
caps the bytes it keeps.

local function must(value, err)
if err ~= nil then
error(tostring(err), 0)
end
return value
end

must(adapter.run(function(runtime)
local owned = must(runtime:start_server():await())
local created = must(owned.server
:new_session({
name = "demo",
window_name = "main",
argv = { "/bin/cat" },
})
:await())
-- Observation keeps one control-mode client open (tmux 3.7 or newer).
local observation = must(owned.server:observe(created.session):await())
local watch = must(observation:watch_pane(created.pane):await())
<!-- excerpt: examples/api/watch_pane.lua -->

must(created.pane:send_text("watched"):await())
```lua
local function read_answer(watch, deadline)
local output = ""
while not output:find("watched", 1, true) do
output = output .. must(watch:next({ timeout = 5000 }):await()).data
while true do
local event, err = watch:next({ deadline = deadline }):await()
assert(event, "calculator reply: " .. tostring(err))
local bytes = assert(event.data)
assert(#output + #bytes <= 256, "calculator output exceeded 256 bytes")
output = output .. bytes
local answer = ("\n" .. output):match("\nanswer: ([^\r\n]*)\r?\n")
if answer then
return answer
end
end
print("output: watched")

must(observation:close():await())
must(owned:stop():await())
return true
end))
```

```console
$ lua examples/api/watch_pane.lua
output: watched
end
```

Each event carries the pane's bytes and a sequence number. A slow reader loses
Expand Down Expand Up @@ -797,12 +770,19 @@ Reference: [libtmux.org][ref-index] ·
Registry: [LuaRocks][luarocks-libtmux] · Changelog: [`CHANGES.md`](CHANGES.md) ·
Modules: [`lua/libtmux/`](lua/libtmux/README.md)

To install from a checkout instead of LuaRocks:
To try the published `0.1.1-1` rock, open a fresh shell in the checkout.
The query filters a Lua table and runs without tmux or `luv`.

```console
$ luarocks --local make rockspecs/libtmux-scm-1.rockspec
$ luarocks --local install libtmux 0.1.1-1 && \
eval "$(luarocks --local path)" && \
lua examples/native_query.lua
%1 nvim
%3 vim
```

To install the checkout as a rock, follow the [shell quick start](#quick-start).

## What it leaves out

- **Starting a server on connect.** [`Runtime:connect`][ref-runtime-connect]
Expand Down Expand Up @@ -876,6 +856,7 @@ Part of the [libtmux.org](https://libtmux.org/) family alongside Python
[ref-pane-wait-for-text]: https://libtmux.org/en/lua/latest/reference/libtmux-pane-wait_for_text/
[ref-query]: https://libtmux.org/en/lua/latest/reference/libtmux-query/
[ref-query-select]: https://libtmux.org/en/lua/latest/reference/libtmux-query-select/
[read-screen]: #type-into-a-pane-and-read-the-answer
[ref-request]: https://libtmux.org/en/lua/latest/reference/libtmux-request/
[ref-request-await]: https://libtmux.org/en/lua/latest/reference/libtmux-request-await/
[ref-runtime]: https://libtmux.org/en/lua/latest/reference/libtmux-runtime/
Expand Down
2 changes: 1 addition & 1 deletion examples/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ to select a different build.
| [send_keys.lua](send_keys.lua) | Send text and press Enter | `lua input ready` |
| [capture.lua](capture.lua) | Read a completed command's output | `lua capture ready` |
| [wait_for_text.lua](wait_for_text.lua) | Wait for text on the visible screen | `lua wait ready` |
| [watch_pane.lua](watch_pane.lua) | Stream a pane's output over control mode (tmux 3.7 or newer) | `output: watched` |
| [watch_pane.lua](watch_pane.lua) | Send a sum to `awk` and read its reply over control mode (tmux 3.7 or newer) | `19 + 23 = 42` |
| [vote_counter.lua](vote_counter.lua) | Send votes and read each tally over control mode (tmux 3.7 or newer) | Three tallies ending at `yes=2 no=1` |
| [unsupported_version.lua](unsupported_version.lua) | Handle a tmux below the minimum | `unsupported_version` and its message |

Expand Down
4 changes: 2 additions & 2 deletions examples/api/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@
"libtmux.Observation:watch_pane"
],
"file": "examples/api/watch_pane.lua",
"description": "Stream a pane's output from a control-mode observation and wait for typed text to arrive.",
"description": "Send an addition expression to a calculator pane and read its reply over control mode.",
"min_tmux": "3.7",
"stdout": "output: watched\n"
"stdout": "19 + 23 = 42\n"
},
{
"id": "vote_counter",
Expand Down
78 changes: 58 additions & 20 deletions examples/api/watch_pane.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
local adapter = require("libtmux.runtime.luv")
local luv = require("libtmux.runtime.luv")
local nvim = require("libtmux.runtime.nvim")

local editor = rawget(_G, "vim")
---@diagnostic disable-next-line: different-requires
local uv = editor and editor.uv or require("luv")
local binary = os.getenv("TMUX_BIN")

local expression = ... or "19 + 23"
local left, right = expression:match("^(%d%d?%d?)%s*%+%s*(%d%d?%d?)$")
assert(left and right, "add two integers from 0 to 999, for example '19 + 23'")
local a, b = assert(tonumber(left)), assert(tonumber(right))
local question = ("%d + %d"):format(a, b)
local expected = tostring(a + b)

local function must(value, err)
if err ~= nil then
Expand All @@ -7,27 +20,52 @@ local function must(value, err)
return value
end

must(adapter.run(function(runtime)
local owned = must(runtime:start_server():await())
local created = must(owned.server
:new_session({
name = "demo",
window_name = "main",
argv = { "/bin/cat" },
})
:await())
-- Observation keeps one control-mode client open (tmux 3.7 or newer).
local observation = must(owned.server:observe(created.session):await())
local watch = must(observation:watch_pane(created.pane):await())

must(created.pane:send_text("watched"):await())
local function read_answer(watch, deadline)
local output = ""
while not output:find("watched", 1, true) do
output = output .. must(watch:next({ timeout = 5000 }):await()).data
while true do
local event, err = watch:next({ deadline = deadline }):await()
assert(event, "calculator reply: " .. tostring(err))
local bytes = assert(event.data)
assert(#output + #bytes <= 256, "calculator output exceeded 256 bytes")
output = output .. bytes
local answer = ("\n" .. output):match("\nanswer: ([^\r\n]*)\r?\n")
if answer then
return answer
end
end
print("output: watched")
end

local function run(runtime)
local owned = must(runtime:start_server({ binary = binary }):await())
local argv = { "awk", [[{ printf "answer: %d\n", $1 + $3; fflush() }]] }
local options = { name = "calculator", argv = argv }
local created = must(owned.server:new_session(options):await())
local pane = created.pane
local observation = must(owned.server:observe(created.session):await())
local watch = must(observation:watch_pane(pane):await())

local deadline = uv.hrtime() / 1e6 + 5000
local send = { process = { deadline = deadline } }
must(pane:send_text(question, send):await())
must(pane:send_keys({ "Enter" }, send):await())
local answer = read_answer(watch, deadline)
local mismatch = "expected %s, calculator replied %s"
assert(answer == expected, mismatch:format(expected, answer))

must(observation:close():await())
must(owned:stop():await())
return true
end))
return question .. " = " .. answer
end

if editor then
local started, failure = nvim.start(run, function(answer, err)
if err then
editor.notify(tostring(err), editor.log.levels.ERROR)
else
print(answer)
end
end)
assert(started, tostring(failure))
else
print(must(luv.run(run)))
end
Loading
Loading