コンテンツにスキップ

リファレンス Paneflow Lua API

このページでは、Paneflow 0.20.0 が実装する Lua API の全体を掲載しています。関数の説明は英語のままです。Paneflow が API を追加するのはグローバルな paneflow テーブルだけです。Lua 5.4 を table、string、utf8、math、 coroutine、io、os、package ライブラリとともに実行します。io.popen と os.execute はエラーになります。プログラムはシェルを起動しない paneflow.exec で実行してください。debug は読み込まれず、C モジュールも読み込めません。使い方は Lua スクリプト を参照してください。

各関数が動く場所

Paneflow は Lua を 2 か所で実行します。設定ファイル init.lua ($PANEFLOW_HOME、なければ ~/.paneflow) とスクリプトです。以下の各関数には、動く場所を示すタグが付いています。

タグ説明
Configinit.lua で動きます。worker が読み込み、ファイルが変わると再読み込みします。
Scriptpaneflow do で実行するスクリプトで動きます。
Configat load読み込み時、ファイルが上から下へ実行される間だけ動きます。
Configlaterその後、アクション、イベントハンドラー、タイマーの中でだけ動きます。

完全には動かない点は、関数の説明の先頭に記載しています。

  • Raises an error: 呼び出しがメッセージとともにコードを止めます。
  • No effect: 呼び出しは受け付けられますが、役に立つことは何もしません。スクリプトのキーバインドがウィンドウに届くことはありません。
  • Fails: 呼び出しが nil と理由を返します。

待機する関数 (呼び出し、paneflow.wait、paneflow.sleep、paneflow.exec、 paneflow.ui) は、coroutine.create や coroutine.wrap で作ったコルーチンの中ではエラーになります。

アクションとキーバインド

paneflow.action(spec)

Configat loadScript

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説明
nameLowercase letters, digits and underscores
titleShown in the command palette
descriptionOptional
categoryPalette group, Actions by default
keywordsExtra words the palette filter matches
argsArgument types such as "string" or "number?", or JSON Schema tables
agentsWhether agents may run the action, false by default
runfunction(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])

ConfigScript

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])

Configat load

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)

Configat load

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()

ConfigScript

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)

ConfigScript

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.

Paneflow の呼び出し

paneflow.call(method[, params])

ConfigScript

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>{...}

ConfigScript

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 }

イベントとタイマー

paneflow.on(event, fn)

Configat loadScript

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]])

ConfigScript

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)

ConfigScript

Raises inside a coroutine made with coroutine.create or coroutine.wrap

Wait this many seconds.

paneflow.after(seconds, fn)

ConfigScript

Call fn(ctx) once after seconds. Returns a timer.

paneflow.every(seconds, fn)

ConfigScript

Call fn(ctx) every seconds until the timer is cancelled. Returns a timer. In paneflow do, a running timer keeps the script alive.

timer:cancel()

ConfigScript

Stop the timer; returns whether it was active.

timer:active()

ConfigScript

Return whether the timer is still active.

paneflow.stop([status])

ConfigScript

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.

イベントの種類

paneflow.on と paneflow.wait は worker からこれらのイベントを受け取ります。各イベントが送られるタイミングは イベント を参照してください。 ev には type、seq、イベントにあれば session、そして以下のフィールドが入ります。サーフェス、ペイン、タブ、ワークスペースの ID は ctx にあります。 paneflow do では、--all を付けない限り、スクリプトは自分のワークスペースのイベントだけを受け取ります。

イベントフィールド
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.changedrevision
terminal.cwd_changedcwd
terminal.title_changedtitle
terminal.bellbell_at_ms
terminal.exitedlifecycle (exited, failed, lost or unverified); exit_code and, when a signal ended it, signal, when lifecycle is exited
agent.state_changedtool, previous and state (busy, idle, attention or errored)
config.reloadedok, found, path, actions, bindings, errors, warnings and, when there is one, the first problem
grant.changedrevision, revoked and grants
events.resyncNone: sent when buffered events were dropped

プログラムの実行

paneflow.exec(argv[, opts])

ConfigScript

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説明
cwdDirectory to run in
envVariables to set, false removes one
clear_envStart from an empty environment
stdinText to write to stdin, or false for no stdin
timeoutSeconds before the process tree is terminated
stdoutfalse discards, a function receives output as it arrives
stderrfalse discards, a function receives output as it arrives
textDecode output as text and turn CRLF into LF, true by default
detachKeep the program running when the scope that started it ends; its output is discarded unless a function receives it
result説明
codeThe exit code, nil when a signal ended the program
signalThe signal that ended the program, on Unix
stdoutCaptured output, nil when stdout = false
stderrCaptured errors, nil when stderr = false
timed_outTrue when the timeout stopped the program
okTrue 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)
end

Each program runs in its own process tree. At the timeout it gets TERM, then KILL 2 s later.

paneflow.exec.start(argv[, opts])

ConfigScript

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])

ConfigScript

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)

ConfigScript

Raises inside a coroutine made with coroutine.create or coroutine.wrap

Write to the program's stdin. Returns true, or nil and a message.

handle:close_stdin()

ConfigScript

Close the program's stdin.

handle:kill([signal])

ConfigScript

Send a signal to the program, TERM by default.

handle:running()

ConfigScript

Return whether the program is still running.

handle.pid

ConfigScript

The program's process id. Call the handle's methods with a colon, as handle:wait(5).

ユーザーへの問い合わせ

paneflow.ui.input(spec)

ConfiglaterScript

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説明
titleRequired
bodyShown under the title, line breaks kept; at most 16384 bytes
placeholderOptional
valueText the field starts with
confirmLabel of the confirming row
timeoutSeconds 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)

ConfiglaterScript

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説明
itemsAt most 2000; a string is its own id and title
multipleTick several items; the answer is the list of ids in the order of items
allow_otherAccept typed text that matches no item; the answer is { text = ... }
item説明
idReturned when the item is chosen
titleThe label shown and filtered on, the id by default
subtitleOptional
icondocument, folder, branch, terminal, code, server, database, package, globe, link, person, tag, clock, star, gear or plus
detailText shown at the end of the row
selectedStarts ticked when multiple is true

レイアウト

paneflow.layout.pane([spec])

ConfigScript

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)

ConfigScript

Stack two nodes, the first taking ratio of the height.

paneflow.layout.vertical(ratio, first, second)

ConfigScript

Put two nodes side by side, the first taking ratio of the width.

その他の関数

paneflow.json.encode(value[, pretty])

ConfigScript

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)

ConfigScript

Decode JSON; null becomes nil and integers stay integers. Returns the value, or nil and a message.

paneflow.log(level, message)

ConfigScript

Log a message at the debug, info, warn or error level.

スクリプトの値

paneflow.args

Script

Config: 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

ConfigScript

Where the code runs. Handlers and timers receive the same table as their first parameter.

ctx説明
surface_idThe surface the script, handler or timer belongs to
pane_idThe pane that holds it
tab_idThe tab that holds it
workspace_idThe layout workspace that holds it
originWhat started this code: "cli" in a script, "event" in init.lua, "timer" in a timer

制限

  • init.lua は読み込みのたびに新しい Lua の状態を受け取り、メモリ上限は 256 MiB です。読み込みに失敗した場合は、以前の設定が有効なまま残ります。
  • init.lua は最後の変更から 300 ms 後と、paneflow config reload で再読み込みされます。
  • アクションの実行は 30 秒で止まり、アクションは互いに 16 段まで呼び出せます。
  • paneflow do には、--memory-limit や --deadline を付けない限り、メモリ上限も期限もありません。