Zsh Shell

Friday, October 29, 2021

1. 给zsh添加自定义补全

  1. 在.zshrc添加补全激活

    $ vim ~/.zshrc
    ...
    autoload -U compinit
    compinit
    ...
    
  2. 查看fpath, 选择一个写脚本的地方

    $ print -rl -- $fpath
    /Users/xxx/.oh-my-zsh/plugins/vi-mode
    /Users/xxx/.oh-my-zsh/plugins/zsh-syntax-highlighting
    /Users/xxx/.oh-my-zsh/plugins/zsh-autosuggestions
    /Users/xxx/.oh-my-zsh/plugins/git
    /Users/xxx/.oh-my-zsh/plugins/z
    /Users/xxx/.oh-my-zsh/functions
    /Users/xxx/.oh-my-zsh/completions
    /Users/xxx/.oh-my-zsh/plugins/vi-mode
    /Users/xxx/.oh-my-zsh/plugins/zsh-syntax-highlighting
    /Users/xxx/.oh-my-zsh/plugins/zsh-autosuggestions
    /Users/xxx/.oh-my-zsh/plugins/git
    /Users/xxx/.oh-my-zsh/plugins/z
    /Users/xxx/.oh-my-zsh/functions
    /Users/xxx/.oh-my-zsh/completions
    /usr/local/share/zsh/site-functions
    /usr/share/zsh/site-functions
    /usr/share/zsh/5.8/functions
    
  3. 如果没有想要放置的目录,就把自定义的目录(此处是~/newdir)添加到fpath

    # zsh
    $ vim ~/.zshrc
    ...
    fpath=(~/newdir $fpath)
    ...
    
    # zsh
    $ print -rl -- $fpath
    ...
    /usr/share/zsh/site-functions
    /usr/share/zsh/5.8/functions
    /Users/xxx/newdir
    
  4. 在你自定义的目录下添加补全方法

    1. 定义方法

      # zsh
      $ vim /Users/xxx/newdir/_yourFunc
      
      #compdef _yourFunc yourAimFunc1 yourAimFunc2 ...  # 这行不能少, 自动加载补全到你的命令, 且'#'必须紧挨compdef, 否则无法注册函数
      
      function _yourFunc {
          compadd api mqtt interval kafka ftp celery  # 给命令添加候选项
          # 详见 https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org
      }
      
      _yourFunc
      
    2. 刷新zsh

      $ source ~/.zshrc
      
  5. 测试

    $ yourAimFunc1 <Tab>
    api       celery    ftp       interval  kafka     mqtt