Referencias API de Lua de Paneflow
Esta página recoge toda la API de Lua que expone Paneflow, tal como la
implementa Paneflow 0.20.0. Las descripciones de las funciones están en inglés.
Paneflow solo añade API a la tabla global paneflow. Ejecuta Lua 5.4 con las
bibliotecas table, string, utf8, math, coroutine, io, os y
package. io.popen y os.execute lanzan un error: ejecuta programas con
paneflow.exec, que nunca inicia un shell. debug no se carga y los módulos C
no se pueden cargar. Consulta scripting en Lua para una
guía.
Dónde funciona cada función
Paneflow ejecuta Lua en dos sitios, el archivo de configuración init.lua (en
$PANEFLOW_HOME, si no en ~/.paneflow) y los scripts, y cada función de abajo
lleva una etiqueta que indica dónde funciona:
| Etiqueta | Descripción |
|---|---|
| Config | Funciona en init.lua, que el worker carga y recarga cuando cambia el archivo. |
| Script | Funciona en scripts ejecutados con paneflow do. |
| Configat load | Solo al cargar, mientras el archivo se ejecuta de arriba abajo. |
| Configlater | Solo después, dentro de una acción, un manejador de eventos o un temporizador. |
Todo lo que no funciona del todo se indica al principio de la función.
- Raises an error: la llamada detiene el código con un mensaje.
- No effect: la llamada se acepta y no hace nada útil. Los atajos de teclado de un script nunca llegan a una ventana.
- Fails: la llamada devuelve
nily un motivo.
Las funciones que esperan (llamadas, paneflow.wait, paneflow.sleep,
paneflow.exec, paneflow.ui) lanzan un error dentro de una corrutina creada con
coroutine.create o coroutine.wrap.
Acciones y atajos de teclado
paneflow.action(spec)
paneflow.action(spec)Config, later: raises an error · Script: top level only, and the action exists only in that script
Declare an action while init.lua loads. Keys, the command palette, paneflow do <action>, the API and agents can run it; agents only when agents = true. A later declaration with the same name replaces the earlier one, with a warning.
spec | Descripción |
|---|---|
name | Lowercase letters, digits and underscores |
title | Shown in the command palette |
description | Optional |
category | Palette group, Actions by default |
keywords | Extra words the palette filter matches |
args | Argument types such as "string" or "number?", or JSON Schema tables |
agents | Whether agents may run the action, false by default |
run | function(ctx, args), whose return value is the action's result |
paneflow.action{
name = "dev_workspace",
title = "Open a dev workspace",
args = { cwd = "string" },
run = function(ctx, args)
return paneflow.workspace.create{ name = "dev", cwd = args.cwd }
end,
}A run is stopped after 30 s; a paneflow.ui prompt pauses that limit while it waits. Actions can invoke each other 16 deep.
paneflow.invoke(name[, args])
paneflow.invoke(name[, args])Raises inside a coroutine made with coroutine.create or coroutine.wrap
Run an action with arguments and return what it returned, or nil and a message when it fails. In a script, an action the script declared runs in the script; any other runs on the worker.
paneflow.bind(key, action[, args])
paneflow.bind(key, action[, args])Config, later: raises an error · Script: no effect
Bind a key to an action name while init.lua loads. key uses the syntax of paneflow.json shortcuts, such as "ctrl-alt-d". action is a Lua action or a built-in action name, and args are arguments for a Lua action.
A shortcut set in paneflow.json for the same key always wins. Otherwise the binding replaces the window's default for that key.
paneflow.bind("ctrl-alt-d", "dev_workspace", { cwd = "/srv/app" })paneflow.unbind(key)
paneflow.unbind(key)Config, later: raises an error · Script: no effect
Remove this file's bindings of a key and drop the window's default for it.
paneflow.bindings()
paneflow.bindings()Script: lists only the script's own bindings
Return the bindings init.lua declared, each a table with key, action, args and source.
paneflow.client.queue(name)
paneflow.client.queue(name)Raises inside a coroutine made with coroutine.create or coroutine.wrap
Queue a built-in window action, by a name from paneflow.client.list_actions. Inside an action run, it runs once run returns without error and is dropped if the run fails. Anywhere else it is sent at once.
Llamar a Paneflow
paneflow.call(method[, params])
paneflow.call(method[, params])Raises inside a coroutine made with coroutine.create or coroutine.wrap
Call any method by its full name. Returns the result, or nil, a message and the error code.
local result, message, code = paneflow.call("surface.list")paneflow.<namespace>.<method>{...}
paneflow.<namespace>.<method>{...}Raises inside a coroutine made with coroutine.create or coroutine.wrap
Every method of the API is a function that takes the method's parameters as one table and returns like paneflow.call.
The streams (agent.follow, events.follow and events.subscribe) cannot be called; react to events with paneflow.on or paneflow.wait.
local result = paneflow.surface.read{ surface_id = 7, lines = 20 }Eventos y temporizadores
paneflow.on(event, fn)
paneflow.on(event, fn)Config, later: raises an error · Script: top level only, not in a handler or a timer
Call fn(ctx, ev) for every matching event. A name may be a family such as terminal.*.
paneflow.on("terminal.exited", function(ctx, ev)
paneflow.log("info", ev.lifecycle)
end)paneflow.wait(event[, filter[, timeout]])
paneflow.wait(event[, filter[, timeout]])Raises inside an event handler · Raises inside a coroutine made with coroutine.create or coroutine.wrap
Wait for the next matching event since the script started; nil and "timeout" when timeout seconds pass first. filter is a table of fields to match or a function of ev and ctx. Returns the event and its ctx.
paneflow.sleep(seconds)
paneflow.sleep(seconds)Raises inside a coroutine made with coroutine.create or coroutine.wrap
Wait this many seconds.
paneflow.every(seconds, fn)
paneflow.every(seconds, fn)Call fn(ctx) every seconds until the timer is cancelled. Returns a timer. In paneflow do, a running timer keeps the script alive.
paneflow.stop([status])
paneflow.stop([status])End the script at once with this exit status.
In init.lua it stops the whole configuration: its handlers, timers and actions stop until the next reload.
Tipos de eventos
paneflow.on y paneflow.wait reciben estos eventos del worker. Consulta Eventos para saber cuándo se envía cada uno. ev contiene
type, seq, session cuando el evento tiene una, y los campos de abajo. Los
identificadores de la superficie, el panel, la pestaña y el espacio de trabajo
están en ctx. En paneflow do, un script solo oye los eventos de su propio
espacio de trabajo, salvo que se ejecute con --all.
| Evento | Campos |
|---|---|
workspace.created | |
workspace.closed | |
workspace.renamed | |
workspace.selected | |
tab.created | |
tab.closed | |
tab.renamed | |
tab.selected | |
pane.created | |
pane.closed | |
pane.focused | |
surface.created | |
surface.closed | |
surface.renamed | |
layout.changed | revision |
terminal.cwd_changed | cwd |
terminal.title_changed | title |
terminal.bell | bell_at_ms |
terminal.exited | lifecycle (exited, failed, lost or unverified); exit_code and, when a signal ended it, signal, when lifecycle is exited |
agent.state_changed | tool, previous and state (busy, idle, attention or errored) |
config.reloaded | ok, found, path, actions, bindings, errors, warnings and, when there is one, the first problem |
grant.changed | revision, revoked and grants |
events.resync | None: sent when buffered events were dropped |
Ejecutar programas
paneflow.exec(argv[, opts])
paneflow.exec(argv[, opts])Raises inside a coroutine made with coroutine.create or coroutine.wrap
Run a program from an argument list, never through a shell, and wait for it. Returns the result, or nil and a message.
opts | Descripción |
|---|---|
cwd | Directory to run in |
env | Variables to set, false removes one |
clear_env | Start from an empty environment |
stdin | Text to write to stdin, or false for no stdin |
timeout | Seconds before the process tree is terminated |
stdout | false discards, a function receives output as it arrives |
stderr | false discards, a function receives output as it arrives |
text | Decode output as text and turn CRLF into LF, true by default |
detach | Keep the program running when the scope that started it ends; its output is discarded unless a function receives it |
result | Descripción |
|---|---|
code | The exit code, nil when a signal ended the program |
signal | The signal that ended the program, on Unix |
stdout | Captured output, nil when stdout = false |
stderr | Captured errors, nil when stderr = false |
timed_out | True when the timeout stopped the program |
ok | True when the code is 0 and the program did not time out |
local result = paneflow.exec({ "git", "status", "--short" }, { cwd = "/srv/app" })
if result and result.ok then
paneflow.log("info", result.stdout)
endEach program runs in its own process tree. At the timeout it gets TERM, then KILL 2 s later.
paneflow.exec.start(argv[, opts])
paneflow.exec.start(argv[, opts])Start a program and return a handle at once, or nil and a message. It takes the options of paneflow.exec.
The program is stopped when the code that started it ends (the init.lua load, an action run, a handler call or a timer callback), unless detach is set.
handle:wait([seconds])
handle:wait([seconds])Raises inside a coroutine made with coroutine.create or coroutine.wrap
Wait for the program to end and return its result; nil and "timeout" when seconds pass first.
handle:write(data)
handle:write(data)Raises inside a coroutine made with coroutine.create or coroutine.wrap
Write to the program's stdin. Returns true, or nil and a message.
Preguntar al usuario
paneflow.ui.input(spec)
paneflow.ui.input(spec)Config, at load: fails with "failed" · Raises inside a coroutine made with coroutine.create or coroutine.wrap
Ask the user for a line of text in every window that can show it; the first answer wins and the action's 30 s limit pauses while it waits.
Returns the text, or nil and a reason when nobody answers: "cancelled", "timeout", "no_client", "unsupported", "busy", "rate_limited" or "failed" (with a detail).
spec | Descripción |
|---|---|
title | Required |
body | Shown under the title, line breaks kept; at most 16384 bytes |
placeholder | Optional |
value | Text the field starts with |
confirm | Label of the confirming row |
timeout | Seconds before the prompt ends with "timeout", 300 by default, at most 3600 |
local branch, reason = paneflow.ui.input{ title = "New branch", placeholder = "feature/" }paneflow.ui.pick(spec)
paneflow.ui.pick(spec)Config, at load: fails with "failed" · Raises inside a coroutine made with coroutine.create or coroutine.wrap
Ask the user to choose among items; the answer is an id, a list of ids with multiple, or { text = ... } with allow_other. It fails like paneflow.ui.input and takes its fields, plus:
spec | Descripción |
|---|---|
items | At most 2000; a string is its own id and title |
multiple | Tick several items; the answer is the list of ids in the order of items |
allow_other | Accept typed text that matches no item; the answer is { text = ... } |
item | Descripción |
|---|---|
id | Returned when the item is chosen |
title | The label shown and filtered on, the id by default |
subtitle | Optional |
icon | document, folder, branch, terminal, code, server, database, package, globe, link, person, tag, clock, star, gear or plus |
detail | Text shown at the end of the row |
selected | Starts ticked when multiple is true |
Disposiciones
paneflow.layout.pane([spec])
paneflow.layout.pane([spec])Build a pane node for a layout document, as paneflow.workspace.create{ layout = ... } and paneflow.workspace.restore_layout take. spec describes the pane's one surface (command, cwd, name, env, focus and the other surface fields), or lists several in surfaces.
paneflow.workspace.create{
name = "review",
layout = paneflow.layout.vertical(0.5,
paneflow.layout.pane{ command = "claude" },
paneflow.layout.pane{ command = "codex" }),
}paneflow.layout.horizontal(ratio, first, second)
paneflow.layout.horizontal(ratio, first, second)Stack two nodes, the first taking ratio of the height.
paneflow.layout.vertical(ratio, first, second)
paneflow.layout.vertical(ratio, first, second)Put two nodes side by side, the first taking ratio of the width.
Otras funciones
paneflow.json.encode(value[, pretty])
paneflow.json.encode(value[, pretty])Encode a value; a table with keys 1 to n becomes an array, any other table an object. Returns the JSON, or nil and a message.
paneflow.json.decode(text)
paneflow.json.decode(text)Decode JSON; null becomes nil and integers stay integers. Returns the value, or nil and a message.
Valores del script
paneflow.args
paneflow.argsConfig: an empty table
The key=value pairs or the --args JSON given to paneflow do. An action receives its arguments as the second parameter of run instead.
paneflow.ctx
paneflow.ctxWhere the code runs. Handlers and timers receive the same table as their first parameter.
ctx | Descripción |
|---|---|
surface_id | The surface the script, handler or timer belongs to |
pane_id | The pane that holds it |
tab_id | The tab that holds it |
workspace_id | The layout workspace that holds it |
origin | What started this code: "cli" in a script, "event" in init.lua, "timer" in a timer |
Límites
init.luarecibe un estado de Lua nuevo en cada carga, con un límite de memoria de 256 MiB. Una carga que falla mantiene activa la configuración anterior.init.luase recarga 300 ms después de su último cambio, y conpaneflow config reload.- La ejecución de una acción se detiene a los 30 s, y las acciones pueden invocarse entre sí hasta 16 niveles.
paneflow dono tiene límite de memoria ni plazo, salvo con--memory-limito--deadline.