zshrs 0.11.5

The first compiled Unix shell — bytecode VM, worker pool, AOP intercept, Rkyv caching
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
//! ZLE parameter interface
//!
//! Port from zsh/Src/Zle/zleparameter.c (186 lines)
//!
//! Functions for the zlewidgets special parameter.                          // c:33
//! Functions for the zlekeymaps special parameter.                          // c:102
//!
//! Provides the special $widgets associative array and $keymaps parameter
//! that let shell scripts query ZLE's internal state.

use std::collections::HashMap;

/// Format a widget's type label as `$widgets[name]` would show it.
/// Port of `widgetstr(Widget w)` from Src/Zle/zleparameter.c. The C source
/// emits "builtin" for `iwidgets.list` entries, "user:fnname" for
/// `zle -N` widgets, and "completion:fnname" for `zle -C` ones —
/// matched here verbatim so shell scripts that grep `$widgets`
/// keep working.
/// WARNING: param names don't match C — Rust=(name, is_user, is_completion) vs C=(w)

// --- AUTO: cross-zle hoisted-fn use glob ---
#[allow(unused_imports)]
use crate::ported::zle::zle_h::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_main::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_misc::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_hist::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_move::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_word::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_params::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_vi::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_utils::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_refresh::*;
#[allow(unused_imports)]
use crate::ported::zle::zle_tricky::*;
#[allow(unused_imports)]
use crate::ported::zle::textobjects::*;
#[allow(unused_imports)]
use crate::ported::zle::deltochar::*;

pub fn widgetstr(name: &str, is_user: bool, is_completion: bool) -> String { // c:37
    if is_completion {
        format!("completion:{}", name)
    } else if is_user {
        format!("user:{}", name)
    } else {
        "builtin".to_string()
    }
}

// Functions for the zlewidgets special parameter.                          // c:33
/// Build the `$widgets` associative array — the snapshot consulted by
/// shell-side `${(k)widgets}` enumeration.
/// Port of `getpmwidgets(UNUSED(HashTable ht), const char *name)` from Src/Zle/zleparameter.c. The C source
/// walks `thingytab` (zle_thingy.c:60 `createthingytab`); we union
/// the static built-in slice with the user + completion widget maps
/// and emit the same per-entry type label widgetstr() produces.
/// WARNING: param names don't match C — Rust=(user_widgets, completion_widgets) vs C=(ht, name)
pub fn getpmwidgets(                                                         // c:59
    builtin_widgets: &[&str],
    user_widgets: &HashMap<String, String>,
    completion_widgets: &HashMap<String, String>,
) -> HashMap<String, String> {
    let mut result = HashMap::new();

    for &name in builtin_widgets {
        result.insert(name.to_string(), "builtin".to_string());
    }

    for (name, func) in user_widgets {
        result.insert(name.to_string(), format!("user:{}", func));
    }

    for (name, func) in completion_widgets {
        result.insert(name.to_string(), format!("completion:{}", func));
    }

    result
}

/// Iterate over every widget for the parameter scan path (used by
/// `${(kv)widgets}` and zsh's `print -l ${(k)widgets}`).
/// Port of `scanpmwidgets(UNUSED(HashTable ht), ScanFunc func, int flags)` from Src/Zle/zleparameter.c. The C
/// source walks the same thingytab the getpmwidgets path uses but
/// invokes the parameter-scan callback on each entry instead of
/// allocating the full hash.
/// WARNING: param names don't match C — Rust=(user_widgets, completion_widgets, callback) vs C=(ht, func, flags)
pub fn scanpmwidgets<F>(                                                     // c:81
    builtin_widgets: &[&str],
    user_widgets: &HashMap<String, String>,
    completion_widgets: &HashMap<String, String>,
    mut callback: F,
) where
    F: FnMut(&str, &str),
{
    for &name in builtin_widgets {
        callback(name, "builtin");
    }
    for (name, func) in user_widgets {
        callback(name, &format!("user:{}", func));
    }
    for (name, func) in completion_widgets {
        callback(name, &format!("completion:{}", func));
    }
}

// Functions for the zlekeymaps special parameter.                          // c:105
/// Build the `$keymaps` array — list of every named keymap.
/// Port of `keymapsgetfn(UNUSED(Param pm))` from Src/Zle/zleparameter.c. The C
/// source walks `keymapnamtab` (zle_keymap.c:153
/// `createkeymapnamtab`); we surface the host-supplied slice
/// directly since our keymap registry already exposes a Vec view.
/// WARNING: param names don't match C — Rust=(keymaps) vs C=(pm)
pub fn keymapsgetfn(keymaps: &[&str]) -> Vec<String> {                       // c:105
    keymaps.iter().map(|s| s.to_string()).collect()
}



