summaryrefslogtreecommitdiffhomepage
path: root/src/edit_builtin.c
blob: 137d19aa66d2463627c466bf6714383d906e54a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
/**
 * @file edit_builtin.c
 * @brief The built-in line editor.
 *
 * A small editor with the emacs and vi modes of bash and the BSD shells,
 * and with bash's default key bindings in emacs mode.  It needs nothing but a
 * terminal that understands a handful of ANSI control sequences (carriage
 * return, "erase to end of line", "cursor right N", "clear screen"), so it has
 * no terminfo or curses dependency, which matters on z/OS.
 *
 * ## Display
 *
 * The line is drawn on a single screen row.  When it is wider than the
 * terminal the view scrolls sideways to keep the cursor visible.  Every
 * change redraws the row: return to column 0, write the prompt and the
 * visible slice of the line, erase what is left of the row, and move the
 * cursor to its place.  That is one write() per keystroke and cannot get
 * out of step with the terminal the way incremental updates can.
 *
 * ## Characters
 *
 * The editor works on bytes.  In an ASCII build, UTF-8 continuation
 * bytes are treated as part of the preceding character for cursor motion,
 * deletion and width, which is enough for text made of single-width
 * characters.  Control characters in the line (a newline inside a
 * recalled multi-line command, for instance) are shown as `^X`.
 *
 * ## Signals
 *
 * The terminal is put in a mode where it still generates signals, so
 * `^C` arrives as SIGINT and interrupts the read.  The editor then gives
 * the terminal back and lets trap_poll() abandon the line.
 */
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>

#include "charset.h"
#include "exec.h"
#include "interact.h"
#include "shell.h"
#include "var.h"

/** @brief Keys that are not single bytes. */
enum {
    K_EOF = -1,  /**< End of input. */
    K_INTR = -2, /**< The read was interrupted by a signal. */
    K_UP = 0x100,
    K_DOWN = 257,
    K_LEFT = 258,
    K_RIGHT = 259,
    K_HOME = 260,
    K_END = 261,
    K_DELETE = 262,
    K_WORD_LEFT = 263,
    K_WORD_RIGHT = 264,
    K_META = 0x1000, /**< Added to a byte: ESC followed by that byte. */
};

/** @brief Everything the editor knows about the line being edited. */
typedef struct editor {
    char *buf;  /**< The line (not NUL-terminated while editing). */
    size_t len; /**< Bytes in `buf`. */
    size_t cap; /**< Allocated size of `buf`. */
    size_t pos; /**< Cursor position, as a byte offset. */

    const char *prompt; /**< Last line of the prompt. */
    size_t pwidth;      /**< Screen columns the prompt occupies. */
    size_t off;         /**< First screen cell of the line that is shown. */

    int hidx;      /**< History entry on show; hist_count() is the new line. */
    char *pending; /**< The new line, kept while history is browsed. */

    char *kill;      /**< Last killed (cut) text, for yank / put. */
    size_t kill_len; /**< Its length. */

    struct termios saved; /**< Terminal modes to restore. */
    bool raw;             /**< The terminal is in editing mode. */
    int unread;           /**< A key pushed back by a sub-mode, or 0. */

    bool vi_cmd;      /**< vi mode: in command (not insert) mode. */
    char *undo;       /**< vi mode: the line before the last change. */
    size_t undo_len;  /**< Its length. */
    size_t undo_pos;  /**< Cursor position to restore with it. */
    char search[128]; /**< vi mode: last `/` or `?` pattern. */

    int rec[512];       /**< vi mode: the keys of the change being made. */
    size_t rec_len;     /**< Keys in `rec`. */
    int last[512];      /**< vi mode: the last change, for `.` and count. */
    size_t last_len;    /**< Keys in `last`. */
    bool changed;       /**< vi mode: the command under way moved the line. */
    bool recording;     /**< vi mode: keys are being recorded into `rec`. */
    int replay[512];    /**< vi mode: keys `.` is replaying, one pass. */
    size_t replay_len;  /**< Keys in `replay`. */
    size_t replay_pos;  /**< Next key to hand out. */
    size_t replay_left; /**< Keys still to hand out, passes included. */
} editor;

/**
 * @brief The one editor.
 */
static editor ed;

/* ---- terminal -------------------------------------------------------- */

/**
 * @brief Can lines be edited on this terminal?
 * @return true if stdin and stderr are terminals and TERM is not "dumb".
 */
bool edit_usable(void) {
    const char *term = var_get("TERM");
    if (!term || !*term || !strcmp(term, "dumb") || !strcmp(term, "emacs"))
        return false;
    return isatty(0) && isatty(2);
}

/**
 * @brief Put the terminal in editing mode.
 *
 * Input is delivered a byte at a time and not echoed. Signal generation
 * stays on, and output processing stays on so that "\n" still means
 * "start of next line".
 */
static void raw_on(void) {
    if (ed.raw || tcgetattr(0, &ed.saved) < 0)
        return;
    struct termios t = ed.saved;
    t.c_lflag &= ~(tcflag_t)(ICANON | ECHO | IEXTEN);
    t.c_iflag &= ~(tcflag_t)(IXON | ICRNL | INLCR);
    t.c_cc[VMIN] = 1;
    t.c_cc[VTIME] = 0;
    if (tcsetattr(0, TCSADRAIN, &t) == 0)
        ed.raw = true;
}

/** @brief Give the terminal back the modes it had before raw_on(). */
static void raw_off(void) {
    if (ed.raw) {
        tcsetattr(0, TCSADRAIN, &ed.saved);
        ed.raw = false;
    }
}

/* ---- buffered terminal output ---------------------------------------- */

/**
 * @brief Bytes queued for the terminal. Sent in one write by ob_flush().
 */
static char *obuf;
static size_t obuf_len;
static size_t obuf_cap;

/** @brief Queue bytes for the terminal. */
static void ob_put(const char *s, size_t n) {
    if (obuf_len + n > obuf_cap) {
        obuf_cap = (obuf_len + n) * 2 + 64;
        obuf = xrealloc(obuf, obuf_cap);
    }
    memcpy(obuf + obuf_len, s, n);
    obuf_len += n;
}

/** @brief Queue a string for the terminal. */
static void ob_puts(const char *s) {
    ob_put(s, strlen(s));
}

/** @brief Queue one byte for the terminal. */
static void ob_putc(char c) {
    ob_put(&c, 1);
}

/**
 * @brief Queue a control sequence: ESC `[`, an optional number, a final
 *        letter.
 * @param n     Parameter, or 0 for none.
 * @param final The letter that ends the sequence.
 */
