From 464922668b25d8d1fe528fc7c8e37827fef661b1 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 14 Nov 2026 22:25:51 +0100 Subject: [PATCH 01/23] test(web): a recorder for the browser keyboard events --- package.json | 1 + tests/ime-web/recorder/index.html | 25 +++++ tests/ime-web/recorder/recorder.js | 149 +++++++++++++++++++++++++++++ tests/ime-web/recorder/serve.mjs | 43 +++++++++ tests/web/recorder.test.ts | 49 ++++++++++ 5 files changed, 267 insertions(+) create mode 100644 tests/ime-web/recorder/index.html create mode 100644 tests/ime-web/recorder/recorder.js create mode 100644 tests/ime-web/recorder/serve.mjs create mode 100644 tests/web/recorder.test.ts diff --git a/package.json b/package.json index c2f283c..84d2d84 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "bench:memory": "scripts/bench.sh memory", "bench:typing": "scripts/bench.sh typing", "ime:record": "scripts/ime-record.sh", + "ime:record:web": "node tests/ime-web/recorder/serve.mjs", "ime:record:ios": "scripts/ime-record-ios.sh", "bench:ios": "scripts/bench-ios.sh", "release": "release-it --only-version", diff --git a/tests/ime-web/recorder/index.html b/tests/ime-web/recorder/index.html new file mode 100644 index 0000000..80515dd --- /dev/null +++ b/tests/ime-web/recorder/index.html @@ -0,0 +1,25 @@ + + + + + + Keyboard recorder + + + + +
+ + + + +

+    
+  
+
diff --git a/tests/ime-web/recorder/recorder.js b/tests/ime-web/recorder/recorder.js
new file mode 100644
index 0000000..bd4fa3e
--- /dev/null
+++ b/tests/ime-web/recorder/recorder.js
@@ -0,0 +1,149 @@
+// Records what a browser keyboard sends to a textarea that holds a window of a document, as WebInputSession will.
+const WINDOW_CAP = 8192;
+const SAMPLE = Array.from({ length: 30 }, (_, i) =>
+  i % 5 === 0 ? `def step_${i}(value):` : `    total = value + ${i}`,
+).join('\n');
+const INITIAL_CARET = SAMPLE.indexOf('\n', SAMPLE.indexOf('step_10'));
+
+const ta = document.getElementById('ta');
+const statusLine = document.getElementById('status');
+const shown = document.getElementById('doc');
+const suggest = new URLSearchParams(location.search).has('suggest');
+for (const [name, on, off] of [
+  ['autocomplete', 'on', 'off'],
+  ['autocorrect', 'on', 'off'],
+  ['autocapitalize', 'sentences', 'off'],
+  ['spellcheck', 'true', 'false'],
+]) {
+  ta.setAttribute(name, suggest ? on : off);
+}
+
+let doc = SAMPLE;
+let anchor = INITIAL_CARET;
+let head = INITIAL_CARET;
+let win = { start: 0, value: '', line: 0 };
+let composing = false;
+let events = [];
+const started = performance.now();
+
+const lineAt = (offset) => doc.slice(0, offset).split('\n').length - 1;
+const lineStart = (line) => {
+  let at = 0;
+  for (let i = 0; i < line; i++) at = doc.indexOf('\n', at) + 1;
+  return at;
+};
+const lineEnd = (line) => {
+  const next = doc.indexOf('\n', lineStart(line));
+  return next < 0 ? doc.length : next;
+};
+const lastLine = () => lineAt(doc.length);
+
+// The caret's line and its two neighbors, widened to a selection, at most WINDOW_CAP units around the head.
+function windowAround() {
+  const first = Math.max(0, lineAt(Math.min(anchor, head)) - 1);
+  const last = Math.min(lastLine(), lineAt(Math.max(anchor, head)) + 1);
+  let start = lineStart(first);
+  let end = lineEnd(last);
+  if (end - start > WINDOW_CAP) {
+    start = Math.min(Math.max(start, head - WINDOW_CAP / 2), end - WINDOW_CAP);
+    end = start + WINDOW_CAP;
+  }
+  return { start, end };
+}
+
+const state = () => ({ value: ta.value, start: ta.selectionStart, end: ta.selectionEnd });
+
+function record(type, extra = {}) {
+  events.push({
+    t: Math.round(performance.now() - started),
+    type,
+    ...extra,
+    isComposing: composing,
+    windowStart: win.start,
+    ta: state(),
+  });
+  render();
+}
+
+function sync() {
+  const { start, end } = windowAround();
+  win = { start, value: doc.slice(start, end), line: lineAt(head) };
+  if (ta.value !== win.value) ta.value = win.value;
+  const a = anchor - start;
+  const h = head - start;
+  ta.setSelectionRange(Math.min(a, h), Math.max(a, h), h < a ? 'backward' : 'forward');
+  record('sync');
+}
+
+// Takes the model selection from the textarea and moves the window when the head left its middle line.
+function follow() {
+  const backward = ta.selectionDirection === 'backward';
+  anchor = win.start + (backward ? ta.selectionEnd : ta.selectionStart);
+  head = win.start + (backward ? ta.selectionStart : ta.selectionEnd);
+  if (!composing && lineAt(head) !== win.line) sync();
+}
+
+function render() {
+  statusLine.textContent = `head ${head}, line ${lineAt(head)}${composing ? ', composing' : ''}, ${events.length} events`;
+  shown.textContent = doc;
+}
+
+ta.addEventListener('keydown', (e) =>
+  record('keydown', { key: e.key, isComposing: e.isComposing }),
+);
+ta.addEventListener('beforeinput', (e) =>
+  record('beforeinput', { inputType: e.inputType, data: e.data }),
+);
+ta.addEventListener('input', (e) => {
+  doc = doc.slice(0, win.start) + ta.value + doc.slice(win.start + win.value.length);
+  win.value = ta.value;
+  record('input', { inputType: e.inputType, data: e.data });
+  follow();
+});
+ta.addEventListener('compositionstart', (e) => {
+  composing = true;
+  record('compositionstart', { data: e.data });
+});
+ta.addEventListener('compositionupdate', (e) => record('compositionupdate', { data: e.data }));
+ta.addEventListener('compositionend', (e) => {
+  composing = false;
+  record('compositionend', { data: e.data });
+  setTimeout(() => {
+    if (!composing) follow();
+  }, 0);
+});
+document.addEventListener('selectionchange', () => {
+  if (document.activeElement !== ta) return;
+  record('selectionchange');
+  if (!composing) follow();
+});
+ta.addEventListener('focus', () => record('focus'));
+ta.addEventListener('blur', () => record('blur'));
+
+function reset() {
+  doc = SAMPLE;
+  anchor = INITIAL_CARET;
+  head = INITIAL_CARET;
+  composing = false;
+  events = [];
+  sync();
+}
+
+document.getElementById('reset').addEventListener('click', reset);
+document.getElementById('save').addEventListener('click', async () => {
+  const recording = {
+    name: document.getElementById('name').value.trim(),
+    browser: document.getElementById('browser').value.trim(),
+    keyboard: document.getElementById('keyboard').value.trim(),
+    ua: navigator.userAgent,
+    recordedAt: new Date().toISOString(),
+    settings: { autoCloseBrackets: false, autoIndent: false },
+    initial: { text: SAMPLE, selection: [INITIAL_CARET, INITIAL_CARET] },
+    events,
+    expected: { text: doc },
+  };
+  const res = await fetch('save', { method: 'POST', body: JSON.stringify(recording) });
+  statusLine.textContent = `${res.status} ${await res.text()}`;
+});
+
+reset();
diff --git a/tests/ime-web/recorder/serve.mjs b/tests/ime-web/recorder/serve.mjs
new file mode 100644
index 0000000..d203b8d
--- /dev/null
+++ b/tests/ime-web/recorder/serve.mjs
@@ -0,0 +1,43 @@
+import { readFile, writeFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import path from 'node:path';
+
+// Serves the keyboard recorder on loopback and saves each recording it posts into tests/ime-web.
+const here = import.meta.dirname;
+const out = path.join(here, '..');
+const NAME = /^[a-z0-9-]+$/;
+const PAGES = { '/': 'index.html', '/recorder.js': 'recorder.js' };
+const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8' };
+
+const server = createServer(async (req, res) => {
+  const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1');
+  if (req.method === 'POST' && pathname === '/save') {
+    let body = '';
+    for await (const chunk of req) body += chunk;
+    let recording = null;
+    try {
+      recording = JSON.parse(body);
+    } catch {}
+    if (typeof recording?.name !== 'string' || !NAME.test(recording.name)) {
+      res.writeHead(400).end('the name takes lowercase letters, digits and dashes');
+      return;
+    }
+    await writeFile(
+      path.join(out, `${recording.name}.json`),
+      `${JSON.stringify(recording, null, 2)}\n`,
+    );
+    res.writeHead(200).end('saved');
+    return;
+  }
+  const file = PAGES[pathname];
+  if (!file) {
+    res.writeHead(404).end();
+    return;
+  }
+  res.writeHead(200, { 'content-type': TYPES[path.extname(file)] });
+  res.end(await readFile(path.join(here, file)));
+});
+
+server.listen(Number(process.argv[2] ?? 8090), '127.0.0.1', () => {
+  console.log(`recorder on http://127.0.0.1:${server.address().port}/`);
+});
diff --git a/tests/web/recorder.test.ts b/tests/web/recorder.test.ts
new file mode 100644
index 0000000..09e4a2a
--- /dev/null
+++ b/tests/web/recorder.test.ts
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { existsSync, readFileSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { test } from 'node:test';
+
+const root = path.join(import.meta.dirname, '..', '..');
+const dir = path.join(root, 'tests', 'ime-web');
+
+// Starts the recorder on a free port and resolves its base URL from the line it prints.
+function start(): Promise<{ url: string; stop: () => void }> {
+  const child = spawn(process.execPath, [path.join(dir, 'recorder', 'serve.mjs'), '0'], {
+    stdio: ['ignore', 'pipe', 'inherit'],
+  });
+  return new Promise((resolve, reject) => {
+    child.on('error', reject);
+    child.on('exit', (code) => reject(new Error(`recorder exited with ${code}`)));
+    child.stdout.on('data', (chunk: Buffer) => {
+      const match = /http:\/\/127\.0\.0\.1:\d+\//.exec(chunk.toString());
+      if (match) resolve({ url: match[0], stop: () => child.kill() });
+    });
+  });
+}
+
+const post = (url: string, body: unknown) =>
+  fetch(`${url}save`, {
+    method: 'POST',
+    headers: { 'content-type': 'application/json' },
+    body: JSON.stringify(body),
+  });
+
+test('the recorder server writes only plain names inside tests/ime-web', async () => {
+  const { url, stop } = await start();
+  const written = path.join(dir, 'ok-name.json');
+  try {
+    const ok = await post(url, { name: 'ok-name', events: [] });
+    assert.equal(ok.status, 200);
+    assert.equal(JSON.parse(readFileSync(written, 'utf8')).name, 'ok-name');
+    for (const name of ['../escape', 'a/b', 'Upper', '']) {
+      const res = await post(url, { name, events: [] });
+      assert.equal(res.status, 400, name);
+    }
+    assert.equal(existsSync(path.join(root, 'tests', 'escape.json')), false);
+    assert.equal(existsSync(path.join(dir, 'a')), false);
+  } finally {
+    rmSync(written, { force: true });
+    stop();
+  }
+});

From b96987bf25830835ed57f1320b04e5adea580cdd Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sat, 14 Nov 2026 22:48:56 +0100
Subject: [PATCH 02/23] test(web): keyboard recordings from Chrome on Android
 and Safari on iOS

---
 tests/ime-web/gboard-emoji.json           | 445 ++++++++++++
 tests/ime-web/gboard-enter-backspace.json | 282 ++++++++
 tests/ime-web/gboard-suggestion.json      | 799 ++++++++++++++++++++++
 tests/ime-web/ios-arabic.json             | 396 +++++++++++
 tests/ime-web/ios-autocorrect.json        | 666 ++++++++++++++++++
 tests/ime-web/ios-japanese-romaji.json    | 779 +++++++++++++++++++++
 tests/ime-web/recorder/recorder.js        |   7 +-
 7 files changed, 3373 insertions(+), 1 deletion(-)
 create mode 100644 tests/ime-web/gboard-emoji.json
 create mode 100644 tests/ime-web/gboard-enter-backspace.json
 create mode 100644 tests/ime-web/gboard-suggestion.json
 create mode 100644 tests/ime-web/ios-arabic.json
 create mode 100644 tests/ime-web/ios-autocorrect.json
 create mode 100644 tests/ime-web/ios-japanese-romaji.json

diff --git a/tests/ime-web/gboard-emoji.json b/tests/ime-web/gboard-emoji.json
new file mode 100644
index 0000000..ca6a487
--- /dev/null
+++ b/tests/ime-web/gboard-emoji.json
@@ -0,0 +1,445 @@
+{
+  "name": "gboard-emoji",
+  "browser": "chrome-android",
+  "keyboard": "Gboard EN FR, suggestions on, emoji suggestion then two Backspaces",
+  "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36",
+  "recordedAt": "2026-11-14T21:33:26.751Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 1,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 1848,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 1854,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 3103,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 3106,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 3108,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 3116,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 3460,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 3461,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 3461,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): h\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 3467,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): h\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 3756,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): h\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 3757,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): h\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 3758,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): he\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 3767,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): he\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 4055,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): he\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 4056,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): he\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 4057,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): hel\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 4074,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): hel\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 26410,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): hel\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 26411,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): hel\n    total = value + 11",
+        "start": 42,
+        "end": 45
+      }
+    },
+    {
+      "t": 26412,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 26413,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 26414,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "👋🏻 ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 26426,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "👋🏻 ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻 \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 26429,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻 \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 27149,
+      "type": "keydown",
+      "key": "Backspace",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻 \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 27152,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻 \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 27156,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 27162,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 27802,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 27805,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): 👋🏻\n    total = value + 11",
+        "start": 42,
+        "end": 46
+      }
+    },
+    {
+      "t": 27808,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 27815,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 28560,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value): \n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/gboard-enter-backspace.json b/tests/ime-web/gboard-enter-backspace.json
new file mode 100644
index 0000000..df8ba1b
--- /dev/null
+++ b/tests/ime-web/gboard-enter-backspace.json
@@ -0,0 +1,282 @@
+{
+  "name": "gboard-enter-backspace",
+  "browser": "chrome-android",
+  "keyboard": "Gboard EN FR, suggestions off",
+  "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36",
+  "recordedAt": "2026-11-14T21:32:28.645Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 1,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 14724,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 14732,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 16040,
+      "type": "keydown",
+      "key": "Enter",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 16049,
+      "type": "beforeinput",
+      "inputType": "insertLineBreak",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 16055,
+      "type": "input",
+      "inputType": "insertLineBreak",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_\n10(value):\n    total = value + 11",
+        "start": 32,
+        "end": 32
+      }
+    },
+    {
+      "t": 16056,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 214,
+      "ta": {
+        "value": "def step_\n10(value):\n    total = value + 11",
+        "start": 10,
+        "end": 10
+      }
+    },
+    {
+      "t": 16062,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 214,
+      "ta": {
+        "value": "def step_\n10(value):\n    total = value + 11",
+        "start": 10,
+        "end": 10
+      }
+    },
+    {
+      "t": 16529,
+      "type": "keydown",
+      "key": "Backspace",
+      "isComposing": false,
+      "windowStart": 214,
+      "ta": {
+        "value": "def step_\n10(value):\n    total = value + 11",
+        "start": 10,
+        "end": 10
+      }
+    },
+    {
+      "t": 16532,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 214,
+      "ta": {
+        "value": "def step_\n10(value):\n    total = value + 11",
+        "start": 10,
+        "end": 10
+      }
+    },
+    {
+      "t": 16541,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 214,
+      "ta": {
+        "value": "def step_10(value):\n    total = value + 11",
+        "start": 9,
+        "end": 9
+      }
+    },
+    {
+      "t": 16546,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 16552,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 17085,
+      "type": "keydown",
+      "key": "Backspace",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 17086,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 17087,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step10(value):\n    total = value + 11",
+        "start": 30,
+        "end": 30
+      }
+    },
+    {
+      "t": 17098,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step10(value):\n    total = value + 11",
+        "start": 30,
+        "end": 30
+      }
+    },
+    {
+      "t": 17630,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step10(value):\n    total = value + 11",
+        "start": 30,
+        "end": 30
+      }
+    },
+    {
+      "t": 17633,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "x",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step10(value):\n    total = value + 11",
+        "start": 30,
+        "end": 30
+      }
+    },
+    {
+      "t": 17636,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "x",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef stepx10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 17644,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef stepx10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    },
+    {
+      "t": 37408,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef stepx10(value):\n    total = value + 11",
+        "start": 31,
+        "end": 31
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef stepx10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/gboard-suggestion.json b/tests/ime-web/gboard-suggestion.json
new file mode 100644
index 0000000..a689362
--- /dev/null
+++ b/tests/ime-web/gboard-suggestion.json
@@ -0,0 +1,799 @@
+{
+  "name": "gboard-suggestion",
+  "browser": "chrome-android",
+  "keyboard": "Gboard EN FR, suggestions on, autocorrect off",
+  "ua": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/157.0.0.0 Mobile Safari/537.36",
+  "recordedAt": "2026-11-14T21:29:53.816Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 2,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 61689,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 61697,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 89250,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 89258,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 89263,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 89270,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 89549,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 89550,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "p",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 89553,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "p",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): p\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 89559,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): p\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 89844,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): p\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 89845,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "r",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): p\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 89846,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "r",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pr\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 89850,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pr\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 90147,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pr\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 90148,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "i",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pr\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 90149,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "i",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pri\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 90157,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pri\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 90455,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pri\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 90456,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pri\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 90457,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): prit\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 90466,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): prit\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 90758,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): prit\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 90759,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "n",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): prit\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 90760,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "n",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 90765,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 91214,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 91215,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 91217,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn \n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 91224,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn \n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 91769,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn \n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 91771,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn \n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 91774,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn h\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 91782,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn h\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 92073,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn h\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 92073,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn h\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 92077,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn he\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 92080,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn he\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 92372,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn he\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 92373,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn he\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 92374,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hel\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 92382,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hel\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 123023,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hel\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 123025,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "lo ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hel\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 123031,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "lo ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello \n    total = value + 11",
+        "start": 54,
+        "end": 54
+      }
+    },
+    {
+      "t": 123040,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello \n    total = value + 11",
+        "start": 54,
+        "end": 54
+      }
+    },
+    {
+      "t": 123674,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello \n    total = value + 11",
+        "start": 54,
+        "end": 54
+      }
+    },
+    {
+      "t": 123675,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello \n    total = value + 11",
+        "start": 54,
+        "end": 54
+      }
+    },
+    {
+      "t": 123676,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello t\n    total = value + 11",
+        "start": 55,
+        "end": 55
+      }
+    },
+    {
+      "t": 123685,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello t\n    total = value + 11",
+        "start": 55,
+        "end": 55
+      }
+    },
+    {
+      "t": 123988,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello t\n    total = value + 11",
+        "start": 55,
+        "end": 55
+      }
+    },
+    {
+      "t": 123990,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello t\n    total = value + 11",
+        "start": 55,
+        "end": 55
+      }
+    },
+    {
+      "t": 123991,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello te\n    total = value + 11",
+        "start": 56,
+        "end": 56
+      }
+    },
+    {
+      "t": 123996,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello te\n    total = value + 11",
+        "start": 56,
+        "end": 56
+      }
+    },
+    {
+      "t": 124281,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello te\n    total = value + 11",
+        "start": 56,
+        "end": 56
+      }
+    },
+    {
+      "t": 124282,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello te\n    total = value + 11",
+        "start": 56,
+        "end": 56
+      }
+    },
+    {
+      "t": 124283,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh\n    total = value + 11",
+        "start": 57,
+        "end": 57
+      }
+    },
+    {
+      "t": 124293,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh\n    total = value + 11",
+        "start": 57,
+        "end": 57
+      }
+    },
+    {
+      "t": 124739,
+      "type": "keydown",
+      "key": "Unidentified",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh\n    total = value + 11",
+        "start": 57,
+        "end": 57
+      }
+    },
+    {
+      "t": 124741,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh\n    total = value + 11",
+        "start": 57,
+        "end": 57
+      }
+    },
+    {
+      "t": 124743,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh \n    total = value + 11",
+        "start": 58,
+        "end": 58
+      }
+    },
+    {
+      "t": 124753,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh \n    total = value + 11",
+        "start": 58,
+        "end": 58
+      }
+    },
+    {
+      "t": 167805,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): pritn hello teh \n    total = value + 11",
+        "start": 58,
+        "end": 58
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value): pritn hello teh \n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/ios-arabic.json b/tests/ime-web/ios-arabic.json
new file mode 100644
index 0000000..18fb650
--- /dev/null
+++ b/tests/ime-web/ios-arabic.json
@@ -0,0 +1,396 @@
+{
+  "name": "ios-arabic",
+  "browser": "safari-ios",
+  "keyboard": "Arabic, iOS 27.2 simulator",
+  "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1",
+  "recordedAt": "2026-11-14T21:46:48.133Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 2,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 11434,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 39940,
+      "type": "keydown",
+      "key": "م",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 40007,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "م",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 40066,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "م",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):م\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 40075,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):م\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 40240,
+      "type": "keydown",
+      "key": "ر",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):م\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 40249,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "ر",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):م\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 40250,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "ر",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مر\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 40250,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مر\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 40640,
+      "type": "keydown",
+      "key": "ح",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مر\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 40646,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "ح",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مر\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 40647,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "ح",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرح\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 40647,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرح\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 41056,
+      "type": "keydown",
+      "key": "ب",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرح\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 41064,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "ب",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرح\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 41064,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "ب",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحب\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 41065,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحب\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 41476,
+      "type": "keydown",
+      "key": "ا",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحب\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 41485,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "ا",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحب\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 41486,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "ا",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 41486,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 42123,
+      "type": "keydown",
+      "key": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 42228,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 42228,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 42231,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 44022,
+      "type": "keydown",
+      "key": "Backspace",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 44036,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا \n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 44036,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 44037,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 44977,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):مرحبا\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/ios-autocorrect.json b/tests/ime-web/ios-autocorrect.json
new file mode 100644
index 0000000..efd2ca0
--- /dev/null
+++ b/tests/ime-web/ios-autocorrect.json
@@ -0,0 +1,666 @@
+{
+  "name": "ios-autocorrect",
+  "browser": "safari-ios",
+  "keyboard": "English US, autocorrect on, iOS 27.2 simulator",
+  "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1",
+  "recordedAt": "2026-11-14T21:45:35.162Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 3,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 10467,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 11926,
+      "type": "keydown",
+      "key": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 11960,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 11985,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 11987,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 12295,
+      "type": "keydown",
+      "key": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 12302,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): \n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 12303,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "t",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): t\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 12304,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): t\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 12711,
+      "type": "keydown",
+      "key": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): t\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 12718,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): t\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 12718,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "e",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): te\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 12719,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): te\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 13112,
+      "type": "keydown",
+      "key": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): te\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 13119,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): te\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 13119,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "h",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): teh\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13120,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): teh\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13761,
+      "type": "keydown",
+      "key": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): teh\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13763,
+      "type": "beforeinput",
+      "inputType": "insertReplacementText",
+      "data": "the",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): teh\n    total = value + 11",
+        "start": 42,
+        "end": 45
+      }
+    },
+    {
+      "t": 13767,
+      "type": "input",
+      "inputType": "insertReplacementText",
+      "data": "the",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13786,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13795,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the\n    total = value + 11",
+        "start": 45,
+        "end": 45
+      }
+    },
+    {
+      "t": 13795,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the \n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 13801,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the \n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 14611,
+      "type": "keydown",
+      "key": "w",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the \n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 14620,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "w",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the \n    total = value + 11",
+        "start": 46,
+        "end": 46
+      }
+    },
+    {
+      "t": 14620,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "w",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the w\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 14622,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the w\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 15011,
+      "type": "keydown",
+      "key": "r",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the w\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 15017,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "r",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the w\n    total = value + 11",
+        "start": 47,
+        "end": 47
+      }
+    },
+    {
+      "t": 15017,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "r",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wr\n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 15018,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wr\n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 15418,
+      "type": "keydown",
+      "key": "o",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wr\n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 15432,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "o",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wr\n    total = value + 11",
+        "start": 48,
+        "end": 48
+      }
+    },
+    {
+      "t": 15432,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "o",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wro\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 15433,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wro\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 15829,
+      "type": "keydown",
+      "key": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wro\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 15847,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wro\n    total = value + 11",
+        "start": 49,
+        "end": 49
+      }
+    },
+    {
+      "t": 15848,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "l",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrol\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 15848,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrol\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 16229,
+      "type": "keydown",
+      "key": "d",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrol\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 16236,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": "d",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrol\n    total = value + 11",
+        "start": 50,
+        "end": 50
+      }
+    },
+    {
+      "t": 16236,
+      "type": "input",
+      "inputType": "insertText",
+      "data": "d",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrold\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16237,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrold\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16897,
+      "type": "keydown",
+      "key": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrold\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16900,
+      "type": "beforeinput",
+      "inputType": "insertReplacementText",
+      "data": "world",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the wrold\n    total = value + 11",
+        "start": 46,
+        "end": 51
+      }
+    },
+    {
+      "t": 16900,
+      "type": "input",
+      "inputType": "insertReplacementText",
+      "data": "world",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16900,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16906,
+      "type": "beforeinput",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world\n    total = value + 11",
+        "start": 51,
+        "end": 51
+      }
+    },
+    {
+      "t": 16906,
+      "type": "input",
+      "inputType": "insertText",
+      "data": " ",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world \n    total = value + 11",
+        "start": 52,
+        "end": 52
+      }
+    },
+    {
+      "t": 16907,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world \n    total = value + 11",
+        "start": 52,
+        "end": 52
+      }
+    },
+    {
+      "t": 36080,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value): the world \n    total = value + 11",
+        "start": 52,
+        "end": 52
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value): the world \n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/ios-japanese-romaji.json b/tests/ime-web/ios-japanese-romaji.json
new file mode 100644
index 0000000..68773e0
--- /dev/null
+++ b/tests/ime-web/ios-japanese-romaji.json
@@ -0,0 +1,779 @@
+{
+  "name": "ios-japanese-romaji",
+  "browser": "safari-ios",
+  "keyboard": "Japanese Romaji, iOS 27.2 simulator",
+  "ua": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Mobile/15E148 Safari/604.1",
+  "recordedAt": "2026-11-14T21:43:23.167Z",
+  "settings": {
+    "autoCloseBrackets": false,
+    "autoIndent": false
+  },
+  "initial": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29",
+    "selection": [233, 233]
+  },
+  "events": [
+    {
+      "t": 5,
+      "type": "sync",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 14095,
+      "type": "focus",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 0,
+        "end": 0
+      }
+    },
+    {
+      "t": 17140,
+      "type": "keydown",
+      "key": "n",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 17190,
+      "type": "compositionstart",
+      "data": "",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 17190,
+      "type": "compositionupdate",
+      "data": "n",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 17234,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "n",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 17322,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "n",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):n\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 17323,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):n\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 17756,
+      "type": "keydown",
+      "key": "i",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):n\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 17800,
+      "type": "compositionupdate",
+      "data": "に",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):n\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 17800,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "に",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):n\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 18011,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "に",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):に\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 18085,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):に\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 18098,
+      "type": "keydown",
+      "key": "h",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):に\n    total = value + 11",
+        "start": 42,
+        "end": 42
+      }
+    },
+    {
+      "t": 18103,
+      "type": "compositionupdate",
+      "data": "にh",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):に\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 18103,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "にh",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):に\n    total = value + 11",
+        "start": 41,
+        "end": 42
+      }
+    },
+    {
+      "t": 18103,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "にh",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にh\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18104,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にh\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 18333,
+      "type": "keydown",
+      "key": "o",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にh\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 18383,
+      "type": "compositionupdate",
+      "data": "にほ",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にh\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18384,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "にほ",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にh\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18392,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "にほ",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほ\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18439,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほ\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 18749,
+      "type": "keydown",
+      "key": "n",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほ\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 18757,
+      "type": "compositionupdate",
+      "data": "にほn",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほ\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18758,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "にほn",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほ\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 18759,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "にほn",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほn\n    total = value + 11",
+        "start": 41,
+        "end": 44
+      }
+    },
+    {
+      "t": 18760,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほn\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 61452,
+      "type": "compositionupdate",
+      "data": "日本",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほn\n    total = value + 11",
+        "start": 41,
+        "end": 44
+      }
+    },
+    {
+      "t": 61665,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "日本",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):にほn\n    total = value + 11",
+        "start": 41,
+        "end": 44
+      }
+    },
+    {
+      "t": 61766,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "日本",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 61878,
+      "type": "beforeinput",
+      "inputType": "deleteCompositionText",
+      "data": null,
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 41,
+        "end": 43
+      }
+    },
+    {
+      "t": 61889,
+      "type": "input",
+      "inputType": "deleteCompositionText",
+      "data": null,
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 61957,
+      "type": "beforeinput",
+      "inputType": "insertFromComposition",
+      "data": "日本",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):\n    total = value + 11",
+        "start": 41,
+        "end": 41
+      }
+    },
+    {
+      "t": 61961,
+      "type": "input",
+      "inputType": "insertFromComposition",
+      "data": "日本",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 61970,
+      "type": "compositionend",
+      "data": "日本",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 61978,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 62252,
+      "type": "keydown",
+      "key": "g",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 62268,
+      "type": "compositionstart",
+      "data": "",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 62268,
+      "type": "compositionupdate",
+      "data": "g",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 62268,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "g",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 62271,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "g",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本g\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 62287,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本g\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 62583,
+      "type": "keydown",
+      "key": "o",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本g\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 62591,
+      "type": "compositionupdate",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本g\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 62591,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本g\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 62604,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 62630,
+      "type": "selectionchange",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 63532,
+      "type": "compositionupdate",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 63532,
+      "type": "beforeinput",
+      "inputType": "insertCompositionText",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 63532,
+      "type": "input",
+      "inputType": "insertCompositionText",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 63533,
+      "type": "beforeinput",
+      "inputType": "deleteCompositionText",
+      "data": null,
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 43,
+        "end": 44
+      }
+    },
+    {
+      "t": 63533,
+      "type": "input",
+      "inputType": "deleteCompositionText",
+      "data": null,
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 63533,
+      "type": "beforeinput",
+      "inputType": "insertFromComposition",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 63534,
+      "type": "input",
+      "inputType": "insertFromComposition",
+      "data": "ご",
+      "isComposing": true,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 63572,
+      "type": "compositionend",
+      "data": "ご",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 63572,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 64500,
+      "type": "keydown",
+      "key": "Backspace",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 64518,
+      "type": "beforeinput",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本ご\n    total = value + 11",
+        "start": 44,
+        "end": 44
+      }
+    },
+    {
+      "t": 64519,
+      "type": "input",
+      "inputType": "deleteContentBackward",
+      "data": null,
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 64520,
+      "type": "selectionchange",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    },
+    {
+      "t": 65568,
+      "type": "blur",
+      "isComposing": false,
+      "windowStart": 192,
+      "ta": {
+        "value": "    total = value + 9\ndef step_10(value):日本\n    total = value + 11",
+        "start": 43,
+        "end": 43
+      }
+    }
+  ],
+  "expected": {
+    "text": "def step_0(value):\n    total = value + 1\n    total = value + 2\n    total = value + 3\n    total = value + 4\ndef step_5(value):\n    total = value + 6\n    total = value + 7\n    total = value + 8\n    total = value + 9\ndef step_10(value):日本\n    total = value + 11\n    total = value + 12\n    total = value + 13\n    total = value + 14\ndef step_15(value):\n    total = value + 16\n    total = value + 17\n    total = value + 18\n    total = value + 19\ndef step_20(value):\n    total = value + 21\n    total = value + 22\n    total = value + 23\n    total = value + 24\ndef step_25(value):\n    total = value + 26\n    total = value + 27\n    total = value + 28\n    total = value + 29"
+  }
+}
diff --git a/tests/ime-web/recorder/recorder.js b/tests/ime-web/recorder/recorder.js
index bd4fa3e..ef2ac81 100644
--- a/tests/ime-web/recorder/recorder.js
+++ b/tests/ime-web/recorder/recorder.js
@@ -8,7 +8,12 @@ const INITIAL_CARET = SAMPLE.indexOf('\n', SAMPLE.indexOf('step_10'));
 const ta = document.getElementById('ta');
 const statusLine = document.getElementById('status');
 const shown = document.getElementById('doc');
