retex-engine 1.3.0

The TeX typesetting engine for retex
Documentation
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
//! pgfkeys (`pgfkeys.code.tex`, pgf 3.1.11a): the macros that every key
//! of a `\pgfkeys` or `\tikzset` list goes through. `\pgfkeys@parse`
//! splits the list at its commas with delimited arguments and calls
//! `\pgfkeys@unpack#1=#2=#3\pgfkeys@stop` for each item; the splitting
//! stays TeX code (TeX's own argument matching does that job fast). The
//! native implementations replace what follows:
//!
//! * `\pgfkeys@unpack` itself:
//!
//!   ```tex
//!   \long\def\pgfkeys@unpack#1=#2=#3\pgfkeys@stop{%
//!     \pgfkeys@spdef\pgfkeyscurrentkey{#1}%
//!     \edef\pgfkeyscurrentkey{\pgfkeyscurrentkey}%
//!     \ifx\pgfkeyscurrentkey\pgfkeys@empty
//!     \else
//!       \pgfkeys@add@path@as@needed
//!       \pgfkeys@spdef\pgfkeyscurrentvalue{#2}%
//!       \ifx\pgfkeyscurrentvalue\pgfkeysnovalue@text
//!         \pgfkeysifdefined{\pgfkeyscurrentkey/.@def}%
//!         {\pgfkeysgetvalue{\pgfkeyscurrentkey/.@def}{\pgfkeyscurrentvalue}}{}%
//!       \fi
//!       \ifx\pgfkeyscurrentvalue\pgfkeysvaluerequired
//!         <error>
//!       \else
//!         \pgfkeys@case@one
//!       \fi
//!     \fi}
//!   ```
//!
//!   It makes the assignments of the two `\pgfkeys@spdef`s, the `\edef`
//!   (with [`deps::edef`]), `\pgfkeys@add@path@as@needed` and the default
//!   value, then leaves the condition stack as TeX does at
//!   `\pgfkeys@case@one` (two `\ifx`s in their `\else` branches: the
//!   key's code runs inside them, where `\currentiflevel` and a look at
//!   the next token can see it) and puts back `\pgfkeys@case@one\fi\fi`.
//!   It declines for a key that requires a value and has none (an error).
//!   The macros it replaces also have their own native implementations,
//!   for their other callers.
//!
//! * `\pgfkeys@spdef#1#2`, which strips the spaces around a key or value
//!   and defines `#1` as the rest:
//!
//!   ```tex
//!   \long\def\pgfkeys@spdef#1#2{%
//!     \futurelet\pgfkeys@possiblespace\pgfkeys@sp@a#2\pgfkeys@stop\pgfkeys@stop
//!       \pgfkeys@stop\relax#1}
//!   \def\pgfkeys@sp@a{%
//!     \ifx\pgfkeys@possiblespace\pgfkeys@sptoken
//!       \expandafter\pgfkeys@sp@b
//!     \else
//!       \expandafter\pgfkeys@sp@b\expandafter<space>%
//!     \fi}
//!   \long\def\pgfkeys@sp@b<space>#1<space>\pgfkeys@stop{\pgfkeys@sp@c#1}
//!   \long\def\pgfkeys@sp@c#1\pgfkeys@stop#2\relax#3{%
//!     \pgfkeys@temptoks{#1}\edef#3{\the\pgfkeys@temptoks}}
//!   ```
//!
//!   (the stops before the second space are `\pgfkeys@stop<space>`). The
//!   delimited arguments strip a pair of braces around the whole value
//!   (at most twice: ` {{x}} ` gives `x`, `{{x}}` gives `{x}`); the
//!   native implementation runs the same matches on the same tokens
//!   ([`delimited`], [`strip`]) and makes the same three assignments
//!   (`\pgfkeys@possiblespace`, `\pgfkeys@temptoks`, `#1`).
//!
//! * `\pgfkeys@add@path@as@needed`, which prefixes `\pgfkeyscurrentkey`
//!   with `\pgfkeysdefaultpath` unless it starts with `/`:
//!   `\futurelet\pgfkeys@possibleslash` on its first token, then
//!   `\pgfkeys@nevermind#1\relax` (`\pgfkeysaddeddefaultpathfalse`,
//!   `\let\pgfkeyscurrentkeyRAW\pgfkeyscurrentkey`) or
//!   `\pgfkeys@addpath#1\relax` (`\pgfkeysaddeddefaultpathtrue`,
//!   `\def\pgfkeyscurrentkeyRAW{#1}`,
//!   `\edef\pgfkeyscurrentkey{\pgfkeysdefaultpath#1}`).
//!
//! * `\pgfkeys@split@path`, which splits `\pgfkeyscurrentkey` at its last
//!   slash into `\pgfkeys@pathtoks` and `\pgfkeyscurrentname`:
//!
//!   ```tex
//!   \def\pgfkeys@split@path{\pgfkeys@pathtoks{}%
//!     \expandafter\pgfkeys@splitter\pgfkeyscurrentkey//}
//!   \def\pgfkeys@splitter#1/#2/{%
//!     \def\pgfkeys@temp{#2}%
//!     \ifx\pgfkeys@temp\pgfkeys@empty
//!       \def\pgfkeyscurrentname{#1}\expandafter\pgfkeys@gobbletoslash
//!     \else
//!       \expandafter\pgfkeys@pathtoks\expandafter{\the\pgfkeys@pathtoks#1/}%
//!     \fi
//!     \pgfkeys@splitter#2/}
//!   \def\pgfkeys@gobbletoslash\pgfkeys@splitter/{%
//!     \if\relax\detokenize\expandafter{\the\pgfkeys@pathtoks}\relax\else
//!       \expandafter\pgfkeys@remove@slash\the\pgfkeys@pathtoks\relax
//!     \fi}
//!   \def\pgfkeys@remove@slash#1/\relax{\pgfkeys@pathtoks{#1}}
//!   ```
//!
//!   The native implementation runs the loop on the key's tokens and
//!   assigns `\pgfkeys@pathtoks`, `\pgfkeyscurrentname` and
//!   `\pgfkeys@temp` (empty, as the last `\def` leaves it).
//!
//! * The dispatch of a key, `\pgfkeys@case@one` (run `<key>/.@cmd`),
//!   `\pgfkeys@case@two` (is `<key>` a value key?),
//!   `\pgfkeys@case@two@extern` (store the value),
//!   `\pgfkeys@case@three` (a handler, `/handlers/<name>/.@cmd`) and
//!   `\pgfkeys@unknown` (`<path>/.unknown/.@cmd`, else
//!   `/handlers/.unknown/.@cmd`). They test with
//!   `\pgfkeysifdefined{<name>}` (`\ifcsname pgfk@<name>\endcsname`),
//!   copy the command with `\pgfkeysgetvalue{<name>}{\pgfkeys@code}`
//!   (`\let\pgfkeys@code` to the `\csname`) and end with
//!   `\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov`, or the macro
//!   of the next case. The native implementations make the same tests
//!   and `\let`, set `\lastnamedcs` as the last `\ifcsname` or `\csname`
//!   does, and put the same tokens back into the input (the key's code
//!   runs as TeX code). For `\pgfkeys@case@two@extern` only the storing
//!   branch is native: without a value, TeX runs the key's value inside
//!   the open `\ifx`.
//!
//! All decline (and the TeX code runs) when a key contains a macro
//! parameter character, `\par` (the splitting macros are not `\long`) or
//! an `\outer` macro, when a name does not expand to characters with the
//! macros, `\the` of token registers and characters that [`name_into`]
//! handles, when the delimited arguments would read past the tokens the
//! TeX code supplies, with `\globaldefs` or a pending `\afterassignment`,
//! and when the macros the TeX code runs have other definitions (other
//! pgf versions, `\pgfkeys@case@three` replaced by key filtering, …).
//!
//! The key's code then runs where TeX runs it, but the tokens put back
//! form one inserted list, so an error inside it shows a shorter context.