static void ob_csi(size_t n, char final) {
    char num[INT_BUFSZ];
    ob_putc(CH_ESC);
    ob_putc('[');
    if (n)
        ob_puts(fmt_int((intmax_t)n, num));
    ob_putc(final);
}

/** @brief Send everything queued to the terminal in one write. */
static void ob_flush(void) {
    size_t done = 0;
    while (done < obuf_len) {
        ssize_t n = write(2, obuf + done, obuf_len - done);
        if (n < 0 && errno == EINTR)
            continue;
        if (n <= 0)
            break;
        done += (size_t)n;
    }
    obuf_len = 0;
}

/* ---- characters and cells -------------------------------------------- */

/**
 * @brief Is this byte the second or later byte of a UTF-8 character?
 *
 * Always false in an EBCDIC build, where text is single-byte.
 */
static bool is_cont(char c) {
#if ZASH_ASCII
    return ((unsigned char)c & 0xc0) == 0x80;
#else
    (void)c;
    return false;
#endif
}

/**
 * @brief Screen cells a byte occupies: 0 for a UTF-8 continuation byte,
 *        2 for a control character (shown as `^X`), otherwise 1.
 */
static size_t cell_width(char c) {
    if (is_cont(c))
        return 0;
    return iscntrl((unsigned char)c) ? 2 : 1;
}

/** @brief Byte offset of the character before `pos`. */
static size_t prev_char(size_t pos) {
    if (pos)
        pos--;
    while (pos && is_cont(ed.buf[pos]))
        pos--;
    return pos;
}

/** @brief Byte offset of the character after the one at `pos`. */
static size_t next_char(size_t pos) {
    if (pos < ed.len)
        pos++;
    while (pos < ed.len && is_cont(ed.buf[pos]))
        pos++;
    return pos;
}

/** @brief Is this byte part of a word, for word motions? */
static bool is_word(char c) {
    return isalnum((unsigned char)c) || c == '_' || is_cont(c) ||
           ((unsigned char)c >= 0x80 && ZASH_ASCII);
}

/** @brief Start of the word before `pos`. */
static size_t word_left(size_t pos) {
    while (pos && !is_word(ed.buf[pos - 1]))
        pos--;
    while (pos && is_word(ed.buf[pos - 1]))
        pos--;
    return pos;
}

/** @brief End of the word after `pos`. */
static size_t word_right(size_t pos) {
    while (pos < ed.len && !is_word(ed.buf[pos]))
        pos++;
    while (pos < ed.len && is_word(ed.buf[pos]))
        pos++;
    return pos;
}

/**
 * @brief Columns a prompt occupies on screen.
 *
 * Control sequences in the prompt are for the terminal, not the screen:
 * colour, a title, a character-set reset from `tput`, a hyperlink.  They
 * are skipped, including the ones a terminal's terminfo entry writes as
 * more than `ESC [` and a final byte.
 *
 * @param s The prompt (one line).
 * @return Its width in columns.
 */
static size_t prompt_width(const char *s) {
    size_t w = 0;
    while (*s) {
        if (*s == CH_ESC) {
            s += esc_seq_len(s);
            continue;
        }
        w += cell_width(*s) ? 1 : 0;
        s++;
    }
    return w;
}

/* ---- drawing --------------------------------------------------------- */

/**
 * @brief Redraw the edited line and place the cursor.
 *
 * See the file comment for the method.  `ed.off` (the horizontal scroll
 * position) is adjusted here so that the cursor is always on screen.
 */
static void refresh(void) {
    size_t cols = term_cols();
    size_t pwidth = ed.pwidth;
    bool show_prompt = pwidth + 10 < cols;
    if (!show_prompt)
        pwidth = 0;
    size_t avail = cols - pwidth - 1;

    size_t cursor = 0; /* cell index of the cursor */
    for (size_t i = 0; i < ed.pos; i++)
        cursor += cell_width(ed.buf[i]);
    if (cursor < ed.off)
        ed.off = cursor;
    else if (cursor >= ed.off + avail)
        ed.off = cursor - avail + 1;

    ob_putc('\r');
    if (show_prompt)
        ob_puts(ed.prompt);
    size_t cell = 0;
    bool shown = false;
    for (size_t i = 0; i < ed.len; i++) {
        char c = ed.buf[i];
        size_t w = cell_width(c);
        if (w == 0) {
            if (shown)
                ob_putc(c);
            continue;
        }
        shown = cell >= ed.off && cell + w <= ed.off + avail;
        if (shown) {
            if (w == 2) {
                ob_putc('^');
                ob_putc(ZASH_ASCII ? (char)((unsigned char)c ^ 0x40) : '?');
            } else {
                ob_putc(c);
            }
        }
        cell += w;
    }
    ob_csi(0, 'K');
    ob_putc('\r');
    if (pwidth + cursor > ed.off)
        ob_csi(pwidth + cursor - ed.off, 'C');
    ob_flush();
}

/* ---- changing the line ----------------------------------------------- */

/** @brief Make room for `extra` more bytes in the line. */
static void reserve(size_t extra) {
    if (ed.len + extra + 1 > ed.cap) {
        ed.cap = (ed.len + extra + 1) * 2;
        ed.buf = xrealloc(ed.buf, ed.cap);
    }
}

/**
 * @brief Insert bytes at the cursor and move the cursor past them.
 * @param s Bytes to insert.
 * @param n How many.
 */
static void insert(const char *s, size_t n) {
    if (!n) /* `y` over an empty range has no kill buffer to paste */
        return;
    reserve(n);
    memmove(ed.buf + ed.pos + n, ed.buf + ed.pos, ed.len - ed.pos);
    memcpy(ed.buf + ed.pos, s, n);
    ed.len += n;
    ed.pos += n;
}

/** @brief Make the bytes in [from, to) the kill buffer. */
static void kill_set(size_t from, size_t to) {
    if (from >= to)
        return;
    free(ed.kill);
    ed.kill_len = to - from;
    ed.kill = xmalloc(ed.kill_len);
    memcpy(ed.kill, ed.buf + from, ed.kill_len);
}

/**
 * @brief Remove the bytes in [from, to) and put the cursor at `from`.
 * @param from First byte to remove.
 * @param to   One past the last.
 * @param save Whether the text becomes the kill buffer (for yank).
 */
static void remove_range(size_t from, size_t to, bool save) {
    if (from >= to)
        return;
    if (save)
        kill_set(from, to);
    memmove(ed.buf + from, ed.buf + to, ed.len - to);
    ed.len -= to - from;
    ed.pos = from;
}

