Skip to content
pi-c Documentation
Login

Documentation

/* Pi's keybindings; see keymap.h. The names, defaults and descriptions are
 * those of Pi's keybindings.ts (packages/coding-agent) and tui keybindings.ts
 * on Linux and macOS (Pi's Windows and WSL variants are not reproduced). */
#include "tui/keymap.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "tui/mjson.h"

#define MAX_KEYS 12
#define NO_KIND (-1)

typedef struct {
    const char *name;
    const char *keys[4]; /* the defaults */
    const char *desc;
    int kind;   /* the tui_key_kind a key bound to it becomes; NO_KIND: pic does nothing for it */
    int action; /* TUI_ACT_* for TUI_KEY_ACTION */
} action_def;

#ifdef __APPLE__
#define TREE_FOLD_UP {"alt+left", "ctrl+left"}
#define TREE_UNFOLD {"alt+right", "ctrl+right"}
#else
#define TREE_FOLD_UP {"ctrl+left", "alt+left"}
#define TREE_UNFOLD {"ctrl+right", "alt+right"}
#endif

/* In Pi's order (the application's actions first). Where several actions share a key the first one with a
 * kind decides what the key does, so the application's actions win over the editor's. */
static const action_def defs[] = {
    {"app.interrupt", {"escape"}, "Cancel or abort", TUI_KEY_ESC, 0},
    {"app.clear", {"ctrl+c"}, "Clear editor", TUI_KEY_CTRL_C, 0},
    {"app.exit", {"ctrl+d"}, "Exit when editor is empty", TUI_KEY_CTRL_D, 0},
    {"app.suspend", {"ctrl+z"}, "Suspend to background", TUI_KEY_CTRL_Z, 0},
    {"app.thinking.cycle", {"shift+tab", "alt+t"}, "Cycle thinking level", TUI_KEY_BACKTAB, 0},
    {"app.thinking.save", {"ctrl+s"}, "Save thinking level", TUI_KEY_CTRL_S, 0},
    {"app.model.cycleForward", {"ctrl+p"}, "Cycle to next model", TUI_KEY_CTRL_P, 0},
    {"app.model.cycleBackward", {"shift+ctrl+p", "ctrl+n"}, "Cycle to previous model", TUI_KEY_CTRL_P_BACK, 0},
    {"app.model.select", {"alt+p"}, "Open model selector", TUI_KEY_CTRL_L, 0},
    {"app.credential.select", {"alt+k"}, "Open key selector (pic)", TUI_KEY_ACTION, TUI_ACT_CREDENTIAL_SELECT},
    {"app.mouse.toggle", {"alt+m"}, "Capture the mouse or leave it to the terminal (pic)", TUI_KEY_ACTION, TUI_ACT_MOUSE_TOGGLE},
    {"app.history.search", {"ctrl+r"}, "Search prompt history (pic; Claude Code's Ctrl+R)", TUI_KEY_ACTION, TUI_ACT_HISTORY_SEARCH},
    {"app.screen.redraw", {"ctrl+l"}, "Redraw the screen (pic; Claude Code's Ctrl+L)", TUI_KEY_ACTION, TUI_ACT_REDRAW},
    {"app.tools.expand", {"ctrl+o"}, "Toggle tool output", TUI_KEY_CTRL_O, 0},
    {"app.thinking.toggle", {"ctrl+t"}, "Toggle thinking blocks", TUI_KEY_CTRL_T, 0},
    {"app.session.toggleNamedFilter", {"ctrl+n"}, "Toggle named session filter", NO_KIND, 0},
    {"app.editor.external", {"ctrl+g"}, "Open external editor", TUI_KEY_CTRL_G, 0},
    {"app.message.copy", {"ctrl+x"}, "Copy selection or last assistant message", TUI_KEY_CTRL_X, 0},
    {"app.message.followUp", {"ctrl+q", "alt+enter"}, "Queue follow-up message", TUI_KEY_ALT_ENTER, 0},
    {"app.message.dequeue", {"alt+up"}, "Restore queued messages", TUI_KEY_ALT_UP, 0},
    {"app.clipboard.pasteImage", {"ctrl+v"}, "Paste files on macOS, images, or text from clipboard", TUI_KEY_CTRL_V, 0},
    {"app.session.new", {NULL}, "Start a new session", TUI_KEY_ACTION, TUI_ACT_SESSION_NEW},
    {"app.session.tree", {NULL}, "Open session tree", TUI_KEY_ACTION, TUI_ACT_SESSION_TREE},
    {"app.session.fork", {NULL}, "Fork current session", TUI_KEY_ACTION, TUI_ACT_SESSION_FORK},
    {"app.session.resume", {NULL}, "Resume a session", TUI_KEY_ACTION, TUI_ACT_SESSION_RESUME},
    {"app.tree.foldOrUp", TREE_FOLD_UP, "Fold tree branch or move up", NO_KIND, 0},
    {"app.tree.unfoldOrDown", TREE_UNFOLD, "Unfold tree branch or move down", NO_KIND, 0},
    {"app.tree.editLabel", {"shift+l"}, "Edit tree label", NO_KIND, 0},
    {"app.tree.toggleLabelTimestamp", {"shift+t"}, "Toggle tree label timestamps", NO_KIND, 0},
    {"app.session.togglePath", {"ctrl+p"}, "Toggle session path display", NO_KIND, 0},
    {"app.session.toggleSort", {"ctrl+s"}, "Toggle session sort mode", NO_KIND, 0},
    {"app.session.rename", {"ctrl+r"}, "Rename session", NO_KIND, 0},
    {"app.session.delete", {"ctrl+d"}, "Delete session", NO_KIND, 0},
    {"app.session.deleteNoninvasive", {"ctrl+backspace"}, "Delete session when query is empty", NO_KIND, 0},
    {"app.models.save", {"ctrl+s"}, "Save model selection", NO_KIND, 0},
    {"app.models.enableAll", {"ctrl+a"}, "Enable all models", NO_KIND, 0},
    {"app.models.clearAll", {"ctrl+x"}, "Clear all models", NO_KIND, 0},
    {"app.models.toggleProvider", {"ctrl+p"}, "Toggle all models for provider", NO_KIND, 0},
    {"app.models.reorderUp", {"alt+up"}, "Move model up in order", NO_KIND, 0},
    {"app.models.reorderDown", {"alt+down"}, "Move model down in order", NO_KIND, 0},
    {"app.tree.filter.default", {"ctrl+d"}, "Tree filter: default view", NO_KIND, 0},
    {"app.tree.filter.noTools", {"ctrl+t"}, "Tree filter: hide tool results", NO_KIND, 0},
    {"app.tree.filter.userOnly", {"ctrl+u"}, "Tree filter: user messages only", NO_KIND, 0},
    {"app.tree.filter.labeledOnly", {"ctrl+l"}, "Tree filter: labeled entries only", NO_KIND, 0},
    {"app.tree.filter.all", {"ctrl+a"}, "Tree filter: show all entries", NO_KIND, 0},
    {"app.tree.filter.cycleForward", {"ctrl+o"}, "Tree filter: cycle forward", NO_KIND, 0},
    {"app.tree.filter.cycleBackward", {"shift+ctrl+o"}, "Tree filter: cycle backward", NO_KIND, 0},

    {"tui.editor.cursorUp", {"up"}, "Move cursor up", TUI_KEY_UP, 0},
    {"tui.editor.cursorDown", {"down"}, "Move cursor down", TUI_KEY_DOWN, 0},
    {"tui.editor.historyPrevious", {NULL}, "Select previous prompt history entry", TUI_KEY_HISTORY_PREV, 0},
    {"tui.editor.historyNext", {NULL}, "Select next prompt history entry", TUI_KEY_HISTORY_NEXT, 0},
    {"tui.editor.cursorLeft", {"left", "ctrl+b"}, "Move cursor left", TUI_KEY_LEFT, 0},
    {"tui.editor.cursorRight", {"right", "ctrl+f"}, "Move cursor right", TUI_KEY_RIGHT, 0},
    {"tui.editor.cursorWordLeft", {"alt+left", "ctrl+left", "alt+b"}, "Move cursor word left", TUI_KEY_WORD_LEFT, 0},
    {"tui.editor.cursorWordRight", {"alt+right", "ctrl+right", "alt+f"}, "Move cursor word right", TUI_KEY_WORD_RIGHT, 0},
    {"tui.editor.cursorLineStart", {"home", "ctrl+a"}, "Move to line start", TUI_KEY_HOME, 0},
    {"tui.editor.cursorLineEnd", {"end", "ctrl+e"}, "Move to line end", TUI_KEY_END, 0},
    {"tui.editor.jumpForward", {"ctrl+]"}, "Jump forward to character", TUI_KEY_JUMP, 0},
    {"tui.editor.jumpBackward", {"ctrl+alt+]"}, "Jump backward to character", TUI_KEY_JUMP_BACK, 0},
    {"tui.editor.pageUp", {"pageUp", "ctrl+pageUp"}, "Page up", TUI_KEY_PAGEUP, 0},
    {"tui.editor.pageDown", {"pageDown", "ctrl+pageDown"}, "Page down", TUI_KEY_PAGEDOWN, 0},
    {"tui.editor.deleteCharBackward", {"backspace"}, "Delete character backward", TUI_KEY_BACKSPACE, 0},
    {"tui.editor.deleteCharForward", {"delete", "ctrl+d"}, "Delete character forward", TUI_KEY_DELETE, 0},
    {"tui.editor.deleteWordBackward", {"ctrl+w", "alt+backspace"}, "Delete word backward", TUI_KEY_DELETE_WORD, 0},
    {"tui.editor.deleteWordForward", {"alt+d", "alt+delete"}, "Delete word forward", TUI_KEY_DELETE_WORD_FWD, 0},
    {"tui.editor.deleteToLineStart", {"ctrl+u"}, "Delete to line start", TUI_KEY_KILL_START, 0},
    {"tui.editor.deleteToLineEnd", {"ctrl+k"}, "Delete to line end", TUI_KEY_KILL_LINE, 0},
    {"tui.editor.yank", {"ctrl+y"}, "Yank", TUI_KEY_YANK, 0},
    {"tui.editor.yankPop", {"alt+y"}, "Yank pop", TUI_KEY_YANK_POP, 0},
    {"tui.editor.undo", {"ctrl+-"}, "Undo", TUI_KEY_UNDO, 0},
    {"tui.input.newLine", {"shift+enter", "ctrl+j"}, "Insert newline", TUI_KEY_NEWLINE, 0},
    {"tui.input.submit", {"enter"}, "Submit input", TUI_KEY_ENTER, 0},
    {"tui.input.tab", {"tab"}, "Tab / autocomplete", TUI_KEY_TAB, 0},
    {"tui.input.copy", {"ctrl+c"}, "Copy selection", NO_KIND, 0},
    {"tui.select.up", {"up"}, "Move selection up", TUI_KEY_UP, 0},
    {"tui.select.down", {"down"}, "Move selection down", TUI_KEY_DOWN, 0},
    {"tui.select.pageUp", {"pageUp"}, "Selection page up", TUI_KEY_PAGEUP, 0},
    {"tui.select.pageDown", {"pageDown"}, "Selection page down", TUI_KEY_PAGEDOWN, 0},
    {"tui.select.confirm", {"enter"}, "Confirm selection", TUI_KEY_ENTER, 0},
    {"tui.select.cancel", {"escape", "ctrl+c"}, "Cancel selection", TUI_KEY_ESC, 0},
    {"tui.altScreen.pageUp", {"pageUp", "shift+up"}, "Scroll viewport up one page", TUI_KEY_PAGEUP, 0},
    {"tui.altScreen.pageDown", {"pageDown", "shift+down"}, "Scroll viewport down one page", TUI_KEY_PAGEDOWN, 0},
    {"tui.altScreen.halfPageUp", {NULL}, "Scroll viewport up half a page", TUI_KEY_ACTION, TUI_ACT_SCROLL_HALF_UP},
    {"tui.altScreen.halfPageDown", {NULL}, "Scroll viewport down half a page", TUI_KEY_ACTION, TUI_ACT_SCROLL_HALF_DOWN},
    {"tui.altScreen.lineUp", {NULL}, "Scroll viewport up one line", TUI_KEY_ACTION, TUI_ACT_SCROLL_LINE_UP},
    {"tui.altScreen.lineDown", {NULL}, "Scroll viewport down one line", TUI_KEY_ACTION, TUI_ACT_SCROLL_LINE_DOWN},
    {"tui.altScreen.previousPrompt", {"ctrl+shift+up", "ctrl+up"}, "Jump to previous semantic prompt", NO_KIND, 0},
    {"tui.altScreen.nextPrompt", {"ctrl+shift+down", "ctrl+down"}, "Jump to next semantic prompt", NO_KIND, 0},
    /* ctrl+f too (Pi's Windows default): Mac Terminal sends no ctrl+shift+f. In fullscreen it searches; elsewhere
     * it stays tui.editor.cursorRight. */
    {"tui.altScreen.search", {"ctrl+shift+f", "ctrl+f"}, "Search the primary scroll view", TUI_KEY_ACTION, TUI_ACT_SEARCH_TOGGLE},
    {"tui.altScreen.searchNext", {"enter", "ctrl+g"}, "Select the next search match", TUI_KEY_ACTION, TUI_ACT_SEARCH_NEXT},
    {"tui.altScreen.searchPrevious", {"shift+enter", "ctrl+shift+g"}, "Select the previous search match", TUI_KEY_ACTION, TUI_ACT_SEARCH_PREV},
    {"tui.altScreen.searchClose", {"escape"}, "Close transcript search", TUI_KEY_ACTION, TUI_ACT_SEARCH_CLOSE},
    {"tui.altScreen.top", {"ctrl+home", "shift+pageUp"}, "Scroll viewport to top", TUI_KEY_CTRL_HOME, 0},
    {"tui.altScreen.bottom", {"ctrl+end", "shift+pageDown"}, "Scroll viewport to bottom", TUI_KEY_CTRL_END, 0},
};
#define NDEFS (sizeof defs / sizeof defs[0])