-const suggest = new URLSearchParams(location.search).has('suggest');
+const params = new URLSearchParams(location.search);
+const suggest = params.has('suggest');
+// The form fields can come from the URL, for keyboards that cannot type them in Latin letters.
+for (const field of ['name', 'browser', 'keyboard']) {
+  if (params.has(field)) document.getElementById(field).value = params.get(field);
+}
 for (const [name, on, off] of [
   ['autocomplete', 'on', 'off'],
   ['autocorrect', 'on', 'off'],

From 20e9c2fbb2387554216d3e15d756c21437aac467 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sat, 14 Nov 2026 23:09:26 +0100
Subject: [PATCH 03/23] fix(web): load the language a markdown fence names

A fence for a language that no injection query names, like go, stayed
plain until the editor's language changed, because the engine cached the
failed lookup. The view now loads the languages its engine could not find
and has the engine look them up again, once per language that registers.
---
 cpp/core/include/codepad.h       |  2 +
 cpp/core/src/engine.cpp          | 21 +++++++++
 cpp/web/host.cpp                 | 32 +++++++++++++-
 src/web/EditorView.ts            | 41 ++++++++++++++++-
 src/web/__tests__/fences.test.ts | 75 ++++++++++++++++++++++++++++++++
 src/web/__tests__/loader.test.ts | 18 ++++++++
 src/web/core/EditorCore.ts       | 17 ++++++++
 src/web/core/module.ts           |  2 +
 src/web/loader.ts                | 24 ++++++++++
 tests/web/render.e2e.mjs         | 59 +++++++++++++++++++++++++
 10 files changed, 288 insertions(+), 3 deletions(-)
 create mode 100644 src/web/__tests__/fences.test.ts

diff --git a/cpp/core/include/codepad.h b/cpp/core/include/codepad.h
index df532c9..e26e0d7 100644
--- a/cpp/core/include/codepad.h
+++ b/cpp/core/include/codepad.h
@@ -305,6 +305,8 @@ CP_API cp_engine *cp_engine_new(const cp_host *host, int64_t budget_micros,
                                 void (*on_snapshot)(void *ctx, cp_snapshot *snapshot));
 // NULL clears the language. A snapshot still in flight keeps the language it was parsed with.
 CP_API void cp_engine_set_language(cp_engine *engine, const cp_language *language);
+// Looks up the injection names that found no language again and repaints, once the host resolves more of them.
+CP_API void cp_engine_refresh_injections(cp_engine *engine);
 // Frees the snapshot on the worker, or on the calling thread once the engine is closed. engine may be NULL then.
 CP_API void cp_engine_release(cp_engine *engine, cp_snapshot *snapshot);
 // No engine work runs after it. The engine frees itself on the worker.
diff --git a/cpp/core/src/engine.cpp b/cpp/core/src/engine.cpp
index a10c6ce..4b0d5d6 100644
--- a/cpp/core/src/engine.cpp
+++ b/cpp/core/src/engine.cpp
@@ -234,6 +234,25 @@ struct Engine : std::enable_shared_from_this {
     });
   }
 