/**
 * @brief Replace the whole line.
 * @param s New contents (NUL-terminated).
 */
static void set_line(const char *s) {
    size_t n = strlen(s);
    ed.len = 0;
    reserve(n);
    memcpy(ed.buf, s, n);
    ed.len = ed.pos = n;
    ed.off = 0;
}

/**
 * @brief Show another history entry.
 *
 * The line being typed is remembered when the user first leaves it and
 * comes back when they return past the newest entry.
 *
 * @param index Entry to show. hist_count() means the line being typed.
 * @return false if `index` is out of range.
 */
static bool show_history(int index) {
    int count = hist_count();
    if (index < 0 || index > count)
        return false;
    if (ed.hidx == count) {
        free(ed.pending);
        ed.pending = xmalloc(ed.len + 1);
        memcpy(ed.pending, ed.buf, ed.len);
        ed.pending[ed.len] = '\0';
    }
    ed.hidx = index;
    set_line(index == count ? ed.pending : hist_entry(index));
    return true;
}

/* ---- bindings -------------------------------------------------------- */

/** @brief The longest key sequence `bind` accepts. */
#define BIND_SEQ_MAX 8
/** @brief How many bindings there is room for. */
#define BIND_MAX 24

/** @brief One key sequence and the code of the action it runs. */
typedef struct binding {
    char seq[BIND_SEQ_MAX];
    unsigned char len;
    int key;
} binding;

static binding binds[BIND_MAX];
static int nbind;

/** @brief The actions `bind` can name, and the code each one runs. */
static const struct {
    const char *name;
    int key;
} bind_actions[] = {
    {"accept-line", '\r'},
    {"backward-char", CH_CTRL_B},
    {"backward-word", K_WORD_LEFT},
    {"beginning-of-line", CH_CTRL_A},
    {"clear-screen", CH_CTRL_L},
    {"complete", '\t'},
    {"delete-char-backward", CH_CTRL_H},
    {"delete-char-forward", CH_CTRL_D},
    {"delete-word-backward", CH_CTRL_W},
    {"delete-word-forward", K_META + 'd'},
    {"down-history", CH_CTRL_N},
    {"end-of-line", CH_CTRL_E},
    {"forward-char", CH_CTRL_F},
    {"forward-word", K_WORD_RIGHT},
    {"kill-to-end-of-line", CH_CTRL_K},
    {"kill-to-start-of-line", CH_CTRL_U},
    {"transpose-chars", CH_CTRL_T},
    {"up-history", CH_CTRL_P},
    {"yank", CH_CTRL_Y},
};

/**
 * @brief The action a `bind` line gave this key sequence, or `k` itself.
 *
 * The defaults are the ones bash has. A binding only takes over for the
 * sequences it names.
 */
static int bind_key(int k, const char *seq, size_t n) {
    for (int i = 0; i < nbind; i++)
        if (binds[i].len == n && memcmp(binds[i].seq, seq, n) == 0)
            return binds[i].key;
    return k;
}

/**
 * @brief Decode the character after `^` in a `bind` key specification.
 *
 * `^[` is Escape, `^?` is Delete, and `^@`..`^_` (letters case-insensitive)
 * map to their control codes in the build's character set.
 *
 * @return The control byte, or -1 if `d` does not name one.
 */
static int ctrl_byte(unsigned char d) {
    if (d == '[')
        return CH_ESC;
    if (d == '?')
        return CH_DEL;
    d = (unsigned char)toupper(d);
#if ZASH_ASCII
    if (d >= '@' && d <= '_')
        return (int)((unsigned)d & 0x1fu);
    return -1;
#else
    static const char letters[] = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_";
    const char *at = strchr(letters, (char)d);
    if (!at)
        return -1;
    return mvs_a2e[(size_t)(at - letters)];
#endif
}

/**
 * @brief Turn the key notation of a `bind` line into bytes.
 *
 * `^X` is a control key, `^[` is Escape and `^?` is Delete. Anything else
 * stands for itself.
 *
 * @return 0, or -1 if the notation is invalid or does not fit BIND_SEQ_MAX.
 */
static int bind_keys(const char *s, size_t len, char *out, size_t *outlen) {
    size_t n = 0;
    for (size_t i = 0; i < len; i++) {
        unsigned char c = (unsigned char)s[i];
        if (c == '^' && i + 1 < len) {
            int cb = ctrl_byte((unsigned char)s[++i]);
            if (cb < 0)
                return -1;
            c = (unsigned char)cb;
        }
        if (n == BIND_SEQ_MAX)
            return -1;
        out[n++] = (char)c;
    }
    if (n == 0)
        return -1;
    *outlen = n;
    return 0;
}

int edit_bind(const char *spec) {
    const char *eq = strchr(spec, '=');
    if (eq == nullptr) {
        sh_warn("bind: %s: expected keys=action", spec);
        return -1;
    }
    char keys[BIND_SEQ_MAX];
    size_t nk = 0;
    if (bind_keys(spec, (size_t)(eq - spec), keys, &nk) < 0) {
        sh_warn("bind: %.*s: that is not a key sequence", (int)(eq - spec),
                spec);
        return -1;
    }
    size_t nact = sizeof bind_actions / sizeof bind_actions[0];
    int key = -1;
    for (size_t i = 0; i < nact; i++)
        if (strcmp(eq + 1, bind_actions[i].name) == 0) {
            key = bind_actions[i].key;
            break;
        }
    if (key < 0) {
        sh_warn("bind: %s: no such editing command", eq + 1);
        return -1;
    }
    for (int i = 0; i < nbind; i++)
        if (binds[i].len == nk && memcmp(binds[i].seq, keys, nk) == 0) {
            binds[i].key = key;
            return 0;
        }
    if (nbind == BIND_MAX) {
        sh_warn("bind: no room for another binding");
        return -1;
    }
    memcpy(binds[nbind].seq, keys, nk);
    binds[nbind].len = (unsigned char)nk;
    binds[nbind].key = key;
    nbind++;
    return 0;
}

void edit_bind_list(void) {
    for (size_t i = 0; i < sizeof bind_actions / sizeof bind_actions[0]; i++)
        out_printf(&out1, "%s\n", bind_actions[i].name);
}

/* ---- reading keys ---------------------------------------------------- */

/**
 * @brief Read one byte from the terminal.
 * @return The byte, K_EOF, or K_INTR if a signal interrupted the read.
 */
static int read_byte(void) {
    unsigned char c;
    ssize_t n = read(0, &c, 1);
    if (n == 1)
        return c;
    return n < 0 && errno == EINTR ? K_INTR : K_EOF;
}