use std::cell::RefCell;
use std::rc::Rc;

use super::Native;
use super::deps::{self, Deps};
use super::latex::{ifx, token_meaning};
use crate::Engine;
use crate::cmd::Cmd;
use crate::eqtb::{Loc, Meaning, Val};
use crate::hash::{CsId, UNDEFINED_CS};
use crate::primitives_gen::assign_int as ip;
use crate::scan::REG_OFFSET;
use crate::token::{Macro, Token, TokenList};

/// `\pgfkeys@unpack`.
pub(super) const UNPACK: Native = Native {
    name: "pgfkeys@unpack",
    fingerprints: &[(110, 0x06cf_faad_e3e9_985f)],
    executes: true,
    run: run_unpack,
};

/// `\pgfkeys@spdef`.
pub(super) const SPDEF: Native = Native {
    name: "pgfkeys@spdef",
    fingerprints: &[(13, 0x7e6f_c7e2_d9c7_179f)],
    executes: true,
    run: run_spdef,
};

/// `\pgfkeys@add@path@as@needed`.
pub(super) const ADD_PATH: Native = Native {
    name: "pgfkeys@add@path@as@needed",
    fingerprints: &[(9, 0xf48b_e1a9_81a3_a4be)],
    executes: true,
    run: run_add_path,
};

/// `\pgfkeys@split@path`.
pub(super) const SPLIT_PATH: Native = Native {
    name: "pgfkeys@split@path",
    fingerprints: &[(9, 0xf3fc_3dcb_44ea_6702)],
    executes: true,
    run: run_split_path,
};

/// `\pgfkeys@case@one`.
pub(super) const CASE_ONE: Native = Native {
    name: "pgfkeys@case@one",
    fingerprints: &[(48, 0x853a_942e_d2d8_e46f)],
    executes: true,
    run: run_case_one,
};

/// `\pgfkeys@case@two`.
pub(super) const CASE_TWO: Native = Native {
    name: "pgfkeys@case@two",
    fingerprints: &[(11, 0xa59e_9440_3043_5652)],
    executes: true,
    run: run_case_two,
};

/// `\pgfkeys@case@two@extern`.
pub(super) const CASE_TWO_EXTERN: Native = Native {
    name: "pgfkeys@case@two@extern",
    fingerprints: &[(15, 0x5ce1_984c_3449_d0dc)],
    executes: true,
    run: run_case_two_extern,
};

/// `\pgfkeys@case@three`.
pub(super) const CASE_THREE: Native = Native {
    name: "pgfkeys@case@three",
    fingerprints: &[(55, 0x8f18_c389_3eea_3632)],
    executes: true,
    run: run_case_three,
};

/// `\pgfkeys@unknown`.
pub(super) const UNKNOWN: Native = Native {
    name: "pgfkeys@unknown",
    fingerprints: &[(85, 0x1009_de85_84f9_edd7)],
    executes: true,
    run: run_unknown,
};

const SP_NAMES: &[&str] = &[
    "pgfkeys@sp@a",
    "pgfkeys@sp@b",
    "pgfkeys@sp@c",
    "pgfkeys@sptoken",
    "pgfkeys@temptoks",
];
const SP_KNOWN: &[u64] = &[0x59cf_ecd0_ee9e_020b];

