npm 和 git 补全噢😯 npm <Tab> 会补全命令
npm实现代码 https://github.com/npm/npm/blob/master/lib/utils/completion.sh
or
npm completion git 实现代码
分终端(zsh,bash..) 分实现文件 https://github.com/git/git/blob/master/contrib/completion/
因为npm 的实现文件只有一个,懒为主。
我的是 zsh
首先定义一个可执行文件 sh
test_completion.sh
if type compdef &>/dev/null; then _test_completion() { } compdef _test_completion npm 当你运行上面 什么都没有的 文件时
or 复制 then 后面那段代码,粘贴到 命令行运行也可以。
之前npm <Tab> 的 提示就会没有
## 代码分解
if type
是为了判断 compdef 是否存在 这是 zsh 定义的 函数命令
&>/del/null
应该是把 错误 文件化 放到 /dev/null
compdef _test_completion npm
这里有三个变量
compdef 是 函数调用
_test_completion 是 compdef 的第一个变量,用来定义 补全规则
compdef(_test_completion)
npm 是 compdef 的第二个变量。补全对象 compdef( _test_completion, npm )
只要把 npm 替换成 git 那么,
git 的 补全命令 也会被替换 什么都没有。
补全规则 _test_completion(){ } zsh 实现了 简便的 命令添加-函数
compadd 源代码中主要
compadd -- $(COMP_CWORD=$((CURRENT-1)) \ COMP_LINE=$BUFFER \ COMP_POINT=0 \ npm completion -- "${words[@]}" \ 2>/dev/null) 这样的 ,不难看出 – $ 后面就是 compadd函数 - 变量定义
源文档太大了,截掉什么看看区别
当我把 npm completion -- "${words[@]}" \ 剪掉
npm <Tab>什么提示都没有了,看来这就是秘密。
不过我们看了终点,不如回到原点。加加看
示例
_test_completion() { compadd -- install } compdef _test_completion npm $ npm <tab> $ npm install 噢 那么就会提示 install
再试试
_test_completion() { echo "${words[@]}" echo $CURRENT echo $BUFFER compadd -- install up } compdef _test_completion npm
...