/**
 * @brief Read one key, decoding arrow and function-key sequences.
 *
 * A key sequence starts with ESC.  ESC on its own (nothing follows
 * within 50 ms) is returned as ESC. ESC followed by an ordinary byte is
 * a "meta" key. ESC `[` or ESC `O` introduces a cursor or editing key.
 *
 * @return A byte value, one of the K_ codes, or K_META plus a byte.
 */
static int read_key_raw(void) {
    if (ed.unread) {
        int k = ed.unread;
        ed.unread = 0;
        return k;
    }
    int c = read_byte();
    if (c < 0)
        return c;
    char seq[BIND_SEQ_MAX];
    size_t n = 0;
    seq[n++] = (char)c;
    if (c != CH_ESC)
        return bind_key(c, seq, n);
    struct pollfd pfd = {.fd = 0, .events = POLLIN};
    if (poll(&pfd, 1, 50) <= 0)
        return bind_key(CH_ESC, seq, n);
    c = read_byte();
    if (c < 0)
        return c;
    seq[n++] = (char)c;
    if (c != '[' && c != 'O') {
        if (opt.vi) { /* vi has no meta keys: ESC, then a command */
            ed.unread = c;
            return CH_ESC;
        }
        return bind_key(K_META + c, seq, n);
    }

    int args[2] = {0, 0};
    int np = 0;
    for (;;) {
        c = read_byte();
        if (c < 0)
            return c;
        if (n < BIND_SEQ_MAX)
            seq[n++] = (char)c;
        if (isdigit(c)) {
            if (args[np] < 100000)
                args[np] = args[np] * 10 + (c - '0');
        } else if (c == ';') {
            if (np < 1)
                np++;
        } else {
            break;
        }
    }
    bool ctrl = args[1] == 5 || args[1] == 3; /* Ctrl- or Alt-arrow */
    int k;
    switch (c) {
    case 'A':
        k = K_UP;
        break;
    case 'B':
        k = K_DOWN;
        break;
    case 'C':
        k = ctrl ? K_WORD_RIGHT : K_RIGHT;
        break;
    case 'D':
        k = ctrl ? K_WORD_LEFT : K_LEFT;
        break;
    case 'H':
        k = K_HOME;
        break;
    case 'F':
        k = K_END;
        break;
    case '~':
        switch (args[0]) {
        case 1:
        case 7:
            k = K_HOME;
            break;
        case 4:
        case 8:
            k = K_END;
            break;
        case 3:
            k = K_DELETE;
            break;
        default:
            k = 0;
            break;
        }
        break;
    default:
        k = 0; /* a key the editor has no use for */
        break;
    }
    return bind_key(k, seq, n);
}

/**
 * @brief Record a key for vi mode's `.`, or give up on this change.
 *
 * A change longer than the record cannot be repeated, and a partial one
 * would repeat the wrong thing, so recording stops instead.
 *
 * @param k The key, or a negative value at end of input.
 * @return true while recording continues.
 */
static bool rec_add(int k) {
    if (ed.rec_len == sizeof ed.rec / sizeof ed.rec[0]) {
        ed.recording = false;
        ed.rec_len = 0;
        return false;
    }
    if (k >= 0)
        ed.rec[ed.rec_len++] = k;
    return true;
}

/**
 * @brief Read one key: from `.`'s replay, or from the terminal.
 *
 * Replaying through here means a repeated change is dispatched exactly
 * like a typed one, insert mode and all.  Every key read while a change
 * is being made is recorded for the next `.`.
 */
static int read_key(void) {
    if (ed.replay_left) {
        int k = ed.replay[ed.replay_pos];
        if (++ed.replay_pos >= ed.replay_len)
            ed.replay_pos = 0;
        ed.replay_left--;
        return k;
    }
    int k = read_key_raw();
    if (ed.recording)
        rec_add(k);
    return k;
}

/* ---- completion ------------------------------------------------------ */

/**
 * @brief Insert completion text, escaping characters the shell would
 *        otherwise treat specially.
 * @param s      Text to insert.
 * @param n      Its length.
 * @param quoted The word is inside quotes: insert it unchanged.
 */
static void insert_escaped(const char *s, size_t n, bool quoted) {
    char *escaped = complete_escaped(s, n, quoted);
    insert(escaped, strlen(escaped));
    free(escaped);
}

/**
 * @brief Does a lone candidate ending in `last` finish the word?
 *
 * Not if it is a directory (`/`), or for data set names a qualifier
 * with more below it (`.`) or a PDS awaiting a member (`(`): the next
 * Tab continues from there.
 */
static bool is_final(const completion *c, char last) {
    return last != '/' && !(c->mvs && (last == '.' || last == '('));
}

/**
 * @brief Complete the word before the cursor (the Tab key).
 *
 * One candidate is inserted whole, followed by a space (or nothing after
 * a directory, so the next Tab descends into it).  Several candidates
 * are completed as far as they agree. If that adds nothing, they are
 * listed.
 */
static void complete(void) {
    completion c;
    complete_line(ed.buf, ed.pos, &c);
    if (!c.count) {
        complete_free(&c);
        ob_putc('\a');
        ob_flush();
        return;
    }
    size_t common = strlen(c.list[0]);
    for (int i = 1; i < c.count; i++) {
        size_t k = 0;
        while (k < common && c.list[i][k] == c.list[0][k])
            k++;
        common = k;
    }
    /* What the user typed, without escapes, is a prefix of every
     * candidate. Replace it only if completion makes it longer. */
    size_t typed = 0;
    for (size_t i = c.start; i < ed.pos; i++) {
        if (ed.buf[i] == '\\' && !c.quoted && i + 1 < ed.pos)
            i++;
        typed++;
    }
    if (c.count == 1 || common > typed) {
        remove_range(c.start, ed.pos, false);
        insert_escaped(c.list[0], common, c.quoted);
        if (c.count == 1 && common && is_final(&c, c.list[0][common - 1])) {
            if (c.quote)
                insert(&c.quote, 1);
            insert(" ", 1);
        }
    } else {
        char *listing = complete_listing(&c, term_cols(), term_rows());
        ob_puts(listing);
        ob_flush();
        free(listing);
    }
    complete_free(&c);
}

/* ---- incremental search (emacs ^R) ----------------------------------- */

/**
 * @brief Search the history backwards as the user types (`^R`).
 *
 * Each printable key extends the pattern. `^R` again finds the next
 * older match. Backspace shortens the pattern. `^G` gives up and restores
 * the line. Enter accepts and runs the match. Any other key accepts the
 * match and is then handled as an ordinary editing key.
 *
 * @return true if the user pressed Enter on a match.
 */