const PATH_NAMES: &[&str] = &[
    "pgfkeys@check@slash",
    "pgfkeys@nevermind",
    "pgfkeys@addpath",
    "pgfkeysaddeddefaultpathtrue",
    "pgfkeysaddeddefaultpathfalse",
];
const PATH_KNOWN: &[u64] = &[0x1b95_6438_f637_aae6];

const SPLIT_NAMES: &[&str] = &[
    "pgfkeys@splitter",
    "pgfkeys@gobbletoslash",
    "pgfkeys@remove@slash",
    "pgfkeys@pathtoks",
    "pgfkeys@empty",
];
const SPLIT_KNOWN: &[u64] = &[0x4898_0410_c139_bdb8];

const KEY_NAMES: &[&str] = &[
    "pgfkeysifdefined",
    "pgfkeysgetvalue",
    "pgfkeyslet",
    "pgfkeys@ifcsname",
    "pgfkeys@firstoftwo",
    "pgfkeys@secondoftwo",
    "pgfkeys@split@path",
];
const UNPACK_NAMES: &[&str] = &["pgfkeys@spdef", "pgfkeys@add@path@as@needed"];
const UNPACK_KNOWN: &[u64] = &[0x8c1a_b7c4_72f7_8d77];

const KEY_KNOWN: &[u64] = &[0x5d68_cef1_7c12_10b9];

thread_local! {
    static SP_DEPS: RefCell<Deps> = RefCell::new(Deps::new("pgfkeys spdef", SP_NAMES, SP_KNOWN));
    static PATH_DEPS: RefCell<Deps> =
        RefCell::new(Deps::new("pgfkeys add path", PATH_NAMES, PATH_KNOWN));
    static SPLIT_DEPS: RefCell<Deps> =
        RefCell::new(Deps::new("pgfkeys split path", SPLIT_NAMES, SPLIT_KNOWN));
    static UNPACK_DEPS: RefCell<Deps> =
        RefCell::new(Deps::new("pgfkeys unpack", UNPACK_NAMES, UNPACK_KNOWN));
    static KEY_DEPS: RefCell<Deps> = RefCell::new(Deps::new("pgfkeys keys", KEY_NAMES, KEY_KNOWN));
}

fn why(what: &str, reason: &str) -> bool {
    if super::debug() {
        eprintln!("[native] {what} declines ({reason})");
    }
    false
}

/// What every implementation requires: no `\globaldefs` (the assignments
/// would be global) and no pending `\afterassignment` (it would be
/// inserted after the first one).
fn plain_state(e: &Engine) -> bool {
    e.eqtb.int(ip::GLOBALDEFS) == 0 && e.after_token.0 == 0
}

fn is_left(t: Token) -> bool {
    !t.is_cs() && t.cmd_code() == Cmd::LeftBrace as u32
}

fn is_right(t: Token) -> bool {
    !t.is_cs() && t.cmd_code() == Cmd::RightBrace as u32
}

fn is_param(t: Token) -> bool {
    !t.is_cs() && (t.cmd_code() == Cmd::MacParam as u32 || t.cmd_code() == Cmd::CarRet as u32)
}

/// TeX's match of a delimited parameter against `s[from..]`: the end of
/// the argument (the first occurrence of `delim` outside braces) and the
/// index after the delimiter; `None` if `s` ends first or has an
/// unmatched right brace (where TeX reads on or complains). The
/// delimiter must not contain braces.
pub(super) fn delimited(s: &[Token], from: usize, delim: &[Token]) -> Option<(usize, usize)> {
    let mut depth = 0u32;
    let mut j = from;
    while j < s.len() {
        let t = s[j];
        if depth == 0 && s[j..].starts_with(delim) {
            return Some((j, j + delim.len()));
        }
        if is_left(t) {
            depth += 1;
        } else if is_right(t) {
            depth = depth.checked_sub(1)?;
        }
        j += 1;
    }
    None
}

/// A delimited argument as TeX passes it: without the braces of a single
/// group that makes up the whole argument.
pub(super) fn strip(arg: &[Token]) -> &[Token] {
    if arg.len() < 2 || !is_left(arg[0]) || !is_right(arg[arg.len() - 1]) {
        return arg;
    }
    let mut depth = 0u32;
    for (k, &t) in arg.iter().enumerate() {
        if is_left(t) {
            depth += 1;
        } else if is_right(t) {
            depth -= 1;
            if depth == 0 {
                return if k == arg.len() - 1 { &arg[1..k] } else { arg };
            }
        }
    }
    arg
}

/// A parameterless macro's meaning with body `body`, as `\def` or
/// `\edef` make it.
fn macro_meaning(body: &[Token]) -> Meaning {
    let mut t = Vec::with_capacity(body.len() + 1);
    t.push(Token::END_MATCH);
    t.extend_from_slice(body);
    Meaning {
        cmd: Cmd::Call,
        chr: 0,
        mac: Some(Rc::new(Macro::new(false, Rc::from(t)))),
    }
}

fn token_list(t: &[Token]) -> TokenList {
    if t.is_empty() {
        crate::token::empty_list()
    } else {
        Rc::from(t)
    }
}

/// The token register a control sequence is `\toksdef`ined to.
fn toks_register(e: &Engine, cs: CsId) -> Option<u32> {
    let m = e.eqtb.meaning(cs);
    (m.cmd == Cmd::AssignToks && m.mac.is_none() && m.chr >= REG_OFFSET).then(|| m.chr - REG_OFFSET)
}

