CEL Owner's Manual
The Client Exchange Layer (CEL) is a hypermedia-driven terminal program framework. It runs applications defined in XML, with styling, behaviour and layout all closely co-located. Client-side scripting is done via a flat-scoped Lua sandbox.
CEL programs can run locally, using the built-in HTTP server binary, or any HTTP 1.1 capable web-server host. Most applications can run on all 3 runtimes without changes.
Principles
- Information density
Use all cells with purpose. Interfaces must take the smallest surface area possible.
- Consistent interface
Programs should not change layout. Inputs must always be visible and appear in the same order and layout.
- Semantic bindings
Design with QuickStrike bindings in mind. Primary inputs must have semantically correct shortcuts.
- Information structure
Guide the eye to what is important. Gray, primary and accent must be applied in 60/30/10 ratios.
- Limited scope
Each interface should do one job. Programs should not expand significantly beyond the MVP stage.
- Size Naturally
Static dimensions may define external size if shrinking is inadequate. Children must prefer SHRINK/FILL over explicit sizing.
- Respect the medium
TUIs must be made for the terminal. Interfaces must be dense, informative, efficient.
- Respect the defaults
The built-in widgets are designed to fit together as a cohesive system. No need to change them.
- Localize behaviour
Always group widget markup, state and event handling. Split off independent units (functions, templates, shared-state) only when reused.
- Make it whimsical
The terminal doesn't have to be boring. Shapes, colours and unique elements should create unique experiences tailored to the utility.
Core concepts
Inputs
All actions are always available using the keyboard. Built-in widgets participate in the QuickStrike system: each instance attempts to assign a unique key for itself. If successful, this key is shown underlined (by default), and CTRL+<key> immediately selects and strikes (activates) the widget.
ALT+e on any multiline field opens the user's $EDITOR and writes the saved buffer into the widget's value.
Custom widgets can implement the same systems.
Runtimes
Three runtimes are supported:
- Local CEL router file
- CEL router file served through HTTP using the bundled server
- CEL markup served by a third party HTTP server
Only local routers are allowed to request shell access. All other features are universal.
Documents vs. Apps
Programs wrapped in
State and scopes
State lives either in the page-shared meta/define/scope, or directly on widget scopes. Reads and writes use the nearest existing value, falling back to page-shared state.
Use page state for values shared across the interface, widget state for values owned and managed by one element.
Widgets with a #reference expose their scope globally, with hyphens converted to underscores. Template children access their owning instance through tmpl.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<scope>prefix = "Status:"</scope>
</define>
</meta>
<row>
<text #status>`prefix` `value`
<scope>value = "Ready"</scope>
</text>
<button>Start
<scope>
table.insert(strike, function()
status.value = "Running"
end)
</scope>
</button>
</row>
]])
end,
}
end

Keep state close to its owner, use references when widgets must communicate and page state when no single widget owns the value.
Templates
All widgets are implemented as templates. Templates are defined in meta/define, and take any number of optional or required arguments, can manage and display internal state and contain other widgets. Built-in templates can be copied using from.
Widgets with a #reference automatically register their internal-global scope into the global Lua namespace. Children refer to the outer template using the tmpl key.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<counter from="row" value=0>
<button>Sub
<scope>
table.insert(strike, function()
tmpl.value = tmpl.value - 1
end)
</scope>
</button>
<text styles={
width = 5,
align_x = CENTER,
style = "@b-black white"
}>`tmpl.value`</text>
<button>Add
<scope>
table.insert(strike, function()
tmpl.value = tmpl.value + 1
end)
</scope>
</button>
</counter>
</define>
</meta>
<counter/>
]])
end,
}
end

