# Focus Events (?1004)

> Have the terminal tell the program when its window gains or loses the keyboard focus.

- **Sequence:** `CSI ? 1004 h`
- **xterm:** [Mouse Tracking](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html)

With `CSI ? 1004 h` set, the terminal sends `CSI I` to the program when its
window gains the keyboard focus and `CSI O` when it loses it, so that an
editor can, for instance, reload a file that changed while it was in the
background. `CSI ? 1004 l` stops the reports. It is xterm's, listed with the
[mouse tracking](https://control-codes.page/modes/mouse/index.html.md) modes, but it can be set with or without any
of them
([`dpmodes`](https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411a/charproc.c#L7827-L7831),
[`SendFocusButton`](https://github.com/ThomasDickey/xterm-snapshots/blob/xterm-411a/button.c#L5676-L5712)).
It is off to begin with, and [RIS](https://control-codes.page/esc/ris/index.html.md) turns it off.

Focus changes come from the window, not from the data a case writes, so the
cases check what DECRQM says and that setting the mode sends nothing on its
own. libghostty-vt passes them.

## Validation

### FOCUS-1: Off to begin with

Input, one step per line:

```text
\e[?1004$p
```

Expected screen:

```text
|____|
reply \e[?1004;2$y
```

### FOCUS-2: Setting it sends nothing

Input, one step per line:

```text
A
\e[?1004h
B
```

Expected screen:

```text
|AB__|
cursor 1,3
reply none
```

### FOCUS-3: Set and reset

Input, one step per line:

```text
\e[?1004h
\e[?1004$p
\e[?1004l
\e[?1004$p
```

Expected screen:

```text
|____|
reply \e[?1004;1$y\e[?1004;2$y
```

### FOCUS-4: RIS turns it off

Input, one step per line:

```text
\e[?1004h
\ec
\e[?1004$p
```

Expected screen:

```text
|____|
reply \e[?1004;2$y
```

---

This is the Markdown version of <https://control-codes.page/modes/focus/>. On that page every validation case runs live in libghostty-vt, the terminal emulation core of Ghostty, compiled to WebAssembly.

The validation cases are written in the notation described in <https://control-codes.page/notation/index.html.md>.