/// The characters of `\csname…\endcsname` text `tokens`, appended to
/// `name`, for text made of characters, macros without parameters
/// (protected ones too: `\csname` expands them) and `\the` of a token
/// register (whose tokens are expanded in turn). `None` for anything
/// else, where TeX might do more than expand; nothing is changed.
fn name_into(e: &Engine, tokens: &[Token], name: &mut Vec<u8>) -> Option<()> {
    let the = cs(e, N::The)?;
    let the = e.eqtb.meaning(the);
    if the.cmd != Cmd::The || the.mac.is_some() {
        return None;
    }
    let the_chr = the.chr;
    let mut stack: Vec<(&[Token], usize)> = vec![(tokens, 0)];
    let mut budget = 200u32;
    while let Some((list, k)) = stack.last_mut() {
        let Some(&t) = list.get(*k) else {
            stack.pop();
            continue;
        };
        *k += 1;
        if !t.is_cs() {
            crate::utf8x::push(name, t.chr());
            continue;
        }
        budget = budget.checked_sub(1)?;
        if stack.len() > 50 {
            return None;
        }
        let m = e.eqtb.meaning(t.cs_id());
        match m.cmd {
            Cmd::Call | Cmd::LongCall => {
                let mac = m.mac.as_ref()?;
                if mac.tokens.first() != Some(&Token::END_MATCH) {
                    return None;
                }
                stack.push((&mac.tokens[1..], 0));
            }
            Cmd::The if m.chr == the_chr && m.mac.is_none() => {
                let (list, k) = stack.last_mut()?;
                let r = *list.get(*k)?;
                *k += 1;
                if !r.is_cs() {
                    return None;
                }
                let reg = toks_register(e, r.cs_id())?;
                stack.push((&e.eqtb.toks[reg as usize].val, 0));
            }
            _ => return None,
        }
    }
    Some(())
}

/// `\pgfkeysifdefined{<text>}` with `<text>` the tokens of `parts`
/// (`\ifcsname pgfk@<text>\endcsname`): the control sequence if it is
/// defined; `Err(())` if the text is outside [`name_into`].
fn key_cs(e: &Engine, parts: &[&[Token]], suffix: &[u8]) -> Result<Option<CsId>, ()> {
    let mut name = b"pgfk@".to_vec();
    for p in parts {
        name_into(e, p, &mut name).ok_or(())?;
    }
    name.extend_from_slice(suffix);
    Ok(e.hash
        .lookup(&name)
        .filter(|&cs| e.eqtb.meaning(cs).cmd != Cmd::UndefinedCs))
}

/// The tokens one expansion step of `cs` gives (as `\expandafter` makes
/// them): the body of a macro without parameters, the token itself if it
/// is not expandable; `None` otherwise.
fn expand_once(e: &Engine, cs: CsId) -> Option<Vec<Token>> {
    let m = e.eqtb.meaning(cs);
    match m.cmd {
        Cmd::Call | Cmd::LongCall => {
            let mac = m.mac.as_ref()?;
            if mac.tokens.first() != Some(&Token::END_MATCH) {
                return None;
            }
            Some(mac.tokens[1..].to_vec())
        }
        c if !c.is_expandable() => Some(vec![Token::cs(cs)]),
        _ => None,
    }
}

/// Whether the tokens can go through the splitting macros: no macro
/// parameter characters, no `\par`, no `\outer` macros.
fn plain_tokens(e: &Engine, t: &[Token], par: Option<CsId>) -> bool {
    t.iter().all(|&t| {
        if !t.is_cs() {
            return !is_param(t);
        }
        if Some(t.cs_id()) == par {
            return false;
        }
        !matches!(
            e.eqtb.meaning(t.cs_id()).cmd,
            Cmd::OuterCall | Cmd::LongOuterCall
        )
    })
}

/// The control sequences the implementations use, by name.
#[derive(Clone, Copy)]
enum N {
    Stop,
    Relax,
    PossibleSpace,
    SpToken,
    TempToks,
    Key,
    PossibleSlash,
    KeyRaw,
    AddedFlag,
    DefaultPath,
    IfTrue,
    IfFalse,
    Par,
    PathToks,
    Temp,
    Name,
    Value,
    Code,
    Eov,
    The,
    CaseTwo,
    CaseTwoExtern,
    CaseThree,
    Unknown,
    NoValueText,
    Path,
    HandlersUnknown,
    Empty,
    ValueRequired,
    CaseOne,
    Fi,
}

const N_NAMES: &[&[u8]] = &[
    b"pgfkeys@stop",
    b"relax",
    b"pgfkeys@possiblespace",
    b"pgfkeys@sptoken",
    b"pgfkeys@temptoks",
    b"pgfkeyscurrentkey",
    b"pgfkeys@possibleslash",
    b"pgfkeyscurrentkeyRAW",
    b"ifpgfkeysaddeddefaultpath",
    b"pgfkeysdefaultpath",
    b"iftrue",
    b"iffalse",
    b"par",
    b"pgfkeys@pathtoks",
    b"pgfkeys@temp",
    b"pgfkeyscurrentname",
    b"pgfkeyscurrentvalue",
    b"pgfkeys@code",
    b"pgfeov",
    b"the",
    b"pgfkeys@case@two",
    b"pgfkeys@case@two@extern",
    b"pgfkeys@case@three",
    b"pgfkeys@unknown",
    b"pgfkeysnovalue@text",
    b"pgfkeyscurrentpath",
    b"pgfk@/handlers/.unknown/.@cmd",
    b"pgfkeys@empty",
    b"pgfkeysvaluerequired",
    b"pgfkeys@case@one",
    b"fi",
];

thread_local! {
    static IDS: [std::cell::Cell<CsId>; N_NAMES.len()] =
        std::array::from_fn(|_| std::cell::Cell::new(UNDEFINED_CS));
}

