Add zsh completions and improve fish completions (#2925)

Adds zsh completion generation and improves fish completion generation
to cover all actions with arguments.

<details>
  <summary>Generated _ghostty contents</summary>
  
  ```zsh
#compdef ghostty

_fonts () {
  local font_list=$(ghostty +list-fonts | grep -Z '^[A-Z]')
  local fonts=(${(f)font_list})
  _describe -t fonts 'fonts' fonts
}

_themes() {
  local theme_list=$(ghostty +list-themes | sed -E 's/^(.*) \(.*\$/\0/')
  local themes=(${(f)theme_list})
  _describe -t themes 'themes' themes
}
_config() {
  _arguments \
    "--help" \
    "--version" \
    "--font-family=-:::_fonts" \
    "--font-family-bold=-:::_fonts" \
    "--font-family-italic=-:::_fonts" \
    "--font-family-bold-italic=-:::_fonts" \
    "--font-style=-:::( )" \
    "--font-style-bold=-:::( )" \
    "--font-style-italic=-:::( )" \
    "--font-style-bold-italic=-:::( )" \
"--font-synthetic-style=-:::(bold no-bold italic no-italic bold-italic
no-bold-italic)" \
    "--font-feature=-:::( )" \
    "--font-size=-:::( )" \
    "--font-variation=-:::( )" \
    "--font-variation-bold=-:::( )" \
    "--font-variation-italic=-:::( )" \
    "--font-variation-bold-italic=-:::( )" \
    "--font-codepoint-map=-:::( )" \
    "--font-thicken=-:::(true false)" \
    "--adjust-cell-width=-:::( )" \
    "--adjust-cell-height=-:::( )" \
    "--adjust-font-baseline=-:::( )" \
    "--adjust-underline-position=-:::( )" \
    "--adjust-underline-thickness=-:::( )" \
    "--adjust-strikethrough-position=-:::( )" \
    "--adjust-strikethrough-thickness=-:::( )" \
    "--adjust-cursor-thickness=-:::( )" \
    "--grapheme-width-method=-:::(legacy unicode)" \
"--freetype-load-flags=-:::(hinting no-hinting force-autohint
no-force-autohint monochrome no-monochrome autohint no-autohint)" \
    "--theme=-:::_themes" \
    "--background=-:::( )" \
    "--foreground=-:::( )" \
    "--selection-foreground=-:::( )" \
    "--selection-background=-:::( )" \
    "--selection-invert-fg-bg=-:::(true false)" \
    "--minimum-contrast=-:::( )" \
    "--palette=-:::( )" \
    "--cursor-color=-:::( )" \
    "--cursor-invert-fg-bg=-:::(true false)" \
    "--cursor-opacity=-:::( )" \
    "--cursor-style=-:::(bar block underline block_hollow)" \
    "--cursor-style-blink=-:::( )" \
    "--cursor-text=-:::( )" \
    "--cursor-click-to-move=-:::(true false)" \
    "--mouse-hide-while-typing=-:::(true false)" \
    "--mouse-shift-capture=-:::(false true always never)" \
    "--mouse-scroll-multiplier=-:::( )" \
    "--background-opacity=-:::( )" \
    "--background-blur-radius=-:::( )" \
    "--unfocused-split-opacity=-:::( )" \
    "--unfocused-split-fill=-:::( )" \
    "--command=-:::( )" \
    "--initial-command=-:::( )" \
    "--wait-after-command=-:::(true false)" \
    "--abnormal-command-exit-runtime=-:::( )" \
    "--scrollback-limit=-:::( )" \
    "--link=-:::( )" \
    "--link-url=-:::(true false)" \
    "--fullscreen=-:::(true false)" \
    "--title=-:::( )" \
    "--class=-:::( )" \
    "--x11-instance-name=-:::( )" \
    "--working-directory=-:::{_files -/}" \
    "--keybind=-:::( )" \
    "--window-padding-x=-:::( )" \
    "--window-padding-y=-:::( )" \
    "--window-padding-balance=-:::(true false)" \
    "--window-padding-color=-:::(background extend extend-always)" \
    "--window-vsync=-:::(true false)" \
    "--window-inherit-working-directory=-:::(true false)" \
    "--window-inherit-font-size=-:::(true false)" \
    "--window-decoration=-:::(true false)" \
    "--window-title-font-family=-:::( )" \
    "--window-theme=-:::(auto system light dark ghostty)" \
    "--window-colorspace=-:::(srgb display-p3)" \
    "--window-height=-:::( )" \
    "--window-width=-:::( )" \
    "--window-save-state=-:::(default never always)" \
    "--window-step-resize=-:::(true false)" \
    "--window-new-tab-position=-:::(current end)" \
    "--resize-overlay=-:::(always never after-first)" \
"--resize-overlay-position=-:::(center top-left top-center top-right
bottom-left bottom-center bottom-right)" \
    "--resize-overlay-duration=-:::( )" \
    "--focus-follows-mouse=-:::(true false)" \
    "--clipboard-read=-:::(allow deny ask)" \
    "--clipboard-write=-:::(allow deny ask)" \
    "--clipboard-trim-trailing-spaces=-:::(true false)" \
    "--clipboard-paste-protection=-:::(true false)" \
    "--clipboard-paste-bracketed-safe=-:::(true false)" \
    "--image-storage-limit=-:::( )" \
    "--copy-on-select=-:::(false true clipboard)" \
    "--click-repeat-interval=-:::( )" \
    "--config-file=-:::_files" \
    "--config-default-files=-:::(true false)" \
    "--confirm-close-surface=-:::(true false)" \
    "--quit-after-last-window-closed=-:::(true false)" \
    "--quit-after-last-window-closed-delay=-:::( )" \
    "--initial-window=-:::(true false)" \
    "--quick-terminal-position=-:::(top bottom left right)" \
    "--quick-terminal-screen=-:::(main mouse macos-menu-bar)" \
    "--quick-terminal-animation-duration=-:::( )" \
    "--shell-integration=-:::(none detect bash elvish fish zsh)" \
"--shell-integration-features=-:::(cursor no-cursor sudo no-sudo title
no-title)" \
    "--osc-color-report-format=-:::(none 8-bit 16-bit)" \
    "--vt-kam-allowed=-:::(true false)" \
    "--custom-shader=-:::_files" \
    "--custom-shader-animation=-:::(false true always)" \
    "--macos-non-native-fullscreen=-:::(false true visible-menu)" \
    "--macos-titlebar-style=-:::(native transparent tabs hidden)" \
    "--macos-titlebar-proxy-icon=-:::(visible hidden)" \
    "--macos-option-as-alt=-:::(false true left right)" \
    "--macos-window-shadow=-:::(true false)" \
    "--macos-auto-secure-input=-:::(true false)" \
    "--macos-secure-input-indication=-:::(true false)" \
    "--linux-cgroup=-:::(never always single-instance)" \
    "--linux-cgroup-memory-limit=-:::( )" \
    "--linux-cgroup-processes-limit=-:::( )" \
    "--linux-cgroup-hard-fail=-:::(true false)" \
    "--gtk-single-instance=-:::(desktop false true)" \
    "--gtk-titlebar=-:::(true false)" \
    "--gtk-tabs-location=-:::(top bottom left right)" \
    "--adw-toolbar-style=-:::(flat raised raised-border)" \
    "--gtk-wide-tabs=-:::(true false)" \
    "--gtk-adwaita=-:::(true false)" \
    "--desktop-notifications=-:::(true false)" \
    "--bold-is-bright=-:::(true false)" \
    "--term=-:::( )" \
    "--enquiry-response=-:::( )" \
    "--auto-update=-:::(off check download)" \

}

_ghostty() {
  typeset -A opt_args
  local context state line
  local opt=('--help' '--version')

  _arguments -C \
    '1:actions:->actions' \
    '*:: :->rest' \

  if [[ "$line[1]" == "--help" || "$line[1]" == "--version" ]]; then
    return
  fi

  if [[ "$line[1]" == -* ]]; then
    _config
    return
  fi

  case "$state" in
    (actions)
      local actions; actions=(
        '+version'
        '+help'
        '+list-fonts'
        '+list-keybinds'
        '+list-themes'
        '+list-colors'
        '+list-actions'
        '+show-config'
        '+validate-config'
        '+crash-report'
      )
      _describe '' opt
      _describe -t action 'action' actions
    ;;
    (rest)
      if [[ "$line[2]" == "--help" ]]; then
        return
      fi

      local help=('--help')
      _describe '' help

      case $line[1] in
        (+list-fonts)
          _arguments \
            '--family=-:::( )' \
            '--style=-:::( )' \
            '--bold=-:::(true false)' \
            '--italic=-:::(true false)' \
        ;;
        (+list-keybinds)
          _arguments \
            '--default=-:::(true false)' \
            '--docs=-:::(true false)' \
            '--plain=-:::(true false)' \
        ;;
        (+list-themes)
          _arguments \
            '--path=-:::(true false)' \
            '--plain=-:::(true false)' \
        ;;
        (+list-actions)
          _arguments \
            '--docs=-:::(true false)' \
        ;;
        (+show-config)
          _arguments \
            '--default=-:::(true false)' \
            '--changes-only=-:::(true false)' \
            '--docs=-:::(true false)' \
        ;;
        (+validate-config)
          _arguments \
            '--config-file=-:::_files' \
        ;;
      esac
    ;;
  esac
}

_ghostty "$@"

  ```
</details>

I agree to relicense my commits to MIT
This commit is contained in:
Mitchell Hashimoto
2024-12-11 08:57:59 -08:00
committed by GitHub
6 changed files with 268 additions and 66 deletions

View File

@ -12,6 +12,7 @@ const terminfo = @import("src/terminfo/main.zig");
const config_vim = @import("src/config/vim.zig");
const config_sublime_syntax = @import("src/config/sublime_syntax.zig");
const fish_completions = @import("src/build/fish_completions.zig");
const zsh_completions = @import("src/build/zsh_completions.zig");
const build_config = @import("src/build_config.zig");
const BuildConfig = build_config.BuildConfig;
const WasmTarget = @import("src/os/wasm/target.zig").Target;
@ -504,6 +505,18 @@ pub fn build(b: *std.Build) !void {
});
}
// zsh shell completions
{
const wf = b.addWriteFiles();
_ = wf.add("_ghostty", zsh_completions.zsh_completions);
b.installDirectory(.{
.source_dir = wf.getDirectory(),
.install_dir = .prefix,
.install_subdir = "share/zsh/site-functions",
});
}
// Vim plugin
{
const wf = b.addWriteFiles();

View File

@ -2,9 +2,6 @@ const std = @import("std");
const Config = @import("../config/Config.zig");
const Action = @import("../cli/action.zig").Action;
const ListFontsConfig = @import("../cli/list_fonts.zig").Config;
const ShowConfigOptions = @import("../cli/show_config.zig").Options;
const ListKeybindsOptions = @import("../cli/list_keybinds.zig").Options;
/// A fish completions configuration that contains all the available commands
/// and options.
@ -100,66 +97,35 @@ fn writeFishCompletions(writer: anytype) !void {
try writer.writeAll("\"\n");
}
for (@typeInfo(ListFontsConfig).Struct.fields) |field| {
if (field.name[0] == '_') continue;
try writer.writeAll("complete -c ghostty -n \"__fish_seen_subcommand_from +list-fonts\" -l ");
try writer.writeAll(field.name);
try writer.writeAll(if (field.type != bool) " -r" else " ");
try writer.writeAll(" -f");
switch (@typeInfo(field.type)) {
.Bool => try writer.writeAll(" -a \"true false\""),
.Enum => |info| {
try writer.writeAll(" -a \"");
for (info.fields, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
try writer.writeAll("\"");
},
else => {},
}
try writer.writeAll("\n");
}
for (@typeInfo(Action).Enum.fields) |field| {
if (std.mem.eql(u8, "help", field.name)) continue;
if (std.mem.eql(u8, "version", field.name)) continue;
for (@typeInfo(ShowConfigOptions).Struct.fields) |field| {
if (field.name[0] == '_') continue;
try writer.writeAll("complete -c ghostty -n \"__fish_seen_subcommand_from +show-config\" -l ");
try writer.writeAll(field.name);
try writer.writeAll(if (field.type != bool) " -r" else " ");
try writer.writeAll(" -f");
switch (@typeInfo(field.type)) {
.Bool => try writer.writeAll(" -a \"true false\""),
.Enum => |info| {
try writer.writeAll(" -a \"");
for (info.fields, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
try writer.writeAll("\"");
},
else => {},
}
try writer.writeAll("\n");
}
const options = @field(Action, field.name).options();
for (@typeInfo(options).Struct.fields) |opt| {
if (opt.name[0] == '_') continue;
try writer.writeAll("complete -c ghostty -n \"__fish_seen_subcommand_from +" ++ field.name ++ "\" -l ");
try writer.writeAll(opt.name);
try writer.writeAll(if (opt.type != bool) " -r" else "");
for (@typeInfo(ListKeybindsOptions).Struct.fields) |field| {
if (field.name[0] == '_') continue;
try writer.writeAll("complete -c ghostty -n \"__fish_seen_subcommand_from +list-keybinds\" -l ");
try writer.writeAll(field.name);
try writer.writeAll(if (field.type != bool) " -r" else " ");
try writer.writeAll(" -f");
switch (@typeInfo(field.type)) {
.Bool => try writer.writeAll(" -a \"true false\""),
.Enum => |info| {
try writer.writeAll(" -a \"");
for (info.fields, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
try writer.writeAll("\"");
},
else => {},
// special case +validate_config --config-file
if (std.mem.eql(u8, "config-file", opt.name)) {
try writer.writeAll(" -F");
} else try writer.writeAll(" -f");
switch (@typeInfo(opt.type)) {
.Bool => try writer.writeAll(" -a \"true false\""),
.Enum => |info| {
try writer.writeAll(" -a \"");
for (info.opts, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
try writer.writeAll("\"");
},
else => {},
}
try writer.writeAll("\n");
}
try writer.writeAll("\n");
}
}

View File

@ -0,0 +1,201 @@
const std = @import("std");
const Config = @import("../config/Config.zig");
const Action = @import("../cli/action.zig").Action;
/// A zsh completions configuration that contains all the available commands
/// and options.
pub const zsh_completions = comptimeGenerateZshCompletions();
fn comptimeGenerateZshCompletions() []const u8 {
comptime {
@setEvalBranchQuota(19000);
var counter = std.io.countingWriter(std.io.null_writer);
try writeZshCompletions(&counter.writer());
var buf: [counter.bytes_written]u8 = undefined;
var stream = std.io.fixedBufferStream(&buf);
try writeZshCompletions(stream.writer());
const final = buf;
return final[0..stream.getWritten().len];
}
}
fn writeZshCompletions(writer: anytype) !void {
try writer.writeAll(
\\#compdef ghostty
\\
\\_fonts () {
\\ local font_list=$(ghostty +list-fonts | grep -Z '^[A-Z]')
\\ local fonts=(${(f)font_list})
\\ _describe -t fonts 'fonts' fonts
\\}
\\
\\_themes() {
\\ local theme_list=$(ghostty +list-themes | sed -E 's/^(.*) \(.*\$/\0/')
\\ local themes=(${(f)theme_list})
\\ _describe -t themes 'themes' themes
\\}
\\
);
try writer.writeAll("_config() {\n");
try writer.writeAll(" _arguments \\\n");
try writer.writeAll(" \"--help\" \\\n");
try writer.writeAll(" \"--version\" \\\n");
for (@typeInfo(Config).Struct.fields) |field| {
if (field.name[0] == '_') continue;
try writer.writeAll(" \"--");
try writer.writeAll(field.name);
try writer.writeAll("=-:::");
if (std.mem.startsWith(u8, field.name, "font-family"))
try writer.writeAll("_fonts")
else if (std.mem.eql(u8, "theme", field.name))
try writer.writeAll("_themes")
else if (std.mem.eql(u8, "working-directory", field.name))
try writer.writeAll("{_files -/}")
else if (field.type == Config.RepeatablePath)
try writer.writeAll("_files") // todo check if this is needed
else {
try writer.writeAll("(");
switch (@typeInfo(field.type)) {
.Bool => try writer.writeAll("true false"),
.Enum => |info| {
for (info.fields, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
},
.Struct => |info| {
if (!@hasDecl(field.type, "parseCLI") and info.layout == .@"packed") {
for (info.fields, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
try writer.writeAll(" no-");
try writer.writeAll(f.name);
}
} else {
//resize-overlay-duration
//keybind
//window-padding-x ...-y
//link
//palette
//background
//foreground
//font-variation*
//font-feature
try writer.writeAll(" ");
}
},
else => try writer.writeAll(" "),
}
try writer.writeAll(")");
}
try writer.writeAll("\" \\\n");
}
try writer.writeAll("\n}\n\n");
try writer.writeAll(
\\_ghostty() {
\\ typeset -A opt_args
\\ local context state line
\\ local opt=('--help' '--version')
\\
\\ _arguments -C \
\\ '1:actions:->actions' \
\\ '*:: :->rest' \
\\
\\ if [[ "$line[1]" == "--help" || "$line[1]" == "--version" ]]; then
\\ return
\\ fi
\\
\\ if [[ "$line[1]" == -* ]]; then
\\ _config
\\ return
\\ fi
\\
\\ case "$state" in
\\ (actions)
\\ local actions; actions=(
\\
);
{
// how to get 'commands'
var count: usize = 0;
const padding = " ";
for (@typeInfo(Action).Enum.fields) |field| {
try writer.writeAll(padding ++ "'+");
try writer.writeAll(field.name);
try writer.writeAll("'\n");
count += 1;
}
}
try writer.writeAll(
\\ )
\\ _describe '' opt
\\ _describe -t action 'action' actions
\\ ;;
\\ (rest)
\\ if [[ "$line[2]" == "--help" ]]; then
\\ return
\\ fi
\\
\\ local help=('--help')
\\ _describe '' help
\\
\\ case $line[1] in
\\
);
{
const padding = " ";
for (@typeInfo(Action).Enum.fields) |field| {
if (std.mem.eql(u8, "help", field.name)) continue;
if (std.mem.eql(u8, "version", field.name)) continue;
const options = @field(Action, field.name).options();
// assumes options will never be created with only <_name> members
if (@typeInfo(options).Struct.fields.len == 0) continue;
try writer.writeAll(padding ++ "(+" ++ field.name ++ ")\n");
try writer.writeAll(padding ++ " _arguments \\\n");
for (@typeInfo(options).Struct.fields) |opt| {
if (opt.name[0] == '_') continue;
try writer.writeAll(padding ++ " '--");
try writer.writeAll(opt.name);
try writer.writeAll("=-:::");
switch (@typeInfo(opt.type)) {
.Bool => try writer.writeAll("(true false)"),
.Enum => |info| {
try writer.writeAll("(");
for (info.opts, 0..) |f, i| {
if (i > 0) try writer.writeAll(" ");
try writer.writeAll(f.name);
}
try writer.writeAll(")");
},
else => {
if (std.mem.eql(u8, "config-file", opt.name)) {
try writer.writeAll("_files");
} else try writer.writeAll("( )");
},
}
try writer.writeAll("' \\\n");
}
try writer.writeAll(padding ++ ";;\n");
}
}
try writer.writeAll(
\\ esac
\\ ;;
\\ esac
\\}
\\
\\_ghostty "$@"
\\
);
}

View File

@ -163,6 +163,26 @@ pub const Action = enum {
return "cli/" ++ filename ++ ".zig";
}
}
/// Returns the options of action. Supports generating shell completions
/// without duplicating the mapping from Action to relevant Option
/// @import(..) declaration.
pub fn options(comptime self: Action) type {
comptime {
return switch (self) {
.version => version.Options,
.help => help.Options,
.@"list-fonts" => list_fonts.Options,
.@"list-keybinds" => list_keybinds.Options,
.@"list-themes" => list_themes.Options,
.@"list-colors" => list_colors.Options,
.@"list-actions" => list_actions.Options,
.@"show-config" => show_config.Options,
.@"validate-config" => validate_config.Options,
.@"crash-report" => crash_report.Options,
};
}
}
};
test "parse action none" {

View File

@ -7,7 +7,7 @@ const font = @import("../font/main.zig");
const log = std.log.scoped(.list_fonts);
pub const Config = struct {
pub const Options = struct {
/// This is set by the CLI parser for deinit.
_arena: ?ArenaAllocator = null,
@ -23,13 +23,13 @@ pub const Config = struct {
bold: bool = false,
italic: bool = false,
pub fn deinit(self: *Config) void {
pub fn deinit(self: *Options) void {
if (self._arena) |arena| arena.deinit();
self.* = undefined;
}
/// Enables "-h" and "--help" to work.
pub fn help(self: Config) !void {
pub fn help(self: Options) !void {
_ = self;
return Action.help_error;
}
@ -59,9 +59,9 @@ pub fn run(alloc: Allocator) !u8 {
}
fn runArgs(alloc_gpa: Allocator, argsIter: anytype) !u8 {
var config: Config = .{};
var config: Options = .{};
defer config.deinit();
try args.parse(Config, alloc_gpa, &config, argsIter);
try args.parse(Options, alloc_gpa, &config, argsIter);
// Use an arena for all our memory allocs
var arena = ArenaAllocator.init(alloc_gpa);

View File

@ -7,6 +7,8 @@ const xev = @import("xev");
const renderer = @import("../renderer.zig");
const gtk = if (build_config.app_runtime == .gtk) @import("../apprt/gtk/c.zig").c else void;
pub const Options = struct {};
/// The `version` command is used to display information about Ghostty.
pub fn run(alloc: Allocator) !u8 {
_ = alloc;