static bool search_history(void) {
    char pat[128];
    size_t plen = 0;
    int idx = hist_count();
    int found = -1;
    char *orig = xmalloc(ed.len + 1);
    memcpy(orig, ed.buf, ed.len);
    orig[ed.len] = '\0';
    bool accepted = false;

    for (;;) {
        const char *match = found >= 0 ? hist_entry(found) : "";
        ob_putc('\r');
        ob_puts("(search)`");
        ob_put(pat, plen);
        ob_puts("': ");
        size_t room = term_cols() > plen + 16 ? term_cols() - plen - 16 : 0;
        for (size_t i = 0; match[i] && i < room; i++)
            ob_putc(iscntrl((unsigned char)match[i]) ? ' ' : match[i]);
        ob_csi(0, 'K');
        ob_flush();

        int k = read_key();
        bool again = false;
        if (k == CH_CTRL_R) {
            idx = found >= 0 ? found : idx;
            again = true;
        } else if (k == CH_DEL || k == CH_CTRL_H) {
            if (plen)
                plen--;
            idx = hist_count();
            again = true;
        } else if (k >= 0 && k < 0x100 && !iscntrl(k) &&
                   plen + 1 < sizeof pat) {
            pat[plen++] = (char)k;
            idx = found >= 0 ? found + 1 : idx;
            again = true;
        }
        if (again) {
            pat[plen] = '\0';
            int hit = -1;
            for (int i = idx - 1; i >= 0 && plen; i--) {
                if (strstr(hist_entry(i), pat)) {
                    hit = i;
                    break;
                }
            }
            if (hit >= 0)
                found = hit;
            else if (plen)
                ob_putc('\a');
            else
                found = -1;
            continue;
        }
        if (k == CH_CTRL_G || k == K_INTR || k == K_EOF) {
            set_line(orig);
            if (k != CH_CTRL_G)
                ed.unread = k;
            break;
        }
        if (found >= 0) {
            ed.hidx = hist_count();
            show_history(found);
        }
        if (k == '\r' || k == '\n')
            accepted = true;
        else
            ed.unread = k;
        break;
    }
    free(orig);
    return accepted;
}

/* ---- vi mode --------------------------------------------------------- */

/** @brief vi: remember the line so that `u` can bring it back. */
static void vi_save_undo(void) {
    free(ed.undo);
    ed.undo = xmalloc(ed.len + 1);
    memcpy(ed.undo, ed.buf, ed.len);
    ed.undo_len = ed.len;
    ed.undo_pos = ed.pos;
    ed.changed = true;
}

/**
 * @brief vi: start recording the keys of a change.
 *
 * A change runs from its command key through the text typed in insert
 * mode, which the main loop records while `vi_cmd` is false.  Keys that
 * `.` hands back are not recorded: `.` keeps the change it repeated.
 */
static void vi_record_start(void) {
    if (ed.replay_left) {
        ed.recording = false;
        return;
    }
    ed.rec_len = 0;
    ed.changed = false;
    ed.recording = true;
}

/**
 * @brief vi: keep the keys of the change just made, for `.`.
 */
static void vi_record_done(void) {
    if (!ed.recording)
        return;
    ed.recording = false;
    if (!ed.changed || !ed.rec_len)
        return;
    memcpy(ed.last, ed.rec, ed.rec_len * sizeof ed.last[0]);
    ed.last_len = ed.rec_len;
}

/** @brief vi: stop recording and forget the change (the line was taken). */
static void vi_record_stop(void) {
    ed.recording = false;
    ed.changed = false;
}

/**
 * @brief vi: hand the last change's keys back, `times` times (`3.`).
 * @param times Repeat count; 0 and 1 both mean once.
 */
static void vi_replay(int times) {
    if (!ed.last_len)
        return;
    memcpy(ed.replay, ed.last, ed.last_len * sizeof ed.replay[0]);
    ed.replay_len = ed.last_len;
    ed.replay_pos = 0;
    ed.replay_left = ed.last_len * (size_t)(times > 0 ? times : 1);
}

/**
 * @brief vi: edit the line in `$VISUAL` or `$EDITOR` (the `v` key).
 *
 * The line goes to a temporary file and the editor is run through the
 * shell, so an editor given with arguments (`emacs -nw`) works.  The
 * terminal is handed back while it runs.  A successful exit puts the
 * file's first line in the buffer with the cursor at its start, ready
 * for the next command-mode key.
 */
static void edit_external(void) {
    const char *tmpdir = var_get("TMPDIR");
    char file[4096];
    int n = snprintf(file, sizeof file, "%s/zash-vi.XXXXXX",
                     tmpdir && *tmpdir ? tmpdir : "/tmp");
    if (n < 0 || (size_t)n >= sizeof file) {
        ob_puts("zash: TMPDIR is too long for `v`\n");
        ob_flush();
        return;
    }
    int fd = mkstemp(file);
    if (fd < 0) {
        ob_puts("zash: `v`: cannot create a temporary file\n");
        ob_flush();
        return;
    }
    if (SYS_MVS)
        sys_tmp_tag(fd);
    size_t off = 0;
    while (off < ed.len) {
        ssize_t w = write(fd, ed.buf + off, ed.len - off);
        if (w < 0 && errno == EINTR)
            continue;
        if (w <= 0)
            break;
        off += (size_t)w;
    }
    ssize_t nl = -1;
    while (off == ed.len && (nl = write(fd, "\n", 1)) < 0 && errno == EINTR)
        ;
    bool wrote = (off == ed.len) && (nl == 1);
    close(fd);
    const char *editor = var_get("VISUAL");
    if (!editor || !*editor)
        editor = var_get("EDITOR");
    if (!editor || !*editor)
        editor = "vi";
    /* The editor is a shell command, the file name is a word: quote it, so
     * a TMPDIR with a space or a `$` in it still names the file. */
    output cmd = {.fd = OUT_MEM};
    out_puts(&cmd, editor);
    out_putc(&cmd, ' ');
    out_quote(&cmd, file);
    out_write(&cmd, "", 1); /* the NUL */
    raw_off();
    ob_flush();
    jmploc jl;
    jmploc *prev = exc_handler;
    int status;
    if (setjmp(jl.buf)) {
        /* The editor command raised: the file must not be left behind. */
        exc_handler = prev;
        raw_on();
        free(cmd.buf);
        unlink(file);
        exc_raise(exc_code);
    }
    exc_catch(&jl);
    status = eval_string(cmd.buf, 0);
    exc_handler = prev;
    raw_on();
    free(cmd.buf);
    char *text = nullptr;
    size_t nread = 0;
    if (status == 0 && wrote && (fd = open(file, O_RDONLY)) >= 0) {
        text = xmalloc(256);
        size_t cap = 256;
        ssize_t r;
        while (nread + 1 < cap) {
            r = read(fd, text + nread, cap - nread - 1);
            if (r < 0 && errno == EINTR)
                continue;
            if (r <= 0)
                break;
            nread += (size_t)r;
            if (nread + 1 == cap) {
                cap *= 2;
                text = xrealloc(text, cap);
            }
        }
        close(fd);
        text[nread] = '\0';
        text[strcspn(text, "\n")] = '\0';
        vi_save_undo();
        set_line(text);
        ed.pos = 0;
    }
    free(text);
    unlink(file);
}