/* Pi's migrations of its earlier action names (KEYBINDING_NAME_MIGRATIONS). */
static const char *const migrations[][2] = {
    {"cursorUp", "tui.editor.cursorUp"}, {"cursorDown", "tui.editor.cursorDown"},
    {"cursorLeft", "tui.editor.cursorLeft"}, {"cursorRight", "tui.editor.cursorRight"},
    {"cursorWordLeft", "tui.editor.cursorWordLeft"}, {"cursorWordRight", "tui.editor.cursorWordRight"},
    {"cursorLineStart", "tui.editor.cursorLineStart"}, {"cursorLineEnd", "tui.editor.cursorLineEnd"},
    {"jumpForward", "tui.editor.jumpForward"}, {"jumpBackward", "tui.editor.jumpBackward"},
    {"pageUp", "tui.editor.pageUp"}, {"pageDown", "tui.editor.pageDown"},
    {"deleteCharBackward", "tui.editor.deleteCharBackward"}, {"deleteCharForward", "tui.editor.deleteCharForward"},
    {"deleteWordBackward", "tui.editor.deleteWordBackward"}, {"deleteWordForward", "tui.editor.deleteWordForward"},
    {"deleteToLineStart", "tui.editor.deleteToLineStart"}, {"deleteToLineEnd", "tui.editor.deleteToLineEnd"},
    {"yank", "tui.editor.yank"}, {"yankPop", "tui.editor.yankPop"}, {"undo", "tui.editor.undo"},
    {"newLine", "tui.input.newLine"}, {"submit", "tui.input.submit"}, {"tab", "tui.input.tab"},
    {"copy", "tui.input.copy"}, {"selectUp", "tui.select.up"}, {"selectDown", "tui.select.down"},
    {"selectPageUp", "tui.select.pageUp"}, {"selectPageDown", "tui.select.pageDown"},
    {"selectConfirm", "tui.select.confirm"}, {"selectCancel", "tui.select.cancel"},
    {"interrupt", "app.interrupt"}, {"clear", "app.clear"}, {"exit", "app.exit"}, {"suspend", "app.suspend"},
    {"cycleThinkingLevel", "app.thinking.cycle"}, {"cycleModelForward", "app.model.cycleForward"},
    {"cycleModelBackward", "app.model.cycleBackward"}, {"selectModel", "app.model.select"},
    {"expandTools", "app.tools.expand"}, {"toggleThinking", "app.thinking.toggle"},
    {"toggleSessionNamedFilter", "app.session.toggleNamedFilter"}, {"externalEditor", "app.editor.external"},
    {"followUp", "app.message.followUp"}, {"dequeue", "app.message.dequeue"},
    {"pasteImage", "app.clipboard.pasteImage"}, {"newSession", "app.session.new"}, {"tree", "app.session.tree"},
    {"fork", "app.session.fork"}, {"resume", "app.session.resume"}, {"treeFoldOrUp", "app.tree.foldOrUp"},
    {"treeUnfoldOrDown", "app.tree.unfoldOrDown"}, {"treeEditLabel", "app.tree.editLabel"},
    {"treeToggleLabelTimestamp", "app.tree.toggleLabelTimestamp"}, {"toggleSessionPath", "app.session.togglePath"},
    {"toggleSessionSort", "app.session.toggleSort"}, {"renameSession", "app.session.rename"},
    {"deleteSession", "app.session.delete"}, {"deleteSessionNoninvasive", "app.session.deleteNoninvasive"},
};

