You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现支持冒号开头参数的zsh命令补全?

Zsh补全:支持自定义工具的:C和多追加:C格式

问题拆解

现有补全逻辑未覆盖两个核心场景:

  • 独立的:C格式参数(比如直接输入:addon1)
  • 无限追加:C的链式参数(比如A:B:C:C:C)
    同时未配置支持多个spec参数同时传入(比如:addon2 build1:test1这种用法)

修复后的完整代码

#compdef _hello hello

function _hello {
    local curcontext="$curcontext" state line
    local suf args builds tests addons
    typeset -A opt_args

    builds=('build1' 'build2' 'build3')
    tests=('test1' 'test2' 'test3')
    addons=('addon1' 'addon2' 'addon3')

    args=(
        '-i[option i]' \
        '-p[option p]' \
        '-R[option R]' \
    )

    # 允许同时传入多个spec参数
    args+=('*:build group or test spec:->dospec')

    _arguments -C -s $args && return 0

    case "$state" in
      dospecrmremPAStxl成部分 express�ummy�com}随意Calculate补全逻辑
      dospec)
        # 处理以冒号开头的情况(比如输入:后补addons)
        if compset -P ':'; then
            _values "addons" $addons
        # 处理前缀以冒号结尾的所有情况
        elif compset -P '*[:]'; then
            # 统计前缀里的冒号数量
            local colon_count=$(echo "$IPREFIX" | tr -cd ':' | wc -c)
            if [[ $colon_count -eq 1 ]]; then
                # 只有一个冒号(比如build1:),补tests
                _values "tests" $tests
            else
                # 两个及以上冒号(比如build1:test1:、:addon1:),一直补addons
                _values "addons" $addons
            fi
        else
            # 无冒号前缀,补builds并自动加冒号后缀
            suf=( -qS ':' )
            _wanted "builds" expl "build" compadd $suf[@] $builds
        fi
      ;;
    esac
}

核心调整说明

  1. 支持多spec参数:把原来的单个位置参数改成*:前缀,让zsh识别可传入任意多个spec参数,适配hello :addon2 build1:test1这类用法。
  2. 冒号开头的补全:新增compset -P ':'判断,当光标前是单独的冒号时,直接补全addons集合。
  3. 动态判断冒号层级:通过统计前缀中的冒号数量决定补全集:
    • 1个冒号(如build1:):补tests
    • 2个及以上冒号(不管是A:B:还是:C:还是A:B:C:):持续补addons,支持无限追加:C格式
  4. 简化逻辑结构:移除原冗余的compset -S判断,统一通过前缀冒号的情况处理,逻辑更清晰。

验证场景

修改后可完美覆盖所有需求示例:

  • hello : → 补全addon1/addon2/addon3
  • hello build1: → 补全test1/test2/test3
  • hello build1:test1: → 补全addons,且输入addon1:后仍可继续补addons
  • hello :add → 补全匹配的addons
  • hello build1 :add → 补全addons

内容的提问来源于stack exchange,提问作者Kurt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:54:52