/** @brief vi: is this byte blank? */
static bool vi_blank(size_t i) {
    return ed.buf[i] == ' ' || ed.buf[i] == '\t';
}

/**
 * @brief vi: character class for the `w`, `b` and `e` motions.
 * @return 0 for blank, 1 for a word character, 2 for punctuation.
 */
static int vi_class(size_t i, bool big) {
    if (vi_blank(i))
        return 0;
    return big || is_word(ed.buf[i]) ? 1 : 2;
}

/**
 * @brief vi: compute where a motion command takes the cursor.
 *
 * @param key       The motion: one of `h l 0 ^ $ w W b B e E` or a
 *                  cursor key.
 * @param count     Repeat count (at least 1).
 * @param inclusive Receives whether an operator using this motion also
 *                  takes the character at the destination (`e`, `$`).
 * @return The destination offset, or SIZE_MAX if `key` is not a motion.
 */
static size_t vi_motion(int key, int count, bool *inclusive) {
    size_t p = ed.pos;
    *inclusive = false;
    bool big = key == 'W' || key == 'B' || key == 'E';
    switch (key) {
    case 'h':
    case K_LEFT:
    case CH_DEL:
    case CH_CTRL_H:
        while (count-- && p)
            p = prev_char(p);
        return p;
    case 'l':
    case ' ':
    case K_RIGHT:
        while (count-- && p < ed.len)
            p = next_char(p);
        return p;
    case '0':
    case K_HOME:
        return 0;
    case '^':
        p = 0;
        while (p < ed.len && vi_blank(p))
            p++;
        return p;
    case '$':
    case K_END:
        *inclusive = true;
        return ed.len;
    case 'w':
    case 'W':
        while (count-- && p < ed.len) {
            int cls = vi_class(p, big);
            while (p < ed.len && vi_class(p, big) == cls && cls)
                p++;
            while (p < ed.len && vi_blank(p))
                p++;
        }
        return p;
    case 'b':
    case 'B':
        while (count-- && p) {
            p--;
            while (p && vi_blank(p))
                p--;
            int cls = vi_class(p, big);
            while (p && vi_class(p - 1, big) == cls)
                p--;
        }
        return p;
    case 'e':
    case 'E':
        *inclusive = true;
        while (count-- && p < ed.len) {
            p++;
            while (p < ed.len && vi_blank(p))
                p++;
            if (p >= ed.len)
                break;
            int cls = vi_class(p, big);
            while (p + 1 < ed.len && vi_class(p + 1, big) == cls)
                p++;
        }
        return p < ed.len ? p : ed.len;
    default:
        return SIZE_MAX;
    }
}

/**
 * @brief vi: search the history for the remembered pattern.
 * @param backwards true to look at older entries (`/`, `n`).
 * @return true if a matching entry was found and is now shown.
 */
static bool vi_search(bool backwards) {
    int step = backwards ? -1 : 1;
    for (int i = ed.hidx + step; i >= 0 && i < hist_count(); i += step) {
        if (strstr(hist_entry(i), ed.search)) {
            show_history(i);
            ed.pos = 0;
            return true;
        }
    }
    return false;
}

/**
 * @brief vi: read a search pattern after `/` or `?`.
 * @return false if the user gave up with ESC or an interrupt.
 */
static bool vi_read_pattern(char lead) {
    /* Read into a buffer of its own: typing over the old pattern and then
     * backspacing past it would otherwise leave a mix of two patterns. */
    char pat[sizeof ed.search];
    size_t n = 0;
    for (;;) {
        ob_putc('\r');
        ob_putc(lead);
        ob_put(pat, n);
        ob_csi(0, 'K');
        ob_flush();
        int k = read_key();
        if (k == '\r' || k == '\n')
            break;
        if (k == CH_ESC || k < 0) {
            if (k < 0)
                ed.unread = k;
            return false;
        }
        if (k == CH_DEL || k == CH_CTRL_H) {
            if (n)
                n--;
        } else if (k < 0x100 && !iscntrl(k) && n + 1 < sizeof pat) {
            pat[n++] = (char)k;
        }
    }
    if (n) { /* an empty pattern repeats the previous search */
        memcpy(ed.search, pat, n);
        ed.search[n] = '\0';
    }
    return ed.search[0] != '\0';
}

/**
 * @brief vi: carry out one command-mode key.
 *
 * Supported: counts. The motions of vi_motion(). `i a I A` (insert);
 * `x X r ~` (single characters). `d c y` with a motion or doubled;
 * `D C` (to end of line). `p P` (put). `u` (undo). `k j - +` and the
 * arrow keys (history). `G` (oldest entry, or entry N). `/ ? n N`
 * (history search). `#` (turn the line into a comment and accept it).
 *
 * @param key The key.
 * @return true if the line is to be accepted as it stands.
 */