/// The control sequence named `n`, if it exists: looked up once, then
/// only checked (comparing a name is cheaper than hashing it).
fn cs(e: &Engine, n: N) -> Option<CsId> {
    let name = N_NAMES[n as usize];
    IDS.with(|ids| {
        let c = ids[n as usize].get();
        if (c.0 as usize) < e.hash.len() && e.hash.name(c) == name {
            return Some(c);
        }
        let c = e.hash.lookup(name)?;
        ids[n as usize].set(c);
        Some(c)
    })
}

fn lookup(e: &Engine, names: &[N]) -> Option<Vec<CsId>> {
    names.iter().map(|&n| cs(e, n)).collect()
}

// ----- \pgfkeys@spdef --------------------------------------------------------

/// The control sequences of the trimming.
struct SpIds {
    stop: CsId,
    relax: CsId,
    possible: CsId,
    sptoken: CsId,
    temptoks: CsId,
    reg: u32,
}

fn sp_ids(e: &Engine) -> Option<SpIds> {
    let ids = lookup(
        e,
        &[N::Stop, N::Relax, N::PossibleSpace, N::SpToken, N::TempToks],
    )?;
    Some(SpIds {
        stop: ids[0],
        relax: ids[1],
        possible: ids[2],
        sptoken: ids[3],
        temptoks: ids[4],
        reg: toks_register(e, ids[4])?,
    })
}

/// `\pgfkeys@spdef<target>{<value>}`: the meaning `\futurelet` gives
/// `\pgfkeys@possiblespace` and the trimmed value.
fn trim(
    e: &Engine,
    ids: &SpIds,
    target: Token,
    value: &[Token],
) -> Result<(Meaning, Vec<Token>), &'static str> {
    if !target.is_cs() {
        return Err("target not a control sequence");
    }
    if target.cs_id() == ids.possible || target.cs_id() == ids.temptoks {
        return Err("target assigned by the code");
    }
    let (stop, relax, sp) = (Token::cs(ids.stop), Token::cs(ids.relax), Token::SPACE);
    let first = value.first().copied().unwrap_or(stop);
    let first_meaning = token_meaning(e, first);
    if matches!(first_meaning.cmd, Cmd::OuterCall | Cmd::LongOuterCall) {
        return Err("outer");
    }
    // \pgfkeys@sp@a: a space is put in front unless there is one.
    let mut s = Vec::with_capacity(value.len() + 7);
    if !ifx(&first_meaning, e.eqtb.meaning(ids.sptoken)) {
        s.push(sp);
    }
    s.extend_from_slice(value);
    s.extend_from_slice(&[stop, stop, sp, stop, relax, target]);
    // \pgfkeys@sp@b<space>#1<space>\pgfkeys@stop.
    if s[0] != sp {
        return Err("implicit space");
    }
    let (end, next) = delimited(&s, 1, &[sp, stop]).ok_or("unmatched")?;
    // \pgfkeys@sp@c#1\pgfkeys@stop#2\relax#3.
    let mut c = strip(&s[1..end]).to_vec();
    c.extend_from_slice(&s[next..]);
    let (end1, next1) = delimited(&c, 0, &[stop]).ok_or("unmatched")?;
    let (_, next2) = delimited(&c, next1, &[relax]).ok_or("unmatched")?;
    if c[next2..] != [target] {
        return Err("unusual value");
    }
    let result = strip(&c[..end1]).to_vec();
    Ok((first_meaning, result))
}

/// Makes the assignments of `\pgfkeys@spdef`.
fn commit_trim(e: &mut Engine, ids: &SpIds, target: CsId, first: Meaning, result: &[Token]) {
    e.eq_define(Loc::Cs(ids.possible), Val::Meaning(first));
    e.eq_define(Loc::Toks(ids.reg), Val::Toks(token_list(result)));
    e.eq_define(Loc::Cs(target), Val::Meaning(macro_meaning(result)));
}

fn run_spdef(e: &mut Engine, args: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@spdef";
    if !plain_state(e) {
        return false;
    }
    let [target] = &args[0][..] else {
        return why(W, "target not one token");
    };
    if !SP_DEPS.with(|d| d.borrow_mut().check(e)) {
        return why(W, "dependencies");
    }
    let Some(ids) = sp_ids(e) else {
        return false;
    };
    let (first, result) = match trim(e, &ids, *target, &args[1]) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    commit_trim(e, &ids, target.cs_id(), first, &result);
    true
}

// ----- \pgfkeys@add@path@as@needed -------------------------------------------

/// The control sequences of the path prefixing.
struct PathIds {
    key: CsId,
    possible: CsId,
    raw: CsId,
    flag: CsId,
    default: CsId,
    relax: CsId,
    iftrue: CsId,
    iffalse: CsId,
    par: CsId,
}

fn path_ids(e: &Engine) -> Option<PathIds> {
    let ids = lookup(
        e,
        &[
            N::Key,
            N::PossibleSlash,
            N::KeyRaw,
            N::AddedFlag,
            N::DefaultPath,
            N::Relax,
            N::IfTrue,
            N::IfFalse,
            N::Par,
        ],
    )?;
    Some(PathIds {
        key: ids[0],
        possible: ids[1],
        raw: ids[2],
        flag: ids[3],
        default: ids[4],
        relax: ids[5],
        iftrue: ids[6],
        iffalse: ids[7],
        par: ids[8],
    })
}

/// What `\pgfkeys@add@path@as@needed` does with a key whose body is
/// `body`: the meaning `\futurelet` gives `\pgfkeys@possibleslash`, and,
/// for a key without a leading slash, `\pgfkeyscurrentkeyRAW` and the new
/// key.
type PathResult = (Meaning, Option<(Vec<Token>, Vec<Token>)>);