+  // Forgets the names that resolved to nothing, then runs the injection pass over the whole text.
+  void refresh_injections() {
+    submit([this] {
+      bool forgot = false;
+      for (auto it = resolved.begin(); it != resolved.end();) {
+        if (it->second) {
+          ++it;
+          continue;
+        }
+        it = resolved.erase(it);
+        forgot = true;
+      }
+      if (!forgot || !text) return;
+      dirty.push_back(0);
+      dirty.push_back(static_cast(text->length()));
+      reparse();
+    });
+  }
+
   // Main thread. Returns the new epoch, 0 once closed.
   uint64_t attach(SharedText next, int32_t rev) {
     if (shut) return 0;
@@ -712,6 +731,8 @@ extern "C" void cp_engine_set_language(cp_engine *engine, const cp_language *lan
   engine->engine->set_language(language);
 }
 
+extern "C" void cp_engine_refresh_injections(cp_engine *engine) { engine->engine->refresh_injections(); }
+
 extern "C" void cp_engine_release(cp_engine *engine, cp_snapshot *snapshot) {
   if (!snapshot) return;
   if (engine) {
diff --git a/cpp/web/host.cpp b/cpp/web/host.cpp
index 4bb17b2..164a7fa 100644
--- a/cpp/web/host.cpp
+++ b/cpp/web/host.cpp
@@ -3,6 +3,7 @@
 #include 
 #include 
 
+#include 
 #include 
 #include 
 #include 
@@ -31,6 +32,8 @@ struct Editor {
   bool closed = false;
   std::vector changes;
   std::vector text;
+  // Injection names that found no language, in the order the engine asked.
+  std::vector missed;
 };
 
 std::deque worker_q;
@@ -64,12 +67,17 @@ const cp_language *find(const std::string &id) {
 }
 
 // An injection name, lowercased. A loaded id wins over the aliases, like LanguageRegistry.canonicalInjectionId.
-const cp_language *resolve(void *, const char *name) {
+// A name that finds nothing is kept for the page, which may load its language, unless an alias says it never injects.
+const cp_language *resolve(void *ctx, const char *name) {
   std::string lower(name ? name : "");
   for (char &c : lower) c = static_cast(tolower(static_cast(c)));
   if (const cp_language *language = find(lower)) return language;
   auto it = aliases.find(lower);
-  return it == aliases.end() || it->second.empty() ? nullptr : find(it->second);
+  if (it != aliases.end() && it->second.empty()) return nullptr;
+  const cp_language *found = it == aliases.end() ? nullptr : find(it->second);
+  auto &missed = static_cast(ctx)->missed;
+  if (!found && std::find(missed.begin(), missed.end(), lower) == missed.end()) missed.push_back(lower);
+  return found;
 }
 
 void on_change(void *ctx, const cp_change *c, const cp_unit *removed, const cp_unit *inserted, int32_t origin) {
@@ -205,6 +213,26 @@ CPW int32_t cpw_snapshot_count(int32_t e) {
   return ed ? ed->snapshots : 0;
 }
 
+// The injection names that found no language since the last call, joined by newlines. Returns the bytes they take,
+// and keeps them for the next call when that is more than cap.
+CPW int32_t cpw_take_missed(int32_t e, char *out, int32_t cap) {
+  Editor *ed = at(e);
+  if (!ed) return 0;
+  std::string joined;
+  for (const std::string &name : ed->missed) joined += (joined.empty() ? "" : "\n") + name;
+  auto size = static_cast(joined.size());
+  if (size > cap) return size;
+  memcpy(out, joined.data(), joined.size());
+  ed->missed.clear();
+  return size;
+}
+
+// Looks the editor's missing injection names up again, after a language they may name registered.
+CPW void cpw_refresh(int32_t e) {
+  Editor *ed = at(e);
+  if (ed && ed->engine) cp_engine_refresh_injections(ed->engine);
+}
+
 // Pins the editor's history clock to millis, for tests. Below zero follows the page clock again.
 CPW void cpw_set_clock(int32_t e, double millis) {
   if (Editor *ed = at(e)) ed->clock = millis;
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 34f874d..fc10d39 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -5,7 +5,7 @@ import { EditorCore, type WebChange } from './core/EditorCore';
 import { Layout } from './core/Layout';
 import type { CoreModule } from './core/module';
 import { type DecodedFrame, decodeFrame } from './frame';
-import { ensureLanguage } from './loader';
+import { ensureInjected, ensureLanguage, onRegistered } from './loader';
 import { registerView, requestPump } from './pump';
 import { type CssTheme, cssTheme } from './theme';
 
@@ -91,6 +91,7 @@ export class EditorView {
   private language = '';
   private languageReady = false;
   private appliedRevision = -1;
+  private drawnSnapshot = 0;
   private seenSnapshots = 0;
   private dirty = true;
   private destroyed = false;
@@ -105,6 +106,12 @@ export class EditorView {
   private frameText = 0;
   private frameTextCap = 0;
   private readonly onScrollEvent = () => this.invalidate();
+  // Injection names the engine found no language for, and the ids this view already refreshed after.
+  private readonly missed = new Set();
+  private readonly refreshedFor = new Set();
+  private readonly offRegistered = onRegistered(() => {
+    if (this.missed.size) this.loadMissed();
+  });
 
   constructor(host: HTMLElement, m: CoreModule, text = '') {
     this.m = m;
@@ -175,6 +182,8 @@ export class EditorView {
     if (id === this.language) return;
     this.language = id;
     this.languageReady = false;
+    this.missed.clear();
+    this.refreshedFor.clear();
     this.core.setLanguage('');
     this.invalidate();
     if (!id) return;
@@ -262,10 +271,12 @@ export class EditorView {
     if (this.core.snapshotCount !== this.seenSnapshots) {
       this.seenSnapshots = this.core.snapshotCount;
       this.dirty = true;
+      this.loadMissed();
     }
     if (!this.dirty) return;
     this.dirty = false;
     this.configure();
+    this.restaleRefreshed();
     const [sx, sy] = this.scrollPosition();
     this.layout.beginDraw(sx, sy);
     let moved = false;
@@ -288,6 +299,7 @@ export class EditorView {
     if (this.destroyed) return;
     this.destroyed = true;
     this.unregister();
+    this.offRegistered();
     this.listenToPage(false);
     this.resize?.disconnect();
     document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent);
@@ -306,6 +318,33 @@ export class EditorView {
     requestPump();
   }
 
+  // A new snapshot at the drawn revision comes from a refresh: its colors changed with no edit, so every cached line
+  // is queried again, since the frame skips a line already at the snapshot's revision.
+  private restaleRefreshed(): void {
+    const snapshot = this.languageReady ? this.core.snapshot : 0;
+    if (snapshot === this.drawnSnapshot) return;
+    this.drawnSnapshot = snapshot;
+    if (snapshot === 0 || this.snapshotInfo(snapshot).revision !== this.appliedRevision) return;
+    for (const entry of this.cache.values()) entry.revision = -1;
+  }
+
+  // Loads the languages the engine could not find, like a Markdown fence's, then has it look them up again.
+  // It refreshes once per language that registered, so a name that never resolves cannot loop.
+  private loadMissed(): void {
+    for (const name of this.core.takeMissedLanguages()) this.missed.add(name);
+    if (!this.missed.size) return;
+    const language = this.language;
+    ensureInjected(this.m, [...this.missed]).then((ids) => {
+      if (this.destroyed || this.language !== language) return;
+      const fresh = ids.filter((id) => !this.refreshedFor.has(id));
+      if (!fresh.length) return;
+      for (const id of fresh) this.refreshedFor.add(id);
+      this.missed.clear();
+      this.core.refreshInjections();
+      this.invalidate();
+    });
+  }
+
   private readonly remeasureEvent = () => this.remeasure();
 
   // A web font finished loading: every line is measured again.
diff --git a/src/web/__tests__/fences.test.ts b/src/web/__tests__/fences.test.ts
new file mode 100644
index 0000000..1824914
--- /dev/null
+++ b/src/web/__tests__/fences.test.ts
@@ -0,0 +1,75 @@
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { expect, test } from '@jest/globals';
+import {
+  builtCore,
+  cstring,
+  highlight,
+  loadCore,
+  loadGrammar,
+  pumpAll,
+  ROOT,
+} from '../../../tests/web/core';
+import { EditorCore } from '../core/EditorCore';
+
+const dir = builtCore('lib/web', 'yarn build:web');
+const grammar = (pkg: string, id: string) => ({
+  wasm: join(ROOT, `languages/${pkg}/web/${id}.wasm`),
+  queries: join(ROOT, `languages/${pkg}/queries/${id}`),
+});
+const markdown = grammar('markdown', 'markdown');
+const inline = grammar('markdown', 'markdown_inline');
+const python = grammar('python', 'python');
+const ready = dir !== null && [markdown, inline, python].every((g) => existsSync(g.wasm));
+if (dir && !ready)
+  console.warn('markdown or python grammar not built, run yarn build:web-grammars');
+
+const FENCE = '```python\ndef f(): pass\n```\n';
+
+(ready ? test : test.skip)('a fence colors once its language loads', async () => {
+  const m = await loadCore(dir as string);
+  loadGrammar(m, markdown.wasm, 'markdown', markdown.queries);
+  loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries);
+  const core = new EditorCore(m, FENCE);
+  const keyword = cstring(m, 'keyword.function', (name) => m._cp_style_id(name));
+  const fenceBody = () => {
+    const line = highlight(m, core.snapshot, 1, 1, core.lineStart(1))[0] as number[];
+    const triples = [];
+    for (let i = 0; i + 2 < line.length; i += 3) triples.push(line.slice(i, i + 3));
+    return triples;
+  };
+  expect(core.setLanguage('markdown')).toBe(true);
+  pumpAll(m);
+  expect(core.takeMissedLanguages()).toEqual(['python']);
+  expect(fenceBody()).not.toContainEqual([0, 3, keyword]);
+
+  loadGrammar(m, python.wasm, 'python', python.queries);
+  core.refreshInjections();
+  pumpAll(m);
+  expect(fenceBody()).toContainEqual([0, 3, keyword]);
+  expect(core.takeMissedLanguages()).toEqual([]);
+  core.close();
+  pumpAll(m);
+});
+
+// The loader refreshes only after a new language registers, since a refresh looks the names up again.
+(ready ? test : test.skip)(
+  'a refresh while the language is still missing reports it again',
+  async () => {
+    const m = await loadCore(dir as string);
+    loadGrammar(m, markdown.wasm, 'markdown', markdown.queries);
+    loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries);
+    const core = new EditorCore(m, FENCE);
+    core.setLanguage('markdown');
+    pumpAll(m);
+    expect(core.takeMissedLanguages()).toEqual(['python']);
+    const before = core.snapshotCount;
+    core.refreshInjections();
+    pumpAll(m);
+    expect(core.takeMissedLanguages()).toEqual(['python']);
+    expect(core.takeMissedLanguages()).toEqual([]);
+    expect(core.snapshotCount).toBe(before + 1);
+    core.close();
+    pumpAll(m);
+  },
+);
diff --git a/src/web/__tests__/loader.test.ts b/src/web/__tests__/loader.test.ts
index 5063df5..692319a 100644
--- a/src/web/__tests__/loader.test.ts
+++ b/src/web/__tests__/loader.test.ts
@@ -226,3 +226,21 @@ test('retries languages.json when its body was cut off by a network error', asyn
   dropped.clear();
   await expect(loader.ensureLanguage(m, 'python')).resolves.toBe(true);
 });
+
+test('loads the installed languages a fence names and resolves with them', async () => {
+  const m = await loader.loadCore();
+  await expect(loader.ensureInjected(m, ['Python', 'py', 'rust'])).resolves.toEqual(['python']);
+  expect(loaded).toEqual(['python']);
+  expect(warn).not.toHaveBeenCalled();
+});
+
+test('tells each listener once when a language registers, whatever loaded it', async () => {
+  const m = await loader.loadCore();
+  const heard: string[] = [];
+  const off = loader.onRegistered((id) => heard.push(id));
+  await loader.ensureLanguage(m, 'python');
+  await loader.ensureInjected(m, ['python']);
+  off();
+  await loader.ensureLanguage(m, 'css');
+  expect(heard).toEqual(['python']);
+});
diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts
index ac3647b..da788e2 100644
--- a/src/web/core/EditorCore.ts
+++ b/src/web/core/EditorCore.ts
@@ -413,6 +413,23 @@ export class EditorCore {
     return this.m._cpw_snapshot_count(this.index);
   }
 
+  // The injection names that found no language since the last call, so the page can load them.
+  takeMissedLanguages(): string[] {
+    for (let cap = 256; ; ) {
+      const out = this.m._malloc(cap);
+      const size = this.m._cpw_take_missed(this.index, out, cap);
+      const joined = size > 0 && size <= cap ? this.m.UTF8ToString(out, size) : '';
+      this.m._free(out);
+      if (size <= cap) return joined ? joined.split('\n') : [];
+      cap = size;
+    }
+  }
+
+  // Looks the missing injection names up again and repaints, after a language they may name registered.
+  refreshInjections(): void {
+    this.m._cpw_refresh(this.index);
+  }
+
   // Pins the history clock to millis, for tests and recordings. Below zero follows the page clock.
   setClock(millis: number): void {
     this.m._cpw_set_clock(this.index, millis);
diff --git a/src/web/core/module.ts b/src/web/core/module.ts
index 675d396..12c6ccb 100644
--- a/src/web/core/module.ts
+++ b/src/web/core/module.ts
@@ -33,6 +33,8 @@ export interface CoreModule {
   _cpw_layout(e: number): Ptr;
   _cpw_snapshot(e: number): Ptr;
   _cpw_snapshot_count(e: number): number;
+  _cpw_take_missed(e: number, out: Ptr, cap: number): number;
+  _cpw_refresh(e: number): void;
   _cpw_set_clock(e: number, millis: number): void;
   _cpw_pump(budgetMs: number): number;
   _cpw_take_changes(
diff --git a/src/web/loader.ts b/src/web/loader.ts
index 4b81d25..1b2e313 100644
--- a/src/web/loader.ts
+++ b/src/web/loader.ts
@@ -23,6 +23,29 @@ let manifest: Promise | null = null;
 let ids: string[] = [];
 // Each language registered on its own, resolving to the ids its injection query names, or null when it failed.
 const languages = new Map>();
+const registered = new Set<(id: string) => void>();
+
+// Calls the listener with each language id the first time it registers, and returns its removal.
+export function onRegistered(listener: (id: string) => void): () => void {
+  registered.add(listener);
+  return () => {
+    registered.delete(listener);
+  };
+}
+
+// Loads the installed languages that injection names map to, and resolves with the ids now registered.
+export async function ensureInjected(m: CoreModule, names: string[]): Promise {
+  const list = await loadManifest().catch(() => null);
+  if (!list) return [];
+  const installed = (id: string) => list.languages.some((l) => l.id === id);
+  const ids = new Set();
+  for (const name of names) {
+    const id = canonicalInjectionId(name, installed);
+    if (id && installed(id)) ids.add(id);
+  }
+  const loaded = await Promise.all([...ids].map((id) => ensureLanguage(m, id)));
+  return [...ids].filter((_, i) => loaded[i]);
+}
 
 // The page's one core, injected by a script tag from the assets folder on first use.
 export function loadCore(): Promise {
@@ -186,6 +209,7 @@ async function loadLanguage(m: CoreModule, id: string): Promise
     );
     return null;
   }
+  for (const listener of [...registered]) listener(id);
   return [...injected];
 }
 
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index a027971..f3f4fc5 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -445,5 +445,64 @@ for (const engine of [chromium, webkit]) {
       assert.deepEqual(errors, []);
       await page.close();
     });
+
+    // The color of "func" in a Go fence, a language no injection query names, so only the fence loads it.
+    async function fenceKeywordColor(page, hosts) {
+      return page.evaluate(async (ids) => {
+        const { EditorView, loadCore, until } = window.codepad;
+        const m = await loadCore();
+        const text = '# Title\n```go\nfunc f() {}\n```\n';
+        const def = (id) =>
+          [...document.querySelectorAll(`#${id} [data-line="2"] span`)].find(
+            (s) => s.textContent === 'func',
+          );
+        const colors = [];
+        for (const id of ids) {
+          new EditorView(document.getElementById(id), m, text).setLanguage('markdown');
+          await until(() => def(id) && getComputedStyle(def(id)).color !== 'rgb(31, 35, 40)');
+          colors.push(getComputedStyle(def(id)).color);
+        }
+        return colors;
+      }, hosts);
+    }
+
+    test('a markdown fence colors go, which no injection query names', async () => {
+      const { page, errors } = await open();
+      assert.deepEqual(await fenceKeywordColor(page, ['a']), [KEYWORD]);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('a second markdown editor colors the same fence', async () => {
+      const { page, errors } = await open();
+      assert.deepEqual(await fenceKeywordColor(page, ['a', 'b']), [KEYWORD, KEYWORD]);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('a fence naming a language that is not installed draws plain and refreshes nothing', async () => {
+      const { page, errors } = await open();
+      const refreshes = await page.evaluate(async () => {
+        const { EditorView, frames, loadCore, until } = window.codepad;
+        const view = new EditorView(
+          document.getElementById('a'),
+          await loadCore(),
+          '```zig\nconst x = 1;\n```\n',
+        );
+        let count = 0;
+        const refresh = view.core.refreshInjections.bind(view.core);
+        view.core.refreshInjections = () => {
+          count++;
+          refresh();
+        };
+        view.setLanguage('markdown');
+        await until(() => view.core.snapshotCount > 0);
+        await frames(10);
+        return count;
+      });
+      assert.equal(refreshes, 0);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
   });
 }

From b7da020a9884adcbc6de4142d1c17daac40f2d6a Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sat, 14 Nov 2026 23:16:21 +0100
Subject: [PATCH 04/23] feat(web): map the keyboard's textarea onto the core

---
 src/web/__tests__/ime-web.test.ts       | 102 ++++++++++++++
 src/web/__tests__/input-session.test.ts | 138 +++++++++++++++++++
 src/web/core/EditorCore.ts              |  13 ++
 src/web/core/module.ts                  |   3 +
 src/web/input/WebInputSession.ts        | 171 ++++++++++++++++++++++++
 src/web/input/window.ts                 |  18 +++
 6 files changed, 445 insertions(+)
 create mode 100644 src/web/__tests__/ime-web.test.ts
 create mode 100644 src/web/__tests__/input-session.test.ts
 create mode 100644 src/web/input/WebInputSession.ts
 create mode 100644 src/web/input/window.ts

diff --git a/src/web/__tests__/ime-web.test.ts b/src/web/__tests__/ime-web.test.ts
new file mode 100644
index 0000000..eff031c
--- /dev/null
+++ b/src/web/__tests__/ime-web.test.ts
@@ -0,0 +1,102 @@
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { expect, test } from '@jest/globals';
+import { builtCore, loadCore, ROOT } from '../../../tests/web/core';
+import { EditorCore } from '../core/EditorCore';
+import { type TextareaState, WebInputSession } from '../input/WebInputSession';
+
+type Event = {
+  type: string;
+  inputType?: string;
+  data?: string | null;
+  isComposing: boolean;
+  windowStart: number;
+  ta: TextareaState;
+};
+type Recording = {
+  settings: { autoCloseBrackets: boolean; autoIndent: boolean };
+  initial: { text: string; selection: [number, number] };
+  events: Event[];
+  expected: { text: string };
+};
+
+const dir = builtCore('lib/web', 'yarn build:web');
+const folder = join(ROOT, 'tests/ime-web');
+const files = existsSync(folder)
+  ? readdirSync(folder)
+      .filter((f) => f.endsWith('.json'))
+      .sort()
+  : [];
+if (files.length === 0) console.warn('tests/ime-web holds no recording');
+
+const state = (ta: TextareaState): TextareaState => ({
+  value: ta.value,
+  start: ta.start,
+  end: ta.end,
+});
+
+// Replays what a browser keyboard did into a recorded textarea and checks the core after every edit.
+for (const file of files) {
+  (dir ? test : test.skip)(file.replace(/\.json$/, ''), async () => {
+    const r = JSON.parse(readFileSync(join(folder, file), 'utf8')) as Recording;
+    const core = new EditorCore(await loadCore(dir as string), r.initial.text);
+    core.settings = { ...core.settings, ...r.settings };
+    core.setSelection(r.initial.selection[0], r.initial.selection[1]);
+    const session = new WebInputSession(core, (edit) => edit());
+    let model = r.initial.text;
+    let value = '';
+    let first = true;
+    // The textarea state the session asked the page to write, until the recording shows the page writing it.
+    let pending: TextareaState | null = null;
+    for (const [i, e] of r.events.entries()) {
+      const at = `event ${i} ${e.type} ${e.inputType ?? ''}`;
+      if (e.type === 'sync') {
+        const got = first ? session.sync() : pending;
+        expect({ at, got, windowStart: session.windowStart }).toEqual({
+          at,
+          got: state(e.ta),
+          windowStart: e.windowStart,
+        });
+        first = false;
+        pending = null;
+        value = e.ta.value;
+      } else if (e.type === 'beforeinput') {
+        session.beforeInput(e.ta);
+      } else if (e.type === 'input') {
+        expect({ at, unwritten: pending }).toEqual({ at, unwritten: null });
+        pending = session.input(
+          { inputType: e.inputType ?? '', data: e.data ?? null, isComposing: e.isComposing },
+          e.ta,
+        );
+        model =
+          model.slice(0, e.windowStart) + e.ta.value + model.slice(e.windowStart + value.length);
+        value = e.ta.value;
+        expect({ at, text: core.text() }).toEqual({ at, text: model });
+        if (e.isComposing) {
+          const c = session.composing;
+          if (e.inputType === 'insertCompositionText')
+            expect({ at, composed: c && core.text(c.start, c.end) }).toEqual({
+              at,
+              composed: e.data,
+            });
+        } else {
+          const { anchor, head } = core.selection;
+          expect({ at, selection: [Math.min(anchor, head), Math.max(anchor, head)] }).toEqual({
+            at,
+            selection: [e.windowStart + e.ta.start, e.windowStart + e.ta.end],
+          });
+        }
+      } else if (e.type === 'compositionstart') {
+        session.compositionStart(e.ta);
+      } else if (e.type === 'compositionend') {
+        pending = session.compositionEnd(e.ta) ?? pending;
+      } else if (e.type === 'selectionchange') {
+        pending = session.selectionChange(e.ta) ?? pending;
+      } else if (e.type === 'blur') {
+        session.finishComposition();
+      }
+    }
+    expect(core.text()).toBe(r.expected.text);
+    core.close();
+  });
+}
diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts
new file mode 100644
index 0000000..30738cb
--- /dev/null
+++ b/src/web/__tests__/input-session.test.ts
@@ -0,0 +1,138 @@
+import { expect, test } from '@jest/globals';
+import { builtCore, loadCore } from '../../../tests/web/core';
+import { EditorCore, type EditorSettings } from '../core/EditorCore';
+import { type InputLike, type TextareaState, WebInputSession } from '../input/WebInputSession';
+import { WINDOW_CAP } from '../input/window';
+
+const dir = builtCore('lib/web', 'yarn build:web');
+const run = dir ? test : test.skip;
+
+async function open(text: string, caret: number, settings: Partial = {}) {
+  const core = new EditorCore(await loadCore(dir as string), text);
+  core.settings = { ...core.settings, ...settings };
+  core.setClock(1000);
+  core.setSelection(caret, caret);
+  const s = new WebInputSession(core, (edit) => edit());
+  s.sync();
+  return { core, s };
+}
+
+const ta = (value: string, start: number, end = start): TextareaState => ({ value, start, end });
+const typed = (data: string): InputLike => ({ inputType: 'insertText', data, isComposing: false });
+const composed = (data: string): InputLike => ({
+  inputType: 'insertCompositionText',
+  data,
+  isComposing: true,
+});
+const back: InputLike = { inputType: 'deleteContentBackward', data: null, isComposing: false };
+const enter: InputLike = { inputType: 'insertLineBreak', data: null, isComposing: false };
+
+// Types one character the way a browser reports it, from the textarea before to the textarea after.
+function type(s: WebInputSession, before: TextareaState, after: TextareaState, data: string) {
+  s.beforeInput(before);
+  return s.input(typed(data), after);
+}
+
+run('a typed ( closes the pair and asks for a new window', async () => {
+  const { core, s } = await open('', 0);
+  expect(type(s, ta('', 0), ta('(', 1), '(')).toEqual(ta('()', 1));
+  expect(core.text()).toBe('()');
+  expect(core.selection).toEqual({ anchor: 1, head: 1 });
+});
+
+run('Enter keeps the indent', async () => {
+  const { core, s } = await open('  a', 3);
+  s.beforeInput(ta('  a', 3));
+  s.input(enter, ta('  a\n', 4));
+  expect(core.text()).toBe('  a\n  ');
+  expect(core.selection.head).toBe(6);
+});
+
+run('Enter before an existing newline lands at the caret', async () => {
+  const { core, s } = await open('a\nb', 1, { autoIndent: false });
+  s.beforeInput(ta('a\nb', 1));
+  s.input(enter, ta('a\n\nb', 2));
+  expect(core.text()).toBe('a\n\nb');
+  expect(core.selection.head).toBe(2);
+});
+
+run('Backspace inside an auto-closed pair deletes both', async () => {
+  const { core, s } = await open('', 0);
+  type(s, ta('', 0), ta('(', 1), '(');
+  s.beforeInput(ta('()', 1));
+  s.input(back, ta(')', 0));
+  expect(core.text()).toBe('');
+});
+
+// The core starts a new undo step at a word boundary, as native does, so the emoji is a step of its own.
+run('a typed emoji goes in whole and one undo takes it out whole', async () => {
+  const { core, s } = await open('', 0);
+  type(s, ta('', 0), ta('a', 1), 'a');
+  type(s, ta('a', 1), ta('a😀', 3), '😀');
+  expect(core.text()).toBe('a😀');
+  expect(core.selection).toEqual({ anchor: 3, head: 3 });
+  core.undo();
+  expect(core.text()).toBe('a');
+});
+
+run('Backspace after an emoji removes both units', async () => {
+  const { core, s } = await open('a😀', 3);
+  s.beforeInput(ta('a😀', 3));
+  s.input(back, ta('a', 1));
+  expect(core.text()).toBe('a');
+  expect(core.selection).toEqual({ anchor: 1, head: 1 });
+});
+
+run('a composed word undoes in one step', async () => {
+  const { core, s } = await open('ab', 2);
+  s.compositionStart(ta('ab', 2));
+  s.beforeInput(ta('ab', 2));
+  expect(s.input(composed('k'), ta('abk', 3))).toBeNull();
+  s.beforeInput(ta('abk', 2, 3));
+  expect(s.input(composed('か'), ta('abか', 3))).toBeNull();
+  expect(s.composing).toEqual({ start: 2, end: 3 });
+  s.compositionEnd(ta('abか', 3));
+  expect(s.composing).toBeNull();
+  core.undo();
+  expect(core.text()).toBe('ab');
+});
+
+run('a quote typed inside a composition does not auto-close', async () => {
+  const { core, s } = await open('', 0);
+  s.compositionStart(ta('', 0));
+  expect(s.input(composed("don'"), ta("don'", 4))).toBeNull();
+  expect(core.text()).toBe("don'");
+});
+
+run('typing over a selection longer than the window replaces all of it', async () => {
+  const { core, s } = await open('a'.repeat(20000), 0);
+  core.selectAll();
+  const window = s.sync() as TextareaState;
+  expect(window.value.length).toBeLessThanOrEqual(WINDOW_CAP);
+  expect([window.start, window.end]).toEqual([0, window.value.length]);
+  s.beforeInput(window);
+  s.input(typed('x'), ta('x', 1));
+  expect(core.text()).toBe('x');
+});
+
+run('a ref edit during a composition ends it', async () => {
+  const { core, s } = await open('ab', 2);
+  s.compositionStart(ta('ab', 2));
+  s.input(composed('か'), ta('abか', 3));
+  s.external();
+  core.replace(0, 0, 'Z');
+  expect(s.composing).toBeNull();
+  expect(s.sync()).toEqual(ta('Zabか', 4));
+  core.undo();
+  expect(core.text()).toBe('abか');
+});
+
+run('blur mid-composition keeps the text and closes the group', async () => {
+  const { core, s } = await open('ab', 2);
+  s.compositionStart(ta('ab', 2));
+  s.input(composed('か'), ta('abか', 3));
+  s.finishComposition();
+  type(s, ta('abか', 3), ta('abかx', 4), 'x');
+  core.undo();
+  expect(core.text()).toBe('abか');
+});
diff --git a/src/web/core/EditorCore.ts b/src/web/core/EditorCore.ts
index da788e2..5a8c4c3 100644
--- a/src/web/core/EditorCore.ts
+++ b/src/web/core/EditorCore.ts
@@ -305,6 +305,19 @@ export class EditorCore {
     this.m._cp_editor_set_selection(this.handle, clampInt(anchor), clampInt(head));
   }
 
+  // Edits between beginGroup and endGroup undo as one step, as a keyboard's composed word does.
+  beginGroup(): void {
+    this.m._cp_editor_begin_group(this.handle);
+  }
+  endGroup(): void {
+    this.m._cp_editor_end_group(this.handle);
+  }
+
+  // True when a backspace at caret would take an auto-closed pair, like the caret between ( and ).
+  deletesPair(caret: number): boolean {
+    return this.m._cp_editor_deletes_pair(this.handle, clampUnsigned(caret)) !== 0;
+  }
+
   move(unit: MoveUnit, forward: boolean, extend: boolean): void {
     this.m._cp_editor_move(this.handle, MOVES.indexOf(unit), forward ? 1 : 0, extend ? 1 : 0);
   }
diff --git a/src/web/core/module.ts b/src/web/core/module.ts
index 12c6ccb..dcf93c7 100644
--- a/src/web/core/module.ts
+++ b/src/web/core/module.ts
@@ -74,6 +74,9 @@ export interface CoreModule {
   _cp_editor_type(ed: Ptr, text: Ptr, length: number): void;
   _cp_editor_command(ed: Ptr, command: number): number;
   _cp_editor_set_selection(ed: Ptr, anchor: number, head: number): void;
+  _cp_editor_begin_group(ed: Ptr): void;
+  _cp_editor_end_group(ed: Ptr): void;
+  _cp_editor_deletes_pair(ed: Ptr, caret: number): number;
   _cp_editor_move(ed: Ptr, unit: number, forward: number, extend: number): void;
   _cp_editor_select_word_at(ed: Ptr, offset: number): void;
   _cp_editor_selection(ed: Ptr): bigint;
diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts
new file mode 100644
index 0000000..36af68c
--- /dev/null
+++ b/src/web/input/WebInputSession.ts
@@ -0,0 +1,171 @@
+import type { EditorCore } from '../core/EditorCore';
+import { windowAround } from './window';
+
+// What the keyboard's textarea holds: its value and its selection, in textarea units.
+export type TextareaState = { value: string; start: number; end: number };
+export type InputLike = { inputType: string; data: string | null; isComposing: boolean };
+type Range = { start: number; end: number };
+
+const codePoints = (s: string) => [...s].length;
+
+// Maps a hidden textarea that holds a window of the document onto the core, the web twin of ImeSession.
+// Every method that can move the window returns the textarea state to write, or null.
+export class WebInputSession {
+  private win = { start: 0, value: '', line: 0 };
+  private before: Range | null = null;
+  private composed: Range | null = null;
+
+  constructor(
+    private readonly core: EditorCore,
+    private readonly apply: (edit: () => void) => void,
+  ) {}
+
+  get windowStart(): number {
+    return this.win.start;
+  }
+
+  // The document range the keyboard is composing, drawn underlined.
+  get composing(): Range | null {
+    return this.composed ? { ...this.composed } : null;
+  }
+
+  // The window around the core's selection, to write into the textarea. Null while composing.
+  sync(): TextareaState | null {
+    if (this.composed) return null;
+    const { start, end } = windowAround(this.core);
+    const { anchor, head } = this.core.selection;
+    this.win = { start, value: this.core.text(start, end), line: this.core.lineAt(head) };
+    // A selection longer than the window shows as the whole window selected.
+    const clamp = (offset: number) => Math.min(Math.max(offset - start, 0), end - start);
+    return {
+      value: this.win.value,
+      start: clamp(Math.min(anchor, head)),
+      end: clamp(Math.max(anchor, head)),
+    };
+  }
+
+  // The selection the edit replaces, which a diff alone cannot place (Enter before a newline).
+  beforeInput(ta: TextareaState): void {
+    this.before = { start: ta.start, end: ta.end };
+  }
+
+  input(e: InputLike, ta: TextareaState): TextareaState | null {
+    const old = this.win.value;
+    const next = ta.value;
+    const ws = this.win.start;
+    const sel = this.before ?? { start: ta.start, end: ta.start };
+    this.before = null;
+    let p = 0;
+    const pMax = Math.min(sel.start, ta.start, old.length, next.length);
+    while (p < pMax && old.charCodeAt(p) === next.charCodeAt(p)) p++;
+    let s = 0;
+    const sMax = Math.min(old.length - Math.max(sel.end, p), next.length - Math.max(ta.end, p));
+    while (s < sMax && old.charCodeAt(old.length - 1 - s) === next.charCodeAt(next.length - 1 - s))
+      s++;
+    let start = ws + p;
+    let end = ws + old.length - s;
+    const inserted = next.slice(p, next.length - s);
+    const { anchor, head } = this.core.selection;
+    const selStart = Math.min(anchor, head);
+    const selEnd = Math.max(anchor, head);
+    const winEnd = ws + old.length;
+    // A selection longer than the window goes whole, though the textarea held only its middle.
+    if (
+      selEnd > selStart &&
+      (selStart < ws || selEnd > winEnd) &&
+      start <= Math.max(selStart, ws) &&
+      end >= Math.min(selEnd, winEnd)
+    ) {
+      start = Math.min(start, selStart);
+      end = Math.max(end, selEnd);
+    }
+    const composing = this.composed !== null || e.isComposing;
+    const lengthBefore = this.core.length;
+    let coreCaret = false;
+    this.apply(() => {
+      const removed = this.core.text(start, end);
+      if (composing) {
+        this.core.inputReplace(start, end, inserted);
+        if (this.composed) this.composed = { start, end: start + inserted.length };
+        this.select(start + inserted.length, start + inserted.length);
+        coreCaret = true;
+      } else if (start === end && inserted === '\n') {
+        this.select(start, start);
+        this.core.insertNewline();
+        coreCaret = true;
+      } else if (start === end && codePoints(inserted) === 1) {
+        this.select(start, start);
+        this.core.typeText(inserted);
+        coreCaret = true;
+      } else if (
+        inserted === '' &&
+        codePoints(removed) === 1 &&
+        selStart === selEnd &&
+        end === selEnd &&
+        this.core.deletesPair(end)
+      ) {
+        this.core.inputReplace(start, end + 1, '', true);
+        coreCaret = true;
+      } else {
+        this.core.inputReplace(start, end, inserted, inserted === '' && codePoints(removed) === 1);
+      }
+      if (!coreCaret) this.select(ws + ta.start, ws + ta.end);
+    });
+    const coreWindow = this.core.text(ws, winEnd + this.core.length - lengthBefore);
+    const caret = this.core.selection;
+    const mirrors =
+      coreWindow === next &&
+      Math.min(caret.anchor, caret.head) === ws + ta.start &&
+      Math.max(caret.anchor, caret.head) === ws + ta.end;
+    if (composing) {
+      this.win.value = next;
+      return null;
+    }
+    if (!mirrors) return this.sync();
+    this.win.value = next;
+    return this.core.lineAt(caret.head) !== this.win.line ? this.sync() : null;
+  }
+
+  compositionStart(ta: TextareaState): void {
+    const ws = this.win.start;
+    this.composed = { start: ws + ta.start, end: ws + ta.end };
+    this.core.beginGroup();
+  }
+
+  compositionEnd(ta: TextareaState): TextareaState | null {
+    this.finishComposition();
+    return this.follow(ta);
+  }
+
+  // The user moved the caret in the textarea. Ignored while composing.
+  selectionChange(ta: TextareaState): TextareaState | null {
+    if (this.composed || ta.value !== this.win.value) return null;
+    const ws = this.win.start;
+    this.apply(() => this.select(ws + ta.start, ws + ta.end));
+    return this.follow(ta);
+  }
+
+  // The core is about to change from outside the keyboard: the composition ends first, so the edit undoes alone.
+  external(): void {
+    this.finishComposition();
+  }
+
+  finishComposition(): void {
+    if (!this.composed) return;
+    this.composed = null;
+    this.core.endGroup();
+  }
+
+  // A new window once the head left the window's middle line or the core no longer matches the textarea.
+  private follow(ta: TextareaState): TextareaState | null {
+    const ws = this.win.start;
+    const head = this.core.selection.head;
+    const same = this.core.text(ws, ws + ta.value.length) === ta.value;
+    return !same || this.core.lineAt(head) !== this.win.line ? this.sync() : null;
+  }
+
+  private select(anchor: number, head: number): void {
+    const s = this.core.selection;
+    if (s.anchor !== anchor || s.head !== head) this.core.setSelection(anchor, head);
+  }
+}
diff --git a/src/web/input/window.ts b/src/web/input/window.ts
new file mode 100644
index 0000000..b232bc1
--- /dev/null
+++ b/src/web/input/window.ts
@@ -0,0 +1,18 @@
+import type { EditorCore } from '../core/EditorCore';
+
+// The most text the keyboard's textarea holds, like the native text window.
+export const WINDOW_CAP = 8192;
+
+// The caret's line and its two neighbors, widened to the selection, at most WINDOW_CAP units around the head.
+export function windowAround(core: EditorCore): { start: number; end: number } {
+  const { anchor, head } = core.selection;
+  const first = Math.max(0, core.lineAt(Math.min(anchor, head)) - 1);
+  const last = Math.min(core.lineCount - 1, core.lineAt(Math.max(anchor, head)) + 1);
+  let start = core.lineStart(first);
+  let end = core.lineEnd(last);
+  if (end - start > WINDOW_CAP) {
+    start = Math.min(Math.max(start, head - WINDOW_CAP / 2), end - WINDOW_CAP);
+    end = start + WINDOW_CAP;
+  }
+  return { start, end };
+}

From 8ea9fac7e107e0d9e769e4dbdbc9eda814219af2 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sat, 14 Nov 2026 23:37:33 +0100
Subject: [PATCH 05/23] feat(web): type into the editor with a caret and focus

---
 src/web/CodeEditor.tsx                |  28 ++-
 src/web/EditorView.ts                 | 255 +++++++++++++++++++++++++-
 src/web/__tests__/CodeEditor.test.tsx |  26 +++
 src/web/input/InputHost.ts            | 136 ++++++++++++++
 tests/web/render.e2e.mjs              | 232 +++++++++++++++++++++++
 5 files changed, 662 insertions(+), 15 deletions(-)
 create mode 100644 src/web/input/InputHost.ts

diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx
index af7f339..385b196 100644
--- a/src/web/CodeEditor.tsx
+++ b/src/web/CodeEditor.tsx
@@ -82,6 +82,8 @@ export const CodeEditor = forwardRef(function Co
     onChange,
     onChangeText,
     onContentSizeChange,
+    onFocus,
+    onBlur,
   });
   handlers.current = {
     onReady,
@@ -90,6 +92,8 @@ export const CodeEditor = forwardRef(function Co
     onChange,
     onChangeText,
     onContentSizeChange,
+    onFocus,
+    onBlur,
   };
   const initial = useRef(initialValue);
 
@@ -113,6 +117,10 @@ export const CodeEditor = forwardRef(function Co
       insertSpaces,
       autoIndent,
       autoCloseBrackets,
+      suggestions,
+      autoFocus,
+      onFocus: () => handlers.current.onFocus?.(),
+      onBlur: () => handlers.current.onBlur?.(),
       onContentSize: (width, height) => handlers.current.onContentSizeChange?.({ width, height }),
       onScroll: (x, y, contentWidth, contentHeight) =>
         handlers.current.onScroll?.({ x, y, contentWidth, contentHeight }),
@@ -149,6 +157,8 @@ export const CodeEditor = forwardRef(function Co
       insertSpaces,
       autoIndent,
       autoCloseBrackets,
+      suggestions,
+      autoFocus,
     ],
   );
   const latest = useRef({ options, language });
@@ -196,13 +206,9 @@ export const CodeEditor = forwardRef(function Co
 
   useEffect(() => {
     if (avoidKeyboard) notYet('avoidKeyboard');
-    if (autoFocus) notYet('autoFocus');
-    if (suggestions !== 'off') notYet('suggestions');
     if (decorations) notYet('decorations');
     if (onGapLayout) notYet('onGapLayout');
-    if (onFocus) notYet('onFocus');
-    if (onBlur) notYet('onBlur');
-  }, [avoidKeyboard, autoFocus, suggestions, decorations, onGapLayout, onFocus, onBlur]);
+  }, [avoidKeyboard, decorations, onGapLayout]);
 
   useEffect(() => {
     view?.setOptions(options);
@@ -242,7 +248,7 @@ export const CodeEditor = forwardRef(function Co
       getVisibleLines: () => viewRef.current?.visibleLines() ?? { first: 0, last: 0 },
       canUndo: () => core()?.canUndo ?? false,
       canRedo: () => core()?.canRedo ?? false,
-      isFocused: () => false,
+      isFocused: () => viewRef.current?.focused ?? false,
       setText: (text, opts) => write((v) => v.core.setText(text, opts?.keepHistory ?? false)),
       setSelection: (sel) => write((v) => v.core.setSelection(sel.anchor, sel.head)),
       selectAll: () => write((v) => v.core.selectAll()),
@@ -263,8 +269,14 @@ export const CodeEditor = forwardRef(function Co
       cut: () => later('cut', undefined),
       copy: () => later('copy', undefined),
       paste: () => later('paste', undefined),
-      focus: () => later('focus', undefined),
-      blur: () => later('blur', undefined),
+      focus: () => {
+        viewRef.current?.focus();
+        return Promise.resolve();
+      },
+      blur: () => {
+        viewRef.current?.blur();
+        return Promise.resolve();
+      },
       setSearch: () => later('setSearch', { count: 0, limited: false }),
       findNext: () => later('findNext', null),
       findPrevious: () => later('findPrevious', null),
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index fc10d39..ea5df82 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -1,10 +1,12 @@
 /// 
 import { githubLight } from '../themes/githubLight';
-import type { ContentInsets, Rect, Theme } from '../types';
+import type { ContentInsets, Rect, Suggestions, Theme } from '../types';
 import { EditorCore, type WebChange } from './core/EditorCore';
 import { Layout } from './core/Layout';
 import type { CoreModule } from './core/module';
 import { type DecodedFrame, decodeFrame } from './frame';
+import { InputHost } from './input/InputHost';
+import { WebInputSession } from './input/WebInputSession';
 import { ensureInjected, ensureLanguage, onRegistered } from './loader';
 import { registerView, requestPump } from './pump';
 import { type CssTheme, cssTheme } from './theme';
@@ -32,6 +34,10 @@ export type ViewOptions = {
   onFirstDraw?: () => void;
   onChange?: (change: WebChange) => void;
   onSelection?: (anchor: number, head: number, revision: number) => void;
+  suggestions: Suggestions;
+  autoFocus: boolean;
+  onFocus?: () => void;
+  onBlur?: () => void;
 };
 
 // The defaults of website/docs/reference/props.md.
@@ -53,6 +59,8 @@ export const DEFAULT_OPTIONS: ViewOptions = {
   insertSpaces: true,
   autoIndent: true,
   autoCloseBrackets: true,
+  suggestions: 'off',
+  autoFocus: false,
 };
 
 const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
@@ -112,6 +120,21 @@ export class EditorView {
   private readonly offRegistered = onRegistered(() => {
     if (this.missed.size) this.loadMissed();
   });
+  readonly session: WebInputSession;
+  private readonly input: InputHost;
+  private readonly selectionLayer = div('position:absolute;left:0;top:0;pointer-events:none;');
+  private readonly composingLayer = div(
+    'position:absolute;left:0;top:0;z-index:1;pointer-events:none;',
+  );
+  private readonly caretEl = div(
+    'position:absolute;width:2px;z-index:1;pointer-events:none;display:none;animation:codepad-blink 1s steps(1) infinite;',
+  );
+  private inputting = false;
+  private readonly onClickEvent = (e: MouseEvent) => this.click(e);
+  // A press on the text keeps the focus where it is, so a click inside a focused editor does not blur it.
+  private readonly onMouseDownEvent = (e: MouseEvent) => {
+    if (e.button === 0 && this.textLayer.contains(e.target as Node)) e.preventDefault();
+  };
 
   constructor(host: HTMLElement, m: CoreModule, text = '') {
     this.m = m;
@@ -125,7 +148,28 @@ export class EditorView {
     this.textLayer = div('position:absolute;left:0;top:0;width:100%;height:100%;');
     this.activeLine = div('position:absolute;left:0;display:none;');
     this.placeholderEl = div('position:absolute;white-space:pre;display:none;pointer-events:none;');
-    this.textLayer.append(this.activeLine, this.placeholderEl);
+    this.textLayer.append(
+      this.activeLine,
+      this.selectionLayer,
+      this.placeholderEl,
+      this.composingLayer,
+      this.caretEl,
+    );
+    this.textLayer.style.userSelect = 'none';
+    this.textLayer.style.webkitUserSelect = 'none';
+    this.caretEl.dataset.caret = '';
+    this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit));
+    this.input = new InputHost(this.root, this.session, {
+      keyDown: () => false,
+      focusChanged: (focused) => {
+        this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.()));
+        this.invalidate();
+      },
+      changed: () => this.invalidate(),
+    });
+    this.scroller.addEventListener('click', this.onClickEvent);
+    this.scroller.addEventListener('mousedown', this.onMouseDownEvent);
+    blinkStyle();
     this.content.append(this.gutter, this.textLayer);
     this.scroller.append(this.content);
     this.root.append(this.scroller);
@@ -157,6 +201,8 @@ export class EditorView {
       before.lineNumbers !== this.o.lineNumbers ||
       before.scrollEnabled !== this.o.scrollEnabled;
     if (before.scrollEnabled !== this.o.scrollEnabled) this.listenToPage(!this.o.scrollEnabled);
+    this.input.setSuggestions(this.o.suggestions);
+    this.input.setReadOnly(this.o.readOnly);
     if (
       before.tabSize !== this.o.tabSize ||
       before.insertSpaces !== this.o.insertSpaces ||
@@ -197,16 +243,171 @@ export class EditorView {
   // Runs an edit, then hands its changes and selection to the cache and the listeners.
   apply(edit: () => void): void {
     if (this.destroyed) return;
+    const outside = !this.inputting;
+    // An edit from outside the keyboard ends a composition first, so it undoes on its own.
+    if (outside) this.session.external();
     edit();
     const changes = this.core.takeChanges();
     for (const change of changes) this.changed(change, changes.length);
-    for (const change of changes) this.o.onChange?.(change);
     const s = this.core.selection;
-    if (s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head) {
-      this.lastSelection = s;
-      this.o.onSelection?.(s.anchor, s.head, this.core.revision);
-    }
+    const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head;
+    if (moved) this.lastSelection = s;
+    if (outside) this.input.write(this.session.sync());
     this.invalidate();
+    // Listeners run last, so one that throws leaves the editor and the textarea in step.
+    for (const change of changes) this.safely(() => this.o.onChange?.(change));
+    if (moved) this.safely(() => this.o.onSelection?.(s.anchor, s.head, this.core.revision));
+  }
+
+  focus(): void {
+    if (this.destroyed) return;
+    this.input.focus();
+  }
+
+  blur(): void {
+    if (this.destroyed) return;
+    this.input.blur();
+  }
+
+  get focused(): boolean {
+    return !this.destroyed && this.input.focused;
+  }
+
+  // The document offset under a page point, or null outside the drawn text.
+  offsetAt(clientX: number, clientY: number): number | null {
+    if (this.destroyed) return null;
+    const d = document as Document & {
+      caretPositionFromPoint?(x: number, y: number): { offsetNode: Node; offset: number } | null;
+      caretRangeFromPoint?(x: number, y: number): Range | null;
+    };
+    let node: Node | null = null;
+    let offset = 0;
+    const position = d.caretPositionFromPoint?.(clientX, clientY);
+    if (position) {
+      node = position.offsetNode;
+      offset = position.offset;
+    } else {
+      const range = d.caretRangeFromPoint?.(clientX, clientY);
+      if (range) {
+        node = range.startContainer;
+        offset = range.startOffset;
+      }
+    }
+    const el = (node instanceof Element ? node : node?.parentElement)?.closest('[data-line]');
+    if (!node || !(el instanceof HTMLElement) || !this.textLayer.contains(el)) {
+      return this.offsetBeside(clientX, clientY);
+    }
+    const line = Number(el.dataset.line);
+    const column = columnOf(el, node, offset);
+    return this.core.lineStart(line) + Math.min(column, this.core.line(line).length);
+  }
+
+  // A point beside the text, past a line's end or in the space below the last line, finds the drawn line by height.
+  private offsetBeside(clientX: number, clientY: number): number | null {
+    let below = true;
+    for (const [line, entry] of this.cache) {
+      if (!this.attached.has(line)) continue;
+      const r = entry.el.getBoundingClientRect();
+      if (clientY >= r.bottom) continue;
+      below = false;
+      if (clientY < r.top) continue;
+      const range = document.createRange();
+      const [node, offset] = textPoint(entry.el, entry.text.length);
+      range.setStart(node, offset);
+      const end = range.getBoundingClientRect().right;
+      return this.core.lineStart(line) + (clientX >= end ? entry.text.length : 0);
+    }
+    return below ? this.core.length : null;
+  }
+
+  private applyInput(edit: () => void): void {
+    this.inputting = true;
+    try {
+      this.apply(edit);
+    } finally {
+      this.inputting = false;
+    }
+  }
+
+  private safely(call: () => void): void {
+    try {
+      call();
+    } catch (e) {
+      queueMicrotask(() => {
+        throw e;
+      });
+    }
+  }
+
+  // A click places the caret and focuses the textarea inside the event, which iOS needs to show its keyboard.
+  private click(e: MouseEvent): void {
+    const offset = this.offsetAt(e.clientX, e.clientY);
+    if (offset !== null) this.apply(() => this.core.setSelection(offset, offset));
+    this.focus();
+  }
+
+  // The caret, the composing underline and the selection, from where the browser drew the text.
+  private drawInput(): void {
+    const box = this.textLayer.getBoundingClientRect();
+    const { anchor, head } = this.core.selection;
+    const caret = this.input.focused ? this.caretRect(head) : null;
+    const rootBox = this.root.getBoundingClientRect();
+    if (caret) {
+      const x = caret.x + rootBox.left - box.left;
+      const y = caret.y + rootBox.top - box.top;
+      const style = this.caretEl.style;
+      style.display = 'block';
+      style.left = `${x}px`;
+      style.top = `${y}px`;
+      style.height = `${caret.height}px`;
+      style.background = this.css.cursor;
+      this.input.place(caret.x, caret.y);
+    } else {
+      this.caretEl.style.display = 'none';
+    }
+    const composing = this.session.composing;
+    this.composingLayer.replaceChildren(
+      ...(composing ? this.rangeRects(composing.start, composing.end) : []).map((r) => {
+        const bar = div(
+          `position:absolute;left:${r.left - box.left}px;top:${r.bottom - box.top - 2}px;width:${r.width}px;height:2px;background:${this.css.cursor};`,
+        );
+        bar.dataset.composing = '';
+        return bar;
+      }),
+    );
+    const from = Math.min(anchor, head);
+    const to = Math.max(anchor, head);
+    this.selectionLayer.replaceChildren(
+      ...(from < to ? this.rangeRects(from, to) : []).map((r) =>
+        div(
+          `position:absolute;left:${r.left - box.left}px;top:${r.top - box.top}px;width:${Math.max(r.width, 4)}px;height:${r.height}px;background:${this.css.selection};`,
+        ),
+      ),
+    );
+  }
+
+  // The page boxes of the document range on the lines that are drawn.
+  private rangeRects(start: number, end: number): DOMRect[] {
+    const out: DOMRect[] = [];
+    const first = this.core.lineAt(start);
+    const last = this.core.lineAt(end);
+    for (let line = first; line <= last; line++) {
+      const entry = this.cache.get(line);
+      if (!entry || !this.attached.has(line)) continue;
+      const lineStart = this.core.lineStart(line);
+      const a = Math.max(start, lineStart) - lineStart;
+      const b = Math.min(end, lineStart + entry.text.length) - lineStart;
+      const range = document.createRange();
+      const [sn, so] = textPoint(entry.el, a);
+      const [en, eo] = textPoint(entry.el, b);
+      range.setStart(sn, so);
+      range.setEnd(en, eo);
+      const rects = [...range.getClientRects()].filter((r) => r.width > 0);
+      // An empty part of a line inside the selection still shows a little.
+      if (rects.length === 0) rects.push(range.getBoundingClientRect());
+      out.push(...rects);
+    }
+    return out;
   }
 
   // Scrolls so the line is at the top of the editor, or of the page when the editor does not scroll.
@@ -284,6 +485,7 @@ export class EditorView {
       const frame = this.readFrame();
       moved = this.prepare(frame);
       this.place(frame);
+      this.drawInput();
     } finally {
       this.layout.endDraw();
     }
@@ -300,6 +502,9 @@ export class EditorView {
     this.destroyed = true;
     this.unregister();
     this.offRegistered();
+    this.input.destroy();
+    this.scroller.removeEventListener('click', this.onClickEvent);
+    this.scroller.removeEventListener('mousedown', this.onMouseDownEvent);
     this.listenToPage(false);
     this.resize?.disconnect();
     document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent);
@@ -645,6 +850,7 @@ export class EditorView {
     if (!this.drawn) {
       this.drawn = true;
       this.o.onFirstDraw?.();
+      if (this.o.autoFocus) this.focus();
     }
     const x = layout.scrollX;
     const y = this.o.scrollEnabled ? layout.scrollY : 0;
@@ -739,6 +945,41 @@ export class EditorView {
   }
 }
 
+// The text node and offset at a column of a line element.
+function textPoint(el: HTMLElement, column: number): [Node, number] {
+  const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+  let at = 0;
+  let last: Text | null = null;
+  for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) {
+    if (column <= at + node.data.length) return [node, column - at];
+    at += node.data.length;
+    last = node;
+  }
+  return last ? [last, last.data.length] : [el, 0];
+}
+
+// The column of a DOM point inside a line element.
+function columnOf(el: HTMLElement, node: Node, offset: number): number {
+  const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+  let at = 0;
+  for (let text = walker.nextNode() as Text | null; text; text = walker.nextNode() as Text | null) {
+    if (text === node) return at + offset;
+    if (node !== el && node.contains(text)) return at;
+    if (node === el && el.childNodes[offset]?.contains(text)) return at;
+    at += text.data.length;
+  }
+  return at;
+}
+
+// The caret's blink, added to the page once.
+function blinkStyle(): void {
+  if (document.getElementById('codepad-blink')) return;
+  const style = document.createElement('style');
+  style.id = 'codepad-blink';
+  style.textContent = '@keyframes codepad-blink { 50% { opacity: 0; } }';
+  document.head.append(style);
+}
+
 function div(css: string): HTMLDivElement {
   const el = document.createElement('div');
   el.style.cssText = css;
diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx
index f5e2bc6..85d83ea 100644
--- a/src/web/__tests__/CodeEditor.test.tsx
+++ b/src/web/__tests__/CodeEditor.test.tsx
@@ -28,6 +28,15 @@ class MockView {
   apply(edit: () => void) {
     edit();
   }
+  focused = false;
+  focus = jest.fn(() => {
+    this.focused = true;
+    this.options.onFocus?.();
+  });
+  blur = jest.fn(() => {
+    this.focused = false;
+    this.options.onBlur?.();
+  });
   destroy() {}
 }
 
@@ -126,3 +135,20 @@ test('settles a write made after the core failed to load', async () => {
   await expect(settled(write as Promise)).resolves.toBeUndefined();
   warn.mockRestore();
 });
+
+test('focus and blur reach the view, isFocused reads it, and onFocus and onBlur fire', async () => {
+  const ref = createRef();
+  const onFocus = jest.fn();
+  const onBlur = jest.fn();
+  await render();
+  await act(async () => {
+    mockCore.resolve({});
+    await tick();
+  });
+  await ref.current?.focus();
+  expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1);
+  expect(ref.current?.isFocused()).toBe(true);
+  await ref.current?.blur();
+  expect(ref.current?.isFocused()).toBe(false);
+  expect([onFocus.mock.calls.length, onBlur.mock.calls.length]).toEqual([1, 1]);
+});
diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts
new file mode 100644
index 0000000..f610af1
--- /dev/null
+++ b/src/web/input/InputHost.ts
@@ -0,0 +1,136 @@
+/// 
+import type { Suggestions } from '../../types';
+import type { TextareaState, WebInputSession } from './WebInputSession';
+
+export type InputHooks = {
+  // True when the key ran an editor command, so the browser must not act on it.
+  keyDown(e: KeyboardEvent): boolean;
+  focusChanged(focused: boolean): void;
+  changed(): void;
+};
+
+const SUGGESTION_ATTRIBUTES: [string, string, string][] = [
+  ['autocomplete', 'on', 'off'],
+  ['autocorrect', 'on', 'off'],
+  ['autocapitalize', 'sentences', 'off'],
+  ['spellcheck', 'true', 'false'],
+];
+
+// The hidden textarea the keyboard types into, wired to a WebInputSession.
+export class InputHost {
+  readonly textarea: HTMLTextAreaElement;
+  // iOS reports the selection as 0,0 for a moment after focus, so selection changes wait a frame.
+  private settling = false;
+  private readonly listeners: [EventTarget, string, EventListener][] = [];
+
+  constructor(
+    root: HTMLElement,
+    private readonly session: WebInputSession,
+    private readonly hooks: InputHooks,
+  ) {
+    const ta = document.createElement('textarea');
+    // 16px keeps iOS from zooming the page on focus.
+    ta.style.cssText =
+      'position:absolute;left:0;top:0;width:2px;height:1px;padding:0;border:0;margin:0;opacity:0;' +
+      'resize:none;overflow:hidden;white-space:pre;font-size:16px;line-height:1;color:transparent;' +
+      'background:transparent;caret-color:transparent;outline:none;pointer-events:none;';
+    this.textarea = ta;
+    this.setSuggestions('off');
+    root.append(ta);
+    this.on(ta, 'beforeinput', () => this.session.beforeInput(this.state()));
+    this.on(ta, 'input', (e) => {
+      const ie = e as InputEvent;
+      this.write(
+        this.session.input(
+          { inputType: ie.inputType ?? '', data: ie.data ?? null, isComposing: !!ie.isComposing },
+          this.state(),
+        ),
+      );
+      this.hooks.changed();
+    });
+    this.on(ta, 'compositionstart', () => {
+      this.session.compositionStart(this.state());
+      this.hooks.changed();
+    });
+    this.on(ta, 'compositionend', () => {
+      const value = ta.value;
+      const next = this.session.compositionEnd(this.state());
+      this.hooks.changed();
+      // A browser may still send the composition's last input after this event.
+      setTimeout(() => {
+        if (ta.value === value && !this.session.composing) this.write(next);
+      }, 0);
+    });
+    this.on(ta, 'keydown', (e) => {
+      if (this.hooks.keyDown(e as KeyboardEvent)) e.preventDefault();
+    });
+    this.on(ta, 'focus', () => {
+      this.settling = true;
+      requestAnimationFrame(() => {
+        this.settling = false;
+      });
+      this.hooks.focusChanged(true);
+    });
+    this.on(ta, 'blur', () => {
+      this.session.finishComposition();
+      this.hooks.focusChanged(false);
+    });
+    this.on(document, 'selectionchange', () => {
+      if (this.settling || document.activeElement !== ta) return;
+      this.write(this.session.selectionChange(this.state()));
+      this.hooks.changed();
+    });
+  }
+
+  get focused(): boolean {
+    return document.activeElement === this.textarea;
+  }
+
+  state(): TextareaState {
+    const ta = this.textarea;
+    return { value: ta.value, start: ta.selectionStart, end: ta.selectionEnd };
+  }
+
+  write(state: TextareaState | null): void {
+    if (!state) return;
+    const ta = this.textarea;
+    if (ta.value !== state.value) ta.value = state.value;
+    if (ta.selectionStart !== state.start || ta.selectionEnd !== state.end)
+      ta.setSelectionRange(state.start, state.end);
+  }
+
+  // Keeps the textarea at the caret, so the keyboard's candidate window opens there.
+  place(x: number, y: number): void {
+    this.textarea.style.left = `${Math.round(x)}px`;
+    this.textarea.style.top = `${Math.round(y)}px`;
+  }
+
+  focus(): void {
+    this.write(this.session.sync());
+    this.textarea.focus({ preventScroll: true });
+  }
+
+  blur(): void {
+    this.textarea.blur();
+  }
+
+  setSuggestions(suggestions: Suggestions): void {
+    for (const [name, on, off] of SUGGESTION_ATTRIBUTES)
+      this.textarea.setAttribute(name, suggestions === 'on' ? on : off);
+  }
+
+  // A read only textarea brings no keyboard on a phone, while selection still works.
+  setReadOnly(readOnly: boolean): void {
+    this.textarea.readOnly = readOnly;
+  }
+
+  destroy(): void {
+    for (const [target, type, fn] of this.listeners) target.removeEventListener(type, fn);
+    this.textarea.remove();
+  }
+
+  private on(target: EventTarget, type: string, fn: EventListener): void {
+    target.addEventListener(type, fn);
+    this.listeners.push([target, type, fn]);
+  }
+}
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index f3f4fc5..9642350 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -86,6 +86,238 @@ for (const engine of [chromium, webkit]) {
       return { page, warnings, errors };
     }
 
+    // An editor on host id, kept as window.views[id], with its text drawn.
+    async function editor(page, id, text, options = {}) {
+      await page.evaluate(
+        async ([id, text, options]) => {
+          const { EditorView, loadCore, until } = window.codepad;
+          const view = new EditorView(document.getElementById(id), await loadCore(), text);
+          view.setOptions(options);
+          window.views = { ...window.views, [id]: view };
+          await until(() => document.querySelector(`#${id} [data-line="0"]`));
+        },
+        [id, text, options],
+      );
+    }
+
+    // Clicks the left edge of a column in a drawn line.
+    async function clickAt(page, id, line, column) {
+      await page.waitForSelector(`#${id} [data-line="${line}"]`, { state: 'attached' });
+      const { x, y } = await page.evaluate(
+        ([id, line, column]) => {
+          const el = document.querySelector(`#${id} [data-line="${line}"]`);
+          const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+          let at = 0;
+          for (let node = walker.nextNode(); node; node = walker.nextNode()) {
+            if (column <= at + node.data.length) {
+              const range = document.createRange();
+              range.setStart(node, column - at);
+              range.setEnd(node, column - at);
+              const r = range.getBoundingClientRect();
+              return { x: r.left + 1, y: r.top + r.height / 2 };
+            }
+            at += node.data.length;
+          }
+          const r = el.getBoundingClientRect();
+          return { x: r.right + 4, y: r.top + r.height / 2 };
+        },
+        [id, line, column],
+      );
+      await page.mouse.click(x, y);
+    }
+
+    const textOf = (page, id) => page.evaluate((id) => window.views[id].core.text(), id);
+    const visible = (page, selector) =>
+      page.evaluate((s) => {
+        const el = document.querySelector(s);
+        return !!el && el.style.display !== 'none' && el.getBoundingClientRect().width > 0;
+      }, selector);
+
+    // Starts a composition of text at the caret: the browser's own IME in Chromium, dispatched events in WebKit.
+    async function compose(page, id, text) {
+      if (engine === chromium) {
+        const cdp = await page.context().newCDPSession(page);
+        await cdp.send('Input.imeSetComposition', {
+          text,
+          selectionStart: text.length,
+          selectionEnd: text.length,
+        });
+        return cdp;
+      }
+      await page.evaluate(
+        ([id, text]) => {
+          const ta = document.querySelector(`#${id} textarea`);
+          const at = ta.selectionStart;
+          ta.dispatchEvent(new CompositionEvent('compositionstart', { data: '' }));
+          ta.value = ta.value.slice(0, at) + text + ta.value.slice(at);
+          ta.setSelectionRange(at + text.length, at + text.length);
+          ta.dispatchEvent(
+            new InputEvent('input', {
+              inputType: 'insertCompositionText',
+              data: text,
+              isComposing: true,
+            }),
+          );
+        },
+        [id, text],
+      );
+      return null;
+    }
+
+    async function commit(page, id, cdp, composed, text) {
+      if (cdp) return cdp.send('Input.insertText', { text });
+      await page.evaluate(
+        ([id, composed, text]) => {
+          const ta = document.querySelector(`#${id} textarea`);
+          const end = ta.selectionStart;
+          ta.value = ta.value.slice(0, end - composed.length) + text + ta.value.slice(end);
+          const at = end - composed.length + text.length;
+          ta.setSelectionRange(at, at);
+          ta.dispatchEvent(
+            new InputEvent('input', {
+              inputType: 'insertCompositionText',
+              data: text,
+              isComposing: true,
+            }),
+          );
+          ta.dispatchEvent(new CompositionEvent('compositionend', { data: text }));
+        },
+        [id, composed, text],
+      );
+    }
+
+    test('a click places the caret and typing inserts there', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'abcdef\nghijkl\n');
+      await clickAt(page, 'a', 1, 3);
+      await page.keyboard.type('xy');
+      assert.equal(await textOf(page, 'a'), 'abcdef\nghixyjkl\n');
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('Enter splits the line and Backspace joins it again', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'ab', { autoIndent: false });
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.press('Enter');
+      assert.equal(await textOf(page, 'a'), 'a\nb');
+      await page.keyboard.press('Backspace');
+      assert.equal(await textOf(page, 'a'), 'ab');
+      await page.close();
+    });
+
+    test('a composition shows its underline then commits', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'ab');
+      await clickAt(page, 'a', 0, 2);
+      const cdp = await compose(page, 'a', 'か');
+      await page.waitForFunction(() => window.views.a.core.text() === 'abか');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), true);
+      await commit(page, 'a', cdp, 'か', '蚊');
+      await page.waitForFunction(() => window.views.a.core.text() === 'ab蚊');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), false);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('clicking elsewhere mid-composition leaves no underline', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'ab\ncd');
+      await clickAt(page, 'a', 0, 2);
+      await compose(page, 'a', 'か');
+      await page.waitForFunction(() => window.views.a.core.text() === 'abか\ncd');
+      await clickAt(page, 'a', 1, 1);
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-composing]'), false);
+      assert.equal(await textOf(page, 'a'), 'abか\ncd');
+      await page.close();
+    });
+
+    test('readOnly keeps the text and still places the caret', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc', { readOnly: true });
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.type('x');
+      assert.equal(await textOf(page, 'a'), 'abc');
+      assert.equal(await page.evaluate(() => window.views.a.core.selection.head), 1);
+      await page.close();
+    });
+
+    test('an onChange that throws keeps the edit and the sync', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', '');
+      await page.evaluate(() =>
+        window.views.a.setOptions({
+          onChange: () => {
+            throw new Error('boom');
+          },
+        }),
+      );
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.type('ab');
+      assert.equal(await textOf(page, 'a'), 'ab');
+      assert.equal(await page.evaluate(() => document.querySelector('#a textarea').value), 'ab');
+      assert.ok(
+        errors.some((e) => /boom/.test(e)),
+        String(errors),
+      );
+      await page.close();
+    });
+
+    test('only the focused editor draws a caret and takes keys', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one');
+      await editor(page, 'b', 'two');
+      await clickAt(page, 'a', 0, 3);
+      await clickAt(page, 'b', 0, 3);
+      await page.keyboard.type('z');
+      assert.equal(await textOf(page, 'b'), 'twoz');
+      assert.equal(await textOf(page, 'a'), 'one');
+      await page.evaluate(() => window.codepad.frames(2));
+      assert.equal(await visible(page, '#a [data-caret]'), false);
+      assert.equal(await visible(page, '#b [data-caret]'), true);
+      await page.close();
+    });
+
+    test('onFocus and onBlur fire once per change', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one');
+      await editor(page, 'b', 'two');
+      await page.evaluate(() => {
+        window.counts = { focus: 0, blur: 0 };
+        window.views.a.setOptions({
+          onFocus: () => window.counts.focus++,
+          onBlur: () => window.counts.blur++,
+        });
+      });
+      await clickAt(page, 'a', 0, 1);
+      await clickAt(page, 'a', 0, 2);
+      await clickAt(page, 'b', 0, 1);
+      assert.deepEqual(await page.evaluate(() => window.counts), { focus: 1, blur: 1 });
+      await page.close();
+    });
+
+    test('typing after replaceRange, setText and undo lands at the core caret', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc');
+      await clickAt(page, 'a', 0, 3);
+      for (const step of [
+        (v) => v.apply(() => v.core.replace(0, 0, 'Q')),
+        (v) => v.apply(() => v.core.setText('new')),
+        (v) => v.apply(() => v.core.undo()),
+      ]) {
+        await page.evaluate(`(${step})(window.views.a)`);
+        const head = await page.evaluate(() => window.views.a.core.selection.head);
+        const before = await textOf(page, 'a');
+        await page.keyboard.type('z');
+        assert.equal(await textOf(page, 'a'), `${before.slice(0, head)}z${before.slice(head)}`);
+      }
+      await page.close();
+    });
+
     test('colors python keywords', async () => {
       const { page, errors } = await open();
       const color = await page.evaluate(async () => {

From 4d5d15761b56ff622a208ac9b69e86d1253c6230 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 00:46:58 +0100
Subject: [PATCH 06/23] feat(web): arrow keys, shortcuts and the typing ref
 methods

---
 src/web/CodeEditor.tsx                |  19 +-
 src/web/EditorView.ts                 | 250 +++++++++++++++++++++++---
 src/web/__tests__/CodeEditor.test.tsx |  25 +++
 src/web/__tests__/caret-mover.test.ts |  49 +++++
 src/web/__tests__/keys.test.ts        |  98 ++++++++++
 src/web/input/CaretMover.ts           |  52 ++++++
 src/web/input/keys.ts                 |  92 ++++++++++
 tests/web/render.e2e.mjs              | 138 ++++++++++++++
 8 files changed, 691 insertions(+), 32 deletions(-)
 create mode 100644 src/web/__tests__/caret-mover.test.ts
 create mode 100644 src/web/__tests__/keys.test.ts
 create mode 100644 src/web/input/CaretMover.ts
 create mode 100644 src/web/input/keys.ts

diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx
index 385b196..e453a5b 100644
--- a/src/web/CodeEditor.tsx
+++ b/src/web/CodeEditor.tsx
@@ -182,7 +182,7 @@ export const CodeEditor = forwardRef(function Co
         v.setLanguage(latest.current.language);
         viewRef.current = v;
         for (const write of queued.current.splice(0)) {
-          v.apply(() => write.edit(v));
+          write.edit(v);
           write.done();
         }
         setView(v);
@@ -221,12 +221,15 @@ export const CodeEditor = forwardRef(function Co
   // Reads see an empty document until the core loads and after unmount. Writes made before the load wait for it.
   useImperativeHandle(ref, () => {
     const core = () => viewRef.current?.core;
-    const write = (edit: (v: EditorView) => void): Promise => {
+    // Runs on the view now, or once the core loads when the call comes before it.
+    const run = (call: (v: EditorView) => void): Promise => {
       const v = viewRef.current;
-      if (v) v.apply(() => edit(v));
-      else if (!gone.current) return new Promise((done) => queued.current.push({ edit, done }));
+      if (v) call(v);
+      else if (!gone.current)
+        return new Promise((done) => queued.current.push({ edit: call, done }));
       return Promise.resolve();
     };
+    const write = (edit: (v: EditorView) => void) => run((v) => v.apply(() => edit(v)));
     return {
       getText: () => core()?.text() ?? '',
       getTextInRange: (range) => core()?.text(range.start, range.end) ?? '',
@@ -283,10 +286,10 @@ export const CodeEditor = forwardRef(function Co
       replaceCurrent: () => later('replaceCurrent', false),
       replaceAll: () => later('replaceAll', 0),
       clearSearch: () => later('clearSearch', undefined),
-      moveCaret: () => later('moveCaret', undefined),
-      typeText: () => later('typeText', undefined),
-      deleteBackward: () => later('deleteBackward', undefined),
-      deleteForward: () => later('deleteForward', undefined),
+      moveCaret: (direction, opts) => run((v) => v.moveCaret(direction, opts?.select ?? false)),
+      typeText: (text) => run((v) => v.typeText(text)),
+      deleteBackward: () => run((v) => v.deleteBackward()),
+      deleteForward: () => run((v) => v.deleteForward()),
     };
   }, []);
 
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index ea5df82..27b3639 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -1,11 +1,13 @@
 /// 
 import { githubLight } from '../themes/githubLight';
-import type { ContentInsets, Rect, Suggestions, Theme } from '../types';
-import { EditorCore, type WebChange } from './core/EditorCore';
+import type { CaretDirection, ContentInsets, Rect, Suggestions, Theme } from '../types';
+import { EditorCore, type MoveUnit, type WebChange } from './core/EditorCore';
 import { Layout } from './core/Layout';
 import type { CoreModule } from './core/module';
 import { type DecodedFrame, decodeFrame } from './frame';
+import { CaretMover, type LineGeometry } from './input/CaretMover';
 import { InputHost } from './input/InputHost';
+import { keyCommand } from './input/keys';
 import { WebInputSession } from './input/WebInputSession';
 import { ensureInjected, ensureLanguage, onRegistered } from './loader';
 import { registerView, requestPump } from './pump';
@@ -65,6 +67,17 @@ export const DEFAULT_OPTIONS: ViewOptions = {
 
 const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
 const SNAPSHOT_INFO_INTS = 7;
+const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
+const MOVES: Partial> = {
+  left: ['char', false],
+  right: ['char', true],
+  wordLeft: ['word', false],
+  wordRight: ['word', true],
+  lineStart: ['lineStart', false],
+  lineEnd: ['lineEnd', true],
+  documentStart: ['docStart', false],
+  documentEnd: ['docEnd', true],
+};
 
 type Entry = {
   el: HTMLDivElement;
@@ -130,6 +143,19 @@ export class EditorView {
     'position:absolute;width:2px;z-index:1;pointer-events:none;display:none;animation:codepad-blink 1s steps(1) infinite;',
   );
   private inputting = false;
+  private readonly mover = new CaretMover();
+  private movingVertically = false;
+  // The caret scrolls into view on the next draw, before the page paints.
+  private revealing = false;
+  // Hidden copies of lines a caret move measured, dropped on the next draw.
+  private readonly measuring = new Map();
+  private readonly geometry: LineGeometry = {
+    rows: (line) => Math.max(1, Math.round(this.lineEl(line).offsetHeight / this.rowHeight)),
+    rowOf: (line, column) =>
+      Math.min(this.pointIn(this.lineEl(line), column).row, this.geometry.rows(line) - 1),
+    caretX: (line, column) => this.pointIn(this.lineEl(line), column).x,
+    columnAt: (line, row, x) => this.columnAt(line, row, x),
+  };
   private readonly onClickEvent = (e: MouseEvent) => this.click(e);
   // A press on the text keeps the focus where it is, so a click inside a focused editor does not blur it.
   private readonly onMouseDownEvent = (e: MouseEvent) => {
@@ -158,9 +184,10 @@ export class EditorView {
     this.textLayer.style.userSelect = 'none';
     this.textLayer.style.webkitUserSelect = 'none';
     this.caretEl.dataset.caret = '';
+    this.selectionLayer.dataset.selection = '';
     this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit));
     this.input = new InputHost(this.root, this.session, {
-      keyDown: () => false,
+      keyDown: (e) => this.keyDown(e),
       focusChanged: (focused) => {
         this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.()));
         this.invalidate();
@@ -252,6 +279,7 @@ export class EditorView {
     const s = this.core.selection;
     const moved = s.anchor !== this.lastSelection.anchor || s.head !== this.lastSelection.head;
     if (moved) this.lastSelection = s;
+    if (moved && !this.movingVertically) this.mover.reset();
     if (outside) this.input.write(this.session.sync());
     this.invalidate();
     // Listeners run last, so one that throws leaves the editor and the textarea in step.
@@ -320,13 +348,149 @@ export class EditorView {
     return below ? this.core.length : null;
   }
 
+  // A keyboard edit or caret move shows the caret, a selection the page wrote back does not.
   private applyInput(edit: () => void): void {
+    const revision = this.core.revision;
+    const before = this.core.selection;
     this.inputting = true;
     try {
       this.apply(edit);
     } finally {
       this.inputting = false;
     }
+    const after = this.core.selection;
+    if (
+      this.core.revision !== revision ||
+      after.anchor !== before.anchor ||
+      after.head !== before.head
+    )
+      this.revealing = true;
+  }
+
+  // A hardware key the editor runs itself. True when the browser must not act on it.
+  private keyDown(e: KeyboardEvent): boolean {
+    if (this.destroyed) return false;
+    const command = keyCommand(e, MAC);
+    if (!command) return false;
+    switch (command.kind) {
+      case 'move':
+        this.perform(() => this.core.move(command.unit, command.forward, command.extend));
+        return true;
+      case 'vertical':
+        this.vertical(command.by === 'page', command.forward, command.extend);
+        return true;
+      case 'selectAll':
+        this.apply(() => this.core.selectAll());
+        return true;
+    }
+    if (this.o.readOnly) return false;
+    const kind = command.kind;
+    this.perform(() => {
+      if (kind === 'tab') this.core.tab();
+      else if (kind === 'shiftTab') this.core.shiftTab();
+      else if (kind === 'undo') this.core.undo();
+      else this.core.redo();
+    });
+    return true;
+  }
+
+  // Runs an edit or a move from a key or the ref, then shows the caret.
+  private perform(edit: () => void): void {
+    this.revealing = true;
+    this.apply(edit);
+  }
+
+  // Moves the caret by rows or by a page of rows, back to the same x after a shorter line.
+  private vertical(page: boolean, forward: boolean, extend: boolean): void {
+    const pageRows = Math.max(1, Math.floor(this.layout.viewportHeight / this.rowHeight));
+    const rows = (page ? pageRows : 1) * (forward ? 1 : -1);
+    const { anchor, head } = this.core.selection;
+    const target = this.mover.target(this.core, this.geometry, head, rows);
+    this.movingVertically = true;
+    try {
+      this.perform(() => this.core.setSelection(extend ? anchor : target, target));
+    } finally {
+      this.movingVertically = false;
+    }
+  }
+
+  // As typed on the keyboard: auto close, indentation on a newline. Nothing under readOnly.
+  typeText(text: string): void {
+    if (this.destroyed || this.o.readOnly || text === '') return;
+    this.perform(() => this.core.typeText(text));
+  }
+
+  // Backspace, an empty auto closed pair in one go. Nothing under readOnly.
+  deleteBackward(): void {
+    if (this.destroyed || this.o.readOnly) return;
+    this.perform(() => this.core.backspace());
+  }
+
+  deleteForward(): void {
+    if (this.destroyed || this.o.readOnly) return;
+    this.perform(() => this.core.delete());
+  }
+
+  // Moves the caret like the matching key, under readOnly too.
+  moveCaret(direction: CaretDirection, extend: boolean): void {
+    if (this.destroyed) return;
+    const move = MOVES[direction];
+    if (move) {
+      this.perform(() => this.core.move(move[0], move[1], extend));
+      return;
+    }
+    const page = direction === 'pageUp' || direction === 'pageDown';
+    this.vertical(page, direction === 'down' || direction === 'pageDown', extend);
+  }
+
+  // The column nearest x on a row of a line, x in pixels from the line's left edge. Lays the line out when it is
+  // not drawn.
+  columnAt(line: number, rowInLine: number, x: number): number {
+    if (this.destroyed) return 0;
+    const el = this.lineEl(line);
+    const text = this.core.line(line);
+    const length = text.length;
+    const rowOf = (c: number) => this.pointIn(el, c).row;
+    const xOf = (c: number) => this.pointIn(el, c).x;
+    // Rows only grow along a line, and x along a row.
+    const first = firstWhere(0, length + 1, (c) => rowOf(c) >= rowInLine);
+    if (first > length) return length;
+    const last = firstWhere(first, length + 1, (c) => rowOf(c) > rowInLine) - 1;
+    const at = firstWhere(first, last + 1, (c) => xOf(c) >= x);
+    let column = at;
+    if (at > last) column = last;
+    else if (at > first && x - xOf(at - 1) < xOf(at) - x) column = at - 1;
+    const unit = text.charCodeAt(column);
+    // Never between the two halves of an emoji.
+    if (column > 0 && unit >= 0xdc00 && unit <= 0xdfff) column--;
+    return column;
+  }
+
+  // The element a line is measured in: the drawn one when it holds the current text, else a hidden copy.
+  private lineEl(line: number): HTMLDivElement {
+    const text = this.core.line(line);
+    const entry = this.cache.get(line);
+    if (entry && this.attached.has(line) && entry.text === text) return entry.el;
+    let el = this.measuring.get(line);
+    if (!el) {
+      el = this.makeLine();
+      this.paint(el, text, null);
+      el.style.visibility = 'hidden';
+      el.style.top = '0px';
+      el.style.left = `${this.layout.textAreaLeft + this.layout.textPadding}px`;
+      el.style.width = this.o.softWrap ? `${this.layout.wrapWidth}px` : '';
+      this.textLayer.append(el);
+      this.measuring.set(line, el);
+    }
+    return el;
+  }
+
+  // The caret at a column of a line element, in pixels from its left edge and in rows from its top.
+  private pointIn(el: HTMLElement, column: number): { x: number; row: number } {
+    const box = el.getBoundingClientRect();
+    const edge = caretEdge(el, column);
+    const middle = edge.top + edge.height / 2 - box.top;
+    return { x: edge.x - box.left, row: Math.max(0, Math.floor(middle / this.rowHeight)) };
   }
 
   private safely(call: () => void): void {
@@ -425,6 +589,12 @@ export class EditorView {
   // Scrolls the least that shows the caret.
   revealSelection(): void {
     if (this.destroyed) return;
+    this.revealing = true;
+    this.invalidate();
+  }
+
+  // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled.
+  private revealCaret(): boolean {
     const caret = this.caretRect(this.core.selection.head);
     const line = this.core.lineAt(this.core.selection.head);
     let row = this.layout.rowStart(line);
@@ -436,8 +606,7 @@ export class EditorView {
     }
     const top = row * this.rowHeight;
     const x = caret ? caret.x - this.layout.textLeft : 0;
-    if (this.layout.reveal(x, top, x + 1, top + this.rowHeight)) this.syncScroll();
-    this.invalidate();
+    return this.layout.reveal(x, top, x + 1, top + this.rowHeight);
   }
 
   // The caret at offset in view coordinates, or null when its line is not drawn.
@@ -446,18 +615,8 @@ export class EditorView {
     const line = this.core.lineAt(offset);
     const entry = this.cache.get(line);
     if (!entry || !this.attached.has(line)) return null;
-    const column = offset - this.core.lineStart(line);
     const box = this.root.getBoundingClientRect();
-    const lineBox = entry.el.getBoundingClientRect();
-    // The base direction is left to right: the caret sits at the leading edge of the next character unless it
-    // reads right to left, then at the trailing edge of the previous one, so Chromium and WebKit agree.
-    const next = charRect(entry.el, column, true);
-    const prev = charRect(entry.el, column, false);
-    let edge: { x: number; top: number } = { x: lineBox.left, top: lineBox.top };
-    if (next && !next.rtl) edge = { x: next.rect.left, top: next.rect.top };
-    else if (prev && !prev.rtl) edge = { x: prev.rect.right, top: prev.rect.top };
-    else if (next) edge = { x: next.rect.right, top: next.rect.top };
-    else if (prev) edge = { x: prev.rect.left, top: prev.rect.top };
+    const edge = caretEdge(entry.el, offset - this.core.lineStart(line));
     return { x: edge.x - box.left, y: edge.top - box.top, width: 1, height: this.rowHeight };
   }
 
@@ -476,25 +635,41 @@ export class EditorView {
     }
     if (!this.dirty) return;
     this.dirty = false;
+    for (const el of this.measuring.values()) el.remove();
+    this.measuring.clear();
     this.configure();
     this.restaleRefreshed();
+    let moved = this.frame();
+    // A caret moved off screen scrolls into view in the same task, so no frame paints without it. A caret line that
+    // was not drawn is revealed by its row first, then again by its x once drawn.
+    for (let pass = 0; this.revealing && pass < 2; pass++) {
+      if (this.caretRect(this.core.selection.head)) this.revealing = false;
+      if (!this.revealCaret()) break;
+      this.syncScroll();
+      moved = this.frame();
+    }
+    this.revealing = false;
+    if (moved) {
+      this.syncScroll();
+      this.dirty = true;
+    }
+    this.report();
+    if (this.dirty) requestPump();
+  }
+
+  // Lays out and places the visible lines at the current scroll. True when measuring moved the layout's scroll.
+  private frame(): boolean {
     const [sx, sy] = this.scrollPosition();
     this.layout.beginDraw(sx, sy);
-    let moved = false;
     try {
       const frame = this.readFrame();
-      moved = this.prepare(frame);
+      const moved = this.prepare(frame);
       this.place(frame);
       this.drawInput();
+      return moved;
     } finally {
       this.layout.endDraw();
     }
-    if (moved) {
-      this.syncScroll();
-      this.dirty = true;
-    }
-    this.report();
-    if (this.dirty) requestPump();
   }
 
   destroy(): void {
@@ -1015,6 +1190,33 @@ function sameSpans(a: Int32Array | null, b: Int32Array | null): boolean {
 
 const RTL = /^[֐-ࣿיִ-﷿ﹰ-]/;
 
+// Where the caret at a column of a line element sits, in page coordinates. The base direction is left to right: the
+// caret is at the leading edge of the next character unless it reads right to left, then at the trailing edge of the
+// previous one, so Chromium and WebKit agree.
+function caretEdge(el: HTMLElement, column: number): { x: number; top: number; height: number } {
+  const next = charRect(el, column, true);
+  const prev = charRect(el, column, false);
+  const at = (x: number, r: DOMRect) => ({ x, top: r.top, height: r.height });
+  if (next && !next.rtl) return at(next.rect.left, next.rect);
+  if (prev && !prev.rtl) return at(prev.rect.right, prev.rect);
+  if (next) return at(next.rect.right, next.rect);
+  if (prev) return at(prev.rect.left, prev.rect);
+  const box = el.getBoundingClientRect();
+  return { x: box.left, top: box.top, height: 0 };
+}
+
+// The first integer in [lo, hi) where test holds, or hi, for a test that stays true once it holds.
+function firstWhere(lo: number, hi: number, test: (n: number) => boolean): number {
+  let a = lo;
+  let b = hi;
+  while (a < b) {
+    const mid = (a + b) >>> 1;
+    if (test(mid)) b = mid;
+    else a = mid + 1;
+  }
+  return a;
+}
+
 // The box of the character after column (forward) or before it, and whether it reads right to left.
 function charRect(
   el: HTMLElement,
diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx
index 85d83ea..032928e 100644
--- a/src/web/__tests__/CodeEditor.test.tsx
+++ b/src/web/__tests__/CodeEditor.test.tsx
@@ -37,6 +37,10 @@ class MockView {
     this.focused = false;
     this.options.onBlur?.();
   });
+  typeText = jest.fn();
+  deleteBackward = jest.fn();
+  deleteForward = jest.fn();
+  moveCaret = jest.fn();
   destroy() {}
 }
 
@@ -152,3 +156,24 @@ test('focus and blur reach the view, isFocused reads it, and onFocus and onBlur
   expect(ref.current?.isFocused()).toBe(false);
   expect([onFocus.mock.calls.length, onBlur.mock.calls.length]).toEqual([1, 1]);
 });
+
+test('typeText, deleteBackward, deleteForward and moveCaret made before the core loads reach the view', async () => {
+  const ref = createRef();
+  await render();
+  const calls = [
+    ref.current?.typeText('x'),
+    ref.current?.deleteBackward(),
+    ref.current?.deleteForward(),
+    ref.current?.moveCaret('pageDown', { select: true }),
+  ];
+  await act(async () => {
+    mockCore.resolve({});
+    await tick();
+  });
+  await expect(settled(Promise.all(calls))).resolves.not.toBe('hung');
+  const view = mockViews[0] as MockView;
+  expect(view.typeText).toHaveBeenCalledWith('x');
+  expect(view.deleteBackward).toHaveBeenCalledTimes(1);
+  expect(view.deleteForward).toHaveBeenCalledTimes(1);
+  expect(view.moveCaret).toHaveBeenCalledWith('pageDown', true);
+});
diff --git a/src/web/__tests__/caret-mover.test.ts b/src/web/__tests__/caret-mover.test.ts
new file mode 100644
index 0000000..ca1fd8c
--- /dev/null
+++ b/src/web/__tests__/caret-mover.test.ts
@@ -0,0 +1,49 @@
+import { expect, test } from '@jest/globals';
+import { CaretMover, type DocLike, type LineGeometry } from '../input/CaretMover';
+
+// Lines laid out in rows of width columns, each column 10 pixels wide.
+function fixture(lines: string[], width: number): { doc: DocLike; geometry: LineGeometry } {
+  const starts = lines.map((_, i) => lines.slice(0, i).reduce((n, l) => n + l.length + 1, 0));
+  const doc: DocLike = {
+    lineCount: lines.length,
+    length: lines.join('\n').length,
+    lineAt: (offset) => starts.filter((s) => s <= offset).length - 1,
+    lineStart: (line) => starts[line] as number,
+  };
+  const len = (line: number) => (lines[line] as string).length;
+  const geometry: LineGeometry = {
+    rows: (line) => Math.max(1, Math.ceil(len(line) / width)),
+    rowOf: (line, column) => Math.min(Math.floor(column / width), geometry.rows(line) - 1),
+    caretX: (line, column) => (column - geometry.rowOf(line, column) * width) * 10,
+    columnAt: (line, row, x) => Math.min(row * width + Math.round(x / 10), len(line)),
+  };
+  return { doc, geometry };
+}
+
+test('Down walks the rows of a wrapped line before the next line, keeping the goal x', () => {
+  const { doc, geometry } = fixture(['abcdefghij', 'xy', 'abcdefgh'], 4);
+  const mover = new CaretMover();
+  const a = mover.target(doc, geometry, 1, 1);
+  expect(a).toBe(5);
+  const b = mover.target(doc, geometry, a, 1);
+  expect(b).toBe(9);
+  const c = mover.target(doc, geometry, b, 1);
+  expect(c).toBe(12);
+  expect(mover.target(doc, geometry, c, 1)).toBe(15);
+});
+
+test('Up from the first row goes to the start and Down from the last row to the end', () => {
+  const { doc, geometry } = fixture(['abc', 'def'], 80);
+  const mover = new CaretMover();
+  expect(mover.target(doc, geometry, 2, -1)).toBe(0);
+  expect(mover.target(doc, geometry, 5, 3)).toBe(7);
+});
+
+test('reset drops the goal x', () => {
+  const { doc, geometry } = fixture(['abcdef', 'ab', 'abcdef'], 80);
+  const mover = new CaretMover();
+  expect(mover.target(doc, geometry, 5, 1)).toBe(9);
+  expect(mover.target(doc, geometry, 9, 1)).toBe(15);
+  mover.reset();
+  expect(mover.target(doc, geometry, 9, 1)).toBe(12);
+});
diff --git a/src/web/__tests__/keys.test.ts b/src/web/__tests__/keys.test.ts
new file mode 100644
index 0000000..bd7ede1
--- /dev/null
+++ b/src/web/__tests__/keys.test.ts
@@ -0,0 +1,98 @@
+import { expect, test } from '@jest/globals';
+import { type KeyLike, keyCommand } from '../input/keys';
+
+const key = (name: string, mods: Partial = {}): KeyLike => ({
+  key: name,
+  shiftKey: false,
+  altKey: false,
+  ctrlKey: false,
+  metaKey: false,
+  isComposing: false,
+  ...mods,
+});
+const move = (unit: string, forward: boolean, extend = false) => ({
+  kind: 'move',
+  unit,
+  forward,
+  extend,
+});
+
+test('arrows move by character, word and line with the platform modifier', () => {
+  expect(keyCommand(key('ArrowLeft'), true)).toEqual(move('char', false));
+  expect(keyCommand(key('ArrowRight'), false)).toEqual(move('char', true));
+  expect(keyCommand(key('ArrowLeft', { altKey: true }), true)).toEqual(move('word', false));
+  expect(keyCommand(key('ArrowLeft', { ctrlKey: true }), false)).toEqual(move('word', false));
+  expect(keyCommand(key('ArrowRight', { metaKey: true }), true)).toEqual(move('lineEnd', true));
+  expect(keyCommand(key('ArrowLeft', { metaKey: true }), true)).toEqual(move('lineStart', false));
+  expect(keyCommand(key('Home'), false)).toEqual(move('lineStart', false));
+  expect(keyCommand(key('End'), true)).toEqual(move('lineEnd', true));
+  expect(keyCommand(key('Home', { ctrlKey: true }), false)).toEqual(move('docStart', false));
+  expect(keyCommand(key('ArrowUp', { metaKey: true }), true)).toEqual(move('docStart', false));
+  expect(keyCommand(key('ArrowDown', { metaKey: true }), true)).toEqual(move('docEnd', true));
+});
+
+test('Shift extends every move', () => {
+  expect(keyCommand(key('ArrowLeft', { shiftKey: true }), true)).toEqual(move('char', false, true));
+  expect(keyCommand(key('End', { shiftKey: true, ctrlKey: true }), false)).toEqual(
+    move('docEnd', true, true),
+  );
+  expect(keyCommand(key('ArrowDown', { shiftKey: true }), false)).toEqual({
+    kind: 'vertical',
+    by: 'row',
+    forward: true,
+    extend: true,
+  });
+});
+
+test('Up, Down, PageUp and PageDown move vertically', () => {
+  expect(keyCommand(key('ArrowUp'), false)).toEqual({
+    kind: 'vertical',
+    by: 'row',
+    forward: false,
+    extend: false,
+  });
+  expect(keyCommand(key('PageDown'), true)).toEqual({
+    kind: 'vertical',
+    by: 'page',
+    forward: true,
+    extend: false,
+  });
+});
+
+test('Tab, undo, redo and select all follow the platform', () => {
+  expect(keyCommand(key('Tab'), true)).toEqual({ kind: 'tab' });
+  expect(keyCommand(key('Tab', { shiftKey: true }), false)).toEqual({ kind: 'shiftTab' });
+  expect(keyCommand(key('z', { metaKey: true }), true)).toEqual({ kind: 'undo' });
+  expect(keyCommand(key('Z', { metaKey: true, shiftKey: true }), true)).toEqual({ kind: 'redo' });
+  expect(keyCommand(key('z', { ctrlKey: true }), false)).toEqual({ kind: 'undo' });
+  expect(keyCommand(key('Z', { ctrlKey: true, shiftKey: true }), false)).toEqual({
+    kind: 'redo',
+  });
+  expect(keyCommand(key('y', { ctrlKey: true }), false)).toEqual({ kind: 'redo' });
+  expect(keyCommand(key('a', { metaKey: true }), true)).toEqual({ kind: 'selectAll' });
+  expect(keyCommand(key('a', { ctrlKey: true }), false)).toEqual({ kind: 'selectAll' });
+});
+
+test('a shortcut on a layout whose key is not a Latin letter reads the physical key', () => {
+  expect(keyCommand(key('ئ', { metaKey: true, code: 'KeyZ' }), true)).toEqual({ kind: 'undo' });
+});
+
+test('keys the textarea handles itself, and every key while composing, give null', () => {
+  for (const k of [
+    key('Enter'),
+    key('Backspace'),
+    key('Delete'),
+    key('Unidentified'),
+    key('Process'),
+    key('a'),
+    key('z', { ctrlKey: true }),
+    key('y', { metaKey: true }),
+    key('Tab', { ctrlKey: true }),
+    key('ArrowLeft', { isComposing: true }),
+    key('ArrowLeft', { keyCode: 229 }),
+  ]) {
+    expect(keyCommand(k, true)).toBeNull();
+  }
+  expect(keyCommand(key('z', { metaKey: true }), false)).toBeNull();
+  expect(keyCommand(key('ArrowLeft', { altKey: true }), false)).toBeNull();
+});
diff --git a/src/web/input/CaretMover.ts b/src/web/input/CaretMover.ts
new file mode 100644
index 0000000..8327726
--- /dev/null
+++ b/src/web/input/CaretMover.ts
@@ -0,0 +1,52 @@
+// The document as the mover reads it.
+export type DocLike = {
+  readonly lineCount: number;
+  readonly length: number;
+  lineAt(offset: number): number;
+  lineStart(line: number): number;
+};
+
+// Visual rows of laid out lines, in pixels from the line's left edge, answered by the view.
+export type LineGeometry = {
+  rows(line: number): number;
+  rowOf(line: number, column: number): number;
+  caretX(line: number, column: number): number;
+  columnAt(line: number, row: number, x: number): number;
+};
+
+// Up, down and page movement by visual rows, the web twin of CaretMover.kt. The goal x lasts until reset.
+export class CaretMover {
+  private goalX: number | null = null;
+
+  reset(): void {
+    this.goalX = null;
+  }
+
+  // The offset rows visual rows from offset (negative is up), clamped to the document ends.
+  target(doc: DocLike, geometry: LineGeometry, offset: number, rows: number): number {
+    let line = doc.lineAt(offset);
+    const column = offset - doc.lineStart(line);
+    let row = geometry.rowOf(line, column);
+    const x = this.goalX ?? geometry.caretX(line, column);
+    this.goalX = x;
+    for (let left = rows; left < 0; left++) {
+      if (row > 0) {
+        row--;
+      } else {
+        if (line === 0) return 0;
+        line--;
+        row = geometry.rows(line) - 1;
+      }
+    }
+    for (let left = rows; left > 0; left--) {
+      if (row < geometry.rows(line) - 1) {
+        row++;
+      } else {
+        if (line === doc.lineCount - 1) return doc.length;
+        line++;
+        row = 0;
+      }
+    }
+    return doc.lineStart(line) + geometry.columnAt(line, row, x);
+  }
+}
diff --git a/src/web/input/keys.ts b/src/web/input/keys.ts
new file mode 100644
index 0000000..1ca0320
--- /dev/null
+++ b/src/web/input/keys.ts
@@ -0,0 +1,92 @@
+import type { MoveUnit } from '../core/EditorCore';
+
+export type KeyLike = {
+  key: string;
+  shiftKey: boolean;
+  altKey: boolean;
+  ctrlKey: boolean;
+  metaKey: boolean;
+  isComposing: boolean;
+  code?: string;
+  keyCode?: number;
+};
+
+export type KeyCommand =
+  | { kind: 'move'; unit: MoveUnit; forward: boolean; extend: boolean }
+  | { kind: 'vertical'; by: 'row' | 'page'; forward: boolean; extend: boolean }
+  | { kind: 'tab' | 'shiftTab' | 'undo' | 'redo' | 'selectAll' };
+
+// Keydown 229 is a key the keyboard's composition takes.
+const COMPOSING_KEY_CODE = 229;
+
+// The letter of a shortcut, from the physical key when the layout's key is not a Latin letter.
+function letter(k: KeyLike): string {
+  const key = k.key.toLowerCase();
+  if (/^[a-z]$/.test(key)) return key;
+  return /^Key[A-Z]$/.test(k.code ?? '') ? (k.code as string).slice(3).toLowerCase() : key;
+}
+
+// What a hardware key asks the editor to do, or null for a key the textarea handles itself.
+export function keyCommand(k: KeyLike, mac: boolean): KeyCommand | null {
+  if (k.isComposing || k.keyCode === COMPOSING_KEY_CODE) return null;
+  const extend = k.shiftKey;
+  const move = (unit: MoveUnit, forward: boolean): KeyCommand => ({
+    kind: 'move',
+    unit,
+    forward,
+    extend,
+  });
+  const vertical = (by: 'row' | 'page', forward: boolean): KeyCommand => ({
+    kind: 'vertical',
+    by,
+    forward,
+    extend,
+  });
+  // Command on a Mac, Control elsewhere.
+  const primary = mac ? k.metaKey && !k.ctrlKey : k.ctrlKey && !k.metaKey;
+  const plain = !k.ctrlKey && !k.metaKey && !k.altKey;
+  switch (k.key) {
+    case 'ArrowLeft':
+    case 'ArrowRight': {
+      const forward = k.key === 'ArrowRight';
+      if (plain) return move('char', forward);
+      if (mac && k.altKey && !k.metaKey && !k.ctrlKey) return move('word', forward);
+      if (mac && k.metaKey && !k.altKey && !k.ctrlKey)
+        return move(forward ? 'lineEnd' : 'lineStart', forward);
+      if (!mac && k.ctrlKey && !k.altKey && !k.metaKey) return move('word', forward);
+      return null;
+    }
+    case 'ArrowUp':
+    case 'ArrowDown': {
+      const forward = k.key === 'ArrowDown';
+      if (plain) return vertical('row', forward);
+      if (mac && k.metaKey && !k.altKey && !k.ctrlKey)
+        return move(forward ? 'docEnd' : 'docStart', forward);
+      return null;
+    }
+    case 'PageUp':
+    case 'PageDown':
+      return plain ? vertical('page', k.key === 'PageDown') : null;
+    case 'Home':
+    case 'End': {
+      const forward = k.key === 'End';
+      if (plain) return move(forward ? 'lineEnd' : 'lineStart', forward);
+      if ((k.ctrlKey || k.metaKey) && !k.altKey)
+        return move(forward ? 'docEnd' : 'docStart', forward);
+      return null;
+    }
+    case 'Tab':
+      if (!plain) return null;
+      return { kind: k.shiftKey ? 'shiftTab' : 'tab' };
+  }
+  if (!primary || k.altKey) return null;
+  switch (letter(k)) {
+    case 'z':
+      return { kind: k.shiftKey ? 'redo' : 'undo' };
+    case 'y':
+      return !mac && !k.shiftKey ? { kind: 'redo' } : null;
+    case 'a':
+      return k.shiftKey ? null : { kind: 'selectAll' };
+  }
+  return null;
+}
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index 9642350..6a30448 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -318,6 +318,144 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    const head = (page) => page.evaluate(() => window.views.a.core.selection.head);
+
+    test('ArrowDown keeps the column across a shorter line', async () => {
+      const { page, errors } = await open();
+      await editor(page, 'a', 'abcdef\nab\nabcdef');
+      await clickAt(page, 'a', 0, 5);
+      await page.keyboard.press('ArrowDown');
+      assert.equal(await head(page), 9);
+      await page.keyboard.press('ArrowDown');
+      assert.equal(await head(page), 15);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
+    test('ArrowDown on the last visible row scrolls and moves', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));
+      await clickAt(page, 'a', 0, 2);
+      const rows = await page.evaluate(() => {
+        const v = window.views.a;
+        return Math.ceil(v.layout.viewportHeight / v.layout.rowHeight);
+      });
+      for (let i = 0; i < rows + 3; i++) await page.keyboard.press('ArrowDown');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const caret = v.caretRect(v.core.selection.head);
+        return { line: v.core.lineAt(v.core.selection.head), y: caret?.y ?? null };
+      });
+      assert.equal(result.line, rows + 3);
+      assert.ok(result.y !== null && result.y >= 0 && result.y < 300, `caret y ${result.y}`);
+      await page.close();
+    });
+
+    test('Enter on the last visible row keeps the caret in view', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n'));
+      const last = await page.evaluate(() => {
+        const v = window.views.a;
+        return Math.floor(v.layout.viewportHeight / v.layout.rowHeight) - 1;
+      });
+      await clickAt(page, 'a', last, 6);
+      for (let i = 0; i < 3; i++) await page.keyboard.press('Enter');
+      const y = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        return v.caretRect(v.core.selection.head)?.y ?? null;
+      });
+      assert.ok(y !== null && y >= 0 && y < 300, `caret y ${y}`);
+      await page.close();
+    });
+
+    test('PageDown moves by the visible rows', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press('PageDown');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const caret = v.caretRect(v.core.selection.head);
+        return {
+          line: v.core.lineAt(v.core.selection.head),
+          page: Math.floor(v.layout.viewportHeight / v.layout.rowHeight),
+          y: caret?.y ?? null,
+        };
+      });
+      assert.equal(result.line, result.page);
+      assert.ok(result.y !== null && result.y >= 0 && result.y < 300, `caret y ${result.y}`);
+      await page.close();
+    });
+
+    test('Shift+ArrowRight draws a selection', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdef');
+      await clickAt(page, 'a', 0, 1);
+      await page.keyboard.press('Shift+ArrowRight');
+      await page.keyboard.press('Shift+ArrowRight');
+      const result = await page.evaluate(async () => {
+        const v = window.views.a;
+        await window.codepad.frames(2);
+        const boxes = [...document.querySelectorAll('#a [data-selection] > div')];
+        return { selection: v.core.selection, width: boxes[0]?.getBoundingClientRect().width ?? 0 };
+      });
+      assert.deepEqual(result.selection, { anchor: 1, head: 3 });
+      assert.ok(result.width > 0, 'no selection drawn');
+      await page.close();
+    });
+
+    test('Tab indents, keeps the focus, and the platform undo key takes it back', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc');
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press('Tab');
+      assert.notEqual(await textOf(page, 'a'), 'abc');
+      assert.equal(await page.evaluate(() => document.activeElement?.tagName), 'TEXTAREA');
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+z`);
+      assert.equal(await textOf(page, 'a'), 'abc');
+      await page.close();
+    });
+
+    test('ref typeText auto-closes and moveCaret up keeps the goal column', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdefghij\nab\nabcdef');
+      const result = await page.evaluate(() => {
+        const v = window.views.a;
+        v.apply(() => v.core.setSelection(20, 20));
+        v.typeText('(');
+        const typed = { text: v.core.text(), head: v.core.selection.head };
+        v.moveCaret('up', false);
+        const first = v.core.selection.head;
+        v.moveCaret('up', false);
+        return { typed, first, second: v.core.selection.head };
+      });
+      assert.deepEqual(result, {
+        typed: { text: 'abcdefghij\nab\nabcdef()', head: 21 },
+        first: 13,
+        second: 7,
+      });
+      await page.close();
+    });
+
+    test('the typing ref methods do nothing under readOnly while moveCaret still moves', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abc', { readOnly: true });
+      const result = await page.evaluate(() => {
+        const v = window.views.a;
+        v.apply(() => v.core.setSelection(1, 1));
+        v.typeText('x');
+        v.deleteBackward();
+        v.deleteForward();
+        v.moveCaret('right', true);
+        return { text: v.core.text(), selection: v.core.selection };
+      });
+      assert.deepEqual(result, { text: 'abc', selection: { anchor: 1, head: 2 } });
+      await page.close();
+    });
+
     test('colors python keywords', async () => {
       const { page, errors } = await open();
       const color = await page.evaluate(async () => {

From 974bd973b0d8548fc2033f4976449cc880d99f5c Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 00:50:00 +0100
Subject: [PATCH 07/23] feat(web): avoidKeyboard follows the visual viewport

---
 example/src/EditorApp.web.tsx           | 30 +++++++++++++++++----
 src/web/CodeEditor.tsx                  |  5 ++--
 src/web/EditorView.ts                   | 25 ++++++++++++++---
 src/web/__tests__/keyboardInset.test.ts |  8 ++++++
 src/web/input/keyboardInset.ts          | 29 ++++++++++++++++++++
 src/web/pump.ts                         | 36 ++++++++++++++++++++++++-
 6 files changed, 122 insertions(+), 11 deletions(-)
 create mode 100644 src/web/__tests__/keyboardInset.test.ts
 create mode 100644 src/web/input/keyboardInset.ts

diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx
index 761f84e..339606d 100644
--- a/example/src/EditorApp.web.tsx
+++ b/example/src/EditorApp.web.tsx
@@ -1,6 +1,7 @@
-import { useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
 import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
 import { CodeEditor, Codepad } from 'react-native-codepad';
+import { generateJavaScript } from './bench/generate';
 import { GENERATED_FILES, SAMPLE_FILES } from './files';
 import { NESTED_SNIPPET } from './screens/nestedSnippet';
 import { THEMES } from './themes';
@@ -24,14 +25,32 @@ export function EditorApp() {
   const [scrollEnabled, setScrollEnabled] = useState(true);
   const [demo, setDemo] = useState('editor');
   const theme = THEMES[themeIndex % THEMES.length]?.theme;
+  // Lines of the generated JavaScript file the typing bench opened, 0 for a picked file.
+  const [benchLines, setBenchLines] = useState(0);
   const file = FILES.find((f) => f.id === fileId) ?? FILES[0];
-  const text = useMemo(() => file?.load() ?? '', [file]);
+  const text = useMemo(
+    () => (benchLines ? generateJavaScript(benchLines) : (file?.load() ?? '')),
+    [file, benchLines],
+  );
   // Set when a file or a demo is picked, so the first paint counts from the tap.
   const started = useRef(performance.now());
   const pick = (set: (value: T) => void, value: T) => {
     started.current = performance.now();
+    setBenchLines(0);
     set(value);
   };
+
+  // scripts/bench-web.mjs opens its file through this hook.
+  useEffect(() => {
+    if (!__DEV__) return;
+    (globalThis as { __codepadBench?: { open(lines: number): void } }).__codepadBench = {
+      open: (lines) => {
+        started.current = performance.now();
+        setDemo('editor');
+        setBenchLines(lines);
+      },
+    };
+  }, []);
   const ready = (label: string) => () =>
     console.log(
       `[example] ${label} first paint ${Math.round(performance.now() - started.current)} ms`,
@@ -71,14 +90,15 @@ export function EditorApp() {
       
       {demo === 'editor' ? (
         
       ) : null}
       {demo === 'nested' ? (
diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx
index e453a5b..209af18 100644
--- a/src/web/CodeEditor.tsx
+++ b/src/web/CodeEditor.tsx
@@ -119,6 +119,7 @@ export const CodeEditor = forwardRef(function Co
       autoCloseBrackets,
       suggestions,
       autoFocus,
+      avoidKeyboard,
       onFocus: () => handlers.current.onFocus?.(),
       onBlur: () => handlers.current.onBlur?.(),
       onContentSize: (width, height) => handlers.current.onContentSizeChange?.({ width, height }),
@@ -159,6 +160,7 @@ export const CodeEditor = forwardRef(function Co
       autoCloseBrackets,
       suggestions,
       autoFocus,
+      avoidKeyboard,
     ],
   );
   const latest = useRef({ options, language });
@@ -205,10 +207,9 @@ export const CodeEditor = forwardRef(function Co
   }, []);
 
   useEffect(() => {
-    if (avoidKeyboard) notYet('avoidKeyboard');
     if (decorations) notYet('decorations');
     if (onGapLayout) notYet('onGapLayout');
-  }, [avoidKeyboard, decorations, onGapLayout]);
+  }, [decorations, onGapLayout]);
 
   useEffect(() => {
     view?.setOptions(options);
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 27b3639..93eae2b 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -7,10 +7,11 @@ import type { CoreModule } from './core/module';
 import { type DecodedFrame, decodeFrame } from './frame';
 import { CaretMover, type LineGeometry } from './input/CaretMover';
 import { InputHost } from './input/InputHost';
+import { overlapOf, watchViewport } from './input/keyboardInset';
 import { keyCommand } from './input/keys';
 import { WebInputSession } from './input/WebInputSession';
 import { ensureInjected, ensureLanguage, onRegistered } from './loader';
-import { registerView, requestPump } from './pump';
+import { probeKey, probing, registerView, requestPump } from './pump';
 import { type CssTheme, cssTheme } from './theme';
 
 export type ViewOptions = {
@@ -38,6 +39,7 @@ export type ViewOptions = {
   onSelection?: (anchor: number, head: number, revision: number) => void;
   suggestions: Suggestions;
   autoFocus: boolean;
+  avoidKeyboard: boolean;
   onFocus?: () => void;
   onBlur?: () => void;
 };
@@ -63,6 +65,7 @@ export const DEFAULT_OPTIONS: ViewOptions = {
   autoCloseBrackets: true,
   suggestions: 'off',
   autoFocus: false,
+  avoidKeyboard: false,
 };
 
 const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
@@ -127,6 +130,9 @@ export class EditorView {
   private frameText = 0;
   private frameTextCap = 0;
   private readonly onScrollEvent = () => this.invalidate();
+  private offViewport: () => void = () => {};
+  // The keyboard's overlap with the editor, part of the bottom inset under avoidKeyboard.
+  private keyboard = 0;
   // Injection names the engine found no language for, and the ids this view already refreshed after.
   private readonly missed = new Set();
   private readonly refreshedFor = new Set();
@@ -228,6 +234,10 @@ export class EditorView {
       before.lineNumbers !== this.o.lineNumbers ||
       before.scrollEnabled !== this.o.scrollEnabled;
     if (before.scrollEnabled !== this.o.scrollEnabled) this.listenToPage(!this.o.scrollEnabled);
+    if (before.avoidKeyboard !== this.o.avoidKeyboard) {
+      this.offViewport();
+      this.offViewport = this.o.avoidKeyboard ? watchViewport(this.onScrollEvent) : () => {};
+    }
     this.input.setSuggestions(this.o.suggestions);
     this.input.setReadOnly(this.o.readOnly);
     if (
@@ -350,6 +360,7 @@ export class EditorView {
 
   // A keyboard edit or caret move shows the caret, a selection the page wrote back does not.
   private applyInput(edit: () => void): void {
+    const start = probing ? performance.now() : 0;
     const revision = this.core.revision;
     const before = this.core.selection;
     this.inputting = true;
@@ -358,6 +369,7 @@ export class EditorView {
     } finally {
       this.inputting = false;
     }
+    if (probing) probeKey(this, performance.now() - start);
     const after = this.core.selection;
     if (
       this.core.revision !== revision ||
@@ -681,6 +693,7 @@ export class EditorView {
     this.scroller.removeEventListener('click', this.onClickEvent);
     this.scroller.removeEventListener('mousedown', this.onMouseDownEvent);
     this.listenToPage(false);
+    this.offViewport();
     this.resize?.disconnect();
     document.fonts?.removeEventListener?.('loadingdone', this.remeasureEvent);
     this.scroller.removeEventListener('scroll', this.onScrollEvent);
@@ -797,7 +810,12 @@ export class EditorView {
     if (this.layout.gutterWidth !== gutter) this.layout.gutterWidth = gutter;
     if (this.layout.textPadding !== o.textPadding) this.layout.textPadding = o.textPadding;
     this.layout.resize(width, height);
-    this.layout.setInsets(insets.top ?? 0, insets.bottom ?? 0, insets.left ?? 0, insets.right ?? 0);
+    // An editor that sizes to its text leaves the keyboard to the page.
+    const keyboard = o.avoidKeyboard && o.scrollEnabled ? overlapOf(this.root) : 0;
+    if (keyboard > this.keyboard && this.input.focused) this.revealing = true;
+    this.keyboard = keyboard;
+    const bottom = (insets.bottom ?? 0) + keyboard;
+    this.layout.setInsets(insets.top ?? 0, bottom, insets.left ?? 0, insets.right ?? 0);
     if (o.softWrap && this.layout.textAreaWidth !== before) this.relayout();
   }
 
@@ -1017,7 +1035,8 @@ export class EditorView {
   private report(): void {
     const layout = this.layout;
     const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight;
-    const height = layout.insetTop + layout.contentHeight + layout.insetBottom;
+    // The keyboard's inset is not the content's size.
+    const height = layout.insetTop + layout.contentHeight + layout.insetBottom - this.keyboard;
     if (width !== this.lastContent.width || height !== this.lastContent.height) {
       this.lastContent = { width, height };
       this.o.onContentSize?.(width, height);
diff --git a/src/web/__tests__/keyboardInset.test.ts b/src/web/__tests__/keyboardInset.test.ts
new file mode 100644
index 0000000..d6df4b0
--- /dev/null
+++ b/src/web/__tests__/keyboardInset.test.ts
@@ -0,0 +1,8 @@
+import { expect, test } from '@jest/globals';
+import { keyboardOverlap } from '../input/keyboardInset';
+
+test('the keyboard covers what lies below the visual viewport', () => {
+  expect(keyboardOverlap(800, 0, 500)).toBe(300);
+  expect(keyboardOverlap(400, 0, 500)).toBe(0);
+  expect(keyboardOverlap(800, 100, 500)).toBe(200);
+});
diff --git a/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts
new file mode 100644
index 0000000..473f25a
--- /dev/null
+++ b/src/web/input/keyboardInset.ts
@@ -0,0 +1,29 @@
+/// 
+
+// How far the editor reaches below the visual viewport, which the keyboard shrinks on phones.
+export function keyboardOverlap(
+  editorBottom: number,
+  viewportTop: number,
+  viewportHeight: number,
+): number {
+  return Math.max(0, editorBottom - (viewportTop + viewportHeight));
+}
+
+// The keyboard's overlap with an element's box, 0 where the page has no visual viewport.
+export function overlapOf(el: HTMLElement): number {
+  const vv = typeof window === 'undefined' ? undefined : window.visualViewport;
+  if (!vv) return 0;
+  return Math.round(keyboardOverlap(el.getBoundingClientRect().bottom, vv.offsetTop, vv.height));
+}
+
+// Calls back when the visual viewport moves or resizes, as the keyboard opens, closes or animates. Returns the removal.
+export function watchViewport(changed: () => void): () => void {
+  const vv = typeof window === 'undefined' ? undefined : window.visualViewport;
+  if (!vv) return () => {};
+  vv.addEventListener('resize', changed);
+  vv.addEventListener('scroll', changed);
+  return () => {
+    vv.removeEventListener('resize', changed);
+    vv.removeEventListener('scroll', changed);
+  };
+}
diff --git a/src/web/pump.ts b/src/web/pump.ts
index 72fd53c..24cc8f8 100644
--- a/src/web/pump.ts
+++ b/src/web/pump.ts
@@ -4,11 +4,34 @@ import type { CoreModule } from './core/module';
 export const PUMP_BUDGET_MS = 6;
 
 type View = { draw(): void };
+type Probe = { work: number[]; pumps: number[] };
 
 const views = new Set();
 let core: CoreModule | null = null;
 let scheduled = false;
 
+// With localStorage codepad_debug set to 1 at load, the bench reads key and frame times from globalThis.
+const probe: Probe | null = debugOn() ? { work: [], pumps: [] } : null;
+if (probe) (globalThis as { __codepadProbe?: Probe }).__codepadProbe = probe;
+let keyView: View | null = null;
+let keyMs = 0;
+
+function debugOn(): boolean {
+  try {
+    return globalThis.localStorage?.getItem('codepad_debug') === '1';
+  } catch {
+    return false;
+  }
+}
+
+export const probing = probe !== null;
+
+// A key's handler time, counted into the work of the next frame that draws its view.
+export function probeKey(view: View, ms: number): void {
+  keyView = view;
+  keyMs += ms;
+}
+
 export function setPumpCore(m: CoreModule): void {
   core = m;
 }
@@ -31,7 +54,18 @@ export function requestPump(): void {
 
 function frame(): void {
   scheduled = false;
+  const start = probe ? performance.now() : 0;
   const left = core ? core._cpw_pump(PUMP_BUDGET_MS) : 0;
-  for (const view of [...views]) view.draw();
+  const pumped = probe ? performance.now() - start : 0;
+  for (const view of [...views]) {
+    const drawStart = probe ? performance.now() : 0;
+    view.draw();
+    if (probe && view === keyView) {
+      probe.work.push(keyMs + pumped + performance.now() - drawStart);
+      keyView = null;
+      keyMs = 0;
+    }
+  }
+  if (probe) probe.pumps.push(performance.now() - start);
   if (left > 0) requestPump();
 }

From 1022d41e573dad4c5bd4d221424b99600437d006 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 00:50:35 +0100
Subject: [PATCH 08/23] chore(web): a typing bench for Chrome on a phone

---
 package.json          |  1 +
 scripts/bench-web.mjs | 62 +++++++++++++++++++++++++++++++++++++++++++
 src/web/EditorView.ts | 11 ++++----
 src/web/pump.ts       | 19 ++++++++++---
 4 files changed, 85 insertions(+), 8 deletions(-)
 create mode 100644 scripts/bench-web.mjs

diff --git a/package.json b/package.json
index 84d2d84..a9793ac 100644
--- a/package.json
+++ b/package.json
@@ -67,6 +67,7 @@
     "ime:record:web": "node tests/ime-web/recorder/serve.mjs",
     "ime:record:ios": "scripts/ime-record-ios.sh",
     "bench:ios": "scripts/bench-ios.sh",
+    "bench:web": "node scripts/bench-web.mjs",
     "release": "release-it --only-version",
     "docs": "yarn workspace react-native-codepad-website dev",
     "docs:build": "yarn workspace react-native-codepad-website build",
diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs
new file mode 100644
index 0000000..988882d
--- /dev/null
+++ b/scripts/bench-web.mjs
@@ -0,0 +1,62 @@
+// Typing bench for the web editor in Chrome on an Android phone: yarn bench:web [lines] [port].
+// First: yarn example web --port , adb reverse tcp: tcp:, the example open in Chrome on the phone.
+// The port is the example's, 8082 by default.
+import { execFileSync } from 'node:child_process';
+import { chromium } from 'playwright';
+
+const lines = Number(process.argv[2] ?? 300);
+const CHARS = 60;
+const GAP_MS = 150;
+const TEXT = 'let total = value + 1; '.repeat(3).slice(0, CHARS);
+const PORT = 9222;
+const WEB_PORT = process.argv[3] ?? '8082';
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const pct = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
+const ms = (n) => `${n.toFixed(1)} ms`;
+
+execFileSync('adb', ['forward', `tcp:${PORT}`, 'localabstract:chrome_devtools_remote']);
+const browser = await chromium.connectOverCDP(`http://127.0.0.1:${PORT}`);
+try {
+  const page = browser
+    .contexts()
+    .flatMap((c) => c.pages())
+    .find((p) => new RegExp(`//(localhost|127\\.0\\.0\\.1):${WEB_PORT}/`).test(p.url()));
+  if (!page) throw new Error(`open http://localhost:${WEB_PORT} in Chrome on the phone first`);
+  await page.evaluate(() => localStorage.setItem('codepad_debug', '1'));
+  await page.reload();
+  await page.waitForFunction(() => globalThis.__codepadBench && globalThis.__codepadProbe);
+  const opened = page.waitForEvent('console', {
+    predicate: (m) => m.text().includes(`bench ${lines} first paint`),
+    timeout: 60000,
+  });
+  await page.evaluate((n) => globalThis.__codepadBench.open(n), lines);
+  console.log((await opened).text());
+  const box = await page.locator('[data-line="2"]').first().boundingBox();
+  if (!box) throw new Error('the editor drew no line 2');
+  await page.mouse.click(box.x + 4, box.y + box.height / 2);
+  await sleep(1000);
+  await page.evaluate(() => {
+    for (const list of Object.values(globalThis.__codepadProbe)) list.length = 0;
+  });
+  const cdp = await page.context().newCDPSession(page);
+  for (const ch of TEXT) {
+    await cdp.send('Input.insertText', { text: ch });
+    await sleep(GAP_MS);
+  }
+  await sleep(500);
+  const probe = await page.evaluate(() => globalThis.__codepadProbe);
+  const stats = (list) => {
+    const sorted = [...list].sort((a, b) => a - b);
+    return `p50 ${ms(pct(sorted, 0.5))}, p95 ${ms(pct(sorted, 0.95))}, max ${ms(sorted.at(-1) ?? 0)}`;
+  };
+  console.log(`${lines} lines, ${probe.work.length} of ${CHARS} keys`);
+  for (const part of ['work', 'handler', 'engine', 'draw']) {
+    console.log(`  ${part.padEnd(8)}${stats(probe[part])}`);
+  }
+  console.log(`  largest pump ${ms(Math.max(0, ...probe.pumps))} of ${probe.pumps.length}`);
+  await page.evaluate(() => localStorage.removeItem('codepad_debug'));
+} finally {
+  await browser.close();
+  execFileSync('adb', ['forward', '--remove', `tcp:${PORT}`]);
+}
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 93eae2b..1dfb234 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -369,14 +369,15 @@ export class EditorView {
     } finally {
       this.inputting = false;
     }
-    if (probing) probeKey(this, performance.now() - start);
     const after = this.core.selection;
     if (
-      this.core.revision !== revision ||
-      after.anchor !== before.anchor ||
-      after.head !== before.head
+      this.core.revision === revision &&
+      after.anchor === before.anchor &&
+      after.head === before.head
     )
-      this.revealing = true;
+      return;
+    this.revealing = true;
+    if (probing) probeKey(this, performance.now() - start);
   }
 
   // A hardware key the editor runs itself. True when the browser must not act on it.
diff --git a/src/web/pump.ts b/src/web/pump.ts
index 24cc8f8..9015f9e 100644
--- a/src/web/pump.ts
+++ b/src/web/pump.ts
@@ -4,14 +4,23 @@ import type { CoreModule } from './core/module';
 export const PUMP_BUDGET_MS = 6;
 
 type View = { draw(): void };
-type Probe = { work: number[]; pumps: number[] };
+// Per key: work and its three parts, the handler, the engine share of the frame that draws it, and that draw.
+type Probe = {
+  work: number[];
+  handler: number[];
+  engine: number[];
+  draw: number[];
+  pumps: number[];
+};
 
 const views = new Set();
 let core: CoreModule | null = null;
 let scheduled = false;
 
 // With localStorage codepad_debug set to 1 at load, the bench reads key and frame times from globalThis.
-const probe: Probe | null = debugOn() ? { work: [], pumps: [] } : null;
+const probe: Probe | null = debugOn()
+  ? { work: [], handler: [], engine: [], draw: [], pumps: [] }
+  : null;
 if (probe) (globalThis as { __codepadProbe?: Probe }).__codepadProbe = probe;
 let keyView: View | null = null;
 let keyMs = 0;
@@ -61,7 +70,11 @@ function frame(): void {
     const drawStart = probe ? performance.now() : 0;
     view.draw();
     if (probe && view === keyView) {
-      probe.work.push(keyMs + pumped + performance.now() - drawStart);
+      const drawn = performance.now() - drawStart;
+      probe.work.push(keyMs + pumped + drawn);
+      probe.handler.push(keyMs);
+      probe.engine.push(pumped);
+      probe.draw.push(drawn);
       keyView = null;
       keyMs = 0;
     }

From 827d82943fe9edf88236c097863767f042d3bcbd Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 01:14:11 +0100
Subject: [PATCH 09/23] perf(web): write only the styles a draw changes

In Chrome on an Android phone, typing in a 300-line file spent most of each
key's draw rewriting every gutter number and line position and laying the
page out twice, for a work p50 of 10.6-15.3 ms. A draw now writes a style or
a text only when it changes, and the reveal reads the caret the draw already
measured. The work p50 is now 8.2-11.5 ms.
---
 src/web/EditorView.ts      | 136 +++++++++++++++++++++++--------------
 src/web/input/InputHost.ts |   8 ++-
 2 files changed, 90 insertions(+), 54 deletions(-)

diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 1dfb234..b0271a0 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -153,6 +153,10 @@ export class EditorView {
   private movingVertically = false;
   // The caret scrolls into view on the next draw, before the page paints.
   private revealing = false;
+  // The caret as the last frame measured it, null while its line is not drawn.
+  private drawnCaret: Rect | null = null;
+  // The row of the drawn caret inside its wrapped line.
+  private drawnCaretRow = 0;
   // Hidden copies of lines a caret move measured, dropped on the next draw.
   private readonly measuring = new Map();
   private readonly geometry: LineGeometry = {
@@ -524,43 +528,58 @@ export class EditorView {
   }
 
   // The caret, the composing underline and the selection, from where the browser drew the text.
+  // Every read comes before every write, so a draw lays the page out once.
   private drawInput(): void {
     const box = this.textLayer.getBoundingClientRect();
     const { anchor, head } = this.core.selection;
-    const caret = this.input.focused ? this.caretRect(head) : null;
+    const caret = this.caretRect(head);
+    this.drawnCaret = caret;
     const rootBox = this.root.getBoundingClientRect();
-    if (caret) {
-      const x = caret.x + rootBox.left - box.left;
-      const y = caret.y + rootBox.top - box.top;
-      const style = this.caretEl.style;
-      style.display = 'block';
-      style.left = `${x}px`;
-      style.top = `${y}px`;
-      style.height = `${caret.height}px`;
-      style.background = this.css.cursor;
-      this.input.place(caret.x, caret.y);
-    } else {
-      this.caretEl.style.display = 'none';
-    }
+    const caretLine = this.cache.get(this.core.lineAt(head))?.el;
+    this.drawnCaretRow =
+      caret && caretLine
+        ? Math.max(
+            0,
+            Math.round(
+              (caret.y + rootBox.top - caretLine.getBoundingClientRect().top) / this.rowHeight,
+            ),
+          )
+        : 0;
     const composing = this.session.composing;
-    this.composingLayer.replaceChildren(
-      ...(composing ? this.rangeRects(composing.start, composing.end) : []).map((r) => {
-        const bar = div(
-          `position:absolute;left:${r.left - box.left}px;top:${r.bottom - box.top - 2}px;width:${r.width}px;height:2px;background:${this.css.cursor};`,
-        );
-        bar.dataset.composing = '';
-        return bar;
-      }),
-    );
+    const bars = composing ? this.rangeRects(composing.start, composing.end) : [];
     const from = Math.min(anchor, head);
     const to = Math.max(anchor, head);
-    this.selectionLayer.replaceChildren(
-      ...(from < to ? this.rangeRects(from, to) : []).map((r) =>
-        div(
-          `position:absolute;left:${r.left - box.left}px;top:${r.top - box.top}px;width:${Math.max(r.width, 4)}px;height:${r.height}px;background:${this.css.selection};`,
+    const selected = from < to ? this.rangeRects(from, to) : [];
+    if (caret && this.input.focused) {
+      put(this.caretEl, 'display', 'block');
+      put(this.caretEl, 'left', `${caret.x + rootBox.left - box.left}px`);
+      put(this.caretEl, 'top', `${caret.y + rootBox.top - box.top}px`);
+      put(this.caretEl, 'height', `${caret.height}px`);
+      put(this.caretEl, 'background', this.css.cursor);
+      this.input.place(caret.x, caret.y);
+    } else {
+      put(this.caretEl, 'display', 'none');
+    }
+    if (bars.length || this.composingLayer.childElementCount) {
+      this.composingLayer.replaceChildren(
+        ...bars.map((r) => {
+          const bar = div(
+            `position:absolute;left:${r.left - box.left}px;top:${r.bottom - box.top - 2}px;width:${r.width}px;height:2px;background:${this.css.cursor};`,
+          );
+          bar.dataset.composing = '';
+          return bar;
+        }),
+      );
+    }
+    if (selected.length || this.selectionLayer.childElementCount) {
+      this.selectionLayer.replaceChildren(
+        ...selected.map((r) =>
+          div(
+            `position:absolute;left:${r.left - box.left}px;top:${r.top - box.top}px;width:${Math.max(r.width, 4)}px;height:${r.height}px;background:${this.css.selection};`,
+          ),
         ),
-      ),
-    );
+      );
+    }
   }
 
   // The page boxes of the document range on the lines that are drawn.
@@ -608,14 +627,12 @@ export class EditorView {
 
   // Scrolls the least that shows the caret, by its line's row while the line is not drawn. True when it scrolled.
   private revealCaret(): boolean {
-    const caret = this.caretRect(this.core.selection.head);
+    const caret = this.drawnCaret;
     const line = this.core.lineAt(this.core.selection.head);
     let row = this.layout.rowStart(line);
-    const el = this.cache.get(line)?.el;
-    if (caret && el) {
+    if (caret) {
       // The caret's row inside a wrapped line, from where the browser drew it.
-      const lineY = el.getBoundingClientRect().top - this.root.getBoundingClientRect().top;
-      row += Math.max(0, Math.round((caret.y - lineY) / this.rowHeight));
+      row += this.drawnCaretRow;
     }
     const top = row * this.rowHeight;
     const x = caret ? caret.x - this.layout.textLeft : 0;
@@ -656,7 +673,7 @@ export class EditorView {
     // A caret moved off screen scrolls into view in the same task, so no frame paints without it. A caret line that
     // was not drawn is revealed by its row first, then again by its x once drawn.
     for (let pass = 0; this.revealing && pass < 2; pass++) {
-      if (this.caretRect(this.core.selection.head)) this.revealing = false;
+      if (this.drawnCaret) this.revealing = false;
       if (!this.revealCaret()) break;
       this.syncScroll();
       moved = this.frame();
@@ -962,10 +979,10 @@ export class EditorView {
     const left = layout.textAreaLeft + layout.textPadding;
     const width = layout.textAreaLeft + layout.contentWidth + layout.insetRight;
     const height = layout.insetTop + layout.contentHeight + layout.insetBottom;
-    this.content.style.width = `${width}px`;
-    this.content.style.height = `${height}px`;
-    this.gutter.style.width = `${layout.insetLeft + layout.gutterWidth}px`;
-    this.gutter.style.height = `${height}px`;
+    put(this.content, 'width', `${width}px`);
+    put(this.content, 'height', `${height}px`);
+    put(this.gutter, 'width', `${layout.insetLeft + layout.gutterWidth}px`);
+    put(this.gutter, 'height', `${height}px`);
     if (!this.o.scrollEnabled) this.root.style.height = `${height}px`;
     const visible = new Set();
     for (let line = frame.first; line <= frame.last; line++) {
@@ -973,10 +990,9 @@ export class EditorView {
       if (!entry) continue;
       visible.add(line);
       const top = layout.lineTop(line) + scrollY;
-      const s = entry.el.style;
-      s.top = `${top}px`;
-      s.left = `${left}px`;
-      s.width = this.o.softWrap ? `${layout.wrapWidth}px` : '';
+      put(entry.el, 'top', `${top}px`);
+      put(entry.el, 'left', `${left}px`);
+      put(entry.el, 'width', this.o.softWrap ? `${layout.wrapWidth}px` : '');
       if (!entry.el.isConnected) this.textLayer.append(entry.el);
       this.attached.add(line);
       this.number(line, top, frame.caretLine === line);
@@ -994,14 +1010,14 @@ export class EditorView {
     this.evict(visible);
     const collapsed = frame.anchor === frame.head;
     const showActive = this.o.highlightActiveLine && collapsed && visible.has(frame.caretLine);
-    this.activeLine.style.display = showActive ? 'block' : 'none';
+    put(this.activeLine, 'display', showActive ? 'block' : 'none');
     if (showActive) {
-      this.activeLine.style.top = `${layout.lineTop(frame.caretLine) + scrollY}px`;
-      this.activeLine.style.height = `${layout.rows(frame.caretLine) * this.rowHeight}px`;
-      this.activeLine.style.width = `${width}px`;
+      put(this.activeLine, 'top', `${layout.lineTop(frame.caretLine) + scrollY}px`);
+      put(this.activeLine, 'height', `${layout.rows(frame.caretLine) * this.rowHeight}px`);
+      put(this.activeLine, 'width', `${width}px`);
     }
     const empty = frame.length === 0 && this.o.placeholder !== '';
-    this.placeholderEl.style.display = empty ? 'block' : 'none';
+    put(this.placeholderEl, 'display', empty ? 'block' : 'none');
     if (empty) {
       this.placeholderEl.textContent = this.o.placeholder;
       this.placeholderEl.style.top = `${layout.insetTop}px`;
@@ -1017,10 +1033,10 @@ export class EditorView {
       this.gutter.append(el);
       this.gutterLines.set(line, el);
     }
-    el.textContent = String(line + 1);
-    el.style.top = `${top}px`;
-    el.style.width = `${this.layout.insetLeft + this.layout.gutterWidth - this.charWidth}px`;
-    el.style.color = active ? this.css.gutterActiveForeground : '';
+    put(el, 'text', String(line + 1));
+    put(el, 'top', `${top}px`);
+    put(el, 'width', `${this.layout.insetLeft + this.layout.gutterWidth - this.charWidth}px`);
+    put(el, 'color', active ? this.css.gutterActiveForeground : '');
   }
 
   // Keeps about three screens of laid out lines.
@@ -1225,6 +1241,22 @@ function caretEdge(el: HTMLElement, column: number): { x: number; top: number; h
   return { x: box.left, top: box.top, height: 0 };
 }
 
+const written = new WeakMap>();
+
+// Sets a style, or the text with key text, only when it differs from what this last set, so a draw that moves
+// nothing leaves the page's layout valid.
+function put(el: HTMLElement, key: string, value: string): void {
+  let last = written.get(el);
+  if (!last) {
+    last = {};
+    written.set(el, last);
+  }
+  if (last[key] === value) return;
+  last[key] = value;
+  if (key === 'text') el.textContent = value;
+  else el.style.setProperty(key, value);
+}
+
 // The first integer in [lo, hi) where test holds, or hi, for a test that stays true once it holds.
 function firstWhere(lo: number, hi: number, test: (n: number) => boolean): number {
   let a = lo;
diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts
index f610af1..e4cb598 100644
--- a/src/web/input/InputHost.ts
+++ b/src/web/input/InputHost.ts
@@ -101,8 +101,12 @@ export class InputHost {
 
   // Keeps the textarea at the caret, so the keyboard's candidate window opens there.
   place(x: number, y: number): void {
-    this.textarea.style.left = `${Math.round(x)}px`;
-    this.textarea.style.top = `${Math.round(y)}px`;
+    const s = this.textarea.style;
+    const left = `${Math.round(x)}px`;
+    const top = `${Math.round(y)}px`;
+    // An unchanged write still invalidates the page's layout.
+    if (s.left !== left) s.left = left;
+    if (s.top !== top) s.top = top;
   }
 
   focus(): void {

From 671f9045a1823717e6fdafd7b4249b6193c1bfa0 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 01:22:52 +0100
Subject: [PATCH 10/23] chore(example): a suggestions switch on the web example

---
 example/src/EditorApp.web.tsx | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/example/src/EditorApp.web.tsx b/example/src/EditorApp.web.tsx
index 339606d..6f4f2de 100644
--- a/example/src/EditorApp.web.tsx
+++ b/example/src/EditorApp.web.tsx
@@ -23,6 +23,7 @@ export function EditorApp() {
   const [fileId, setFileId] = useState('python');
   const [themeIndex, setThemeIndex] = useState(0);
   const [scrollEnabled, setScrollEnabled] = useState(true);
+  const [suggestions, setSuggestions] = useState<'on' | 'off'>('off');
   const [demo, setDemo] = useState('editor');
   const theme = THEMES[themeIndex % THEMES.length]?.theme;
   // Lines of the generated JavaScript file the typing bench opened, 0 for a picked file.
@@ -59,7 +60,7 @@ export function EditorApp() {
 
   return (
     
-      
+      
         {(['editor', 'nested', 'two'] as Demo[]).map((d) => (
            pick(setDemo, d)} />
         ))}
@@ -73,6 +74,11 @@ export function EditorApp() {
           on={!scrollEnabled}
           onPress={() => setScrollEnabled((s) => !s)}
         />
+         setSuggestions((s) => (s === 'on' ? 'off' : 'on'))}
+        />
       
       
         {FILES.map((f) => (
@@ -97,6 +103,7 @@ export function EditorApp() {
           theme={theme}
           fontFamily={FONT}
           scrollEnabled={scrollEnabled}
+          suggestions={suggestions}
           avoidKeyboard
           onReady={ready(benchLines ? `bench ${benchLines}` : (file?.name ?? ''))}
         />
@@ -142,6 +149,7 @@ export function EditorApp() {
 const styles = StyleSheet.create({
   page: { flex: 1, height: '100%' },
   bar: { flexDirection: 'row', gap: 8, padding: 8, alignItems: 'center' },
+  wrap: { flexWrap: 'wrap' },
   files: { flexGrow: 0 },
   chip: { paddingHorizontal: 10, paddingVertical: 6, borderRadius: 14, backgroundColor: '#8884' },
   chipOn: { backgroundColor: '#0969da' },

From 53a0922e2b6a93e16ae52f85ae36bb59631f6037 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 01:29:55 +0100
Subject: [PATCH 11/23] perf(web): draw a key's frame before the parse runs

In Chrome on an Android phone the parse ran inside the frame that drew each
key and overran its 6 ms budget, for a typing work p95 of 19-25 ms on a
10k-line file. Frames now draw first and the parse runs in a task after the
page paints. An edit that drops colors its lines had still parses first, so
no frame paints them plain. Work p95 is now 8.2-8.5 ms at 10k lines.
---
 scripts/bench-web.mjs    |  3 ++-
 src/web/EditorView.ts    | 12 +++++++++++
 src/web/pump.ts          | 41 +++++++++++++++++++++++++++++++-----
 tests/web/render.e2e.mjs | 45 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 95 insertions(+), 6 deletions(-)

diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs
index 988882d..d40ed7c 100644
--- a/scripts/bench-web.mjs
+++ b/scripts/bench-web.mjs
@@ -54,7 +54,8 @@ try {
   for (const part of ['work', 'handler', 'engine', 'draw']) {
     console.log(`  ${part.padEnd(8)}${stats(probe[part])}`);
   }
-  console.log(`  largest pump ${ms(Math.max(0, ...probe.pumps))} of ${probe.pumps.length}`);
+  console.log(`  largest frame ${ms(Math.max(0, ...probe.pumps))} of ${probe.pumps.length}`);
+  console.log(`  engine tasks ${stats(probe.tasks)} of ${probe.tasks.length}`);
   await page.evaluate(() => localStorage.removeItem('codepad_debug'));
 } finally {
   await browser.close();
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index b0271a0..085f4a4 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -119,6 +119,8 @@ export class EditorView {
   private seenSnapshots = 0;
   private dirty = true;
   private destroyed = false;
+  // The next frame parses before it draws: the lines on screen lost colors an edit could not keep, or none came yet.
+  urgent = false;
   private drawn = false;
   private rowHeight = 0;
   private charWidth = 0;
@@ -277,6 +279,7 @@ export class EditorView {
     ensureLanguage(this.m, id).then((ok) => {
       if (this.destroyed || this.language !== id || !ok) return;
       this.languageReady = this.core.setLanguage(id);
+      this.urgent = this.languageReady;
       this.invalidate();
     });
   }
@@ -723,6 +726,11 @@ export class EditorView {
     requestPump();
   }
 
+  // True when the next frame has something to draw: a change, or a snapshot not drawn yet.
+  pending(): boolean {
+    return !this.destroyed && (this.dirty || this.core.snapshotCount !== this.seenSnapshots);
+  }
+
   private invalidate(): void {
     if (this.destroyed) return;
     this.dirty = true;
@@ -959,6 +967,7 @@ export class EditorView {
     }
     if (revision >= 0) {
       this.appliedRevision = revision;
+      this.urgent = false;
       this.kept = null;
     }
     let widest = -1;
@@ -1105,6 +1114,7 @@ export class EditorView {
   // Moves the cache along an edit and keeps the edited line's spans shifted until the parse catches up.
   private changed(change: WebChange, count: number): void {
     if (count > 1) {
+      this.urgent = this.languageReady;
       this.kept = null;
       this.relayout();
       return;
@@ -1112,7 +1122,9 @@ export class EditorView {
     const first = this.core.lineAt(change.start);
     const oldCount = lineSpan(change.removed);
     const newCount = lineSpan(change.inserted);
+    const hadSpans = this.cache.get(first)?.spans != null;
     this.keepSpans(first, oldCount, newCount, change);
+    if (hadSpans && this.kept === null) this.urgent = true;
     const delta = newCount - oldCount;
     const moved: [number, Entry][] = [];
     for (const [line, entry] of this.cache) {
diff --git a/src/web/pump.ts b/src/web/pump.ts
index 9015f9e..ffb4c0c 100644
--- a/src/web/pump.ts
+++ b/src/web/pump.ts
@@ -1,9 +1,10 @@
 import type { CoreModule } from './core/module';
 
-// The engine's share of a frame, so a key still draws inside it.
+// The engine's share of a task, so a key still draws soon after it.
 export const PUMP_BUDGET_MS = 6;
 
-type View = { draw(): void };
+// urgent: the view's next frame waits for the parse. pending: it has something to draw.
+type View = { draw(): void; readonly urgent: boolean; pending(): boolean };
 // Per key: work and its three parts, the handler, the engine share of the frame that draws it, and that draw.
 type Probe = {
   work: number[];
@@ -11,6 +12,8 @@ type Probe = {
   engine: number[];
   draw: number[];
   pumps: number[];
+  // Each engine task run between frames.
+  tasks: number[];
 };
 
 const views = new Set();
@@ -19,7 +22,7 @@ let scheduled = false;
 
 // With localStorage codepad_debug set to 1 at load, the bench reads key and frame times from globalThis.
 const probe: Probe | null = debugOn()
-  ? { work: [], handler: [], engine: [], draw: [], pumps: [] }
+  ? { work: [], handler: [], engine: [], draw: [], pumps: [], tasks: [] }
   : null;
 if (probe) (globalThis as { __codepadProbe?: Probe }).__codepadProbe = probe;
 let keyView: View | null = null;
@@ -54,7 +57,8 @@ export function registerView(view: View): () => void {
   };
 }
 
-// One shared frame: the engine runs its queued work, then every view draws. A view asks for the next frame here.
+// One shared frame: every view draws, then the engine runs in a task after the page paints, so a key's frame never
+// waits for a parse. A view whose lines would lose their colors makes the frame run the engine first.
 export function requestPump(): void {
   if (scheduled) return;
   scheduled = true;
@@ -64,7 +68,8 @@ export function requestPump(): void {
 function frame(): void {
   scheduled = false;
   const start = probe ? performance.now() : 0;
-  const left = core ? core._cpw_pump(PUMP_BUDGET_MS) : 0;
+  const urgent = [...views].some((v) => v.urgent);
+  const left = core && urgent ? core._cpw_pump(PUMP_BUDGET_MS) : 0;
   const pumped = probe ? performance.now() - start : 0;
   for (const view of [...views]) {
     const drawStart = probe ? performance.now() : 0;
@@ -81,4 +86,30 @@ function frame(): void {
   }
   if (probe) probe.pumps.push(performance.now() - start);
   if (left > 0) requestPump();
+  else postEngine();
+}
+
+let channel: MessageChannel | null = null;
+let engineQueued = false;
+
+function postEngine(): void {
+  if (engineQueued || !core) return;
+  engineQueued = true;
+  if (!channel && typeof MessageChannel !== 'undefined') {
+    channel = new MessageChannel();
+    channel.port1.onmessage = runEngine;
+  }
+  if (channel) channel.port2.postMessage(0);
+  else setTimeout(runEngine, 0);
+}
+
+// The engine's queued work between frames: a snapshot it publishes draws in the next frame.
+function runEngine(): void {
+  engineQueued = false;
+  if (!core) return;
+  const start = probe ? performance.now() : 0;
+  const left = core._cpw_pump(PUMP_BUDGET_MS);
+  if (probe) probe.tasks.push(performance.now() - start);
+  if ([...views].some((v) => v.pending())) requestPump();
+  if (left > 0) postEngine();
 }
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index 6a30448..c1b9500 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -370,6 +370,51 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('the frame after a letter, an Enter and a joining Backspace keeps the keyword colors', async () => {
+      const { page } = await open();
+      await page.evaluate(async () => {
+        const { EditorView, ensureLanguage, loadCore, until } = window.codepad;
+        await ensureLanguage('python');
+        const host = document.getElementById('a');
+        const view = new EditorView(host, await loadCore(), 'def a():\n    return b\n');
+        view.setLanguage('python');
+        window.views = { a: view };
+        await until(() => host.querySelector('[data-line="1"] span'));
+      });
+      await clickAt(page, 'a', 0, 8);
+      const result = await page.evaluate(async (keyword) => {
+        const v = window.views.a;
+        const colored = (line) =>
+          [...document.querySelectorAll(`#a [data-line="${line}"] span`)].filter(
+            (s) => getComputedStyle(s).color === keyword,
+          ).length;
+        const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));
+        const out = {};
+        v.apply(() => v.core.typeText('x'));
+        await nextFrame();
+        out.letter = colored(0);
+        v.apply(() => v.core.setSelection(20, 20));
+        await window.codepad.frames(2);
+        v.apply(() => v.core.insertNewline());
+        await nextFrame();
+        out.enter = colored(1);
+        await window.codepad.frames(2);
+        const joinFrom = v.core.lineEnd(1);
+        v.apply(() => v.core.replace(joinFrom, v.core.selection.head, ''));
+        await nextFrame();
+        out.join = colored(1);
+        out.text = v.core.text();
+        return out;
+      }, KEYWORD);
+      assert.deepEqual(result, {
+        letter: 1,
+        enter: 1,
+        join: 1,
+        text: 'def a():x\n    return b\n',
+      });
+      await page.close();
+    });
+
     test('PageDown moves by the visible rows', async () => {
       const { page } = await open();
       await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));

From de06c845506a2bf01ec11a970e70646cec9245ef Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:00:58 +0100
Subject: [PATCH 12/23] fix(web): keep a select all whole when the browser
 echoes it

Select all in a 3000-line file left only its last 8 KB selected, so the next
Backspace deleted that part alone. The textarea holds a window of the
document, and the browser's selectionchange for the clamped range it was
given replaced the real selection. That echo is now ignored.
---
 src/web/__tests__/input-session.test.ts | 12 ++++++++++++
 src/web/input/WebInputSession.ts        | 12 ++++++++----
 2 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts
index 30738cb..5288bfd 100644
--- a/src/web/__tests__/input-session.test.ts
+++ b/src/web/__tests__/input-session.test.ts
@@ -136,3 +136,15 @@ run('blur mid-composition keeps the text and closes the group', async () => {
   core.undo();
   expect(core.text()).toBe('abか');
 });
+
+run('the browser echoing a clamped select all leaves the whole document selected', async () => {
+  const text = 'x'
+    .repeat(40)
+    .concat('\n')
+    .repeat(Math.ceil((WINDOW_CAP * 3) / 41));
+  const { core, s } = await open(text, 0);
+  core.selectAll();
+  const written = s.sync() as TextareaState;
+  expect(s.selectionChange(written)).toBeNull();
+  expect(core.selection).toEqual({ anchor: 0, head: core.length });
+});
diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts
index 36af68c..5ce974d 100644
--- a/src/web/input/WebInputSession.ts
+++ b/src/web/input/WebInputSession.ts
@@ -8,12 +8,13 @@ type Range = { start: number; end: number };
 
 const codePoints = (s: string) => [...s].length;
 
-// Maps a hidden textarea that holds a window of the document onto the core, the web twin of ImeSession.
-// Every method that can move the window returns the textarea state to write, or null.
+// The web twin of ImeSession: maps a textarea holding a window of the document onto the core.
 export class WebInputSession {
   private win = { start: 0, value: '', line: 0 };
   private before: Range | null = null;
   private composed: Range | null = null;
+  // The textarea state sync last handed out.
+  private written: TextareaState | null = null;
 
   constructor(
     private readonly core: EditorCore,
@@ -37,11 +38,12 @@ export class WebInputSession {
     this.win = { start, value: this.core.text(start, end), line: this.core.lineAt(head) };
     // A selection longer than the window shows as the whole window selected.
     const clamp = (offset: number) => Math.min(Math.max(offset - start, 0), end - start);
-    return {
+    this.written = {
       value: this.win.value,
       start: clamp(Math.min(anchor, head)),
       end: clamp(Math.max(anchor, head)),
     };
+    return { ...this.written };
   }
 
   // The selection the edit replaces, which a diff alone cannot place (Enter before a newline).
@@ -137,9 +139,11 @@ export class WebInputSession {
     return this.follow(ta);
   }
 
-  // The user moved the caret in the textarea. Ignored while composing.
+  // The user moved the caret, ignored while composing and for the echo of what sync wrote.
   selectionChange(ta: TextareaState): TextareaState | null {
     if (this.composed || ta.value !== this.win.value) return null;
+    const w = this.written;
+    if (w && ta.value === w.value && ta.start === w.start && ta.end === w.end) return null;
     const ws = this.win.start;
     this.apply(() => this.select(ws + ta.start, ws + ta.end));
     return this.follow(ta);

From b27af199aa19165f2b9dfad4303f3a6bf0610fa4 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:01:02 +0100
Subject: [PATCH 13/23] fix(web): leave avoidKeyboard at zero when no keyboard
 is open

An editor reaching 200 px below a desktop window got a 200 px bottom inset,
so it scrolled through blank space past its last line. The inset now counts
only the part of the layout viewport the visual viewport lost, and nothing
while the page is pinch-zoomed.
---
 src/web/__tests__/keyboardInset.test.ts | 11 ++++++++---
 src/web/input/keyboardInset.ts          | 13 ++++++++-----
 2 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/src/web/__tests__/keyboardInset.test.ts b/src/web/__tests__/keyboardInset.test.ts
index d6df4b0..c3930a1 100644
--- a/src/web/__tests__/keyboardInset.test.ts
+++ b/src/web/__tests__/keyboardInset.test.ts
@@ -2,7 +2,12 @@ import { expect, test } from '@jest/globals';
 import { keyboardOverlap } from '../input/keyboardInset';
 
 test('the keyboard covers what lies below the visual viewport', () => {
-  expect(keyboardOverlap(800, 0, 500)).toBe(300);
-  expect(keyboardOverlap(400, 0, 500)).toBe(0);
-  expect(keyboardOverlap(800, 100, 500)).toBe(200);
+  expect(keyboardOverlap(800, 0, 500, 900)).toBe(300);
+  expect(keyboardOverlap(400, 0, 500, 900)).toBe(0);
+  expect(keyboardOverlap(800, 100, 500, 900)).toBe(200);
+});
+
+test('an editor that runs past the window with no keyboard gets no inset', () => {
+  expect(keyboardOverlap(1100, 0, 900, 900)).toBe(0);
+  expect(keyboardOverlap(1100, 0, 500, 900)).toBe(400);
 });
diff --git a/src/web/input/keyboardInset.ts b/src/web/input/keyboardInset.ts
index 473f25a..805df8a 100644
--- a/src/web/input/keyboardInset.ts
+++ b/src/web/input/keyboardInset.ts
@@ -1,19 +1,22 @@
 /// 
 
-// How far the editor reaches below the visual viewport, which the keyboard shrinks on phones.
+// The editor's overlap with what the visual viewport lost from the layout viewport, which a keyboard covers.
 export function keyboardOverlap(
   editorBottom: number,
   viewportTop: number,
   viewportHeight: number,
+  layoutHeight: number,
 ): number {
-  return Math.max(0, editorBottom - (viewportTop + viewportHeight));
+  return Math.max(0, Math.min(editorBottom, layoutHeight) - (viewportTop + viewportHeight));
 }
 
-// The keyboard's overlap with an element's box, 0 where the page has no visual viewport.
+// The keyboard's overlap with an element's box, 0 where the page has no visual viewport or is pinch-zoomed.
 export function overlapOf(el: HTMLElement): number {
   const vv = typeof window === 'undefined' ? undefined : window.visualViewport;
-  if (!vv) return 0;
-  return Math.round(keyboardOverlap(el.getBoundingClientRect().bottom, vv.offsetTop, vv.height));
+  if (!vv || Math.abs(vv.scale - 1) > 0.01) return 0;
+  const bottom = el.getBoundingClientRect().bottom;
+  const layout = document.documentElement.clientHeight;
+  return Math.round(keyboardOverlap(bottom, vv.offsetTop, vv.height, layout));
 }
 
 // Calls back when the visual viewport moves or resizes, as the keyboard opens, closes or animates. Returns the removal.

From a326b12b9cdd8a747cf4d83020a9c97c31b97e3a Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:01:05 +0100
Subject: [PATCH 14/23] fix(web): run ref focus and blur made before the core
 loads

---
 src/web/CodeEditor.tsx                | 10 ++--------
 src/web/__tests__/CodeEditor.test.tsx | 12 ++++++++++++
 2 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/src/web/CodeEditor.tsx b/src/web/CodeEditor.tsx
index 209af18..77f53b5 100644
--- a/src/web/CodeEditor.tsx
+++ b/src/web/CodeEditor.tsx
@@ -273,14 +273,8 @@ export const CodeEditor = forwardRef(function Co
       cut: () => later('cut', undefined),
       copy: () => later('copy', undefined),
       paste: () => later('paste', undefined),
-      focus: () => {
-        viewRef.current?.focus();
-        return Promise.resolve();
-      },
-      blur: () => {
-        viewRef.current?.blur();
-        return Promise.resolve();
-      },
+      focus: () => run((v) => v.focus()),
+      blur: () => run((v) => v.blur()),
       setSearch: () => later('setSearch', { count: 0, limited: false }),
       findNext: () => later('findNext', null),
       findPrevious: () => later('findPrevious', null),
diff --git a/src/web/__tests__/CodeEditor.test.tsx b/src/web/__tests__/CodeEditor.test.tsx
index 032928e..bf3d34f 100644
--- a/src/web/__tests__/CodeEditor.test.tsx
+++ b/src/web/__tests__/CodeEditor.test.tsx
@@ -177,3 +177,15 @@ test('typeText, deleteBackward, deleteForward and moveCaret made before the core
   expect(view.deleteForward).toHaveBeenCalledTimes(1);
   expect(view.moveCaret).toHaveBeenCalledWith('pageDown', true);
 });
+
+test('focus called before the core loads focuses the editor once it does', async () => {
+  const ref = createRef();
+  await render();
+  const focused = ref.current?.focus();
+  await act(async () => {
+    mockCore.resolve({});
+    await tick();
+  });
+  await expect(settled(focused as Promise)).resolves.toBeUndefined();
+  expect(mockViews[0]?.focus).toHaveBeenCalledTimes(1);
+});

From a5e1926cab201dec7258dd71aa7cb3a0dd8e72b8 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:01:21 +0100
Subject: [PATCH 15/23] fix(web): no plain frame after two quick edits or a
 join under a blank line

Two edits on a colored line before one frame, or Backspace joining a code line
to the blank line above it, painted that line without colors for one frame.
The view now counts colors from every edited line and from spans kept by an
earlier edit, and parses before drawing when they would be lost. A click on
the line numbers also no longer blurs and refocuses the editor.
---
 scripts/bench-web.mjs    |  4 +--
 src/web/EditorView.ts    | 53 +++++++++++++++++-----------
 src/web/pump.ts          |  3 +-
 tests/web/render.e2e.mjs | 74 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 109 insertions(+), 25 deletions(-)

diff --git a/scripts/bench-web.mjs b/scripts/bench-web.mjs
index d40ed7c..ac6d11c 100644
--- a/scripts/bench-web.mjs
+++ b/scripts/bench-web.mjs
@@ -1,6 +1,4 @@
-// Typing bench for the web editor in Chrome on an Android phone: yarn bench:web [lines] [port].
-// First: yarn example web --port , adb reverse tcp: tcp:, the example open in Chrome on the phone.
-// The port is the example's, 8082 by default.
+// Typing bench in Chrome on a phone: yarn bench:web [lines] [port], the example served on that port through adb reverse.
 import { execFileSync } from 'node:child_process';
 import { chromium } from 'playwright';
 
diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 085f4a4..705e5e9 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -169,9 +169,11 @@ export class EditorView {
     columnAt: (line, row, x) => this.columnAt(line, row, x),
   };
   private readonly onClickEvent = (e: MouseEvent) => this.click(e);
-  // A press on the text keeps the focus where it is, so a click inside a focused editor does not blur it.
+  // A press on the text or the line numbers keeps the focus, so a click in a focused editor never blurs it.
   private readonly onMouseDownEvent = (e: MouseEvent) => {
-    if (e.button === 0 && this.textLayer.contains(e.target as Node)) e.preventDefault();
+    const target = e.target as Node;
+    const inside = this.textLayer.contains(target) || this.gutter.contains(target);
+    if (e.button === 0 && inside) e.preventDefault();
   };
 
   constructor(host: HTMLElement, m: CoreModule, text = '') {
@@ -463,8 +465,7 @@ export class EditorView {
     this.vertical(page, direction === 'down' || direction === 'pageDown', extend);
   }
 
-  // The column nearest x on a row of a line, x in pixels from the line's left edge. Lays the line out when it is
-  // not drawn.
+  // The column nearest x (pixels from the line's left) on a row of a line, laid out first when not drawn.
   columnAt(line: number, rowInLine: number, x: number): number {
     if (this.destroyed) return 0;
     const el = this.lineEl(line);
@@ -530,8 +531,7 @@ export class EditorView {
     this.focus();
   }
 
-  // The caret, the composing underline and the selection, from where the browser drew the text.
-  // Every read comes before every write, so a draw lays the page out once.
+  // The caret, composing underline and selection, every read before every write so the page lays out once.
   private drawInput(): void {
     const box = this.textLayer.getBoundingClientRect();
     const { anchor, head } = this.core.selection;
@@ -673,8 +673,7 @@ export class EditorView {
     this.configure();
     this.restaleRefreshed();
     let moved = this.frame();
-    // A caret moved off screen scrolls into view in the same task, so no frame paints without it. A caret line that
-    // was not drawn is revealed by its row first, then again by its x once drawn.
+    // A caret moved off screen scrolls into view before the paint: by row while its line is not drawn, then by x.
     for (let pass = 0; this.revealing && pass < 2; pass++) {
       if (this.drawnCaret) this.revealing = false;
       if (!this.revealCaret()) break;
@@ -737,8 +736,7 @@ export class EditorView {
     requestPump();
   }
 
-  // A new snapshot at the drawn revision comes from a refresh: its colors changed with no edit, so every cached line
-  // is queried again, since the frame skips a line already at the snapshot's revision.
+  // A new snapshot at the drawn revision is a refresh, so every cached line is queried again.
   private restaleRefreshed(): void {
     const snapshot = this.languageReady ? this.core.snapshot : 0;
     if (snapshot === this.drawnSnapshot) return;
@@ -747,8 +745,7 @@ export class EditorView {
     for (const entry of this.cache.values()) entry.revision = -1;
   }
 
-  // Loads the languages the engine could not find, like a Markdown fence's, then has it look them up again.
-  // It refreshes once per language that registered, so a name that never resolves cannot loop.
+  // Loads languages the engine could not find, like a fence's, and refreshes once per language that registered.
   private loadMissed(): void {
     for (const name of this.core.takeMissedLanguages()) this.missed.add(name);
     if (!this.missed.size) return;
@@ -1122,9 +1119,18 @@ export class EditorView {
     const first = this.core.lineAt(change.start);
     const oldCount = lineSpan(change.removed);
     const newCount = lineSpan(change.inserted);
-    const hadSpans = this.cache.get(first)?.spans != null;
+    // Colors the edited lines show, from the cache or from an earlier edit since the last frame.
+    const inside = (line: number) => line >= first && line < first + oldCount;
+    const kept = this.kept;
+    let colored =
+      kept !== null &&
+      ((inside(kept.line) && kept.spans !== null) || (inside(kept.line + 1) && kept.tail !== null));
+    for (const [line, entry] of this.cache) {
+      if (colored) break;
+      colored = inside(line) && entry.spans !== null;
+    }
     this.keepSpans(first, oldCount, newCount, change);
-    if (hadSpans && this.kept === null) this.urgent = true;
+    if (colored && this.kept === null) this.urgent = true;
     const delta = newCount - oldCount;
     const moved: [number, Entry][] = [];
     for (const [line, entry] of this.cache) {
@@ -1141,9 +1147,19 @@ export class EditorView {
     }
   }
 
+  // The spans a line shows now: its cache entry, else what an edit since the last frame kept for it.
+  private shownSpans(line: number): Int32Array | null {
+    const entry = this.cache.get(line);
+    if (entry) return entry.spans;
+    const kept = this.kept;
+    if (!kept) return null;
+    if (line === kept.line) return kept.spans;
+    return line === kept.line + 1 ? kept.tail : null;
+  }
+
   private keepSpans(first: number, oldCount: number, newCount: number, change: WebChange): void {
+    const spans = this.shownSpans(first);
     this.kept = null;
-    const spans = this.cache.get(first)?.spans;
     if (oldCount !== 1 || !spans) return;
     const column = change.start - this.core.lineStart(first);
     const revision = this.core.revision;
@@ -1238,9 +1254,7 @@ function sameSpans(a: Int32Array | null, b: Int32Array | null): boolean {
 
 const RTL = /^[֐-ࣿיִ-﷿ﹰ-]/;
 
-// Where the caret at a column of a line element sits, in page coordinates. The base direction is left to right: the
-// caret is at the leading edge of the next character unless it reads right to left, then at the trailing edge of the
-// previous one, so Chromium and WebKit agree.
+// The caret at a column in page coordinates: the leading edge of the next character unless it reads right to left.
 function caretEdge(el: HTMLElement, column: number): { x: number; top: number; height: number } {
   const next = charRect(el, column, true);
   const prev = charRect(el, column, false);
@@ -1255,8 +1269,7 @@ function caretEdge(el: HTMLElement, column: number): { x: number; top: number; h
 
 const written = new WeakMap>();
 
-// Sets a style, or the text with key text, only when it differs from what this last set, so a draw that moves
-// nothing leaves the page's layout valid.
+// Writes a style, or the text under key text, only when it changed, so an unchanged draw keeps the layout valid.
 function put(el: HTMLElement, key: string, value: string): void {
   let last = written.get(el);
   if (!last) {
diff --git a/src/web/pump.ts b/src/web/pump.ts
index ffb4c0c..4f64fe8 100644
--- a/src/web/pump.ts
+++ b/src/web/pump.ts
@@ -57,8 +57,7 @@ export function registerView(view: View): () => void {
   };
 }
 
-// One shared frame: every view draws, then the engine runs in a task after the page paints, so a key's frame never
-// waits for a parse. A view whose lines would lose their colors makes the frame run the engine first.
+// One shared frame: every view draws, then the engine runs after the paint unless a view is urgent.
 export function requestPump(): void {
   if (scheduled) return;
   scheduled = true;
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index c1b9500..dce471d 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -300,6 +300,42 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('select all then Backspace empties a file longer than the textarea window', async () => {
+      const { page } = await open();
+      await editor(
+        page,
+        'a',
+        Array.from({ length: 3000 }, (_, i) => `line number ${i}`).join('\n'),
+      );
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+a`);
+      await page.evaluate(() => window.codepad.frames(3));
+      await page.keyboard.press('Backspace');
+      assert.equal(await textOf(page, 'a'), '');
+      await page.close();
+    });
+
+    test('a click on a line number keeps the focus where it is', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'one\ntwo');
+      await page.evaluate(() => {
+        window.counts = { focus: 0, blur: 0 };
+        window.views.a.setOptions({
+          onFocus: () => window.counts.focus++,
+          onBlur: () => window.counts.blur++,
+        });
+      });
+      await clickAt(page, 'a', 0, 1);
+      const { x, y } = await page.evaluate(() => {
+        const host = document.getElementById('a').getBoundingClientRect();
+        const line = document.querySelector('#a [data-line="1"]').getBoundingClientRect();
+        return { x: host.left + 4, y: line.top + line.height / 2 };
+      });
+      await page.mouse.click(x, y);
+      assert.deepEqual(await page.evaluate(() => window.counts), { focus: 1, blur: 0 });
+      await page.close();
+    });
+
     test('typing after replaceRange, setText and undo lands at the core caret', async () => {
       const { page } = await open();
       await editor(page, 'a', 'abc');
@@ -415,6 +451,44 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('two edits before a frame and a join under a blank line keep the keyword colors', async () => {
+      const { page } = await open();
+      const result = await page.evaluate(async (keyword) => {
+        const { EditorView, ensureLanguage, frames, loadCore, until } = window.codepad;
+        await ensureLanguage('python');
+        const host = document.getElementById('a');
+        const v = new EditorView(
+          host,
+          await loadCore(),
+          'def a():\n    pass\n\ndef c():\n    pass\n',
+        );
+        v.setLanguage('python');
+        await until(() => host.querySelector('[data-line="3"] span'));
+        const colored = (line) =>
+          [...host.querySelectorAll(`[data-line="${line}"] span`)].filter(
+            (s) => getComputedStyle(s).color === keyword,
+          ).length;
+        const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r()));
+        v.apply(() => v.core.setSelection(8, 8));
+        await frames(2);
+        v.apply(() => v.core.typeText('x'));
+        v.apply(() => v.core.typeText('y'));
+        await nextFrame();
+        const twice = colored(0);
+        await frames(3);
+        const blank = v.core.lineEnd(2);
+        v.apply(() => v.core.replace(blank, blank + 1, ''));
+        await nextFrame();
+        return { twice, join: colored(2), text: v.core.text() };
+      }, KEYWORD);
+      assert.deepEqual(result, {
+        twice: 1,
+        join: 1,
+        text: 'def a():xy\n    pass\ndef c():\n    pass\n',
+      });
+      await page.close();
+    });
+
     test('PageDown moves by the visible rows', async () => {
       const { page } = await open();
       await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));

From 46ef63c6ba3554eadd6798d44d494db5973bef63 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:13:02 +0100
Subject: [PATCH 16/23] test(web): read the PageDown page size before the key

Chromium on Linux keeps its scrollbars, and the test read the page size
after PageDown, so a horizontal scrollbar during the first frames made the
key move 14 rows where the test expected 15. The test now reads the size
once the layout has settled, as the key does.
---
 tests/web/render.e2e.mjs | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index dce471d..6d6cf37 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -493,6 +493,12 @@ for (const engine of [chromium, webkit]) {
       const { page } = await open();
       await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'));
       await clickAt(page, 'a', 0, 0);
+      // The page the key moves by, read once the first frames have settled the scrollbars.
+      const rows = await page.evaluate(async () => {
+        await window.codepad.frames(3);
+        const v = window.views.a;
+        return Math.floor(v.layout.viewportHeight / v.layout.rowHeight);
+      });
       await page.keyboard.press('PageDown');
       const result = await page.evaluate(async () => {
         const v = window.views.a;
@@ -500,11 +506,10 @@ for (const engine of [chromium, webkit]) {
         const caret = v.caretRect(v.core.selection.head);
         return {
           line: v.core.lineAt(v.core.selection.head),
-          page: Math.floor(v.layout.viewportHeight / v.layout.rowHeight),
           y: caret?.y ?? null,
         };
       });
-      assert.equal(result.line, result.page);
+      assert.equal(result.line, rows);
       assert.ok(result.y !== null && result.y >= 0 && result.y < 300, `caret y ${result.y}`);
       await page.close();
     });

From 26a185733d4afd69879dbe3ce127639efbf565a8 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:21:15 +0100
Subject: [PATCH 17/23] fix(web): paste as written and keep the caret right
 after long replacements

A pasted ( became () because every one-letter input took the typing path,
and typing over a selection that started before the textarea window left the
caret 15,904 units past the letter. Only typed input now auto-closes and
indents, the caret follows a replacement that grew past the window, and a
caret moved back to where the window put it is followed again.
---
 src/web/__tests__/input-session.test.ts | 31 +++++++++++++++++++++++++
 src/web/input/WebInputSession.ts        | 15 +++++++++---
 2 files changed, 43 insertions(+), 3 deletions(-)

diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts
index 5288bfd..dbc51ce 100644
--- a/src/web/__tests__/input-session.test.ts
+++ b/src/web/__tests__/input-session.test.ts
@@ -148,3 +148,34 @@ run('the browser echoing a clamped select all leaves the whole document selected
   expect(s.selectionChange(written)).toBeNull();
   expect(core.selection).toEqual({ anchor: 0, head: core.length });
 });
+
+const paste: InputLike = { inputType: 'insertFromPaste', data: null, isComposing: false };
+
+run('a pasted ( and a pasted newline stay literal', async () => {
+  const { core, s } = await open('  a', 3);
+  s.beforeInput(ta('  a', 3));
+  s.input(paste, ta('  a(', 4));
+  expect(core.text()).toBe('  a(');
+  s.beforeInput(ta('  a(', 4));
+  s.input(paste, ta('  a(\n', 5));
+  expect(core.text()).toBe('  a(\n');
+});
+
+run('typing over a selection starting before the window puts the caret after it', async () => {
+  const { core, s } = await open('a'.repeat(50000), 0);
+  core.setSelection(1000, 21000);
+  const w = s.sync() as TextareaState;
+  expect(s.windowStart).toBeGreaterThan(1000);
+  s.beforeInput(w);
+  s.input(typed('x'), ta(`x${w.value.slice(w.end)}`, 1));
+  expect(core.text()).toBe(`${'a'.repeat(1000)}x${'a'.repeat(29000)}`);
+  expect(core.selection).toEqual({ anchor: 1001, head: 1001 });
+});
+
+run('a caret moved away and back to where sync put it is followed', async () => {
+  const { core, s } = await open('abc', 2);
+  s.selectionChange(ta('abc', 1));
+  expect(core.selection.head).toBe(1);
+  s.selectionChange(ta('abc', 2));
+  expect(core.selection.head).toBe(2);
+});
diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts
index 5ce974d..17f5282 100644
--- a/src/web/input/WebInputSession.ts
+++ b/src/web/input/WebInputSession.ts
@@ -7,6 +7,8 @@ export type InputLike = { inputType: string; data: string | null; isComposing: b
 type Range = { start: number; end: number };
 
 const codePoints = (s: string) => [...s].length;
+// Input that auto-closes and indents as typing does. A paste or a replacement goes in as written.
+const TYPED = new Set(['insertText', 'insertLineBreak', 'insertParagraph']);
 
 // The web twin of ImeSession: maps a textarea holding a window of the document onto the core.
 export class WebInputSession {
@@ -52,6 +54,9 @@ export class WebInputSession {
   }
 
   input(e: InputLike, ta: TextareaState): TextareaState | null {
+    this.written = null;
+    const typing = TYPED.has(e.inputType);
+    let grown = false;
     const old = this.win.value;
     const next = ta.value;
     const ws = this.win.start;
@@ -79,6 +84,7 @@ export class WebInputSession {
       end >= Math.min(selEnd, winEnd)
     ) {
       start = Math.min(start, selStart);
+      grown = true;
       end = Math.max(end, selEnd);
     }
     const composing = this.composed !== null || e.isComposing;
@@ -91,11 +97,11 @@ export class WebInputSession {
         if (this.composed) this.composed = { start, end: start + inserted.length };
         this.select(start + inserted.length, start + inserted.length);
         coreCaret = true;
-      } else if (start === end && inserted === '\n') {
+      } else if (typing && start === end && inserted === '\n') {
         this.select(start, start);
         this.core.insertNewline();
         coreCaret = true;
-      } else if (start === end && codePoints(inserted) === 1) {
+      } else if (typing && start === end && codePoints(inserted) === 1) {
         this.select(start, start);
         this.core.typeText(inserted);
         coreCaret = true;
@@ -111,7 +117,9 @@ export class WebInputSession {
       } else {
         this.core.inputReplace(start, end, inserted, inserted === '' && codePoints(removed) === 1);
       }
-      if (!coreCaret) this.select(ws + ta.start, ws + ta.end);
+      const caret = start + inserted.length;
+      if (grown) this.select(caret, caret);
+      else if (!coreCaret) this.select(ws + ta.start, ws + ta.end);
     });
     const coreWindow = this.core.text(ws, winEnd + this.core.length - lengthBefore);
     const caret = this.core.selection;
@@ -145,6 +153,7 @@ export class WebInputSession {
     const w = this.written;
     if (w && ta.value === w.value && ta.start === w.start && ta.end === w.end) return null;
     const ws = this.win.start;
+    this.written = null;
     this.apply(() => this.select(ws + ta.start, ws + ta.end));
     return this.follow(ta);
   }

From 959f8874c17b6ed6696c329809d7985634f5ef30 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:23:28 +0100
Subject: [PATCH 18/23] fix(web): keep the textarea window until a composition
 has settled

On lines longer than the textarea window, ending a composition that replaced
a selection moved the window at once, while the textarea still held the old
one. An input the browser sent after compositionend then diffed against the
wrong text and changed the document a second time. The window now moves in
the task after compositionend.
---
 src/web/__tests__/ime-web.test.ts       |  3 ++-
 src/web/__tests__/input-session.test.ts | 21 ++++++++++++++++++++-
 src/web/input/InputHost.ts              |  8 ++++----
 src/web/input/WebInputSession.ts        |  9 +++++++--
 4 files changed, 33 insertions(+), 8 deletions(-)

diff --git a/src/web/__tests__/ime-web.test.ts b/src/web/__tests__/ime-web.test.ts
index eff031c..fbfea94 100644
--- a/src/web/__tests__/ime-web.test.ts
+++ b/src/web/__tests__/ime-web.test.ts
@@ -89,7 +89,8 @@ for (const file of files) {
       } else if (e.type === 'compositionstart') {
         session.compositionStart(e.ta);
       } else if (e.type === 'compositionend') {
-        pending = session.compositionEnd(e.ta) ?? pending;
+        session.compositionEnd();
+        pending = session.settle(e.ta) ?? pending;
       } else if (e.type === 'selectionchange') {
         pending = session.selectionChange(e.ta) ?? pending;
       } else if (e.type === 'blur') {
diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts
index dbc51ce..523af3a 100644
--- a/src/web/__tests__/input-session.test.ts
+++ b/src/web/__tests__/input-session.test.ts
@@ -91,7 +91,7 @@ run('a composed word undoes in one step', async () => {
   s.beforeInput(ta('abk', 2, 3));
   expect(s.input(composed('か'), ta('abか', 3))).toBeNull();
   expect(s.composing).toEqual({ start: 2, end: 3 });
-  s.compositionEnd(ta('abか', 3));
+  s.compositionEnd();
   expect(s.composing).toBeNull();
   core.undo();
   expect(core.text()).toBe('ab');
@@ -179,3 +179,22 @@ run('a caret moved away and back to where sync put it is followed', async () =>
   s.selectionChange(ta('abc', 2));
   expect(core.selection.head).toBe(2);
 });
+
+run(
+  'an input sent after compositionend maps onto the window the textarea still holds',
+  async () => {
+    const text = ['a', 'b', 'c'].map((c) => c.repeat(6000)).join('\n');
+    const { core, s } = await open(text, 0);
+    core.setSelection(core.lineStart(1) + 3000, core.lineStart(2) + 3000);
+    const w = s.sync() as TextareaState;
+    s.compositionStart(w);
+    const after = ta(`${w.value.slice(0, w.start)}X${w.value.slice(w.end)}`, w.start + 1);
+    s.beforeInput(w);
+    s.input(composed('X'), after);
+    s.compositionEnd();
+    const committed = core.text();
+    s.beforeInput(after);
+    s.input(typed('X'), after);
+    expect(core.text()).toBe(committed);
+  },
+);
diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts
index e4cb598..ef58b89 100644
--- a/src/web/input/InputHost.ts
+++ b/src/web/input/InputHost.ts
@@ -53,12 +53,12 @@ export class InputHost {
       this.hooks.changed();
     });
     this.on(ta, 'compositionend', () => {
-      const value = ta.value;
-      const next = this.session.compositionEnd(this.state());
+      this.session.compositionEnd();
       this.hooks.changed();
-      // A browser may still send the composition's last input after this event.
+      // A browser may still send the composition's last input after this event, so the window moves a task later.
       setTimeout(() => {
-        if (ta.value === value && !this.session.composing) this.write(next);
+        this.write(this.session.settle(this.state()));
+        this.hooks.changed();
       }, 0);
     });
     this.on(ta, 'keydown', (e) => {
diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts
index 17f5282..8353c0f 100644
--- a/src/web/input/WebInputSession.ts
+++ b/src/web/input/WebInputSession.ts
@@ -142,9 +142,14 @@ export class WebInputSession {
     this.core.beginGroup();
   }
 
-  compositionEnd(ta: TextareaState): TextareaState | null {
+  // The window stays as the textarea shows it, since a browser may still send the composition's last input.
+  compositionEnd(): void {
     this.finishComposition();
-    return this.follow(ta);
+  }
+
+  // After compositionend has settled: a new window when the caret left the window's middle line.
+  settle(ta: TextareaState): TextareaState | null {
+    return this.composed ? null : this.follow(ta);
   }
 
   // The user moved the caret, ignored while composing and for the echo of what sync wrote.

From c30c244f635037686b59f6ce956e437e63c7ff5f Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:24:54 +0100
Subject: [PATCH 19/23] fix(web): copy and cut the whole selection, not the
 textarea window

After select all in a 3000-line file, copy put nothing on the clipboard in a
synthetic event and the browser's own copy took only the 8 KB textarea
window, while cut deleted the whole document. Copy and cut now write the
editor's selection to the clipboard, and cut deletes that same range.
---
 src/web/EditorView.ts      | 12 ++++++++++++
 src/web/input/InputHost.ts | 12 ++++++++++++
 tests/web/render.e2e.mjs   | 24 ++++++++++++++++++++++++
 3 files changed, 48 insertions(+)

diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index 705e5e9..a2d1929 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -202,6 +202,7 @@ export class EditorView {
     this.session = new WebInputSession(this.core, (edit) => this.applyInput(edit));
     this.input = new InputHost(this.root, this.session, {
       keyDown: (e) => this.keyDown(e),
+      clipboard: (cut) => this.clipboard(cut),
       focusChanged: (focused) => {
         this.safely(() => (focused ? this.o.onFocus?.() : this.o.onBlur?.()));
         this.invalidate();
@@ -389,6 +390,17 @@ export class EditorView {
     if (probing) probeKey(this, performance.now() - start);
   }
 
+  // The selected text for copy or cut. A cut deletes it, except under readOnly.
+  private clipboard(cut: boolean): string | null {
+    const { anchor, head } = this.core.selection;
+    const from = Math.min(anchor, head);
+    const to = Math.max(anchor, head);
+    if (this.destroyed || from === to) return null;
+    const text = this.core.text(from, to);
+    if (cut && !this.o.readOnly) this.perform(() => this.core.inputReplace(from, to, ''));
+    return text;
+  }
+
   // A hardware key the editor runs itself. True when the browser must not act on it.
   private keyDown(e: KeyboardEvent): boolean {
     if (this.destroyed) return false;
diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts
index ef58b89..b4f4225 100644
--- a/src/web/input/InputHost.ts
+++ b/src/web/input/InputHost.ts
@@ -5,6 +5,8 @@ import type { TextareaState, WebInputSession } from './WebInputSession';
 export type InputHooks = {
   // True when the key ran an editor command, so the browser must not act on it.
   keyDown(e: KeyboardEvent): boolean;
+  // The selected text for the clipboard, deleted first for a cut. Null leaves the event to the browser.
+  clipboard(cut: boolean): string | null;
   focusChanged(focused: boolean): void;
   changed(): void;
 };
@@ -61,6 +63,8 @@ export class InputHost {
         this.hooks.changed();
       }, 0);
     });
+    this.on(ta, 'copy', (e) => this.clip(e as ClipboardEvent, false));
+    this.on(ta, 'cut', (e) => this.clip(e as ClipboardEvent, true));
     this.on(ta, 'keydown', (e) => {
       if (this.hooks.keyDown(e as KeyboardEvent)) e.preventDefault();
     });
@@ -133,6 +137,14 @@ export class InputHost {
     this.textarea.remove();
   }
 
+  // The textarea holds only a window, so the clipboard takes the editor's whole selection.
+  private clip(e: ClipboardEvent, cut: boolean): void {
+    const text = this.hooks.clipboard(cut);
+    if (text === null || !e.clipboardData) return;
+    e.clipboardData.setData('text/plain', text);
+    e.preventDefault();
+  }
+
   private on(target: EventTarget, type: string, fn: EventListener): void {
     target.addEventListener(type, fn);
     this.listeners.push([target, type, fn]);
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index 6d6cf37..c0f961c 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -315,6 +315,30 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('copy and cut after select all carry the whole document', async () => {
+      const { page } = await open();
+      const text = Array.from({ length: 3000 }, (_, i) => `line number ${i}`).join('\n');
+      await editor(page, 'a', text);
+      await clickAt(page, 'a', 0, 0);
+      await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+a`);
+      const result = await page.evaluate(async () => {
+        await window.codepad.frames(2);
+        const ta = document.querySelector('#a textarea');
+        const clip = (type) => {
+          const data = new DataTransfer();
+          ta.dispatchEvent(
+            new ClipboardEvent(type, { clipboardData: data, bubbles: true, cancelable: true }),
+          );
+          return data.getData('text/plain').length;
+        };
+        const copied = clip('copy');
+        const cut = clip('cut');
+        return { copied, cut, left: window.views.a.core.length };
+      });
+      assert.deepEqual(result, { copied: text.length, cut: text.length, left: 0 });
+      await page.close();
+    });
+
     test('a click on a line number keeps the focus where it is', async () => {
       const { page } = await open();
       await editor(page, 'a', 'one\ntwo');

From ed8b8dd8ae32594c14b071e9b85ba906605801d9 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:28:00 +0100
Subject: [PATCH 20/23] fix(web): land vertical moves on the nearest column in
 right-to-left text

Down into an Arabic run landed up to 50 px from the nearest column, because
the column search assumed x grows along a row. A row holding right-to-left
text now measures every column. A line edited after a caret move measured
it but before the next draw is also measured again, where it kept its old
text and sent the next Down to the wrong line.
---
 src/web/EditorView.ts    | 36 +++++++++++++++++++++++----------
 tests/web/render.e2e.mjs | 43 ++++++++++++++++++++++++++++++++++++++++
 2 files changed, 68 insertions(+), 11 deletions(-)

diff --git a/src/web/EditorView.ts b/src/web/EditorView.ts
index a2d1929..c899553 100644
--- a/src/web/EditorView.ts
+++ b/src/web/EditorView.ts
@@ -71,6 +71,8 @@ export const DEFAULT_OPTIONS: ViewOptions = {
 const MONOSPACE = 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace';
 const SNAPSHOT_INFO_INTS = 7;
 const MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform);
+// A run of Hebrew or Arabic script anywhere in a row.
+const RTL_TEXT = /[\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF]/;
 const MOVES: Partial> = {
   left: ['char', false],
   right: ['char', true],
@@ -160,7 +162,7 @@ export class EditorView {
   // The row of the drawn caret inside its wrapped line.
   private drawnCaretRow = 0;
   // Hidden copies of lines a caret move measured, dropped on the next draw.
-  private readonly measuring = new Map();
+  private readonly measuring = new Map();
   private readonly geometry: LineGeometry = {
     rows: (line) => Math.max(1, Math.round(this.lineEl(line).offsetHeight / this.rowHeight)),
     rowOf: (line, column) =>
@@ -489,10 +491,17 @@ export class EditorView {
     const first = firstWhere(0, length + 1, (c) => rowOf(c) >= rowInLine);
     if (first > length) return length;
     const last = firstWhere(first, length + 1, (c) => rowOf(c) > rowInLine) - 1;
-    const at = firstWhere(first, last + 1, (c) => xOf(c) >= x);
-    let column = at;
-    if (at > last) column = last;
-    else if (at > first && x - xOf(at - 1) < xOf(at) - x) column = at - 1;
+    let column = first;
+    if (RTL_TEXT.test(text.slice(first, last + 1))) {
+      // x does not grow along a row that holds right to left text, so every column is measured.
+      for (let c = first + 1; c <= last; c++)
+        if (Math.abs(xOf(c) - x) < Math.abs(xOf(column) - x)) column = c;
+    } else {
+      const at = firstWhere(first, last + 1, (c) => xOf(c) >= x);
+      column = at;
+      if (at > last) column = last;
+      else if (at > first && x - xOf(at - 1) < xOf(at) - x) column = at - 1;
+    }
     const unit = text.charCodeAt(column);
     // Never between the two halves of an emoji.
     if (column > 0 && unit >= 0xdc00 && unit <= 0xdfff) column--;
@@ -504,18 +513,23 @@ export class EditorView {
     const text = this.core.line(line);
     const entry = this.cache.get(line);
     if (entry && this.attached.has(line) && entry.text === text) return entry.el;
-    let el = this.measuring.get(line);
-    if (!el) {
-      el = this.makeLine();
+    let copy = this.measuring.get(line);
+    if (copy && copy.text !== text) {
+      copy.el.remove();
+      copy = undefined;
+    }
+    if (!copy) {
+      const el = this.makeLine();
       this.paint(el, text, null);
       el.style.visibility = 'hidden';
       el.style.top = '0px';
       el.style.left = `${this.layout.textAreaLeft + this.layout.textPadding}px`;
       el.style.width = this.o.softWrap ? `${this.layout.wrapWidth}px` : '';
       this.textLayer.append(el);
-      this.measuring.set(line, el);
+      copy = { el, text };
+      this.measuring.set(line, copy);
     }
-    return el;
+    return copy.el;
   }
 
   // The caret at a column of a line element, in pixels from its left edge and in rows from its top.
@@ -680,7 +694,7 @@ export class EditorView {
     }
     if (!this.dirty) return;
     this.dirty = false;
-    for (const el of this.measuring.values()) el.remove();
+    for (const copy of this.measuring.values()) copy.el.remove();
     this.measuring.clear();
     this.configure();
     this.restaleRefreshed();
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index c0f961c..1c9bcc6 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -538,6 +538,49 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('a caret move after an edit to a line not drawn measures its new text', async () => {
+      const { page } = await open();
+      await editor(page, 'a', Array.from({ length: 100 }, (_, i) => `line ${i}`).join('\n'), {
+        softWrap: true,
+      });
+      const line = await page.evaluate(() => {
+        const v = window.views.a;
+        v.moveCaret('pageDown', false);
+        v.moveCaret('pageDown', false);
+        const at = v.core.lineAt(v.core.selection.head);
+        const start = v.core.lineStart(at);
+        v.apply(() => v.core.replace(start, v.core.lineEnd(at), 'x'.repeat(300)));
+        v.apply(() => v.core.setSelection(start + 20, start + 20));
+        v.moveCaret('down', false);
+        return { at, now: v.core.lineAt(v.core.selection.head) };
+      });
+      assert.equal(line.now, line.at);
+      await page.close();
+    });
+
+    test('ArrowDown into right-to-left text lands on the nearest column', async () => {
+      const { page } = await open();
+      await editor(page, 'a', 'abcdefghijklmnopq\nab مرحبا بالعالم cd');
+      const columns = await page.evaluate(() => {
+        const v = window.views.a;
+        const out = [];
+        for (let c = 4; c <= 15; c++) {
+          v.apply(() => v.core.setSelection(c, c));
+          const goal = v.caretRect(c).x;
+          v.moveCaret('down', false);
+          const start = v.core.lineStart(1);
+          const x = (o) => v.caretRect(o).x;
+          let best = Infinity;
+          for (let o = start; o <= v.core.lineEnd(1); o++)
+            best = Math.min(best, Math.abs(x(o) - goal));
+          out.push(Math.abs(x(v.core.selection.head) - goal) - best);
+        }
+        return out;
+      });
+      assert.ok(Math.max(...columns) < 1, `extra distance ${columns}`);
+      await page.close();
+    });
+
     test('Shift+ArrowRight draws a selection', async () => {
       const { page } = await open();
       await editor(page, 'a', 'abcdef');

From 53f747fe00e09ff5d4f88722a24ee1864afda7d9 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 02:29:52 +0100
Subject: [PATCH 21/23] fix(core): color a fence when two refreshes queue
 before the pump

A Markdown fence stayed plain when two languages registered before the
engine ran. The first refresh forgot the missing names but deferred its pass
to the queued second one, which found no names left and returned. A refresh
now runs the pass whenever ranges are still marked dirty.
---
 cpp/core/src/engine.cpp          | 11 +++++++----
 src/web/__tests__/fences.test.ts | 20 ++++++++++++++++++++
 2 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/cpp/core/src/engine.cpp b/cpp/core/src/engine.cpp
index 4b0d5d6..bf2a69b 100644
--- a/cpp/core/src/engine.cpp
+++ b/cpp/core/src/engine.cpp
@@ -246,10 +246,13 @@ struct Engine : std::enable_shared_from_this {
         it = resolved.erase(it);
         forgot = true;
       }
-      if (!forgot || !text) return;
-      dirty.push_back(0);
-      dirty.push_back(static_cast(text->length()));
-      reparse();
+      if (!text) return;
+      if (forgot) {
+        dirty.push_back(0);
+        dirty.push_back(static_cast(text->length()));
+      }
+      // A refresh queued behind another one finds no names left, so it runs the pass the first one deferred.
+      if (!dirty.empty()) reparse();
     });
   }
 
diff --git a/src/web/__tests__/fences.test.ts b/src/web/__tests__/fences.test.ts
index 1824914..9430617 100644
--- a/src/web/__tests__/fences.test.ts
+++ b/src/web/__tests__/fences.test.ts
@@ -52,6 +52,26 @@ const FENCE = '```python\ndef f(): pass\n```\n';
   pumpAll(m);
 });
 
+(ready ? test : test.skip)('two refreshes queued before a pump still color the fence', async () => {
+  const m = await loadCore(dir as string);
+  loadGrammar(m, markdown.wasm, 'markdown', markdown.queries);
+  loadGrammar(m, inline.wasm, 'markdown_inline', inline.queries);
+  const core = new EditorCore(m, FENCE);
+  const keyword = cstring(m, 'keyword.function', (name) => m._cp_style_id(name));
+  expect(core.setLanguage('markdown')).toBe(true);
+  pumpAll(m);
+  loadGrammar(m, python.wasm, 'python', python.queries);
+  core.refreshInjections();
+  core.refreshInjections();
+  pumpAll(m);
+  const line = highlight(m, core.snapshot, 1, 1, core.lineStart(1))[0] as number[];
+  const triples = [];
+  for (let i = 0; i + 2 < line.length; i += 3) triples.push(line.slice(i, i + 3));
+  expect(triples).toContainEqual([0, 3, keyword]);
+  core.close();
+  pumpAll(m);
+});
+
 // The loader refreshes only after a new language registers, since a refresh looks the names up again.
 (ready ? test : test.skip)(
   'a refresh while the language is still missing reports it again',

From b0be27844e1233228307167aab49dad6f268c173 Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 11:28:10 +0100
Subject: [PATCH 22/23] fix(web): stop the composition settle once the editor
 unmounts

The settle that runs one task after compositionend was never cancelled, so
an editor unmounted in that task still read the selection and the text
through the core handle cpw_close had already freed. destroy() now clears
the timer.
---
 src/web/input/InputHost.ts |  6 +++++-
 tests/web/render.e2e.mjs   | 26 ++++++++++++++++++++++++++
 2 files changed, 31 insertions(+), 1 deletion(-)

diff --git a/src/web/input/InputHost.ts b/src/web/input/InputHost.ts
index b4f4225..64911e6 100644
--- a/src/web/input/InputHost.ts
+++ b/src/web/input/InputHost.ts
@@ -23,6 +23,7 @@ export class InputHost {
   readonly textarea: HTMLTextAreaElement;
   // iOS reports the selection as 0,0 for a moment after focus, so selection changes wait a frame.
   private settling = false;
+  private settleTimer: ReturnType | undefined;
   private readonly listeners: [EventTarget, string, EventListener][] = [];
 
   constructor(
@@ -58,7 +59,9 @@ export class InputHost {
       this.session.compositionEnd();
       this.hooks.changed();
       // A browser may still send the composition's last input after this event, so the window moves a task later.
-      setTimeout(() => {
+      clearTimeout(this.settleTimer);
+      this.settleTimer = setTimeout(() => {
+        this.settleTimer = undefined;
         this.write(this.session.settle(this.state()));
         this.hooks.changed();
       }, 0);
@@ -133,6 +136,7 @@ export class InputHost {
   }
 
   destroy(): void {
+    clearTimeout(this.settleTimer);
     for (const [target, type, fn] of this.listeners) target.removeEventListener(type, fn);
     this.textarea.remove();
   }
diff --git a/tests/web/render.e2e.mjs b/tests/web/render.e2e.mjs
index 1c9bcc6..795fe4f 100644
--- a/tests/web/render.e2e.mjs
+++ b/tests/web/render.e2e.mjs
@@ -717,6 +717,32 @@ for (const engine of [chromium, webkit]) {
       await page.close();
     });
 
+    test('a composition ended just before unmount reads nothing from the closed core', async () => {
+      const { page, errors } = await open();
+      const reads = await page.evaluate(async () => {
+        const { EditorView, loadCore, until } = window.codepad;
+        const m = await loadCore();
+        const a = new EditorView(document.getElementById('a'), m, 'first');
+        await until(() => document.querySelector('#a [data-line="0"]'));
+        const ta = document.querySelector('#a textarea');
+        ta.dispatchEvent(new CompositionEvent('compositionstart'));
+        ta.dispatchEvent(new CompositionEvent('compositionend'));
+        a.destroy();
+        let count = 0;
+        Object.defineProperty(a.core, 'selection', {
+          get: () => {
+            count++;
+            return { anchor: 0, head: 0 };
+          },
+        });
+        await new Promise((resolve) => setTimeout(resolve, 20));
+        return count;
+      });
+      assert.equal(reads, 0);
+      assert.deepEqual(errors, []);
+      await page.close();
+    });
+
     test('unmounting during a parse closes the engine and keeps no snapshot', async () => {
       const { page, errors } = await open('test');
       const result = await page.evaluate(async () => {

From de1ef389a914f173f3e5ffa04c453ae92665a3ac Mon Sep 17 00:00:00 2001
From: Rayen Sbai 
Date: Sun, 15 Nov 2026 11:28:14 +0100
Subject: [PATCH 23/23] fix(web): add no undo step for an input that changes
 nothing

A browser can send the composition's last input after compositionend with
the textarea already matching. That empty replacement still reached the
core, which kept it as an undo step of its own, so the first undo after a
composition did nothing visible. The session now skips it.
---
 src/web/__tests__/input-session.test.ts | 15 +++++++++++++++
 src/web/input/WebInputSession.ts        |  2 +-
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/src/web/__tests__/input-session.test.ts b/src/web/__tests__/input-session.test.ts
index 523af3a..3471c5b 100644
--- a/src/web/__tests__/input-session.test.ts
+++ b/src/web/__tests__/input-session.test.ts
@@ -97,6 +97,21 @@ run('a composed word undoes in one step', async () => {
   expect(core.text()).toBe('ab');
 });
 
+run(
+  'an input with no change after compositionend leaves the composition one undo away',
+  async () => {
+    const { core, s } = await open('ab', 2);
+    s.compositionStart(ta('ab', 2));
+    s.beforeInput(ta('ab', 2));
+    s.input(composed('か'), ta('abか', 3));
+    s.compositionEnd();
+    s.beforeInput(ta('abか', 3));
+    s.input(typed('か'), ta('abか', 3));
+    core.undo();
+    expect(core.text()).toBe('ab');
+  },
+);
+
 run('a quote typed inside a composition does not auto-close', async () => {
   const { core, s } = await open('', 0);
   s.compositionStart(ta('', 0));
diff --git a/src/web/input/WebInputSession.ts b/src/web/input/WebInputSession.ts
index 8353c0f..7ada5f7 100644
--- a/src/web/input/WebInputSession.ts
+++ b/src/web/input/WebInputSession.ts
@@ -114,7 +114,7 @@ export class WebInputSession {
       ) {
         this.core.inputReplace(start, end + 1, '', true);
         coreCaret = true;
-      } else {
+      } else if (start !== end || inserted !== '') {
         this.core.inputReplace(start, end, inserted, inserted === '' && codePoints(removed) === 1);
       }
       const caret = start + inserted.length;