# Keyboard and focus

A surface consumes only the keys its focused element needs; all other keys pass
through to your program as normal terminal input. This lets your program's own
keybindings continue working while a surface has focus. You can also configure
in the document which keys a surface handles and which it forwards to your
program.

## Who has the keyboard

By default, the terminal owns keyboard input. A surface gains keyboard focus
only when the user clicks a focusable element inside it or your program
explicitly focuses it with `a=focus`
([§10.1](https://hotty.neuroplast.io/docs/protocol#101-who-has-the-keyboard)):

```text
program → ESC ] 7279 ; a=focus:s=login:t=user ST
```

If `t` is omitted, focus stays on the currently focused element in that surface,
or moves to the first focusable element if none is focused. The following
elements take focus on click (unless disabled):

- `<input>`, `<select>`, `<textarea>`, and `<button>`;
- links with `href`, except `target="_blank"` hyperlinks (which are handled by
  the terminal);
- the first `<summary>` of a `<details>` element;
- `contenteditable` elements;
- any element with `tabindex >= 0`.

Clicking a `<label>` focuses its associated control. Clicking a non-focusable
element does not move focus to the surface—if a surface has no focusable
elements, all keys always reach your program.

Keyboard focus returns to the terminal, and the host emits `blur`, when:

- the user clicks terminal cells, another surface, or a non-focusable area of
  the current surface;
- `tab` moves past the last focusable element or `shift+tab` moves before the
  first;
- your program sends `a=blur`, hides the surface, or places it as a backdrop
  ([Surfaces](https://hotty.neuroplast.io/docs/concepts/surfaces#backdrops)).

If a text field is focused when the surface blurs, the host commits its value
first, emitting `change` (if modified) before `blur`. `escape` is never consumed
by a surface except to close an open `<select>` popup; otherwise it passes
through to your program, which can respond with `a=blur`.

Surfaces cannot steal focus on their own: `autofocus` is ignored
([Security](https://hotty.neuroplast.io/docs/concepts/security)). Detached surfaces can never hold focus; detaching a
focused surface returns the keyboard to the terminal without emitting `change`
or `blur` ([§5.5](https://hotty.neuroplast.io/docs/protocol#55-ownership-adetach)). Backdrops (drawn behind
terminal cells) also cannot take focus—sending `a=focus` to a backdrop returns
`EINVAL` ([§5.2](https://hotty.neuroplast.io/docs/protocol#52-placement-aplace)).

## Following focus

Whenever the user moves focus (by clicking or pressing `tab`), the host emits a
`focus` event targeting the nearest element with an `id` walking outward from
the focused element. For example, if the user types a username and presses
`tab`:

```text
host → ESC ] 7279 ; a=ev:s=login:e=change:t=user ; {"value": "ada"} ST
host → ESC ] 7279 ; a=ev:s=login:e=focus:t=pass ST
```

Programmatic focus via `a=focus` does not echo a `focus` event. If you need to
know when the user clicks a surface that has no focusable elements, enable
`p=1` on the placement to receive `press` events ([Input](https://hotty.neuroplast.io/docs/concepts/input#presses)).

## The keys a surface uses

While a surface has focus, its focused element consumes only the keys relevant
to it, and everything else passes through to your program
([§10.2](https://hotty.neuroplast.io/docs/protocol#102-keys)):

| focused element | consumed keys |
| --- | --- |
| text fields (`<input>` of text types, `<textarea>`, `contenteditable`) | typed characters and keys bound in the active keymap (see below) |
| date/time `<input>` | characters, `space`, `backspace`, `delete`, arrow keys, `home`, `end`, `page_up`, `page_down`, `enter` |
| `<select>` | characters, `space`, `arrow_up`, `arrow_down`, `home`, `end`, `page_up`, `page_down`, `enter` |
| `<button>`, link, `<summary>`, checkbox, radio button | `space` and `enter` |

Outside text fields, these keys are only consumed unmodified or with `shift`.
`tab` and `shift+tab` move focus between elements. In a scrollable document,
scrolling keys scroll the surface ([Keymaps](#keymaps)). Every other key is
delivered to your program in its active keyboard encoding, just as if no surface
were present.

**`<select>` controls** support keyboard selection directly (like a closed
`<select>` in a browser on Linux and Windows). Each selection change immediately
emits `input` (if requested) followed by `change`.

Hosts are not required to render a dropdown popup; if a host does not, `space`
and `enter` do nothing on a `<select>`. If you need a consistent dropdown menu
across all hosts, build it with a `<button>` and a higher-`z` surface anchored
to the click's `area`.

**Text fields** behave like standard browser inputs: arrow keys, `home`, `end`,
`backspace`, and `delete` move and edit; `shift` extends selection; and
`mod+c`, `mod+v`, and `mod+z` copy, paste, and undo. Pressing `enter` in an
`<input>` commits the value (emitting `change`) and submits the enclosing form
if any; in a `<textarea>`, `enter` inserts a newline.

When nothing is selected, `mod+c` has nothing to copy and passes through to your
program—so `ctrl+c` still sends an interrupt on Linux. Each field maintains its
own undo history, which is cleared when the program sets a new value.

**Key release events** are outside hotty's scope. Programs that need release
events (such as games) should enable the kitty keyboard protocol's event types
directly ([§10.3](https://hotty.neuroplast.io/docs/protocol#103-key-releases)).

## Keymaps

Keymaps let you customize which keys an element handles and which it forwards to
your program. Write space-separated `key=action` bindings in two attributes
([keymaps](https://hotty.neuroplast.io/docs/protocol#keymaps)):

- **`data-keys`** applies only when the element itself is focused.
- **`data-keys-inner`** applies when a descendant element is focused, not the
  element itself. To apply a binding to both, set it in both attributes.

```html
<main data-keys-inner="ctrl+u=delete-to-line-start mod+k=prefix">
  <input id=cmd name=cmd data-keys="ctrl+c=program">
</main>
```

- **Inheritance order:** the effective keymap for a focused element is built by
  merging `data-keys-inner` from the document root down to the element's parent,
  followed by the element's own `data-keys`. Later bindings override earlier
  ones per key. Define shared field shortcuts once on a container's
  `data-keys-inner`, and override individual fields with `data-keys`.
- **Element-owned keys:** keys that an element inherently uses (typed characters
  in a text field, `space` on a button) can only be redirected to `program`,
  `prefix`, or `default` via that element's own `data-keys`—never by an
  ancestor's `data-keys-inner`. For example, binding `j=program` in a list's
  `data-keys-inner` will not stop an `<input>` inside the list from typing `j`.
- **Text field defaults:** text fields start with a default keymap covering
  standard editing keys, platform `mod` shortcuts, and host editing shortcuts
  ([text fields](https://hotty.neuroplast.io/docs/protocol#text-fields))—matching standard browser inputs,
  including Cocoa bindings like `ctrl+a` and `ctrl+e` on macOS.
- **`program`** forwards the key to your program even if the element would
  normally consume it (for example, `ctrl+c=program` in a REPL input).
- **`prefix`** forwards the key and all subsequent keys to your program until
  the sequence ends (see below).
- **Scroll actions** (such as `scroll-down` and `scroll-page-up`) scroll a
  scrollable surface.
- **Ignored bindings:** unparseable keys, unknown actions, `default` inside
  `data-keys-inner`, and any binding on `tab`, `shift+tab`, or `escape` are
  ignored.

Each element only applies actions that are meaningful to it; inapplicable
bindings are ignored. Outside text fields, only `program`, `prefix`, and scroll
actions apply (plus `copy` when the document has a text selection). For example,
a focused button inside a scrolling surface would normally scroll on arrow keys;
setting `data-keys="arrow_up=program arrow_down=program"` forwards them to your
program instead. When no element is focused, the document uses the `<body>`
keymap (the root's and `<body>`'s `data-keys-inner`, then `<body>`'s
`data-keys`), so place document-wide bindings on `<body>`.

**Scrolling keys** let a surface scroll with the same keys your program uses in
terminal cells ([scrolling keys](https://hotty.neuroplast.io/docs/protocol#scrolling-keys)). For example, a
pager can bind vi-style navigation on its scrollable container (in `data-keys`
for when the container is focused, and `data-keys-inner` for when a link inside
it is focused):

```html
<article tabindex=0
  data-keys="j=scroll-down k=scroll-up g=scroll-start shift+g=scroll-end space=scroll-page-down shift+space=scroll-page-up b=scroll-page-up"
  data-keys-inner="j=scroll-down k=scroll-up g=scroll-start shift+g=scroll-end space=scroll-page-down shift+space=scroll-page-up b=scroll-page-up">…</article>
```

If the document root itself scrolls, setting `data-keys-inner` on the root
covers both focused descendants and the unfocused state. Text fields ignore
scroll actions (so typing `j` still inserts `j`), and buttons retain `space`.
Scroll actions never scroll the host terminal itself, and only take effect in a
scrollable document ([§5.3](https://hotty.neuroplast.io/docs/protocol#53-geometry)). The host stylesheet
draws focus rings only on form controls and links, not on generic focusable
containers like `<article tabindex=0>` ([§8](https://hotty.neuroplast.io/docs/protocol#8-the-host-stylesheet)).

SDKs expose keymaps as structured data. Every SDK provides `TerminalKeys`—matching
Bubble Tea's text input and text area bindings
([SDK design §3.10](https://hotty.neuroplast.io/docs/sdk-design#310-keys))—so you can apply consistent
bindings to both your surfaces (via `data-keys-inner`) and cell-based inputs.

## Key names

hotty uses [*myelin key names* 0.1](https://github.com/neuroplastio/myelin/blob/myelinkey/v0.1.0/myelinkey/SPEC.md)
([§10.4](https://hotty.neuroplast.io/docs/protocol#104-key-names)), which follow Ghostty's naming
vocabulary. A key name consists of modifiers separated by `+`, followed by a
physical key, a character, or a standalone modifier:

| name | meaning |
| --- | --- |
| `ctrl+a` | Control + the key that produces `a` |
| `ctrl+key_a` | Control + the physical key at the US-layout A position, regardless of layout |
| `shift+g` | Shift + `g` (produces `G`) |
| `?` | the key that produces `?` (Shift is already implied) |
| `alt+arrow_left` | Alt + left arrow |
| `page_down`, `enter`, `space` | physical-only keys |
| `mod+s` | `ctrl+s` on Linux/Windows, `super+s` on macOS |
| `shift` | Shift tapped alone |

- **Modifiers** appear in canonical order: `super`, `ctrl`, `alt`, `shift`.
  `super` is Command on macOS and Super/Windows elsewhere.
- **Physical keys** use snake_case W3C key codes, such as `page_down`, `key_w`,
  or `numpad_enter`.
- **Characters** represent the typed character. Letters are lowercase with
  explicit `shift+` for uppercase; shifted punctuation characters (like `?`)
  already imply Shift.
- **`mod`** is the platform command modifier (`super` on macOS, `ctrl`
  elsewhere), reported as `mod` in host capabilities. Use `mod` when writing
  keymaps; key events always report the concrete modifier.

Key parsing is lenient: modifiers may appear in any order or case, and aliases
like `cmd`, `opt`, `control`, `PageDown`, and `pgdn` are accepted. Uppercase
letters are normalized to lowercase (`G` is read as `g`; write `shift+g` for
Shift+G). Hosts reject `meta` (which is ambiguous between `super` and `alt`)
and reject combining `mod` with `super` or `ctrl`.

Pointer and drag events encode modifiers in the `mods` bitmask using the same
names: `1` (`shift`), `2` (`alt`), `4` (`ctrl`), `8` (`super`).

## Two names for one press

A single key press can match up to two names, and the host checks the physical
key name first. Hosts that receive raw OS key events (native terminal emulators
and browsers) offer non-text key presses to the surface before checking the
terminal's own shortcuts.

A key pressed with `ctrl` or `super` has both a physical name and a character
name—on a US layout, Control+W is both `ctrl+key_w` and `ctrl+w`. If the
surface binds either name, it consumes the press; if both are bound, the
physical binding wins. Hosts may reserve a few system shortcuts (such as
`ctrl+t` in a browser).

If the surface does not consume the raw key press, the key continues down the
normal terminal pipeline: terminal shortcuts run, and remaining keys are encoded
into terminal input bytes. The host then offers those encoded bytes to the
surface a second time, matched by a single name (the character or physical key
represented by the bytes).

Text input (including IME composition) arrives only through this second,
byte-level stage. Hosts that only see a byte stream (such as `hotty run` inside
another terminal) deliver all keys this way. Because bytes carry characters
rather than physical key positions:

- **Bind by character for portability:** use `ctrl+w` instead of `ctrl+key_w`
  when a binding must work across all hosts.
- **Legacy encoding aliases:** in legacy terminal encoding, `ctrl+backspace`
  may arrive as `ctrl+h`, and macOS terminals often send Command+Left as
  `ctrl+a`.
- **`program` persists across stages:** if either name is bound to `program` at
  the raw stage, the resulting bytes still pass through to your program (for
  example, `ctrl+key_a=program` in a text field forwards `ctrl+a` on Linux
  rather than triggering Select All).
- **Standalone modifiers** are recognized on release (`shift_left` and `shift`)
  and never produce terminal bytes; binding one to `program` has no effect.

## Key sequences and prefixes

Your program handles multi-key sequences (such as a leader key or `g g`) using
the same keymap logic it uses in terminal cells
([§10.5](https://hotty.neuroplast.io/docs/protocol#105-key-sequences)). Binding the starter key to `prefix`
tells the host to forward that key and every subsequent key to your program
until the sequence finishes:

```html
<main data-keys-inner="mod+k=prefix">
  <ul id=files tabindex=0 data-keys="g=prefix">…</ul>
</main>
```

Here, pressing `mod+k` anywhere inside `<main>` or `g` on the file list hands
all following keys—including `tab` and `escape`—to your program. Your program
manages any sequence timeout, and returns keyboard focus with `a=focus` once
the sequence completes, times out, or is canceled with `escape`:

```text
host    → g                        (terminal input: the list's prefix)
program → ESC ] 7279 ; a=menu:show=1 ; {"seq": ["g"]} ST
host    → g                        (the program's, whatever is focused)
program → ESC ] 7279 ; a=menu:show=0 ST
program → ESC ] 7279 ; a=focus:s=browser ST
```

Sending `a=focus` without `t` preserves the previously focused element. A
prefix mode also ends if your program sends `a=blur`, the surface loses focus,
or the user clicks to focus an element. The host notifies your program of
user-initiated changes via `focus` or `blur` events—with one exception: if the
focused element disappears due to a layout change alone (focus fixup), focus
clears silently without emitting an event
([§10.1](https://hotty.neuroplast.io/docs/protocol#101-who-has-the-keyboard)), leaving the last `focus`
event stale.

## Edit commands in the cells

Programs that implement text editing inside terminal cells can receive standard
editing shortcuts as semantic `command` events rather than raw control bytes
([§10.6](https://hotty.neuroplast.io/docs/protocol#106-commands-in-the-cells)). Normally, `ctrl+c` sends an
interrupt and `ctrl+v` quotes the next character; by claiming edit commands
with `a=edit`, your program can handle copy, paste, undo, and redo cleanly:

```text
program → ESC ] 7279 ; a=edit:take=copy,paste,undo,redo ST
host    → ESC ] 7279 ; a=ev:e=command ; {"name": "paste", "key": "ctrl+v", "text": "hello"} ST
```

- **Event payload:** pressing a claimed shortcut emits `command` instead of raw
  bytes. `key` identifies the pressed key, and `paste` includes the clipboard's
  `text` ordered cleanly with surrounding keystrokes.
- **Fallback behavior:** your program decides how to handle the command. For
  example, on `copy` with no selection, your program can fall back to the
  meaning of `key` so `ctrl+c` still interrupts.
- **Terminal selection takes precedence:** if the user has selected text in the
  terminal cells, the terminal's copy shortcut copies that selection directly
  and does not emit `command`.
- **Surface focus takes precedence:** if a surface holds keyboard focus, the
  surface sees the key first.
- **Native menus:** invoking an Edit menu item from the terminal's UI emits the
  corresponding claimed `command` without a `key` field.
- **Screen-scoped:** each `a=edit` replaces the previous set, tracked
  separately for the main and alternate screens. Full-screen apps should send
  `a=edit` after entering the alternate screen.

Hosts supporting edit commands advertise their shortcut bindings under `edit`
in capabilities and emit `caps` if those bindings change. `command` events are
not tied to a surface, so they omit `s` and `t`.

## The program's menu

A program can publish its command menu to the host along with the key sequences
that trigger each action ([§10.7](https://hotty.neuroplast.io/docs/protocol#107-menus)). Hosts can display
a menu level as a key-hint overlay while a multi-key sequence is in progress,
and multiplexers or agents can surface items in a command palette or automation
UI.

```text
program → ESC ] 7279 ; a=menu ; {"label": "files", "items": [
            {"key": "g", "label": "go", "enabled": true, "items": [
              {"key": "g", "label": "top", "name": "top", "enabled": true},
              {"key": "shift+g", "label": "bottom", "name": "bottom", "enabled": true}]},
            {"key": "mod+s", "label": "save", "name": "save", "enabled": false},
            {"label": "reload", "name": "reload", "enabled": true}]} ST
```

- **Item fields:** each item can specify `key` (relative to its parent group),
  `label`, `name` (the command name emitted when picked), and nested `items`
  (up to 8 levels deep).
- **Enabled state:** items default to disabled if `enabled` is omitted, so set
  `"enabled": true` on active items. An empty `items` array does not create a
  group.
- **Lifetime:** the menu persists until replaced by another `a=menu` or cleared
  with an empty `a=menu`. Main and alternate screens keep separate menus; clear
  your menu before exiting.

While waiting for the next key in a sequence, send `a=menu:show=1` with
`{"seq": ["g"]}` to display the corresponding submenu (here, the `go` group:
`g` for top, `shift+g` for bottom). Hosts may delay showing the overlay briefly
so fast typists are not interrupted.

The overlay remains visible until you show another level or send
`a=menu:show=0`. The host also dismisses it on `escape`, on any key not listed
in that level, or on a screen switch. Key routing is unaffected by the overlay.

Picking an item from the menu or command palette emits a `command` event with
the item's `name` and no `key`:

```text
host → ESC ] 7279 ; a=ev:e=command ; {"name": "reload"} ST
```

Disabled items cannot be triggered. Items without a `key` (such as `reload`
above) are reachable only via menu or palette selection. Terminals without a
command palette simply omit palette integration.

Menu support is gated by the `menu` capability. On hosts without it, `a=menu`
returns `EINVAL`, and your program should render its own menu in cells or in a
higher-`z` surface. SDKs build these commands with `Menu`, `MenuShow`, and
`MenuHide` ([SDK design](https://hotty.neuroplast.io/docs/sdk-design#34-commands)).