fn add_path(e: &Engine, ids: &PathIds, body: &[Token]) -> Result<PathResult, &'static str> {
    if !plain_tokens(e, body, Some(ids.par)) {
        return Err("unusual key");
    }
    let relax_t = Token::cs(ids.relax);
    let first = body.first().copied().unwrap_or(relax_t);
    let first_meaning = token_meaning(e, first);
    let slash = Meaning::prim(Cmd::OtherChar, u32::from(b'/'));
    // \pgfkeys@nevermind#1\relax or \pgfkeys@addpath#1\relax.
    let mut s = body.to_vec();
    s.push(relax_t);
    let (end, next) = delimited(&s, 0, &[relax_t]).ok_or("unmatched")?;
    if next != s.len() {
        return Err("\\relax in the key");
    }
    if ifx(&first_meaning, &slash) {
        return Ok((first_meaning, None));
    }
    let arg = strip(&s[..end]).to_vec();
    let mut t = vec![Token::cs(ids.default)];
    t.extend_from_slice(&arg);
    let x = deps::edef(e, &t).ok_or("default path")?;
    if x.iter().any(|&t| is_param(t)) {
        return Err("parameter characters");
    }
    Ok((first_meaning, Some((arg, x))))
}

/// Makes the assignments of `\pgfkeys@add@path@as@needed`.
fn commit_path(e: &mut Engine, ids: &PathIds, r: PathResult) {
    e.eq_define(Loc::Cs(ids.possible), Val::Meaning(r.0));
    match r.1 {
        None => {
            let f = e.eqtb.meaning(ids.iffalse).clone();
            e.eq_define(Loc::Cs(ids.flag), Val::Meaning(f));
            let k = e.eqtb.meaning(ids.key).clone();
            e.eq_define(Loc::Cs(ids.raw), Val::Meaning(k));
        }
        Some((raw, key)) => {
            let t = e.eqtb.meaning(ids.iftrue).clone();
            e.eq_define(Loc::Cs(ids.flag), Val::Meaning(t));
            e.eq_define(Loc::Cs(ids.raw), Val::Meaning(macro_meaning(&raw)));
            e.eq_define(Loc::Cs(ids.key), Val::Meaning(macro_meaning(&key)));
        }
    }
}

fn run_add_path(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@add@path@as@needed";
    if !plain_state(e) {
        return false;
    }
    if !PATH_DEPS.with(|d| d.borrow_mut().check(e)) {
        return why(W, "dependencies");
    }
    let Some(ids) = path_ids(e) else {
        return false;
    };
    let Some(body) = deps::plain_body(e, ids.key) else {
        return why(W, "key not a macro");
    };
    let r = match add_path(e, &ids, body) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    commit_path(e, &ids, r);
    true
}

// ----- \pgfkeys@unpack ------------------------------------------------------

/// Opens a conditional as an `\ifx` that was false and whose `\else` has
/// been read: what TeX's condition stack holds while the `\else` branch
/// runs.
fn open_ifx_else(e: &mut Engine) {
    use crate::cond::{CondRecord, FI_CODE, if_codes::IFX};
    let c = &mut e.cond;
    c.stack.push(CondRecord {
        if_limit: c.if_limit,
        cur_if: c.cur_if,
        if_line: c.if_line,
    });
    c.cur_if = IFX;
    c.if_limit = FI_CODE;
    c.if_line = e.input.line();
}

fn run_unpack(e: &mut Engine, args: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@unpack";
    if !plain_state(e) {
        return false;
    }
    for (deps, label) in [
        (&UNPACK_DEPS, "dependencies"),
        (&SP_DEPS, "spdef dependencies"),
        (&PATH_DEPS, "path dependencies"),
        (&KEY_DEPS, "key dependencies"),
    ] {
        if !deps.with(|d| d.borrow_mut().check(e)) {
            return why(W, label);
        }
    }
    let (Some(sp), Some(p), Some(ids)) = (
        sp_ids(e),
        path_ids(e),
        lookup(
            e,
            &[
                N::Value,
                N::Empty,
                N::NoValueText,
                N::ValueRequired,
                N::CaseOne,
                N::Fi,
            ],
        ),
    ) else {
        return false;
    };
    let [value, empty, novalue, required, case_one, fi] = ids[..] else {
        return false;
    };
    // \pgfkeys@spdef\pgfkeyscurrentkey{#1}.
    let (kfirst, kt) = match trim(e, &sp, Token::cs(p.key), &args[0]) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    // \edef\pgfkeyscurrentkey{\pgfkeyscurrentkey}: the trimmed key
    // expanded (with the meanings before the trimming's assignments,
    // which must not matter).
    if kt
        .iter()
        .any(|&t| is_param(t) || t == Token::cs(p.key) || t == Token::cs(sp.possible))
    {
        return why(W, "unusual key");
    }
    let Some(k) = deps::edef(e, &kt) else {
        return why(W, "key expansion");
    };
    if k.iter().any(|&t| is_param(t)) {
        return why(W, "parameter characters");
    }
    if ifx(&macro_meaning(&k), e.eqtb.meaning(empty)) {
        // An empty key: skipped.
        commit_trim(e, &sp, p.key, kfirst, &kt);
        e.eq_define(Loc::Cs(p.key), Val::Meaning(macro_meaning(&k)));
        return true;
    }
    // \pgfkeys@add@path@as@needed.
    let path = match add_path(e, &p, &k) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    // \pgfkeys@spdef\pgfkeyscurrentvalue{#2}.
    let (vfirst, vt) = match trim(e, &sp, Token::cs(value), &args[1]) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    // Without a value, the default (\pgfkeysifdefined and
    // \pgfkeysgetvalue{<key>/.@def}{\pgfkeyscurrentvalue}).
    let mut vmeaning = macro_meaning(&vt);
    let mut default = None;
    if ifx(&vmeaning, e.eqtb.meaning(novalue)) {
        let key = path.1.as_ref().map_or(&k, |(_, x)| x);
        let d = match key_cs(e, &[key], b"/.@def") {
            Ok(d) => d,
            Err(()) => return why(W, "key name"),
        };
        if let Some(d) = d {
            vmeaning = e.eqtb.meaning(d).clone();
        }
        default = Some(d);
    }
    if ifx(&vmeaning, e.eqtb.meaning(required)) {
        return why(W, "value required");
    }
    // Commit.
    commit_trim(e, &sp, p.key, kfirst, &kt);
    e.eq_define(Loc::Cs(p.key), Val::Meaning(macro_meaning(&k)));
    commit_path(e, &p, path);
    commit_trim(e, &sp, value, vfirst, &vt);
    match default {
        Some(Some(d)) => {
            e.eq_define(Loc::Cs(value), Val::Meaning(vmeaning));
            e.last_cs_name = d;
        }
        Some(None) => e.last_cs_name = UNDEFINED_CS,
        None => {}
    }
    // \pgfkeys@case@one runs inside both \ifx's \else branches.
    open_ifx_else(e);
    open_ifx_else(e);
    e.native_insert(vec![Token::cs(case_one), Token::cs(fi), Token::cs(fi)]);
    true
}