static bool vi_command(int key) {
    int count = 0;
    while ((key >= '1' && key <= '9') || (count && key == '0')) {
        if (count < 100000)
            count = count * 10 + (key - '0');
        key = read_key();
    }
    bool counted = count > 0;
    if (!count)
        count = 1;
    bool inclusive;
    size_t dest = vi_motion(key, count, &inclusive);
    if (dest != SIZE_MAX) {
        ed.pos = dest;
        return false;
    }
    switch (key) {
    case 'i':
        ed.vi_cmd = false;
        break;
    case 'a':
        ed.pos = next_char(ed.pos);
        ed.vi_cmd = false;
        break;
    case 'I':
        ed.pos = 0;
        ed.vi_cmd = false;
        break;
    case 'A':
        ed.pos = ed.len;
        ed.vi_cmd = false;
        break;
    case 'x':
    case K_DELETE: {
        size_t to = ed.pos;
        while (count-- && to < ed.len)
            to = next_char(to);
        vi_save_undo();
        remove_range(ed.pos, to, true);
        break;
    }
    case 'X': {
        size_t from = ed.pos;
        while (count-- && from)
            from = prev_char(from);
        vi_save_undo();
        remove_range(from, ed.pos, true);
        break;
    }
    case 'r': {
        int c = read_key();
        if (c > 0 && c < 0x100 && !iscntrl(c) && ed.pos < ed.len) {
            vi_save_undo();
            size_t p = ed.pos;
            remove_range(p, next_char(p), false);
            char ch = (char)c;
            insert(&ch, 1);
            ed.pos = p;
        }
        break;
    }
    case '~':
        vi_save_undo();
        while (count-- && ed.pos < ed.len) {
            unsigned char c = (unsigned char)ed.buf[ed.pos];
            ed.buf[ed.pos] = (char)(islower(c) ? toupper(c) : tolower(c));
            ed.pos++;
        }
        break;
    case 'D':
        vi_save_undo();
        remove_range(ed.pos, ed.len, true);
        break;
    case 'C':
        vi_save_undo();
        remove_range(ed.pos, ed.len, true);
        ed.vi_cmd = false;
        break;
    case 'S':
        vi_save_undo();
        remove_range(0, ed.len, true);
        ed.vi_cmd = false;
        break;
    case 'd':
    case 'c':
    case 'y': {
        int m = read_key();
        size_t from = ed.pos;
        size_t to;
        if (m == key) { /* dd, cc, yy: the whole line */
            from = 0;
            to = ed.len;
        } else {
            /* "cw" changes to the end of the word, as in vi. */
            if (key == 'c' && (m == 'w' || m == 'W'))
                m = m == 'w' ? 'e' : 'E';
            to = vi_motion(m, count, &inclusive);
            if (to == SIZE_MAX)
                break;
            if (inclusive && to < ed.len)
                to = next_char(to);
            if (to < from) {
                size_t t = from;
                from = to;
                to = t;
            }
        }
        if (key == 'y') {
            /* Yank: the text becomes the kill buffer and stays put.  Going
             * through remove_range() and inserting it back pasted an older
             * kill buffer when the range was empty (`y0` at column 0). */
            kill_set(from, to);
            ed.pos = from;
            break;
        }
        vi_save_undo();
        remove_range(from, to, true);
        if (key == 'c')
            ed.vi_cmd = false;
        break;
    }
    case 'p':
    case 'P':
        if (ed.kill_len) {
            vi_save_undo();
            if (key == 'p')
                ed.pos = next_char(ed.pos);
            insert(ed.kill, ed.kill_len);
            ed.pos = prev_char(ed.pos);
        }
        break;
    case '.':
        vi_replay(count);
        break;
    case 'v':
        edit_external();
        break;
    case 'u':
        if (ed.undo) {
            char *now = xmalloc(ed.len + 1);
            size_t now_len = ed.len;
            size_t now_pos = ed.pos;
            memcpy(now, ed.buf, ed.len);
            ed.len = 0;
            reserve(ed.undo_len);
            memcpy(ed.buf, ed.undo, ed.undo_len);
            ed.len = ed.undo_len;
            ed.pos = ed.undo_pos;
            free(ed.undo);
            ed.undo = now;
            ed.undo_len = now_len;
            ed.undo_pos = now_pos;
        }
        break;
    case 'k':
    case '-':
    case K_UP:
        while (count-- && show_history(ed.hidx - 1))
            ed.pos = 0;
        break;
    case 'j':
    case '+':
    case K_DOWN:
        while (count-- && show_history(ed.hidx + 1))
            ed.pos = 0;
        break;
    case 'G':
        if (show_history(counted ? count - 1 : 0))
            ed.pos = 0;
        break;
    case '/':
    case '?':
        if (vi_read_pattern((char)key) && !vi_search(key == '/'))
            ob_putc('\a');
        break;
    case 'n':
    case 'N':
        if (!ed.search[0] || !vi_search(key == 'n'))
            ob_putc('\a');
        break;
    case '#':
        ed.pos = 0;
        insert("#", 1);
        return true;
    default:
        break;
    }
    /* In command mode the cursor sits on a character, not after the end. */
    if (ed.vi_cmd && ed.pos >= ed.len && ed.len)
        ed.pos = prev_char(ed.len);
    return false;
}

/* ---- the main loop --------------------------------------------------- */

/**
 * @brief Handle a signal that interrupted the editor.
 *
 * The terminal is handed back first, because trap_poll() usually does
 * not return: for `^C` at the prompt it abandons the line by raising an
 * exception.  If it does return (a trap action ran), editing resumes.
 */
static void interrupted(void) {
    raw_off();
    ob_flush();
    trap_poll();
    raw_on();
}

/**
 * @brief Carry out one emacs-mode (or vi insert-mode) key.
 * @param k The key.
 * @return true if the line is to be accepted.
 */