/// Port of `setup_(UNUSED(Module m))` from `Src/Zle/zleparameter.c:147`. C body
/// is `return 0;` (UNUSED `Module m`).
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn setup_() -> i32 {                                                 // c:147
    0                                                                    // c:154
}

/// Port of `features_(UNUSED(Module m), UNUSED(char ***features))` from `Src/Zle/zleparameter.c:154`. C body
/// is `*features = featuresarray(m, &module_features); return 0;`.
/// Static-link path: 0.
/// WARNING: param names don't match C — Rust=() vs C=(m, features)
pub fn features_() -> i32 {                                              // c:154
    0                                                                    // c:162
}

/// Port of `enables_(UNUSED(Module m), UNUSED(int **enables))` from `Src/Zle/zleparameter.c:162`. C body
/// is `return handlefeatures(m, &module_features, enables);`.
/// Static-link path: 0.
/// WARNING: param names don't match C — Rust=() vs C=(m, enables)
pub fn enables_() -> i32 {                                               // c:162
    0                                                                    // c:169
}

/// Port of `boot_(UNUSED(Module m))` from `Src/Zle/zleparameter.c:169`. C body is
/// `return 0;` (UNUSED `Module m`).
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn boot_() -> i32 {                                                  // c:169
    0                                                                    // c:176
}

/// Port of `cleanup_(UNUSED(Module m))` from `Src/Zle/zleparameter.c:176`. C body
/// is `return setfeatureenables(m, &module_features, NULL);`.
/// Static-link path: 0.
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn cleanup_() -> i32 {                                               // c:176
    0                                                                    // c:183
}

/// Port of `finish_(UNUSED(Module m))` from `Src/Zle/zleparameter.c:183`. C body
/// is `return 0;` (UNUSED `Module m`).
/// WARNING: param names don't match C — Rust=() vs C=(m)
pub fn finish_() -> i32 {                                                // c:183
    0                                                                    // c:183
}

/// Default builtin widget names for the $widgets parameter
pub const BUILTIN_WIDGETS: &[&str] = &[
    "accept-and-hold",
    "accept-and-infer-next-history",
    "accept-line",
    "accept-line-and-down-history",
    "backward-char",
    "backward-delete-char",
    "backward-kill-line",
    "backward-kill-word",
    "backward-word",
    "beep",
    "beginning-of-buffer-or-history",
    "beginning-of-history",
    "beginning-of-line",
    "beginning-of-line-hist",
    "capitalize-word",
    "clear-screen",
    "complete-word",
    "copy-prev-word",
    "copy-region-as-kill",
    "delete-char",
    "delete-char-or-list",
    "delete-word",
    "describe-key-briefly",
    "digit-argument",
    "down-case-word",
    "down-history",
    "down-line",
    "down-line-or-history",
    "down-line-or-search",
    "emacs-backward-word",
    "emacs-forward-word",
    "end-of-buffer-or-history",
    "end-of-history",
    "end-of-line",
    "end-of-line-hist",
    "exchange-point-and-mark",
    "execute-last-named-cmd",
    "execute-named-cmd",
    "expand-history",
    "expand-or-complete",
    "expand-or-complete-prefix",
    "expand-word",
    "forward-char",
    "forward-word",
    "get-line",
    "gosmacs-transpose-chars",
    "history-beginning-search-backward",
    "history-beginning-search-forward",
    "history-incremental-search-backward",
    "history-incremental-search-forward",
    "history-search-backward",
    "history-search-forward",
    "insert-last-word",
    "kill-buffer",
    "kill-line",
    "kill-region",
    "kill-whole-line",
    "kill-word",
    "list-choices",
    "list-expand",
    "magic-space",
    "menu-complete",
    "menu-expand-or-complete",
    "neg-argument",
    "overwrite-mode",
    "pound-insert",
    "push-input",
    "push-line",
    "push-line-or-edit",
    "quoted-insert",
    "bslashquote-line",
    "bslashquote-region",
    "read-command",
    "recursive-edit",
    "redisplay",
    "redo",
    "reset-prompt",
    "reverse-menu-complete",
    "run-help",
    "self-insert",
    "self-insert-unmeta",
    "send-break",
    "set-mark-command",
    "spell-word",
    "split-undo",
    "transpose-chars",
    "transpose-words",
    "undefined-key",
    "undo",
    "universal-argument",
    "up-case-word",
    "up-history",
    "up-line",
    "up-line-or-history",
    "up-line-or-search",
    "vi-add-eol",
    "vi-add-next",
    "vi-backward-blank-word",
    "vi-backward-char",
    "vi-backward-delete-char",
    "vi-backward-kill-word",
    "vi-backward-word",
    "vi-beginning-of-line",
    "vi-caps-lock-panic",
    "vi-change",
    "vi-change-eol",
    "vi-change-whole-line",
    "vi-cmd-mode",
    "vi-delete",
    "vi-delete-char",
    "vi-digit-or-beginning-of-line",
    "vi-down-line-or-history",
    "vi-end-of-line",
    "vi-fetch-history",
    "vi-find-next-char",
    "vi-find-next-char-skip",
    "vi-find-prev-char",
    "vi-find-prev-char-skip",
    "vi-first-non-blank",
    "vi-forward-blank-word",
    "vi-forward-blank-word-end",
    "vi-forward-char",
    "vi-forward-word",
    "vi-forward-word-end",
    "vi-goto-column",
    "vi-goto-mark",
    "vi-goto-mark-line",
    "vi-history-search-backward",
    "vi-history-search-forward",
    "vi-indent",
    "vi-insert",
    "vi-insert-bol",
    "vi-join",
    "vi-kill-eol",
    "vi-kill-line",
    "vi-match-bracket",
    "vi-open-line-above",
    "vi-open-line-below",
    "vi-oper-swap-case",
    "vi-pound-insert",
    "vi-put-after",
    "vi-put-before",
    "vi-quoted-insert",
    "vi-repeat-change",
    "vi-repeat-find",
    "vi-repeat-search",
    "vi-replace",
    "vi-replace-chars",
    "vi-rev-repeat-find",
    "vi-rev-repeat-search",
    "vi-set-buffer",
    "vi-set-mark",
    "vi-substitute",
    "vi-swap-case",
    "vi-undo-change",
    "vi-unindent",
    "vi-up-line-or-history",
    "vi-yank",
    "vi-yank-eol",
    "vi-yank-whole-line",
    "what-cursor-position",
    "where-is",
    "which-command",
    "yank",
    "yank-pop",
    "zap-to-char",
];