// ----- \pgfkeys@split@path ---------------------------------------------------

/// The result of `\pgfkeys@split@path` on the body of
/// `\pgfkeyscurrentkey`: the path (`\pgfkeys@pathtoks`) and the name.
fn split(e: &Engine, key: CsId) -> Result<(Vec<Token>, Vec<Token>), &'static str> {
    let body = deps::plain_body(e, key).ok_or("key not a macro")?;
    let par = cs(e, N::Par);
    if !plain_tokens(e, body, par) {
        return Err("unusual key");
    }
    let slash = Token::other(u32::from(b'/'));
    let mut s = body.to_vec();
    s.extend_from_slice(&[slash, slash]);
    let mut path: Vec<Token> = Vec::new();
    let mut i = 0;
    let name = loop {
        // \pgfkeys@splitter#1/#2/, then #2/ is put back.
        let (e1, n1) = delimited(&s, i, &[slash]).ok_or("unmatched")?;
        let (e2, n2) = delimited(&s, n1, &[slash]).ok_or("unmatched")?;
        let a1 = strip(&s[i..e1]).to_vec();
        let a2 = strip(&s[n1..e2]).to_vec();
        if a2.is_empty() {
            // \pgfkeys@gobbletoslash\pgfkeys@splitter/ ends it: all the
            // tokens must have been read.
            if n2 != s.len() {
                return Err("empty path element");
            }
            break a1;
        }
        path.extend_from_slice(&a1);
        path.push(slash);
        let mut rest = a2;
        rest.push(slash);
        rest.extend_from_slice(&s[n2..]);
        s = rest;
        i = 0;
    };
    if !path.is_empty() {
        // \pgfkeys@remove@slash#1/\relax.
        let relax = Token::cs(cs(e, N::Relax).ok_or("relax")?);
        path.push(relax);
        let (end, next) = delimited(&path, 0, &[slash, relax]).ok_or("unmatched")?;
        if next != path.len() {
            return Err("unusual path");
        }
        path = strip(&path[..end]).to_vec();
    }
    Ok((path, name))
}

/// Makes the assignments of `\pgfkeys@split@path`.
fn commit_split(e: &mut Engine, ids: &SplitIds, path: &[Token], name: &[Token]) {
    e.eq_define(Loc::Toks(ids.pathtoks), Val::Toks(token_list(path)));
    e.eq_define(Loc::Cs(ids.temp), Val::Meaning(macro_meaning(&[])));
    e.eq_define(Loc::Cs(ids.name), Val::Meaning(macro_meaning(name)));
}

struct SplitIds {
    key: CsId,
    pathtoks: u32,
    temp: CsId,
    name: CsId,
}

fn split_ids(e: &Engine) -> Option<SplitIds> {
    let ids = lookup(e, &[N::Key, N::PathToks, N::Temp, N::Name])?;
    Some(SplitIds {
        key: ids[0],
        pathtoks: toks_register(e, ids[1])?,
        temp: ids[2],
        name: ids[3],
    })
}

fn run_split_path(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@split@path";
    if !plain_state(e) {
        return false;
    }
    if !SPLIT_DEPS.with(|d| d.borrow_mut().check(e)) {
        return why(W, "dependencies");
    }
    let Some(ids) = split_ids(e) else {
        return false;
    };
    let (path, name) = match split(e, ids.key) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    commit_split(e, &ids, &path, &name);
    true
}

// ----- The dispatch ----------------------------------------------------------

/// The control sequences the dispatch uses.
struct KeyIds {
    key: CsId,
    value: CsId,
    code: CsId,
    eov: CsId,
    relax: CsId,
}

fn key_ids(e: &Engine) -> Option<KeyIds> {
    let ids = lookup(e, &[N::Key, N::Value, N::Code, N::Eov, N::Relax])?;
    Some(KeyIds {
        key: ids[0],
        value: ids[1],
        code: ids[2],
        eov: ids[3],
        relax: ids[4],
    })
}

fn key_checks(e: &Engine, what: &str) -> Option<KeyIds> {
    if !plain_state(e) {
        return None;
    }
    if !KEY_DEPS.with(|d| d.borrow_mut().check(e)) {
        why(what, "dependencies");
        return None;
    }
    key_ids(e)
}

/// `\expandafter\pgfkeys@code\pgfkeyscurrentvalue\pgfeov`: the tokens
/// to put back (the `\let` of `\pgfkeys@code` does not change them).
fn call_tokens(e: &Engine, ids: &KeyIds) -> Option<Vec<Token>> {
    let mut t = vec![Token::cs(ids.code)];
    t.extend(expand_once(e, ids.value)?);
    t.push(Token::cs(ids.eov));
    Some(t)
}