/* ---- key ids -------------------------------------------------------------- */

static const char *const km_named[] = {"escape", "esc", "enter", "return", "tab", "space", "backspace", "delete", "insert",
                                    "clear", "home", "end", "pageUp", "pageDown", "up", "down", "left", "right",
                                    "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12"};
static const char symbols[] = "`-=[]\\;',./!@#$%^&*()_+|~{}:<>?";

static unsigned mod_bit(const char *s, size_t n)
{
    if (n == 4 && strncmp(s, "ctrl", 4) == 0)
        return TUI_MOD_CTRL;
    if (n == 5 && strncmp(s, "shift", 5) == 0)
        return TUI_MOD_SHIFT;
    if (n == 3 && strncmp(s, "alt", 3) == 0)
        return TUI_MOD_ALT;
    if (n == 5 && strncmp(s, "super", 5) == 0)
        return TUI_MOD_SUPER;
    return 0;
}

int tui_keyid_parse(const char *s, tui_keyid *out)
{
    const char *p = s;
    unsigned mods = 0;
    int count = 0;
    memset(out, 0, sizeof *out);
    for (;;) {
        const char *plus = strchr(p, '+');
        unsigned bit;
        if (!plus || plus == p || !p[(size_t)(plus - p) + 1] || !(bit = mod_bit(p, (size_t)(plus - p))))
            break;
        if ((mods & bit) || ++count > 4)
            return -1;
        mods |= bit;
        p = plus + 1;
    }
    if (strlen(p) > sizeof out->base - 1 || strlen(s) > sizeof out->text - 1)
        return -1;
    if ((p[0] >= 'a' && p[0] <= 'z') || (p[0] >= '0' && p[0] <= '9')) {
        if (p[1] != '\0') {
            int ok = 0;
            for (size_t i = 0; i < sizeof km_named / sizeof km_named[0]; i++)
                ok |= strcmp(p, km_named[i]) == 0;
            if (!ok)
                return -1;
        }
    } else if (p[0] && p[1] == '\0' && strchr(symbols, p[0])) {
        /* a symbol key */
    } else {
        return -1;
    }
    (void)snprintf(out->base, sizeof out->base, "%s", strcmp(p, "esc") == 0 ? "escape" : strcmp(p, "return") == 0 ? "enter" : p);
    out->mods = mods;
    (void)snprintf(out->text, sizeof out->text, "%s", s);
    return 0;
}