static bool edit_key(int k) {
    switch (k) {
    case '\r':
    case '\n':
        return true;
    case CH_CTRL_A:
    case K_HOME:
        ed.pos = 0;
        break;
    case CH_CTRL_E:
    case K_END:
        ed.pos = ed.len;
        break;
    case CH_CTRL_B:
    case K_LEFT:
        ed.pos = prev_char(ed.pos);
        break;
    case CH_CTRL_F:
    case K_RIGHT:
        ed.pos = next_char(ed.pos);
        break;
    case K_META + 'b':
    case K_WORD_LEFT:
        ed.pos = word_left(ed.pos);
        break;
    case K_META + 'f':
    case K_WORD_RIGHT:
        ed.pos = word_right(ed.pos);
        break;
    case CH_CTRL_P:
    case K_UP:
        show_history(ed.hidx - 1);
        break;
    case CH_CTRL_N:
    case K_DOWN:
        show_history(ed.hidx + 1);
        break;
    case K_META + '<':
        show_history(0);
        break;
    case K_META + '>':
        show_history(hist_count());
        break;
    case CH_DEL:
    case CH_CTRL_H:
        remove_range(prev_char(ed.pos), ed.pos, false);
        break;
    case CH_CTRL_D:
    case K_DELETE:
        remove_range(ed.pos, next_char(ed.pos), false);
        break;
    case CH_CTRL_K:
        remove_range(ed.pos, ed.len, true);
        break;
    case CH_CTRL_U:
        remove_range(0, ed.pos, true);
        break;
    case CH_CTRL_W: {
        size_t from = ed.pos;
        while (from && (ed.buf[from - 1] == ' ' || ed.buf[from - 1] == '\t'))
            from--;
        while (from && ed.buf[from - 1] != ' ' && ed.buf[from - 1] != '\t')
            from--;
        remove_range(from, ed.pos, true);
        break;
    }
    case K_META + CH_DEL:
    case K_META + CH_CTRL_H:
        remove_range(word_left(ed.pos), ed.pos, true);
        break;
    case K_META + 'd':
        remove_range(ed.pos, word_right(ed.pos), true);
        break;
    case K_META + 'u':
    case K_META + 'l':
    case K_META + 'c': {
        /* Change the case of the word after the cursor, as bash does.
         * `\c` capitalises its first character and lowercases the rest. */
        size_t to = word_right(ed.pos);
        bool first = true;
        for (size_t i = ed.pos; i < to; i++) {
            unsigned char c = (unsigned char)ed.buf[i];
            if (k == K_META + 'u')
                ed.buf[i] = (char)toupper(c);
            else if (k == K_META + 'l' || !first)
                ed.buf[i] = (char)tolower(c);
            else
                ed.buf[i] = (char)toupper(c);
            if (is_word(ed.buf[i]))
                first = false;
        }
        ed.pos = to;
        break;
    }
    case K_META + 't': {
        /* Transpose the words on either side of the cursor, as bash does:
         * word1, space, word2 becomes word2, space, word1 in place. */
        size_t a1 = word_left(ed.pos), b1 = ed.pos;
        while (b1 > a1 && !is_word(ed.buf[b1 - 1]))
            b1--;
        size_t a2 = ed.pos;
        while (a2 < ed.len && !is_word(ed.buf[a2]))
            a2++;
        size_t b2 = word_right(a2);
        if (a1 == b1 || a2 == b2)
            break; /* there is no word on one side */
        size_t n1 = b1 - a1, gap = a2 - b1, n2 = b2 - a2;
        char *tmp = xmalloc(n1 + gap + n2);
        memcpy(tmp, ed.buf + a2, n2);
        memcpy(tmp + n2, ed.buf + b1, gap);
        memcpy(tmp + n2 + gap, ed.buf + a1, n1);
        memcpy(ed.buf + a1, tmp, n1 + gap + n2);
        free(tmp);
        ed.pos = b2;
        break;
    }
    case K_META + '.': {
        /* Insert the last word of the previous line, as bash does. */
        int idx = ed.hidx < hist_count() ? ed.hidx - 1 : hist_count() - 1;
        if (idx < 0)
            break;
        const char *h = hist_entry(idx);
        size_t n = strlen(h);
        while (n && (h[n - 1] == ' ' || h[n - 1] == '\t'))
            n--;
        size_t from = n;
        while (from && h[from - 1] != ' ' && h[from - 1] != '\t')
            from--;
        if (from < n)
            insert(h + from, n - from);
        break;
    }
    case K_META + '\\': {
        /* Delete the blanks around the cursor, as bash does. */
        size_t from = ed.pos, to = ed.pos;
        while (from && (ed.buf[from - 1] == ' ' || ed.buf[from - 1] == '\t'))
            from--;
        while (to < ed.len && (ed.buf[to] == ' ' || ed.buf[to] == '\t'))
            to++;
        if (from < to)
            remove_range(from, to, false);
        break;
    }
    case CH_CTRL_Y:
        if (ed.kill_len)
            insert(ed.kill, ed.kill_len);
        break;
    case CH_CTRL_T:
        if (ed.pos && ed.len > 1) {
            size_t b = ed.pos < ed.len ? ed.pos : prev_char(ed.pos);
            size_t a = prev_char(b);
            size_t end = next_char(b);
            size_t alen = b - a;
            size_t blen = end - b;
            char tmp[16];
            if (alen <= sizeof tmp) {
                memcpy(tmp, ed.buf + a, alen);
                memmove(ed.buf + a, ed.buf + b, blen);
                memcpy(ed.buf + a + blen, tmp, alen);
                ed.pos = end;
            }
        }
        break;
    case CH_CTRL_L:
        ob_csi(0, 'H');
        ob_csi(2, 'J');
        break;
    case CH_CTRL_R:
        return search_history();
    case CH_CTRL_V: {
        int c = read_key();
        if (c >= 0 && c < 0x100) {
            char ch = (char)c;
            insert(&ch, 1);
        }
        break;
    }
    case '\t':
        complete();
        break;
    default:
        if (k > 0 && k < 0x100 && !iscntrl(k)) {
            char ch = (char)k;
            insert(&ch, 1);
        }
        break;
    }
    return false;
}

/**
 * @brief Read one line with editing.
 *
 * @param prompt Text to show before the line.  If it has several lines,
 *               all but the last are printed once and the last is the
 *               prompt that is redrawn.
 * @param len    Receives the length of the line.
 * @return The line, NUL-terminated and without a newline, valid until the
 *         next call. nullptr at end of input (`^D` on an empty line).
 */
char *edit_readline(const char *prompt, size_t *len) {
    const char *last = strrchr(prompt, '\n');
    if (last) {
        ob_put(prompt, (size_t)(last - prompt) + 1);
        prompt = last + 1;
    }
    ed.prompt = prompt;
    ed.pwidth = prompt_width(prompt);
    ed.len = ed.pos = ed.off = 0;
    ed.hidx = hist_count();
    ed.unread = 0;
    ed.vi_cmd = false;
    ed.recording = false;
    ed.replay_left = 0;
    reserve(64);
    raw_on();

    bool eof = false;
    for (;;) {
        refresh();
        /* A change is recorded from its command key: `.` repeats it. */
        if (opt.vi && ed.vi_cmd)
            vi_record_start();
        int k = read_key();
        if (k == K_INTR) {
            interrupted();
            continue;
        }
        if (k == K_EOF || (k == CH_CTRL_D && ed.len == 0)) {
            eof = true;
            break;
        }
        if (opt.vi) {
            if (ed.vi_cmd) {
                if (k == '\r' || k == '\n' || vi_command(k)) {
                    vi_record_stop();
                    break;
                }
                if (ed.vi_cmd)
                    vi_record_done();
                continue;
            }
            if (k == CH_ESC) {
                ed.vi_cmd = true;
                ed.pos = prev_char(ed.pos);
                vi_record_done();
                continue;
            }
            /* In insert mode the basic editing keys still work. */
        }
        if (edit_key(k)) {
            vi_record_stop();
            break;
        }
    }
    ed.pos = ed.len;
    if (!eof)
        refresh();
    ob_puts("\n");
    ob_flush();
    raw_off();
    if (eof)
        return nullptr;
    ed.buf[ed.len] = '\0';
    *len = ed.len;
    return ed.buf;
}