/// The `\let\pgfkeys@code` and `\lastnamedcs` of
/// `\pgfkeysgetvalue{…}{\pgfkeys@code}` for a defined `cmd`.
fn let_code(e: &mut Engine, ids: &KeyIds, cmd: CsId) {
    let m = e.eqtb.meaning(cmd).clone();
    e.eq_define(Loc::Cs(ids.code), Val::Meaning(m));
    e.last_cs_name = cmd;
}

fn insert_cs(e: &mut Engine, name: N) -> bool {
    let Some(cs) = cs(e, name) else {
        return false;
    };
    e.native_insert(vec![Token::cs(cs)]);
    true
}

fn run_case_one(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@case@one";
    let Some(ids) = key_checks(e, W) else {
        return false;
    };
    let key = [Token::cs(ids.key)];
    let Ok(cmd) = key_cs(e, &[&key], b"/.@cmd") else {
        return why(W, "key name");
    };
    let Some(cmd) = cmd else {
        // \pgfkeys@case@two.
        if !insert_cs(e, N::CaseTwo) {
            return false;
        }
        e.last_cs_name = UNDEFINED_CS;
        return true;
    };
    let relax = e.eqtb.meaning(ids.relax);
    if ifx(e.eqtb.meaning(cmd), relax) {
        // \pgfkeys@unknown.
        if cs(e, N::Unknown).is_none() {
            return false;
        }
        let_code(e, &ids, cmd);
        return insert_cs(e, N::Unknown);
    }
    let Some(tokens) = call_tokens(e, &ids) else {
        return why(W, "value");
    };
    let_code(e, &ids, cmd);
    e.native_insert(tokens);
    true
}

fn run_case_two(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@case@two";
    let Some(ids) = key_checks(e, W) else {
        return false;
    };
    let key = [Token::cs(ids.key)];
    let Ok(cs) = key_cs(e, &[&key], b"") else {
        return why(W, "key name");
    };
    let next = if cs.is_some() {
        N::CaseTwoExtern
    } else {
        N::CaseThree
    };
    if !insert_cs(e, next) {
        return false;
    }
    e.last_cs_name = cs.unwrap_or(UNDEFINED_CS);
    true
}

fn run_case_two_extern(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@case@two@extern";
    let Some(ids) = key_checks(e, W) else {
        return false;
    };
    let Some(novalue) = cs(e, N::NoValueText) else {
        return false;
    };
    let value = e.eqtb.meaning(ids.value).clone();
    if ifx(&value, e.eqtb.meaning(novalue)) {
        return why(W, "no value");
    }
    // \pgfkeyslet{\pgfkeyscurrentkey}\pgfkeyscurrentvalue:
    // \expandafter\let\csname pgfk@<key>\endcsname\pgfkeyscurrentvalue.
    let mut name = b"pgfk@".to_vec();
    if name_into(e, &[Token::cs(ids.key)], &mut name).is_none() {
        return why(W, "key name");
    }
    let cs = e.hash.lookup_or_insert(&name);
    e.eq_define(Loc::Cs(cs), Val::Meaning(value));
    e.last_cs_name = cs;
    true
}

fn run_case_three(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@case@three";
    let Some(ids) = key_checks(e, W) else {
        return false;
    };
    if !SPLIT_DEPS.with(|d| d.borrow_mut().check(e)) {
        return why(W, "dependencies");
    }
    let Some(sids) = split_ids(e) else {
        return false;
    };
    let (path, name) = match split(e, sids.key) {
        Ok(r) => r,
        Err(reason) => return why(W, reason),
    };
    // /handlers/<name>/.@cmd, with \pgfkeyscurrentname defined as the
    // name.
    let mut hname = b"pgfk@/handlers/".to_vec();
    if name_into(e, &name, &mut hname).is_none() {
        return why(W, "handler name");
    }
    hname.extend_from_slice(b"/.@cmd");
    let handler = e
        .hash
        .lookup(&hname)
        .filter(|&cs| e.eqtb.meaning(cs).cmd != Cmd::UndefinedCs);
    let tokens = match handler {
        Some(_) => {
            let Some(t) = call_tokens(e, &ids) else {
                return why(W, "value");
            };
            t
        }
        None => {
            let Some(u) = cs(e, N::Unknown) else {
                return false;
            };
            vec![Token::cs(u)]
        }
    };
    // Commit.
    commit_split(e, &sids, &path, &name);
    match handler {
        Some(h) => let_code(e, &ids, h),
        None => e.last_cs_name = UNDEFINED_CS,
    }
    e.native_insert(tokens);
    true
}

fn run_unknown(e: &mut Engine, _: &[TokenList]) -> bool {
    const W: &str = "pgfkeys@unknown";
    let Some(ids) = key_checks(e, W) else {
        return false;
    };
    let Some(path) = cs(e, N::Path) else {
        return false;
    };
    let Ok(cmd) = key_cs(e, &[&[Token::cs(path)]], b"/.unknown/.@cmd") else {
        return why(W, "path");
    };
    let cmd = match cmd {
        Some(c) => c,
        None => match cs(e, N::HandlersUnknown)
            .filter(|&cs| e.eqtb.meaning(cs).cmd != Cmd::UndefinedCs)
        {
            Some(c) => c,
            None => return why(W, "no /handlers/.unknown"),
        },
    };
    let Some(tokens) = call_tokens(e, &ids) else {
        return why(W, "value");
    };
    let_code(e, &ids, cmd);
    e.native_insert(tokens);
    true
}