/// Default keymap names
pub const DEFAULT_KEYMAPS: &[&str] = &[
    "emacs", "viins", "vicmd", "viopp", "visual", "isearch", "command", "main", ".safe",
];

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_widgetstr() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        assert_eq!(widgetstr("self-insert", false, false), "builtin");
        assert_eq!(widgetstr("my-widget", true, false), "user:my-widget");
        assert_eq!(widgetstr("my-comp", false, true), "completion:my-comp");
    }

    #[test]
    fn test_getpmwidgets() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let user = HashMap::new();
        let comp = HashMap::new();
        let widgets = getpmwidgets(&["accept-line", "backward-char"], &user, &comp);
        assert_eq!(widgets.get("accept-line"), Some(&"builtin".to_string()));
        assert_eq!(widgets.len(), 2);
    }

    #[test]
    fn test_keymapsgetfn() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        let keymaps = keymapsgetfn(DEFAULT_KEYMAPS);
        assert!(keymaps.contains(&"emacs".to_string()));
        assert!(keymaps.contains(&"vicmd".to_string()));
    }

    #[test]
    fn test_builtin_widget_count() {
        let _g = crate::ported::zle::zle_main::zle_test_setup();
        // zsh has ~160 builtin widgets
        assert!(BUILTIN_WIDGETS.len() > 150);
    }

    /// c:37 — `widgetstr` user form preserves the function name in
    /// the suffix so `${widgets[my-widget]}` reads `user:my-fn`.
    /// Pinning the suffix shape catches a regression that drops the
    /// function-name part (which scripts grep for to bind to widgets).
    #[test]
    fn widgetstr_user_form_carries_function_name_after_colon() {
        let s = widgetstr("a-fn", true, false);
        let (kind, rest) = s.split_once(':').expect("missing colon");
        assert_eq!(kind, "user");
        assert_eq!(rest, "a-fn", "function-name suffix must round-trip");
    }

    /// c:37 — `widgetstr(_, true, true)` — both flags true. The C
    /// dispatch order is is_completion FIRST, so this branch yields
    /// "completion:..." not "user:...". Pin the precedence so a
    /// regen flipping branch order gets caught (would silently swap
    /// the type label for completion widgets).
    #[test]
    fn widgetstr_completion_wins_over_user_when_both_true() {
        let s = widgetstr("foo", true, true);
        assert!(s.starts_with("completion:"),
            "is_completion must dominate is_user, got: {}", s);
    }

    /// c:59 — `getpmwidgets` should NOT silently de-dup. If a user
    /// or completion widget shares a name with a builtin, the user/
    /// completion entry overwrites the builtin (HashMap semantics
    /// last-write-wins on equal keys). Pin the overwrite direction
    /// so a regen flipping insert order silently changes which type
    /// `${widgets[x]}` reports.
    #[test]
    fn getpmwidgets_user_overrides_builtin_on_name_collision() {
        let mut user = HashMap::new();
        user.insert("accept-line".to_string(), "my-fn".to_string());
        let comp = HashMap::new();
        let widgets = getpmwidgets(&["accept-line", "backward-char"], &user, &comp);
        // "accept-line" should be the user entry, NOT "builtin"
        assert_eq!(widgets.get("accept-line"), Some(&"user:my-fn".to_string()),
            "user widget must override builtin of same name");
        // "backward-char" stays builtin (no user entry)
        assert_eq!(widgets.get("backward-char"), Some(&"builtin".to_string()));
    }

    /// c:81 — `scanpmwidgets` callback fires once per entry across
    /// all three buckets. Counter-test ensures no bucket is silently
    /// skipped.
    #[test]
    fn scanpmwidgets_callback_fires_for_every_bucket() {
        let mut user = HashMap::new();
        user.insert("u-widget".to_string(), "u-fn".to_string());
        let mut comp = HashMap::new();
        comp.insert("c-widget".to_string(), "c-fn".to_string());
        let mut seen: Vec<(String, String)> = Vec::new();
        scanpmwidgets(&["b-widget"], &user, &comp, |n, t| {
            seen.push((n.to_string(), t.to_string()));
        });
        let names: std::collections::HashSet<_> = seen.iter().map(|(n, _)| n.clone()).collect();
        assert!(names.contains("b-widget"));
        assert!(names.contains("u-widget"));
        assert!(names.contains("c-widget"));
        // Type labels also carry the bucket prefix
        let types: std::collections::HashSet<_> = seen.iter().map(|(_, t)| t.clone()).collect();
        assert!(types.contains("builtin"));
        assert!(types.iter().any(|t| t.starts_with("user:")));
        assert!(types.iter().any(|t| t.starts_with("completion:")));
    }

    /// c:105 — `keymapsgetfn` returns a copy, not a reference. Mutating
    /// the result must NOT affect the input slice. Pin the
    /// allocation contract because the C source uses `ztrdup` per
    /// entry — the Rust port's `.iter().map(|s| s.to_string())` must
    /// preserve that.
    #[test]
    fn keymapsgetfn_returns_independent_copies() {
        let input: &[&str] = &["a", "b", "c"];
        let mut out = keymapsgetfn(input);
        out.push("d".to_string());
        // Input still has 3, out has 4
        assert_eq!(input.len(), 3);
        assert_eq!(out.len(), 4);
    }

    /// `BUILTIN_WIDGETS` must not contain duplicates — the C source's
    /// thingytab is keyed by name and would silently dedupe; the
    /// Rust hardcoded list must do the same proactively.
    #[test]
    fn builtin_widgets_has_no_duplicates() {
        let unique: std::collections::HashSet<_> = BUILTIN_WIDGETS.iter().copied().collect();
        assert_eq!(unique.len(), BUILTIN_WIDGETS.len(),
            "duplicate widget name in BUILTIN_WIDGETS — would corrupt $widgets");
    }

    /// `BUILTIN_WIDGETS` entries must follow the `lowercase-with-
    /// hyphens` convention zsh's own widget names use. Catches a
    /// regression that adds an underscore-named or uppercase entry
    /// which couldn't be bound via `bindkey` without quoting.
    #[test]
    fn builtin_widgets_entries_are_kebab_case() {
        for w in BUILTIN_WIDGETS {
            assert!(!w.is_empty(), "empty widget name");
            for c in w.chars() {
                assert!(c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-',
                    "widget {:?} has non-kebab-case char {:?}", w, c);
            }
            assert!(!w.starts_with('-'),
                "widget {:?} starts with '-' — would parse as a flag", w);
            assert!(!w.ends_with('-'), "widget {:?} ends with '-'", w);
        }
    }

    /// `DEFAULT_KEYMAPS` must include the four POSIX-required
    /// names (emacs, viins, vicmd, main). zsh's startup expects
    /// each of these to exist; a regression that drops "main"
    /// would silently break every user's `bindkey -A main`.
    #[test]
    fn default_keymaps_includes_required_names() {
        for required in ["emacs", "viins", "vicmd", "main"] {
            assert!(DEFAULT_KEYMAPS.contains(&required),
                "DEFAULT_KEYMAPS missing required name: {}", required);
        }
    }

    /// c:147-183 — module-lifecycle stubs all return 0 in C.
    #[test]
    fn module_lifecycle_shims_all_return_zero() {
        assert_eq!(setup_(), 0);
        assert_eq!(boot_(), 0);
        assert_eq!(cleanup_(), 0);
        assert_eq!(finish_(), 0);
    }
}