Events
Events are dispatched to the trigger widget without bubbling. Handlers are functions added to the relevant event-table, removed when the UNSUBSCRIBE sentinel is returned.
Available events: init, strike([key]), focus/blur, input([key]),layout`
poll is shared per page.
Long-running tasks
Programs are only evaluated when input is given, and evaluation blocks further input until it is complete. Polling is used to redraw at a regular rate. The global LOADING is automatically set for the duration of potentially long-running task: poll hits, HTTP requests, shell evaluation. Any long-running custom task must also set it.
LOADING = true
my_long_function()
LOADING = false
Command line interfaces
All programs must declare a CLI, even if empty. Parsed results are passed into the main function.
require("cli").create({
file = {
positional = true,
help = "Source file."
},
large = {
default = false,
help = "Use large mode."
}
})
function main(cli)
return {
["/"] = function()
return fmt(document([[
<tower>
<text>file: %cli.file%</text>
<text>large: %tostring(cli.large)%</text>
</tower>
]]))
end,
}
end
Security
Running remote applications on local hardware is never going to be bulletproof. CEL's Lua sandbox is reasonably secure, but it should not be trusted to be bulletproof. Shell commands can only run with the correct perm declarations, but any file on disk may be read using io.open. Don't run untrusted applications, verify source when possible.
Building a CEL program
Concept
- What does it do?
Find the one core function of the program. "Converts timezones" or "Creates drawings".
- How should it look?
Most programs should have at least 1 input and 1 output panel. Output can be decorative and stylised.
- What options are available?
What other knobs can the user turn beyond the "one thing"? Provide a known-good experience, avoid self-serving configuration.
Implementation
Evaluate per-page:
- What state must be managed?
The "one thing" should imply a small number of state fields. List all of them.
- Where does state semantically belong?
Assign each piece of state to elements of the planned layout.
Evaluate per-state:
- Can this be removed?
Strive for the smallest state possible. Prune aggressively, reduce complexity.
- Who should own this?
- State displayed and managed by 1 widget should be internal to it
- State shared by multiple widgets should be defined in the closest shared scope
- State and its altering functions should be defined in the same scope
- Internal state may be altered externally using functions through
#references:
-- meta/define
<canvas from="zml">
<scope>
local cells = {}
function set(x, y, value)
-- ...
end
</scope>
</canvas>
-- ...
<canvas #target/>
<button>Set
<scope> table.insert(strike, function()
target.set(4, 3, true) end)
</scope>
</button>
Tips and guidelines
- Use the built-in components.
- Design interfaces as physical devices.
- Always include a
<header>. - Use non-palette colours only when semantically beneficial.
- Do not explain the interface in the interface.
- Limit text, labels and avoid instructions.
- Do not use emoji.
Have fun.
TMUX compatibility
To run CEL programs in TMUX, add the following to your TMUX configuration:
set -s extended-keys on
set -as terminal-features ',*:extkeys'
set -g allow-passthrough on
API reference
Interpolation
Backtick pairs evaluate client-side Lua expressions. In routers, % pairs evaluate server-side Lua through fmt. Use fmt(document(...)) or fmt(app(...)) for route-local values. Both forms perform text replacement, so strings inserted into client Lua must be quoted.
require("cli").create({})
function main(cli)
return {
["/"] = function()
local server_int = 10
local server_str = "server"
return fmt(document([[
<meta>
<define>
<scope>
sender = "%server_str%"
state = %server_int%
</scope>
</define>
</meta>
<text>`sender` (double): `state * 2`</text>
]]))
end,
}
end
Prints "server (double): 20".
Markup structure
CEL markup is based on XML, with the following differences:
- No entities,
&remains literal text <and>are valid in attributes and inner text{}attributes contain Lua tables or expressions:table={ a=1 } var={ data.name }- Multiline inner text is dedented
Pages have one <document> or <app> root, containing an optional <meta> followed by one root widget. Tags support paired and self-closing forms, with names made from ASCII letters, numbers, -, _ and ..
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta title="Example" version="1" poll-rate=500>
<define>
<message from="text"/>
<scope>name = "CEL"</scope>
</define>
<perm prefix="git status"/>
</meta>
<tower>
<message>Hello, `name`</message>
</tower>
]])
end,
}
end
meta accepts title, version and a non-negative integer poll-rate, with only define or perm children.
Quoted attributes are strings. Unquoted attributes support decimal numbers, booleans or nil; bare attributes are true.
<custom-sized hidden multiline=false styles={ height=FILL }/>
#name is shorthand for ref="name".
Templates
Templates are declared in meta/define and available across the page, with later definitions shadowing earlier ones.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<greeting
*name
short=false
phrases={ "Hello", "Hi" }
>
`phrases[short and 2 or 1]`, `name`.
</greeting>
<danger
from="button"
styles={
style = "@red black",
selected = { style = "@b-red white" }
}
/>
<label from="text">
<_slot>`content`</_slot>
</label>
</define>
</meta>
<tower>
<greeting name="Reader" short/>
<danger>Delete</danger>
<label>Note</label>
</tower>
]])
end,
}
end
Ordinary attributes declare optional arguments and defaults, while *name declares a required, non-empty argument. from inherits from built-in templates.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<danger
from="button"
styles={
style = "@red white",
selected = { style = "@b-red black bold" }
}
/>
</define>
</meta>
<danger>Delete</danger>
]])
end,
}
end

A self-closing inherited definition keeps its inherited children. A paired definition replaces them while retaining the inherited scope.
<_slot/> inserts instance children. A named slot instead captures instance text as a string:
<label from="text">
<_slot>`content`</_slot>
</label>
Definitions and instances support one direct <scope>. Template-owned children access their instance through tmpl. Full-page loads reset built-ins, definitions and page state.
Styling
Widgets receive a styles table, evaluated every frame with access to widget and page state. Top-level values define the idle style, while selected overrides them during selection. Values cascade from the built-in through the derived template to the instance.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<row>
<button styles={
frame = FRM.heavy:pad(" "),
selected = { style = "@red black" }
}>Delete</button>
<button styles={
frame = FRM.heavy:pad(" "),
selected = { style = "@red black" }
}>Cancel</button>
</row>
]])
end,
}
end

| Key | Description |
|---|---|
style |
Style applied to all cells |
frame_style |
Style applied to frame cells |
target_style |
Style applied to the QuickStrike target |
width, height |
Integer, SHRINK or FILL |
layout |
STACK_X or STACK_Y |
gap |
Cells between stacked children |
align_x, align_y |
START, CENTER or END |
scroll |
Root-only vertical scrolling |
frame |
Scalar, 4-side or 8-side/corner frame |
FRM contains ascii, light, heavy, double, rounded, light_dashed, heavy_dashed, light_dotted and heavy_dotted. frame:pad(padding, outer) adds padding to all four sides. It goes inside by default and outside when outer is true. frame:join(side, pad) removes the named edge, replacing it with a space by default or an empty string when pad is false. Both return a chainable frame, such as FRM.heavy:join("left"):pad(" "):
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<row styles={ gap = 0 }>
<text styles={ frame = FRM.light:join("right") }>Left</text>
<text styles={ frame = FRM.light }>Right</text>
</row>
]])
end,
}
end

Style values contain one space-delimited ZML group. They are parsed left to right, with the last conflicting value winning; a leading & is replaced with the inherited style.
| Type | Values | Unsetter |
|---|---|---|
| Text style | bold, dim, italic, underline, blink, invert, strike |
/<setter> |
| Foreground | red, b-red, #12, #abc, #aabbcc |
/# |
| Background | @red, @#12, @#abc, @#aabbcc |
/@ |
Enable ZML with the <zml> template or w.has_zml=true. Definitions expose their styles as styles.<underscored_template_name>, allowing page-wide changes:
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<error-button from="button"/>
<scope>
styles.error_button.frame = FRM.double
</scope>
</define>
</meta>
<error-button>Error</error-button>
]])
end,
}
end

create_theme(primary) returns a theme, its primary and a complementary accent. The default uses blue and yellow, with ERROR, SUCCESS and WARNING semantic colours.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<define>
<scope>
THEME, PRIMARY, ACCENT = create_theme("yellow")
</scope>
</define>
</meta>
<tower styles={ frame = "" }>
<button>Primary</button>
<row>
<text>Primary:</text>
<zml>[yellow]`PRIMARY`</zml>
</row>
<row>
<text>Accent:</text>
<zml>[blue]`ACCENT`</zml>
</row>
</tower>
]])
end,
}
end

Layout
Static dimensions are allocated first. SHRINK uses the smallest size containing a widget's children or inner text, then remaining space is divided between FILL children. For n such children, each receives (remaining - gap*(n-1)) / n.
Stacks position children on their layout axis and use align_x or align_y on the opposite axis. Hidden children consume no space or gap. On the outermost document widget, a FILL height behaves as SHRINK; only this root widget accepts scroll=true. Horizontal overflow is compressed where possible, then clipped.
Widget API
Built-in templates are tower, row, label, header, _target, text, title, zml, pad, button, toggle, link and field. Widget scopes have access to a safe subset of Lua defaults and some CEL-specific functions; see _ENV for the full list.
Scope
Each widget owns a flat Lua scope. Name resolution checks widget state first, then falls back to page-shared state.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<tower>
<text>`count`
<scope>count = 0</scope>
</text>
<row>
<text #status>Ready</text>
<button>Clear
<scope>
table.insert(strike, function()
status.content = ""
end)
</scope>
</button>
</row>
</tower>
]])
end,
}
end
#some-ref exports the scope as some_ref, normalizing hyphens to underscores. References must be unique, with _root reserved for the root widget.
<text #status>Ready</text>
<button>Clear
<scope>
table.insert(strike, function()
status.content = ""
end)
</scope>
</button>
Page state is reset during full-page navigation. Definition scope runs once in that shared environment; widget scopes and init callbacks run parent-first, while layout runs child-first after sizing and wrapping.
require loads page-local .cel or .lua modules. The built-in JSON parser is available through require("json").
Events
Insert handlers into init, input, layout, strike, focus or blur. They run in insertion order and remove themselves by returning UNSUBSCRIBE.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<button>Save
<scope>
table.insert(strike, function()
content = "Saved"
return UNSUBSCRIBE
end)
</scope>
</button>
]])
end,
}
end
| Event | Arguments | Description |
|---|---|---|
init |
() |
Widget initialized |
input |
([key]) |
Key pressed or repeated |
layout |
() |
Layout completed |
strike |
([key]) |
Widget activated |
focus |
() |
Widget selected |
blur |
() |
Widget deselected |
init and input are also available in meta/define/scope for page-wide handlers. poll runs at the rate configured by meta's poll-rate.
Native widget state
Every widget scope exposes its underlying widget as w:
| Key | Access | Description |
|---|---|---|
w.type |
Read | Template name |
w.ref |
Read | Reference name or nil |
w.width, w.height |
Read | Laid-out dimensions |
w.content_width |
Read | Inner width |
w.content_height |
Read | Natural wrapped height |
w.lines |
Read | Wrapped-line metadata |
w.has_selection |
Read/write | Is selectable leaf, or has selectable descendants |
w.trap_input |
Read/write | Input captured before navigation |
w.hidden |
Read/write | Widget hidden |
w.has_cursor |
Read/write | Cursor enabled |
w.has_zml |
Read/write | ZML parsing enabled |
w.cursor_offset |
Read/write | Cursor offset as {x, y} |
w.has_qs |
Write | QuickStrike target styling enabled |
Widget methods and helpers:
w.strike([key])
w.input([key, [repeated]])
w.clear()
-- convert detected strings to numbers, nil or booleans
infer(val)
-- spawn $EDITOR, return resulting saved text
spawn_editor(initial, extension)
-- bind QS key to widget, return nil on failure
qs_assign(w, key)
-- prefer key, then assign from text
qs_autoassign(w, text, key)
-- clear QS binding for widget
qs_unassign(w)
-- trigger QS binding for key
qs_trigger(key)
Requests
Widget and router scopes share the same HTTP client:
resp = get("/users", { admin = true })
resp = post("/users", { name = "Marty" })
resp = put("/users/123", data) -- could be <field #data/>
resp = patch("/users/123", changes)
resp = delete("/users/123")
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<tower styles={ frame = "" }>
<field #name placeholder="Name"/>
<button>Send
<scope>
table.insert(strike, function()
post("/greet", name).into(output)
end)
</scope>
</button>
<_target #output>
<text>Response appears here.</text>
</_target>
</tower>
]])
end,
["/greet"] = {
POST = function(ctx, args, data)
return fmt(document("<text>Hello, %data.name%</text>"))
end,
},
}
end

Request data tables are merged left to right, with later values winning. String, number and boolean values are form-encoded; referenced widget scopes contribute { ref=value }. GET and DELETE append this data to the query, while other methods send an URL-encoded body.
Responses expose code, headers, text() and table(). Widget scopes also expose into(target).
Relative requests target the local router in local mode and the same-origin server in HTTP mode. Absolute HTTP(S) requests use the network.
into(_root) atomically replaces the page with fresh state, preserving the current page when loading fails. into(target) replaces a _target's children; its response must still contain a complete <document> or <app> page.
HTTP status does not prevent either form of replacement.
Shell
meta/perm requests command prefixes for local full-page programs. Remote pages and partial insertions cannot request shell access. Commands run without a shell: quotes and escapes work, while operators, expansion, redirection and pipelines are rejected.
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta>
<perm prefix="git status"/>
</meta>
<button>Run
<scope>
table.insert(strike, function()
local result = run_cmd("git status --short")
content = result.stdout .. "status " .. result.status
end)
</scope>
</button>
]])
end,
}
end
run_cmd sets LOADING, blocks, then returns stdout, stderr and status.
For non-blocking work, start_cmd returns a task whose update method collects new output until completion:
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document([[
<meta poll-rate=50>
<perm prefix="printf"/>
</meta>
<tower>
<text #output>Starting...</text>
<text #errors/>
<text #status/>
<scope>
task = nil
table.insert(init, function()
task = start_cmd("printf complete")
end)
table.insert(poll, function()
task.update()
output.content = task.stdout
errors.content = task.stderr
if task.done then
status.content = "status " .. task.status
return UNSUBSCRIBE
end
end)
</scope>
</tower>
]])
end,
}
end
Tasks stop when their page is replaced or closed.
Router API
.cel routers execute as Lua 5.4 files. They can access the entire Lua built-in library, as well as some CEL-specific functions.
Each declares a CLI and defines main, returning a route table:
require("cli").create({})
function main(cli)
return {
["/"] = function(ctx, args, data)
return document([[
<text>Hello, CEL</text>
]])
end,
["/users/{id}"] = {
GET = function(ctx, args, data)
ctx.resp.headers["X-User"] = args.id
return fmt(document("<text>User %args.id%</text>"))
end,
PATCH = function(ctx, args, data)
ctx.resp.code = 204
end,
},
}
end
{name} captures one non-empty path segment. A route mapped directly to a function handles GET; method tables support GET, HEAD, POST, PUT, PATCH and DELETE. Exact routes take priority over parameterized routes.
Handlers receive:
| Argument | Description |
|---|---|
ctx |
Request and response context |
ctx.path |
Request path without query |
ctx.req.method, ctx.req.headers |
Request information |
ctx.resp.code, ctx.resp.headers |
Response information |
args |
Captured route arguments |
data |
Query parameters or decoded form body |
Each request gets a fresh Lua environment. GET and DELETE receive query data, while other methods receive a decoded form body. Responses default to application/x-cel.
fmt(content) performs server-side % interpolation. app(content) and document(content) add the matching root.
CLI parsing
All routers declare a CLI, even if empty:
-- cel app.cel input.txt --verbose
require("cli").create({
file = {
positional = true,
help = "Input file"
},
verbose = {
default = false,
help = "Print extra output"
}
})
function main(cli)
return {
["/"] = function()
return fmt(document([[
<text>%cli.file%: %tostring(cli.verbose)%</text>
]]))
end,
}
end
Every argument requires help; a default makes it optional, while no default makes it required. Boolean defaults create --name, --no-name and a single-letter alias when unique. Named values use --name value or their unique alias, always consuming the next token. Parsed values are passed to main.
Running locally
cel app.cel
cel app.cel/settings
cel - <<'CEL'
require("cli").create({})
function main(cli)
return {
["/"] = function()
return document("<text>Hello, CEL</text>")
end,
}
end
CEL
Appending a route to the .cel path selects that route. - reads source from stdin, with remaining arguments passed to the program CLI. Relative requests re-enter the router without using the network. Shell APIs are available.
Running remotely
cel https://example.com/app/path --name value
Program arguments are sent with every same-origin request as JSON in the Cel-Argv header. Remote programs have no shell APIs and cannot declare permissions. The bundled server executes the same router files; third-party HTTP/1.1 servers serve CEL directly by returning application/x-cel markup.