/* ---- the map -------------------------------------------------------------- */

struct tui_keymap {
    struct {
        tui_keyid k[MAX_KEYS];
        int n;
    } a[NDEFS];
};

static void set_defaults(tui_keymap *m)
{
    for (size_t i = 0; i < NDEFS; i++) {
        m->a[i].n = 0;
        for (int j = 0; j < 4 && defs[i].keys[j]; j++)
            if (tui_keyid_parse(defs[i].keys[j], &m->a[i].k[m->a[i].n]) == 0)
                m->a[i].n++;
    }
}

tui_keymap *tui_keymap_new(void)
{
    tui_keymap *m = calloc(1, sizeof *m);
    if (m)
        set_defaults(m);
    return m;
}

void tui_keymap_free(tui_keymap *m)
{
    free(m);
}

int tui_keymap_find(const char *name)
{
    for (size_t i = 0; name && i < NDEFS; i++)
        if (strcmp(defs[i].name, name) == 0)
            return (int)i;
    return -1;
}

typedef struct {
    char *p;
    size_t n, cap;
    int oom;
} km_out_t;

static void wr(km_out_t *o, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
static void wr(km_out_t *o, const char *fmt, ...)
{
    va_list ap;
    char line[1024];
    int n;
    va_start(ap, fmt);
    n = vsnprintf(line, sizeof line, fmt, ap);
    va_end(ap);
    if (n <= 0 || o->oom)
        return;
    if ((size_t)n >= sizeof line)
        n = (int)sizeof line - 1;
    if (o->n + (size_t)n + 1 > o->cap) {
        size_t cap = o->cap ? o->cap : 512;
        char *g;
        while (cap < o->n + (size_t)n + 1)
            cap *= 2;
        if (!(g = realloc(o->p, cap))) {
            o->oom = 1;
            return;
        }
        o->p = g;
        o->cap = cap;
    }
    memcpy(o->p + o->n, line, (size_t)n);
    o->n += (size_t)n;
    o->p[o->n] = '\0';
}

static int same_key(const tui_keyid *a, const tui_keyid *b)
{
    return a->mods == b->mods && strcmp(a->base, b->base) == 0;
}

/* Two actions that may share a key because the mode decides: the fullscreen search key against the editor's
 * cursor right (ctrl+f, by default). */
static int by_mode(size_t i, size_t j)
{
    const char *a = defs[i].name, *b = defs[j].name;
    return (strcmp(a, "tui.altScreen.search") == 0 && strcmp(b, "tui.editor.cursorRight") == 0) ||
           (strcmp(b, "tui.altScreen.search") == 0 && strcmp(a, "tui.editor.cursorRight") == 0);
}

int tui_keymap_load(tui_keymap *m, const char *json, size_t n, const char *label, char **warnings)
{
    km_out_t w = {NULL, 0, 0, 0};
    char err[160];
    mj *root;
    unsigned char claimed[NDEFS];
    set_defaults(m);
    memset(claimed, 0, sizeof claimed);
    root = json ? mj_parse(json, n, err, sizeof err) : NULL;
    if (json && !root) {
        wr(&w, "%s: %s; using the default keybindings\n", label, err);
    } else if (root && root->kind != MJ_OBJ) {
        wr(&w, "%s: expected an object of actions; using the default keybindings\n", label);
    } else if (root) {
        for (size_t i = 0; i < root->n; i++) {
            const char *name = root->keys[i];
            const mj *val = root->kids[i];
            int idx;
            tui_keyid ids[MAX_KEYS];
            int nid = 0, bad = 0;
            if (strcmp(name, "$schema") == 0)
                continue;
            for (size_t j = 0; j < sizeof migrations / sizeof migrations[0]; j++) {
                if (strcmp(name, migrations[j][0]) == 0) {
                    if (mj_get(root, migrations[j][1]))
                        name = NULL; /* the new name is there too and wins */
                    else
                        name = migrations[j][1];
                    break;
                }
            }
            if (!name)
                continue;
            if ((idx = tui_keymap_find(name)) < 0) {
                wr(&w, "%s: unknown action \"%s\" is ignored\n", label, root->keys[i]);
                continue;
            }
            if (val->kind == MJ_STR) {
                bad = tui_keyid_parse(val->str, &ids[nid++]) != 0;
                if (bad)
                    wr(&w, "%s: \"%s\" is not a valid key for %s; its default is kept\n", label, val->str, name);
            } else if (val->kind == MJ_ARR) {
                for (size_t j = 0; j < val->n && !bad; j++) {
                    if (val->kids[j]->kind != MJ_STR || tui_keyid_parse(val->kids[j]->str, &ids[nid]) != 0) {
                        wr(&w, "%s: %s is not a valid key for %s; its default is kept\n", label,
                           val->kids[j]->kind == MJ_STR ? val->kids[j]->str : "an entry that is not a string", name);
                        bad = 1;
                    } else {
                        int dup = 0;
                        for (int q = 0; q < nid; q++)
                            dup |= same_key(&ids[q], &ids[nid]);
                        if (!dup && nid < MAX_KEYS)
                            nid++;
                    }
                }
            } else {
                wr(&w, "%s: %s needs a key or a list of keys; its default is kept\n", label, name);
                bad = 1;
            }
            if (bad)
                continue;
            memcpy(m->a[idx].k, ids, (size_t)nid * sizeof ids[0]);
            m->a[idx].n = nid;
            claimed[idx] = 1;
        }
        /* Pi's getConflicts: a key the user gave to more than one action. */
        for (size_t i = 0; i < NDEFS; i++) {
            for (int q = 0; claimed[i] && q < m->a[i].n; q++) {
                int first = 1;
                for (size_t j = 0; j < i && first; j++)
                    for (int r = 0; claimed[j] && r < m->a[j].n && first; r++)
                        if (same_key(&m->a[j].k[r], &m->a[i].k[q]))
                            first = 0;
                if (!first)
                    continue;
                {
                    int shown = 0;
                    km_out_t names = {NULL, 0, 0, 0};
                    for (size_t j = i; j < NDEFS; j++)
                        for (int r = 0; claimed[j] && r < m->a[j].n; r++)
                            if (same_key(&m->a[j].k[r], &m->a[i].k[q]) && !(j != i && by_mode(i, j))) {
                                wr(&names, "%s%s", shown++ ? ", " : "", defs[j].name);
                                break;
                            }
                    if (shown > 1)
                        wr(&w, "%s: %s is bound to more than one action (%s)\n", label, m->a[i].k[q].text, names.p ? names.p : "");
                    free(names.p);
                }
            }
        }
    }
    mj_free(root);
    if (warnings)
        *warnings = w.p ? w.p : strdup("");
    else
        free(w.p);
    return w.oom ? -1 : 0;
}

int tui_keymap_apply(const tui_keymap *m, tui_key *k)
{
    if (k->kind == TUI_KEY_CHAR || k->kind == TUI_KEY_PASTE || k->kind == TUI_KEY_MOUSE || k->kind == TUI_KEY_ACTION)
        return 1;
    for (size_t i = 0; i < NDEFS; i++) {
        if (defs[i].kind == NO_KIND)
            continue;
        for (int j = 0; j < m->a[i].n; j++) {
            if (m->a[i].k[j].mods == k->mods && strcmp(m->a[i].k[j].base, k->base) == 0) {
                k->kind = (tui_key_kind)defs[i].kind;
                k->action = defs[i].action;
                return 1;
            }
        }
    }
    return 0;
}

int tui_keymap_has(const tui_keymap *m, const char *action, const tui_key *k)
{
    int i = tui_keymap_find(action);
    for (int j = 0; i >= 0 && j < m->a[i].n; j++)
        if (m->a[i].k[j].mods == k->mods && strcmp(m->a[i].k[j].base, k->base) == 0)
            return 1;
    return 0;
}

size_t tui_keymap_count(void)
{
    return NDEFS;
}

const char *tui_keymap_name(size_t i)
{
    return i < NDEFS ? defs[i].name : NULL;
}

const char *tui_keymap_desc(size_t i)
{
    return i < NDEFS ? defs[i].desc : NULL;
}

int tui_keymap_active(size_t i)
{
    return i < NDEFS && defs[i].kind != NO_KIND;
}

void tui_keymap_keys(const tui_keymap *m, size_t i, char *out, size_t cap)
{
    size_t n = 0;
    if (cap)
        out[0] = '\0';
    for (int j = 0; i < NDEFS && j < m->a[i].n && n + 1 < cap; j++)
        n += (size_t)snprintf(out + n, cap - n, "%s%s", j ? ", " : "", m->a[i].k[j].text);
}

void tui_keymap_alt_letters(const tui_keymap *m, char out[40])
{
    size_t n = 0;
    out[0] = '\0';
    for (size_t i = 0; i < NDEFS; i++) {
        for (int j = 0; defs[i].kind != NO_KIND && j < m->a[i].n; j++) {
            const tui_keyid *k = &m->a[i].k[j];
            if (k->mods == TUI_MOD_ALT && k->base[1] == '\0' && !strchr(out, k->base[0]) && n < 39) {
                out[n++] = k->base[0];
                out[n] = '\0';
            }
        }
    }
}

char *tui_keymap_hotkeys(const tui_keymap *m)
{
    static const struct {
        const char *title, *prefix;
    } groups[] = {{"Application", "app."}, {"Editor", "tui.editor."}, {"Input and selection", "tui.input."},
                  {"Selection", "tui.select."}, {"Fullscreen", "tui.altScreen."}};
    km_out_t o = {NULL, 0, 0, 0};
    for (size_t g = 0; g < sizeof groups / sizeof groups[0]; g++) {
        int any = 0;
        for (size_t i = 0; i < NDEFS; i++) {
            char keys[200];
            if (defs[i].kind == NO_KIND || strncmp(defs[i].name, groups[g].prefix, strlen(groups[g].prefix)) != 0)
                continue;
            tui_keymap_keys(m, i, keys, sizeof keys);
            if (!keys[0])
                continue;
            if (!any)
                wr(&o, "%s%s:\n", o.n ? "\n" : "", groups[g].title);
            any = 1;
            wr(&o, "  %-34s %s  (%s)\n", keys, defs[i].desc, defs[i].name);
        }
    }
    if (o.oom) {
        free(o.p);
        return NULL;
    }
    if (o.n && o.p[o.n - 1] == '\n')
        o.p[--o.n] = '\0';
    return o.p ? o.p : strdup("");
}