diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index ff55f36be..7c1cb8967 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,7 +1,7 @@ --- name: Bug report -about: Create a report to help us improve -labels: 'Type: bug' +about: Create a report to help us improve Oh My Zsh +labels: 'Type: support' --- @@ -11,29 +11,26 @@ an issue where no sections have been filled will be deleted without comment. --> **Describe the bug** - +A clear description of what the bug is. **To Reproduce** - **Expected behavior** - +A brief description of what should happen. -**Screenshots or recordings** - +**Screenshots and/or Recordings** +If applicable, add screenshots to help explain your problem. +You can also record an asciinema session: https://asciinema.org/ -**System:** - - OS: [e.g. macOS] - - Zsh version [e.g. 5.6] +**Desktop (please complete the following information):** + - OS / Distro: [e.g. Arch Linux, macOS] + - Latest ohmyzsh Update?: [e.g. Yes/No] + - ZSH Version: [e.g. 5.6] - Terminal emulator [e.g. iTerm2] **Additional context** - +Add any other context about the problem here. This can be themes, plugins, custom configs. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index d9c324a55..346eabaea 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -11,16 +11,16 @@ an issue where no sections have been filled will be deleted without comment. --> **Is your feature request related to a particular plugin or theme? If so, specify it.** - +The name of the plugin or theme that you would like us to improve. [...] **Is your feature request related to a problem? Please describe.** - +A description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** - +A description of what you want to happen. **Describe alternatives you've considered** - +A description of any alternative solutions or features you've considered. This can also include other plugins or aliases. **Additional context** - +Add any other context or screenshots about the feature request here. Also if you have any PRs related to this issue that are already open that you would like us to look at. diff --git a/.github/ISSUE_TEMPLATE/support.md b/.github/ISSUE_TEMPLATE/support.md index 3c69a7d5e..d2638412e 100644 --- a/.github/ISSUE_TEMPLATE/support.md +++ b/.github/ISSUE_TEMPLATE/support.md @@ -5,8 +5,6 @@ labels: 'Type: support' --- - diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..6bcb90efe --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,17 @@ +## Standards checklist: + +- [ ] The PR title is descriptive. +- [ ] The PR doesn't replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [ ] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] The code is efficient, to the best of my ability, and does not waste computer resources. +- [ ] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +- [...] + +## Other comments: + +... diff --git a/.github/main.workflow b/.github/main.workflow deleted file mode 100644 index 0dbb0247a..000000000 --- a/.github/main.workflow +++ /dev/null @@ -1,17 +0,0 @@ -workflow "Triage Pull Request" { - on = "pull_request" - resolves = ["Triage"] -} - -# Only act if there are code changes: if the pull_request -# event's action is either 'opened' (new PR) or 'synchronize' (new commits) -action "Filter actions" { - uses = "actions/bin/filter@0ac6d44" - args = "action 'opened|synchronize'" -} - -action "Triage" { - needs = ["Filter actions"] - uses = "ohmyzsh/github-actions/pull-request-triage@master" - secrets = ["GITHUB_TOKEN"] -} diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 000000000..7ab7efdd6 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,36 @@ +name: CI +on: + pull_request: + types: + - opened + - synchronize + branches: + - master + push: + branches: + - master + +jobs: + tests: + name: Run tests + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - name: Set up git repository + uses: actions/checkout@v2 + - name: Install zsh + if: runner.os == 'Linux' + run: sudo apt-get update; sudo apt-get install zsh + - name: Test installer + run: sh ./tools/install.sh + - name: Check syntax + run: | + for file in ./oh-my-zsh.sh \ + ./lib/*.zsh \ + ./plugins/*/*.plugin.zsh \ + ./plugins/*/_* \ + ./themes/*.zsh-theme; do + zsh -n "$file" || return 1 + done diff --git a/.gitignore b/.gitignore index 87a79cdae..ec24a19bb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ custom/ # temp files directories cache/ log/ +*.swp +.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f575157c2..be67e93b0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,7 +31,7 @@ your problem. If you find one, comment on it so we can know there are more people experiencing it. -If not, look at the [Troubleshooting](https://github.com/robbyrussell/oh-my-zsh/wiki/Troubleshooting) +If not, look at the [Troubleshooting](https://github.com/ohmyzsh/ohmyzsh/wiki/Troubleshooting) page for instructions on how to gather data to better debug your problem. Then, you can go ahead and create an issue with as much detail as you can provide. @@ -62,7 +62,7 @@ maintainers) by mentioning their GitHub handle (starting with `@`) in your messa You should be familiar with the basics of [contributing on GitHub](https://help.github.com/articles/using-pull-requests) and have a fork -[properly set up](https://github.com/robbyrussell/oh-my-zsh/wiki/Contribution-Technical-Practices). +[properly set up](https://github.com/ohmyzsh/ohmyzsh/wiki/Contribution-Technical-Practices). You MUST always create PRs with _a dedicated branch_ based on the latest upstream tree. @@ -85,7 +85,7 @@ maintainers) by mentioning their GitHub handle (starting with `@`) in your messa ### You have an addition -Please [do not](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes#dont-send-us-your-theme-for-now) +Please [do not](https://github.com/ohmyzsh/ohmyzsh/wiki/Themes#dont-send-us-your-theme-for-now) send themes for now. Please be so kind as to [search](#use-the-search-luke) for any pending, merged or rejected Pull Requests @@ -109,7 +109,7 @@ to help you check whether a similar contribution to yours already exists. Please before making any contribution, it avoids duplicates and eases maintenance. Trust me, that works 90% of the time. -You can also take a look at the [FAQ](https://github.com/robbyrussell/oh-my-zsh/wiki/FAQ) +You can also take a look at the [FAQ](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ) to be sure your contribution has not already come up. If all fails, your thing has probably not been reported yet, so you can go ahead @@ -121,5 +121,5 @@ and [create an issue](#reporting-issues) or [submit a PR](#submitting-pull-reque Very nice!! :) -Please have a look at the [Volunteer](https://github.com/robbyrussell/oh-my-zsh/wiki/Volunteers) +Please have a look at the [Volunteer](https://github.com/ohmyzsh/ohmyzsh/wiki/Volunteers) page for instructions on where to start and more. diff --git a/LICENSE.txt b/LICENSE.txt index 4d465b1c3..45ba85a37 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,7 +1,6 @@ -The MIT License (MIT) +MIT License -Copyright (c) 2009-2019 Robby Russell and contributors -See the full list at https://github.com/robbyrussell/oh-my-zsh/contributors +Copyright (c) 2009-2020 Robby Russell and contributors (https://github.com/ohmyzsh/ohmyzsh/contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 78a5b56bd..187cceb7d 100644 --- a/README.md +++ b/README.md @@ -12,16 +12,18 @@ Once installed, your terminal shell will become the talk of the town _or your mo Finally, you'll begin to get the sort of attention that you have always felt you deserved. ...or maybe you'll use the time that you're saving to start flossing more often. ๐Ÿ˜ฌ -To learn more, visit [ohmyz.sh](https://ohmyz.sh) and follow [@ohmyzsh](https://twitter.com/ohmyzsh) on Twitter. +To learn more, visit [ohmyz.sh](https://ohmyz.sh), follow [@ohmyzsh](https://twitter.com/ohmyzsh) on Twitter, and/or join us on Discord. + +[![CI](https://github.com/ohmyzsh/ohmyzsh/workflows/CI/badge.svg)](https://github.com/ohmyzsh/ohmyzsh/actions?query=workflow%3ACI) +[![Follow @ohmyzsh](https://img.shields.io/twitter/follow/ohmyzsh?label=Follow+@ohmyzsh&style=flat)](https://twitter.com/intent/follow?screen_name=ohmyzsh) +[![Discord server](https://img.shields.io/discord/642496866407284746)](https://discord.gg/bpXWhnN) ## Getting Started ### Prerequisites -__Disclaimer:__ _Oh My Zsh works best on macOS and Linux._ - -* Unix-like operating system (macOS or Linux) -* [Zsh](https://www.zsh.org) should be installed (v4.3.9 or more recent). If not pre-installed (`zsh --version` to confirm), check the following instruction here: [Installing ZSH](https://github.com/robbyrussell/oh-my-zsh/wiki/Installing-ZSH) +* A Unix-like operating system: macOS, Linux, BSD. On Windows: WSL is preferred, but cygwin or msys also mostly work. +* [Zsh](https://www.zsh.org) should be installed (v4.3.9 or more recent). If not pre-installed (run `zsh --version` to confirm), check the following instructions here: [Installing ZSH](https://github.com/ohmyzsh/ohmyzsh/wiki/Installing-ZSH) * `curl` or `wget` should be installed * `git` should be installed @@ -32,13 +34,13 @@ Oh My Zsh is installed by running one of the following commands in your terminal #### via curl ```shell -sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" +sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" ``` #### via wget ```shell -sh -c "$(wget -O- https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" +sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" ``` #### Manual inspection @@ -48,7 +50,7 @@ that by downloading the install script first, looking through it so everything l then running it: ```shell -curl -Lo install.sh https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh +curl -Lo install.sh https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh sh install.sh ``` @@ -56,7 +58,7 @@ sh install.sh ### Plugins -Oh My Zsh comes with a shitload of plugins to take advantage of. You can take a look in the [plugins](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins) directory and/or the [wiki](https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins) to see what's currently available. +Oh My Zsh comes with a shitload of plugins to take advantage of. You can take a look in the [plugins](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins) directory and/or the [wiki](https://github.com/ohmyzsh/ohmyzsh/wiki/Plugins) to see what's currently available. #### Enabling Plugins @@ -88,7 +90,7 @@ Most plugins (should! we're working on this) include a __README__, which documen ### Themes -We'll admit it. Early in the Oh My Zsh world, we may have gotten a bit too theme happy. We have over one hundred themes now bundled. Most of them have [screenshots](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes) on the wiki. Check them out! +We'll admit it. Early in the Oh My Zsh world, we may have gotten a bit too theme happy. We have over one hundred themes now bundled. Most of them have [screenshots](https://github.com/ohmyzsh/ohmyzsh/wiki/Themes) on the wiki. Check them out! #### Selecting a Theme @@ -104,7 +106,7 @@ To use a different theme, simply change the value to match the name of your desi ```shell ZSH_THEME="agnoster" # (this is one of the fancy ones) -# see https://github.com/robbyrussell/oh-my-zsh/wiki/Themes#agnoster +# see https://github.com/ohmyzsh/ohmyzsh/wiki/Themes#agnoster ``` _Note: many themes require installing the [Powerline Fonts](https://github.com/powerline/fonts) in order to render properly._ @@ -113,7 +115,7 @@ Open up a new terminal window and your prompt should look something like this: ![Agnoster theme](https://cloud.githubusercontent.com/assets/2618447/6316862/70f58fb6-ba03-11e4-82c9-c083bf9a6574.png) -In case you did not find a suitable theme for your needs, please have a look at the wiki for [more of them](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes). +In case you did not find a suitable theme for your needs, please have a look at the wiki for [more of them](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes). If you're feeling feisty, you can let the computer select one randomly for you each time you open a new terminal window. @@ -131,6 +133,10 @@ ZSH_THEME_RANDOM_CANDIDATES=( ) ``` +### FAQ + +If you have some more questions or issues, you might find a solution in our [FAQ](https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ). + ## Advanced Topics If you're the type that likes to get their hands dirty, these sections might resonate. @@ -159,14 +165,14 @@ flag `--unattended` to the `install.sh` script. This will have the effect of not the default shell, and also won't run `zsh` when the installation has finished. ```shell -sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" "" --unattended +sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended ``` #### Installing from a forked repository The install script also accepts these variables to allow installation of a different repository: -- `REPO` (default: `robbyrussell/oh-my-zsh`): this takes the form of `owner/repository`. If you set +- `REPO` (default: `ohmyzsh/ohmyzsh`): this takes the form of `owner/repository`. If you set this variable, the installer will look for a repository at `https://github.com/{owner}/{repository}`. - `REMOTE` (default: `https://github.com/${REPO}.git`): this is the full URL of the git repository @@ -190,7 +196,7 @@ REPO=apjanke/oh-my-zsh BRANCH=edge sh install.sh ##### 1. Clone the repository: ```shell -git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh +git clone https://github.com/ohmyzsh/ohmyzsh.git ~/.oh-my-zsh ``` ##### 2. *Optionally*, backup your existing `~/.zshrc` file: @@ -272,13 +278,13 @@ Before you participate in our delightful community, please read the [code of con I'm far from being a [Zsh](https://www.zsh.org/) expert and suspect there are many ways to improve โ€“ if you have ideas on how to make the configuration easier to maintain (and faster), don't hesitate to fork and send pull requests! -We also need people to test out pull-requests. So take a look through [the open issues](https://github.com/robbyrussell/oh-my-zsh/issues) and help where you can. +We also need people to test out pull-requests. So take a look through [the open issues](https://github.com/ohmyzsh/ohmyzsh/issues) and help where you can. See [Contributing](CONTRIBUTING.md) for more details. ### Do NOT send us themes -We have (more than) enough themes for the time being. Please add your theme to the [external themes](https://github.com/robbyrussell/oh-my-zsh/wiki/External-themes) wiki page. +We have (more than) enough themes for the time being. Please add your theme to the [external themes](https://github.com/ohmyzsh/ohmyzsh/wiki/External-themes) wiki page. ## Contributors diff --git a/lib/clipboard.zsh b/lib/clipboard.zsh index 333f58dd8..6102f3324 100644 --- a/lib/clipboard.zsh +++ b/lib/clipboard.zsh @@ -54,7 +54,7 @@ function detect-clipboard() { if [[ "${OSTYPE}" == darwin* ]] && (( ${+commands[pbcopy]} )) && (( ${+commands[pbpaste]} )); then function clipcopy() { pbcopy < "${1:-/dev/stdin}"; } function clippaste() { pbpaste; } - elif [[ "${OSTYPE}" == cygwin* ]]; then + elif [[ "${OSTYPE}" == (cygwin|msys)* ]]; then function clipcopy() { cat "${1:-/dev/stdin}" > /dev/clipboard; } function clippaste() { cat /dev/clipboard; } elif [ -n "${WAYLAND_DISPLAY:-}" ] && (( ${+commands[wl-copy]} )) && (( ${+commands[wl-paste]} )); then diff --git a/lib/completion.zsh b/lib/completion.zsh index c7db2eb7b..c932bc925 100644 --- a/lib/completion.zsh +++ b/lib/completion.zsh @@ -71,3 +71,6 @@ if [[ $COMPLETION_WAITING_DOTS = true ]]; then zle -N expand-or-complete-with-dots bindkey "^I" expand-or-complete-with-dots fi + +# automatically load bash completion functions +autoload -Uz bashcompinit && bashcompinit diff --git a/lib/functions.zsh b/lib/functions.zsh index 9f8736bd7..91e9cf895 100644 --- a/lib/functions.zsh +++ b/lib/functions.zsh @@ -3,11 +3,12 @@ function zsh_stats() { } function uninstall_oh_my_zsh() { - env ZSH=$ZSH sh $ZSH/tools/uninstall.sh + env ZSH="$ZSH" sh "$ZSH/tools/uninstall.sh" } function upgrade_oh_my_zsh() { - env ZSH=$ZSH sh $ZSH/tools/upgrade.sh + env ZSH="$ZSH" sh "$ZSH/tools/upgrade.sh" + rm -rf "$ZSH/log/update.lock" } function take() { @@ -21,7 +22,7 @@ function open_command() { case "$OSTYPE" in darwin*) open_cmd='open' ;; cygwin*) open_cmd='cygstart' ;; - linux*) ! [[ $(uname -a) =~ "Microsoft" ]] && open_cmd='xdg-open' || { + linux*) [[ "$(uname -r)" != *icrosoft* ]] && open_cmd='nohup xdg-open' || { open_cmd='cmd.exe /c start ""' [[ -e "$1" ]] && { 1="$(wslpath -w "${1:a}")" || return 1 } } ;; @@ -31,12 +32,7 @@ function open_command() { ;; esac - # don't use nohup on OSX - if [[ "$OSTYPE" == darwin* ]]; then - ${=open_cmd} "$@" &>/dev/null - else - nohup ${=open_cmd} "$@" &>/dev/null - fi + ${=open_cmd} "$@" &>/dev/null } # diff --git a/lib/git.zsh b/lib/git.zsh index 640561e97..00cb00b19 100644 --- a/lib/git.zsh +++ b/lib/git.zsh @@ -12,11 +12,21 @@ function git_prompt_info() { function parse_git_dirty() { local STATUS local -a FLAGS - FLAGS=('--porcelain' '--ignore-submodules=dirty') + FLAGS=('--porcelain') if [[ "$(command git config --get oh-my-zsh.hide-dirty)" != "1" ]]; then if [[ "$DISABLE_UNTRACKED_FILES_DIRTY" == "true" ]]; then FLAGS+='--untracked-files=no' fi + case "$GIT_STATUS_IGNORE_SUBMODULES" in + git) + # let git decide (this respects per-repo config in .gitmodules) + ;; + *) + # if unset: ignore dirty submodules + # other values are passed to --ignore-submodules + FLAGS+="--ignore-submodules=${GIT_STATUS_IGNORE_SUBMODULES:-dirty}" + ;; + esac STATUS=$(command git status ${FLAGS} 2> /dev/null | tail -n1) fi if [[ -n $STATUS ]]; then @@ -189,3 +199,12 @@ function git_current_user_name() { function git_current_user_email() { command git config user.email 2>/dev/null } + +# Output the name of the root directory of the git repository +# Usage example: $(git_repo_name) +function git_repo_name() { + local repo_path + if repo_path="$(git rev-parse --show-toplevel 2>/dev/null)" && [[ -n "$repo_path" ]]; then + echo ${repo_path:t} + fi +} diff --git a/lib/misc.zsh b/lib/misc.zsh index 40ffa479d..61571afc9 100644 --- a/lib/misc.zsh +++ b/lib/misc.zsh @@ -22,7 +22,7 @@ env_default 'PAGER' 'less' env_default 'LESS' '-R' ## super user alias -alias _='sudo' +alias _='sudo ' ## more intelligent acking for ubuntu users if which ack-grep &> /dev/null; then @@ -31,10 +31,5 @@ else alias afind='ack -il' fi -# only define LC_CTYPE if undefined -if [[ -z "$LC_CTYPE" && -z "$LC_ALL" ]]; then - export LC_CTYPE=${LANG%%:*} # pick the first entry from LANG -fi - # recognize comments setopt interactivecomments diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh index aa14f3f07..f5e367fcb 100644 --- a/lib/termsupport.zsh +++ b/lib/termsupport.zsh @@ -75,8 +75,9 @@ function omz_termsupport_preexec { title '$CMD' '%100>...>$LINE%<<' } -precmd_functions+=(omz_termsupport_precmd) -preexec_functions+=(omz_termsupport_preexec) +autoload -U add-zsh-hook +add-zsh-hook precmd omz_termsupport_precmd +add-zsh-hook preexec omz_termsupport_preexec # Keep Apple Terminal.app's current working directory updated @@ -99,7 +100,7 @@ if [[ "$TERM_PROGRAM" == "Apple_Terminal" ]] && [[ -z "$INSIDE_EMACS" ]]; then } # Use a precmd hook instead of a chpwd hook to avoid contaminating output - precmd_functions+=(update_terminalapp_cwd) + add-zsh-hook precmd update_terminalapp_cwd # Run once to get initial cwd set update_terminalapp_cwd fi diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh index 6b2662d5e..30259372c 100644 --- a/oh-my-zsh.sh +++ b/oh-my-zsh.sh @@ -32,8 +32,8 @@ fi is_plugin() { local base_dir=$1 local name=$2 - test -f $base_dir/plugins/$name/$name.plugin.zsh \ - || test -f $base_dir/plugins/$name/_$name + builtin test -f $base_dir/plugins/$name/$name.plugin.zsh \ + || builtin test -f $base_dir/plugins/$name/_$name } # Add all defined plugins to fpath. This must be done @@ -97,25 +97,12 @@ done unset config_file # Load the theme -if [[ "$ZSH_THEME" == "random" ]]; then - if [[ "${(t)ZSH_THEME_RANDOM_CANDIDATES}" = "array" ]] && [[ "${#ZSH_THEME_RANDOM_CANDIDATES[@]}" -gt 0 ]]; then - themes=($ZSH/themes/${^ZSH_THEME_RANDOM_CANDIDATES}.zsh-theme) +if [ ! "$ZSH_THEME" = "" ]; then + if [ -f "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" ]; then + source "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" + elif [ -f "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" ]; then + source "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" else - themes=($ZSH/themes/*zsh-theme) - fi - N=${#themes[@]} - ((N=(RANDOM%N)+1)) - RANDOM_THEME=${themes[$N]} - source "$RANDOM_THEME" - echo "[oh-my-zsh] Random theme '$RANDOM_THEME' loaded..." -else - if [ ! "$ZSH_THEME" = "" ]; then - if [ -f "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" ]; then - source "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" - elif [ -f "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" ]; then - source "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" - else - source "$ZSH/themes/$ZSH_THEME.zsh-theme" - fi + source "$ZSH/themes/$ZSH_THEME.zsh-theme" fi fi diff --git a/plugins/alias-finder/README.md b/plugins/alias-finder/README.md new file mode 100644 index 000000000..409f4b653 --- /dev/null +++ b/plugins/alias-finder/README.md @@ -0,0 +1,46 @@ +# alias-finder plugin + +This plugin searches the defined aliases and outputs any that match the command inputted. This makes learning new aliases easier. + +To use it, add `alias-finder` to the `plugins` array of your zshrc file: +``` +plugins=(... alias-finder) +``` + +## Usage +To see if there is an alias defined for the command, pass it as an argument to `alias-finder`. This can also run automatically before each command you input - add `ZSH_ALIAS_FINDER_AUTOMATIC=true` to your zshrc if you want this. + +## Options + +- Use `--longer` or `-l` to allow the aliases to be longer than the input (match aliases if they contain the input). +- Use `--exact` or `-e` to avoid matching aliases that are shorter than the input. + +## Examples +``` +$ alias-finder "git pull" +gl='git pull' +g=git +``` +``` +$ alias-finder "web_search google oh my zsh" +google='web_search google' +``` +``` +$ alias-finder "git commit -v" +gc="git commit -v" +g=git +``` +``` +$ alias-finder -e "git commit -v" +gc='git commit -v' +``` +``` +$ alias-finder -l "git commit -v" +gc='git commit -v' +'gc!'='git commit -v --amend' +gca='git commit -v -a' +'gca!'='git commit -v -a --amend' +'gcan!'='git commit -v -a --no-edit --amend' +'gcans!'='git commit -v -a -s --no-edit --amend' +'gcn!'='git commit -v --no-edit --amend' +``` diff --git a/plugins/alias-finder/alias-finder.plugin.zsh b/plugins/alias-finder/alias-finder.plugin.zsh new file mode 100644 index 000000000..caee9b5a3 --- /dev/null +++ b/plugins/alias-finder/alias-finder.plugin.zsh @@ -0,0 +1,47 @@ +alias-finder() { + local cmd="" exact="" longer="" wordStart="" wordEnd="" multiWordEnd="" + for i in $@; do + case $i in + -e|--exact) exact=true;; + -l|--longer) longer=true;; + *) + if [[ -z $cmd ]]; then + cmd=$i + else + cmd="$cmd $i" + fi + ;; + esac + done + cmd=$(sed 's/[].\|$(){}?+*^[]/\\&/g' <<< $cmd) # adds escaping for grep + if (( $(wc -l <<< $cmd) == 1 )); then + while [[ $cmd != "" ]]; do + if [[ $longer = true ]]; then + wordStart="'{0,1}" + else + wordEnd="$" + multiWordEnd="'$" + fi + if [[ $cmd == *" "* ]]; then + local finder="'$cmd$multiWordEnd" + else + local finder=$wordStart$cmd$wordEnd + fi + alias | grep -E "=$finder" + if [[ $exact = true || $longer = true ]]; then + break + else + cmd=$(sed -E 's/ {0,1}[^ ]*$//' <<< $cmd) # removes last word + fi + done + fi +} + +preexec_alias-finder() { + if [[ $ZSH_ALIAS_FINDER_AUTOMATIC = true ]]; then + alias-finder $1 + fi +} + +autoload -U add-zsh-hook +add-zsh-hook preexec preexec_alias-finder diff --git a/plugins/arcanist/README.md b/plugins/arcanist/README.md index 4bb8c8090..9c15f09b5 100644 --- a/plugins/arcanist/README.md +++ b/plugins/arcanist/README.md @@ -1,5 +1,29 @@ ## arcanist -**Maintainer:** [@emzar](https://github.com/emzar) +This plugin adds many useful aliases for [arcanist](https://github.com/phacility/arcanist). -This plugin adds many useful aliases. +To use it, add `arcanist` to the plugins array of your zshrc file: + +```zsh +plugins=(... arcanist) +``` + +## Aliases + +| Alias | Command | +|---------|------------------------------------| +| ara | `arc amend` | +| arb | `arc branch` | +| arco | `arc cover` | +| arci | `arc commit` | +| ard | `arc diff` | +| ardc | `arc diff --create` | +| ardnu | `arc diff --nounit` | +| ardnupc | `arc diff --nounit --plan-changes` | +| ardpc | `arc diff --plan-changes` | +| are | `arc export` | +| arh | `arc help` | +| arl | `arc land` | +| arli | `arc lint` | +| arls | `arc list` | +| arpa | `arc patch` | diff --git a/plugins/arcanist/arcanist.plugin.zsh b/plugins/arcanist/arcanist.plugin.zsh index 3f4eb07f4..8918bffdd 100644 --- a/plugins/arcanist/arcanist.plugin.zsh +++ b/plugins/arcanist/arcanist.plugin.zsh @@ -9,6 +9,7 @@ alias arco='arc cover' alias arci='arc commit' alias ard='arc diff' +alias ardc='arc diff --create' alias ardnu='arc diff --nounit' alias ardnupc='arc diff --nounit --plan-changes' alias ardpc='arc diff --plan-changes' diff --git a/plugins/autoenv/README.md b/plugins/autoenv/README.md new file mode 100644 index 000000000..de3881774 --- /dev/null +++ b/plugins/autoenv/README.md @@ -0,0 +1,14 @@ +# Autoenv plugin + +This plugin loads the [Autoenv](https://github.com/inishchith/autoenv). + +To use it, add `autoenv` to the plugins array in your zshrc file: + +```zsh +plugins=(... autoenv) +``` +## Requirements + +In order to make this work, you will need to have the autoenv installed. + +More info on the usage and install: https://github.com/inishchith/autoenv diff --git a/plugins/autojump/autojump.plugin.zsh b/plugins/autojump/autojump.plugin.zsh index 13c1d00ed..d80c88822 100644 --- a/plugins/autojump/autojump.plugin.zsh +++ b/plugins/autojump/autojump.plugin.zsh @@ -1,8 +1,3 @@ -(( $+commands[autojump] )) || { - echo '[oh-my-zsh] Please install autojump first (https://github.com/wting/autojump)' - return -} - declare -a autojump_paths autojump_paths=( $HOME/.autojump/etc/profile.d/autojump.zsh # manual installation diff --git a/plugins/aws/aws.plugin.zsh b/plugins/aws/aws.plugin.zsh index 231ac5ad2..567311372 100644 --- a/plugins/aws/aws.plugin.zsh +++ b/plugins/aws/aws.plugin.zsh @@ -10,7 +10,8 @@ function asp() { return fi - local available_profiles=($(aws_profiles)) + local -a available_profiles + available_profiles=($(aws_profiles)) if [[ -z "${available_profiles[(r)$1]}" ]]; then echo "${fg[red]}Profile '$1' not found in '${AWS_CONFIG_FILE:-$HOME/.aws/config}'" >&2 echo "Available profiles: ${(j:, :)available_profiles:-no profiles found}${reset_color}" >&2 diff --git a/plugins/battery/battery.plugin.zsh b/plugins/battery/battery.plugin.zsh index 8f398cfb3..4c4d0d4fc 100644 --- a/plugins/battery/battery.plugin.zsh +++ b/plugins/battery/battery.plugin.zsh @@ -7,23 +7,25 @@ # Email: neuralsandwich@gmail.com # # Modified to add support for Apple Mac # ########################################### +# Author: J (927589452) # +# Modified to add support for FreeBSD # +########################################### -if [[ "$OSTYPE" = darwin* ]] ; then +if [[ "$OSTYPE" = darwin* ]]; then - function battery_pct() { - local smart_battery_status="$(ioreg -rc "AppleSmartBattery")" - typeset -F maxcapacity=$(echo $smart_battery_status | grep '^.*"MaxCapacity"\ =\ ' | sed -e 's/^.*"MaxCapacity"\ =\ //') - typeset -F currentcapacity=$(echo $smart_battery_status | grep '^.*"CurrentCapacity"\ =\ ' | sed -e 's/^.*CurrentCapacity"\ =\ //') - integer i=$(((currentcapacity/maxcapacity) * 100)) - echo $i + function battery_is_charging() { + ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ Yes' } - function plugged_in() { - [ $(ioreg -rc AppleSmartBattery | grep -c '^.*"ExternalConnected"\ =\ Yes') -eq 1 ] + function battery_pct() { + local battery_status="$(ioreg -rc AppleSmartBattery)" + local -i capacity=$(sed -n -e '/MaxCapacity/s/^.*"MaxCapacity"\ =\ //p' <<< $battery_status) + local -i current=$(sed -n -e '/CurrentCapacity/s/^.*"CurrentCapacity"\ =\ //p' <<< $battery_status) + echo $(( current * 100 / capacity )) } function battery_pct_remaining() { - if plugged_in ; then + if battery_is_charging; then echo "External Power" else battery_pct @@ -32,9 +34,9 @@ if [[ "$OSTYPE" = darwin* ]] ; then function battery_time_remaining() { local smart_battery_status="$(ioreg -rc "AppleSmartBattery")" - if [[ $(echo $smart_battery_status | grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]] ; then - timeremaining=$(echo $smart_battery_status | grep '^.*"AvgTimeToEmpty"\ =\ ' | sed -e 's/^.*"AvgTimeToEmpty"\ =\ //') - if [ $timeremaining -gt 720 ] ; then + if [[ $(echo $smart_battery_status | command grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]]; then + timeremaining=$(echo $smart_battery_status | command grep '^.*"AvgTimeToEmpty"\ =\ ' | sed -e 's/^.*"AvgTimeToEmpty"\ =\ //') + if [ $timeremaining -gt 720 ]; then echo "::" else echo "~$((timeremaining / 60)):$((timeremaining % 60))" @@ -45,39 +47,36 @@ if [[ "$OSTYPE" = darwin* ]] ; then } function battery_pct_prompt () { - if [[ $(ioreg -rc AppleSmartBattery | grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]] ; then - b=$(battery_pct_remaining) - if [ $b -gt 50 ] ; then + local battery_pct color + if ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ No'; then + battery_pct=$(battery_pct_remaining) + if [[ $battery_pct -gt 50 ]]; then color='green' - elif [ $b -gt 20 ] ; then + elif [[ $battery_pct -gt 20 ]]; then color='yellow' else color='red' fi - echo "%{$fg[$color]%}[$(battery_pct_remaining)%%]%{$reset_color%}" + echo "%{$fg[$color]%}[${battery_pct}%%]%{$reset_color%}" else echo "โˆž" fi } - function battery_is_charging() { - [[ $(ioreg -rc "AppleSmartBattery"| grep '^.*"IsCharging"\ =\ ' | sed -e 's/^.*"IsCharging"\ =\ //') == "Yes" ]] - } - -elif [[ "$OSTYPE" = linux* ]] ; then +elif [[ "$OSTYPE" = freebsd* ]]; then function battery_is_charging() { - ! [[ $(acpi 2>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]] + [[ $(sysctl -n hw.acpi.battery.state) -eq 2 ]] } function battery_pct() { - if (( $+commands[acpi] )) ; then - echo "$(acpi 2>/dev/null | cut -f2 -d ',' | tr -cd '[:digit:]')" + if (( $+commands[sysctl] )); then + sysctl -n hw.acpi.battery.life fi } function battery_pct_remaining() { - if [ ! $(battery_is_charging) ] ; then + if ! battery_is_charging; then battery_pct else echo "External Power" @@ -85,76 +84,128 @@ elif [[ "$OSTYPE" = linux* ]] ; then } function battery_time_remaining() { - if [[ $(acpi 2>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]] ; then - echo $(acpi 2>/dev/null | cut -f3 -d ',') + local remaining_time + remaining_time=$(sysctl -n hw.acpi.battery.time) + if [[ $remaining_time -ge 0 ]]; then + ((hour = $remaining_time / 60 )) + ((minute = $remaining_time % 60 )) + printf %02d:%02d $hour $minute fi } function battery_pct_prompt() { - b=$(battery_pct_remaining) - if [[ $(acpi 2>/dev/null | grep -c '^Battery.*Discharging') -gt 0 ]] ; then - if [ $b -gt 50 ] ; then + local battery_pct color + battery_pct=$(battery_pct_remaining) + if battery_is_charging; then + echo "โˆž" + else + if [[ $battery_pct -gt 50 ]]; then color='green' - elif [ $b -gt 20 ] ; then + elif [[ $battery_pct -gt 20 ]]; then color='yellow' else color='red' fi - echo "%{$fg[$color]%}$(battery_pct_remaining)%%%{$reset_color%}" + echo "%{$fg[$color]%}${battery_pct}%%%{$reset_color%}" + fi + } + +elif [[ "$OSTYPE" = linux* ]]; then + + function battery_is_charging() { + ! acpi 2>/dev/null | command grep -v "rate information unavailable" | command grep -q '^Battery.*Discharging' + } + + function battery_pct() { + if (( $+commands[acpi] )); then + acpi 2>/dev/null | command grep -v "rate information unavailable" | command grep -E '^Battery.*(Disc|C)harging' | cut -f2 -d ',' | tr -cd '[:digit:]' + fi + } + + function battery_pct_remaining() { + if ! battery_is_charging; then + battery_pct else + echo "External Power" + fi + } + + function battery_time_remaining() { + if ! battery_is_charging; then + acpi 2>/dev/null | command grep -v "rate information unavailable" | cut -f3 -d ',' + fi + } + + function battery_pct_prompt() { + local battery_pct color + battery_pct=$(battery_pct_remaining) + if battery_is_charging; then echo "โˆž" + else + if [[ $battery_pct -gt 50 ]]; then + color='green' + elif [[ $battery_pct -gt 20 ]]; then + color='yellow' + else + color='red' + fi + echo "%{$fg[$color]%}${battery_pct}%%%{$reset_color%}" fi } else # Empty functions so we don't cause errors in prompts - function battery_pct_remaining() { - } - - function battery_time_remaining() { - } - - function battery_pct_prompt() { - } + function battery_is_charging { false } + function battery_pct \ + battery_pct_remaining \ + battery_time_remaining \ + battery_pct_prompt { } fi function battery_level_gauge() { - local gauge_slots=${BATTERY_GAUGE_SLOTS:-10}; - local green_threshold=${BATTERY_GREEN_THRESHOLD:-6}; - local yellow_threshold=${BATTERY_YELLOW_THRESHOLD:-4}; - local color_green=${BATTERY_COLOR_GREEN:-%F{green}}; - local color_yellow=${BATTERY_COLOR_YELLOW:-%F{yellow}}; - local color_red=${BATTERY_COLOR_RED:-%F{red}}; - local color_reset=${BATTERY_COLOR_RESET:-%{%f%k%b%}}; - local battery_prefix=${BATTERY_GAUGE_PREFIX:-'['}; - local battery_suffix=${BATTERY_GAUGE_SUFFIX:-']'}; - local filled_symbol=${BATTERY_GAUGE_FILLED_SYMBOL:-'โ–ถ'}; - local empty_symbol=${BATTERY_GAUGE_EMPTY_SYMBOL:-'โ–ท'}; - local charging_color=${BATTERY_CHARGING_COLOR:-$color_yellow}; - local charging_symbol=${BATTERY_CHARGING_SYMBOL:-'โšก'}; + local gauge_slots=${BATTERY_GAUGE_SLOTS:-10} + local green_threshold=${BATTERY_GREEN_THRESHOLD:-$(( gauge_slots * 0.6 ))} + local yellow_threshold=${BATTERY_YELLOW_THRESHOLD:-$(( gauge_slots * 0.4 ))} + local color_green=${BATTERY_COLOR_GREEN:-%F{green}} + local color_yellow=${BATTERY_COLOR_YELLOW:-%F{yellow}} + local color_red=${BATTERY_COLOR_RED:-%F{red}} + local color_reset=${BATTERY_COLOR_RESET:-%{%f%k%b%}} + local battery_prefix=${BATTERY_GAUGE_PREFIX:-'['} + local battery_suffix=${BATTERY_GAUGE_SUFFIX:-']'} + local filled_symbol=${BATTERY_GAUGE_FILLED_SYMBOL:-'โ–ถ'} + local empty_symbol=${BATTERY_GAUGE_EMPTY_SYMBOL:-'โ–ท'} + local charging_color=${BATTERY_CHARGING_COLOR:-$color_yellow} + local charging_symbol=${BATTERY_CHARGING_SYMBOL:-'โšก'} - local battery_remaining_percentage=$(battery_pct); + local battery_remaining_percentage=$(battery_pct) + local filled empty gauge_color if [[ $battery_remaining_percentage =~ [0-9]+ ]]; then - local filled=$(((( $battery_remaining_percentage + $gauge_slots - 1) / $gauge_slots))); - local empty=$(($gauge_slots - $filled)); + filled=$(( ($battery_remaining_percentage * $gauge_slots) / 100 )) + empty=$(( $gauge_slots - $filled )) - if [[ $filled -gt $green_threshold ]]; then local gauge_color=$color_green; - elif [[ $filled -gt $yellow_threshold ]]; then local gauge_color=$color_yellow; - else local gauge_color=$color_red; + if [[ $filled -gt $green_threshold ]]; then + gauge_color=$color_green + elif [[ $filled -gt $yellow_threshold ]]; then + gauge_color=$color_yellow + else + gauge_color=$color_red fi else - local filled=$gauge_slots; - local empty=0; - filled_symbol=${BATTERY_UNKNOWN_SYMBOL:-'.'}; + filled=$gauge_slots + empty=0 + filled_symbol=${BATTERY_UNKNOWN_SYMBOL:-'.'} fi - local charging=' ' && battery_is_charging && charging=$charging_symbol; + local charging=' ' + battery_is_charging && charging=$charging_symbol + # Charging status and prefix printf ${charging_color//\%/\%\%}$charging${color_reset//\%/\%\%}${battery_prefix//\%/\%\%}${gauge_color//\%/\%\%} - printf ${filled_symbol//\%/\%\%}'%.0s' {1..$filled} + # Filled slots + [[ $filled -gt 0 ]] && printf ${filled_symbol//\%/\%\%}'%.0s' {1..$filled} + # Empty slots [[ $filled -lt $gauge_slots ]] && printf ${empty_symbol//\%/\%\%}'%.0s' {1..$empty} + # Suffix printf ${color_reset//\%/\%\%}${battery_suffix//\%/\%\%}${color_reset//\%/\%\%} } - - diff --git a/plugins/bundler/README.md b/plugins/bundler/README.md index dc2f17008..9f211b02f 100644 --- a/plugins/bundler/README.md +++ b/plugins/bundler/README.md @@ -2,7 +2,7 @@ - adds completion for basic bundler commands - adds short aliases for common bundler commands - - `be` aliased to `bundle exec`. + - `be` aliased to `bundle exec`. It also supports aliases (if `rs` is `rails server`, `be rs` will bundle-exec `rails server`). - `bl` aliased to `bundle list` - `bp` aliased to `bundle package` @@ -15,7 +15,7 @@ - calls `bundle exec ` otherwise Common gems wrapped by default (by name of the executable): -`annotate`, `cap`, `capify`, `cucumber`, `foodcritic`, `guard`, `hanami`, `irb`, `jekyll`, `kitchen`, `knife`, `middleman`, `nanoc`, `pry`, `puma`, `rackup`, `rainbows`, `rake`, `rspec`, `shotgun`, `sidekiq`, `spec`, `spork`, `spring`, `strainer`, `tailor`, `taps`, `thin`, `thor`, `unicorn` and `unicorn_rails`. +`annotate`, `cap`, `capify`, `cucumber`, `foodcritic`, `guard`, `hanami`, `irb`, `jekyll`, `kitchen`, `knife`, `middleman`, `nanoc`, `pry`, `puma`, `rackup`, `rainbows`, `rake`, `rspec`, `rubocop`, `shotgun`, `sidekiq`, `spec`, `spork`, `spring`, `strainer`, `tailor`, `taps`, `thin`, `thor`, `unicorn` and `unicorn_rails`. ## Configuration @@ -42,7 +42,7 @@ This will exclude the `foreman` and `spin` gems (i.e. their executable) from bei ## Excluded gems -These gems should not be called with `bundle exec`. Please see [issue #2923](https://github.com/robbyrussell/oh-my-zsh/pull/2923) on GitHub for clarification. +These gems should not be called with `bundle exec`. Please see [issue #2923](https://github.com/ohmyzsh/ohmyzsh/pull/2923) on GitHub for clarification. `berks` `foreman` diff --git a/plugins/bundler/bundler.plugin.zsh b/plugins/bundler/bundler.plugin.zsh index 668e15d2f..665cb5e43 100644 --- a/plugins/bundler/bundler.plugin.zsh +++ b/plugins/bundler/bundler.plugin.zsh @@ -27,6 +27,7 @@ bundled_commands=( rainbows rake rspec + rubocop shotgun sidekiq spec @@ -81,7 +82,7 @@ _bundler-installed() { _within-bundled-project() { local check_dir="$PWD" while [ "$check_dir" != "/" ]; do - [ -f "$check_dir/Gemfile" ] && return + [ -f "$check_dir/Gemfile" -o -f "$check_dir/gems.rb" ] && return check_dir="$(dirname $check_dir)" done false @@ -94,7 +95,7 @@ _binstubbed() { _run-with-bundler() { if _bundler-installed && _within-bundled-project; then if _binstubbed $1; then - ./bin/$@ + ./bin/${^^@} else bundle exec $@ fi diff --git a/plugins/bwana/README.md b/plugins/bwana/README.md deleted file mode 100644 index dd4fe9f9c..000000000 --- a/plugins/bwana/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Bwana - -This plugin provides a function to open `man` pages directly with [Bwana](https://www.bruji.com/bwana/). - -To use it add bwana to the plugins array in your zshrc file. - -```bash -plugins=(... bwana) -``` - -The `bwana` function opens the man page of the passed argument in the Bwana app. -For example: `bwana ln` opens the man page for `ln` in Bwana. diff --git a/plugins/bwana/bwana.plugin.zsh b/plugins/bwana/bwana.plugin.zsh deleted file mode 100644 index 71c9eb18d..000000000 --- a/plugins/bwana/bwana.plugin.zsh +++ /dev/null @@ -1,13 +0,0 @@ -# -# Requires https://www.bruji.com/bwana/ -# -if [[ -e /Applications/Bwana.app ]] || - ( system_profiler -detailLevel mini SPApplicationsDataType | grep -q Bwana ) -then - function bwana() { - open "man:$1" - } -else - echo "Bwana lets you read man files in Safari through a man: URI scheme" - echo "To use it within Zsh, install it from https://www.bruji.com/bwana/" -fi diff --git a/plugins/cakephp3/README.md b/plugins/cakephp3/README.md new file mode 100644 index 000000000..7e8f6640d --- /dev/null +++ b/plugins/cakephp3/README.md @@ -0,0 +1,16 @@ +# cakephp3 plugin + +The plugin adds aliases and autocompletion for [cakephp3](https://book.cakephp.org/3.0/en/index.html). + +To use it, add `cakephp3` to the plugins array of your zshrc file: +``` +plugins=(... cakephp3) +``` + +## Aliases + +| Alias | Command | +|-----------|-------------------------------| +| c3 | `bin/cake` | +| c3cache | `bin/cake orm_cache clear` | +| c3migrate | `bin/cake migrations migrate` | diff --git a/plugins/cargo/_cargo b/plugins/cargo/_cargo index 395c517cd..12694901e 100644 --- a/plugins/cargo/_cargo +++ b/plugins/cargo/_cargo @@ -2,489 +2,367 @@ autoload -U regexp-replace -zstyle -T ':completion:*:*:cargo:*' tag-order && \ - zstyle ':completion:*:*:cargo:*' tag-order 'common-commands' - _cargo() { -local context state state_descr line -typeset -A opt_args + local curcontext="$curcontext" ret=1 + local -a command_scope_spec common parallel features msgfmt triple target registry + local -a state line state_descr # These are set by _arguments + typeset -A opt_args -# leading items in parentheses are an exclusion list for the arguments following that arg -# See: http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions -# - => exclude all other options -# 1 => exclude positional arg 1 -# * => exclude all other args -# +blah => exclude +blah -_arguments \ - '(- 1 *)'{-h,--help}'[show help message]' \ - '(- 1 *)--list[list installed commands]' \ - '(- 1 *)'{-V,--version}'[show version information]' \ - {-v,--verbose}'[use verbose output]' \ - --color'[colorization option]' \ - '(+beta +nightly)+stable[use the stable toolchain]' \ - '(+stable +nightly)+beta[use the beta toolchain]' \ - '(+stable +beta)+nightly[use the nightly toolchain]' \ - '1: :->command' \ - '*:: :->args' + common=( + '(-q --quiet)*'{-v,--verbose}'[use verbose output]' + '(-q --quiet -v --verbose)'{-q,--quiet}'[no output printed to stdout]' + '-Z+[pass unstable (nightly-only) flags to cargo]: :_cargo_unstable_flags' + '--frozen[require that Cargo.lock and cache are up-to-date]' + '--locked[require that Cargo.lock is up-to-date]' + '--color=[specify colorization option]:coloring:(auto always never)' + '(- 1 *)'{-h,--help}'[show help message]' + ) -case $state in - command) - _alternative 'common-commands:common:_cargo_cmds' 'all-commands:all:_cargo_all_cmds' - ;; + # leading items in parentheses are an exclusion list for the arguments following that arg + # See: http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions + # - => exclude all other options + # 1 => exclude positional arg 1 + # * => exclude all other args + # +blah => exclude +blah + _arguments -s -S -C $common \ + '(- 1 *)--list[list installed commands]' \ + '(- 1 *)--explain=[provide a detailed explanation of an error message]:error code' \ + '(- 1 *)'{-V,--version}'[show version information]' \ + '(+beta +nightly)+stable[use the stable toolchain]' \ + '(+stable +nightly)+beta[use the beta toolchain]' \ + '(+stable +beta)+nightly[use the nightly toolchain]' \ + '1: :_cargo_cmds' \ + '*:: :->args' - args) - case $words[1] in - bench) - _arguments \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - "${command_scope_spec[@]}" \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-default-features[do not build the default features]' \ - '--no-run[compile but do not run]' \ - '(-p,--package)'{-p=,--package=}'[package to run benchmarks for]:packages:_get_package_names' \ - '--target=[target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--color=:colorization option:(auto always never)' \ - ;; + # These flags are mutually exclusive specifiers for the scope of a command; as + # they are used in multiple places without change, they are expanded into the + # appropriate command's `_arguments` where appropriate. + command_scope_spec=( + '(--bin --example --test --lib)--bench=[specify benchmark name]: :_cargo_benchmark_names' + '(--bench --bin --test --lib)--example=[specify example name]:example name' + '(--bench --example --test --lib)--bin=[specify binary name]:binary name' + '(--bench --bin --example --test)--lib=[specify library name]:library name' + '(--bench --bin --example --lib)--test=[specify test name]:test name' + ) - build) - _arguments \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - "${command_scope_spec[@]}" \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-default-features[do not build the default features]' \ - '(-p,--package)'{-p=,--package=}'[package to build]:packages:_get_package_names' \ - '--release=[build in release mode]' \ - '--target=[target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--color=:colorization option:(auto always never)' \ - ;; + parallel=( + '(-j --jobs)'{-j+,--jobs=}'[specify number of parallel jobs]:jobs [# of CPUs]' + ) - check) - _arguments \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - "${command_scope_spec[@]}" \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-default-features[do not check the default features]' \ - '(-p,--package)'{-p=,--package=}'[package to check]:packages:_get_package_names' \ - '--release=[check in release mode]' \ - '--target=[target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--color=:colorization option:(auto always never)' \ - ;; + features=( + '(--all-features)--features=[specify features to activate]:feature' + '(--features)--all-features[activate all available features]' + "--no-default-features[don't build the default features]" + ) - clean) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-p,--package)'{-p=,--package=}'[package to clean]:packages:_get_package_names' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release[whether or not to clean release artifacts]' \ - '--target=[target triple(default:all)]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + msgfmt='--message-format=[specify error format]:error format [human]:(human json short)' + triple='--target=[specify target triple]:target triple' + target='--target-dir=[specify directory for all generated artifacts]:directory:_directories' + manifest='--manifest-path=[specify path to manifest]:path:_directories' + registry='--registry=[specify registry to use]:registry' - doc) - _arguments \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-deps[do not build docs for dependencies]' \ - '--no-default-features[do not build the default features]' \ - '--open[open docs in browser after the build]' \ - '(-p, --package)'{-p,--package}'=[package to document]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release[build artifacts in release mode, with optimizations]' \ - '--target=[build for the target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + case $state in + args) + curcontext="${curcontext%:*}-${words[1]}:" + case ${words[1]} in + bench) + _arguments -s -A "^--" $common $parallel $features $msgfmt $triple $target $manifest \ + "${command_scope_spec[@]}" \ + '--all-targets[benchmark all targets]' \ + "--no-run[compile but don't run]" \ + '(-p --package)'{-p+,--package=}'[specify package to run benchmarks for]:package:_cargo_package_names' \ + '--exclude=[exclude packages from the benchmark]:spec' \ + '--no-fail-fast[run all benchmarks regardless of failure]' \ + '1: :_guard "^-*" "bench name"' \ + '*:args:_default' + ;; - fetch) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + build) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--all-targets[equivalent to specifying --lib --bins --tests --benches --examples]' \ + "${command_scope_spec[@]}" \ + '(-p --package)'{-p+,--package=}'[specify package to build]:package:_cargo_package_names' \ + '--release[build in release mode]' \ + '--build-plan[output the build plan in JSON]' \ + ;; - generate-lockfile) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + check) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--all-targets[equivalent to specifying --lib --bins --tests --benches --examples]' \ + "${command_scope_spec[@]}" \ + '(-p --package)'{-p+,--package=}'[specify package to check]:package:_cargo_package_names' \ + '--release[check in release mode]' \ + ;; - git-checkout) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--reference=[REF]' \ - '--url=[URL]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + clean) + _arguments -s -S $common $triple $target $manifest \ + '(-p --package)'{-p+,--package=}'[specify package to clean]:package:_cargo_package_names' \ + '--release[clean release artifacts]' \ + '--doc[clean just the documentation directory]' + ;; - help) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '*: :_cargo_cmds' \ - ;; + doc) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--no-deps[do not build docs for dependencies]' \ + '--document-private-items[include non-public items in the documentation]' \ + '--open[open docs in browser after the build]' \ + '(-p --package)'{-p+,--package=}'[specify package to document]:package:_cargo_package_names' \ + '--release[build artifacts in release mode, with optimizations]' \ + ;; - init) - _arguments \ - '--bin[use binary template]' \ - '--vcs:initialize a new repo with a given VCS:(git hg none)' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--name=[set the resulting package name]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + fetch) + _arguments -s -S $common $triple $manifest + ;; - install) - _arguments \ - '--bin=[only install the specified binary]' \ - '--branch=[branch to use when installing from git]' \ - '--color=:colorization option:(auto always never)' \ - '--debug[build in debug mode instead of release mode]' \ - '--example[install the specified example instead of binaries]' \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '--git=[URL from which to install the crate]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - '--no-default-features[do not build the default features]' \ - '--path=[local filesystem path to crate to install]: :_files -/' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--rev=[specific commit to use when installing from git]' \ - '--root=[directory to install packages into]: :_files -/' \ - '--tag=[tag to use when installing from git]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--vers=[version to install from crates.io]' \ - ;; + fix) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + "${command_scope_spec[@]}" \ + '--broken-code[fix code even if it already has compiler errors]' \ + '--edition[fix in preparation for the next edition]' \ + '--edition-idioms[fix warnings to migrate to the idioms of an edition]' \ + '--allow-no-vcs[fix code even if a VCS was not detected]' \ + '--allow-dirty[fix code even if the working directory is dirty]' \ + '--allow-staged[fix code even if the working directory has staged changes]' + ;; - locate-project) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - ;; + generate-lockfile) + _arguments -s -S $common $manifest + ;; - login) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--host=[Host to set the token for]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + git-checkout) + _arguments -s -S $common \ + '--reference=:reference' \ + '--url=:url:_urls' + ;; - metadata) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - "--no-deps[output information only about the root package and don't fetch dependencies]" \ - '--no-default-features[do not include the default feature]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '--format-version=[format version(default: 1)]' \ - '--color=:colorization option:(auto always never)' \ - ;; + help) + _cargo_cmds + ;; - new) - _arguments \ - '--bin[use binary template]' \ - '--vcs:initialize a new repo with a given VCS:(git hg none)' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--name=[set the resulting package name]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + init) + _arguments -s -S $common $registry \ + '--lib[use library template]' \ + '--edition=[specify edition to set for the crate generated]:edition:(2015 2018)' \ + '--vcs=[initialize a new repo with a given VCS]:vcs:(git hg pijul fossil none)' \ + '--name=[set the resulting package name]:name' \ + '1:path:_directories' + ;; - owner) - _arguments \ - '(-a, --add)'{-a,--add}'[add owner LOGIN]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--index[registry index]' \ - '(-l, --list)'{-l,--list}'[list owners of a crate]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-r, --remove)'{-r,--remove}'[remove owner LOGIN]' \ - '--token[API token to use when authenticating]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + install) + _arguments -s -S $common $parallel $features $triple $registry \ + '(-f --force)'{-f,--force}'[force overwriting of existing crates or binaries]' \ + '--bin=[only install the specified binary]:binary' \ + '--branch=[branch to use when installing from git]:branch' \ + '--debug[build in debug mode instead of release mode]' \ + '--example=[install the specified example instead of binaries]:example' \ + '--git=[specify URL from which to install the crate]:url:_urls' \ + '--path=[local filesystem path to crate to install]: :_directories' \ + '--rev=[specific commit to use when installing from git]:commit' \ + '--root=[directory to install packages into]: :_directories' \ + '--tag=[tag to use when installing from git]:tag' \ + '--vers=[version to install from crates.io]:version' \ + '--list[list all installed packages and their versions]' \ + '*: :_guard "^-*" "crate"' + ;; - package) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-l, --list)'{-l,--list}'[print files included in a package without making one]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-metadata[ignore warnings about a lack of human-usable metadata]' \ - '--no-verify[do not build to verify contents]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + locate-project) + _arguments -s -S $common $manifest + ;; - pkgid) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + login) + _arguments -s -S $common $registry \ + '*: :_guard "^-*" "token"' + ;; - publish) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--host=[Host to set the token for]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--no-verify[Do not verify tarball until before publish]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--token[token to use when uploading]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + metadata) + _arguments -s -S $common $features $manifest \ + "--no-deps[output information only about the root package and don't fetch dependencies]" \ + '--format-version=[specify format version]:version [1]:(1)' + ;; - read-manifest) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + new) + _arguments -s -S $common $registry \ + '--lib[use library template]' \ + '--vcs:initialize a new repo with a given VCS:(git hg none)' \ + '--name=[set the resulting package name]' + ;; - run) - _arguments \ - '--example=[name of the bin target]' \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--bin=[name of the bin target]' \ - '--no-default-features[do not build the default features]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release=[build in release mode]' \ - '--target=[target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - '*: :_normal' \ - ;; + owner) + _arguments -s -S $common $registry \ + '(-a --add)'{-a,--add}'[specify name of a user or team to invite as an owner]:name' \ + '--index=[specify registry index]:index' \ + '(-l --list)'{-l,--list}'[list owners of a crate]' \ + '(-r --remove)'{-r,--remove}'[specify name of a user or team to remove as an owner]:name' \ + '--token=[specify API token to use when authenticating]:token' \ + '*: :_guard "^-*" "crate"' + ;; - rustc) - _arguments \ - '--color=:colorization option:(auto always never)' \ - '--features=[features to compile for the package]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'=[number of parallel jobs, defaults to # of CPUs]' \ - '--manifest-path=[path to the manifest to fetch dependencies for]: :_files -/' \ - '--no-default-features[do not compile default features for the package]' \ - '(-p, --package)'{-p,--package}'=[profile to compile for]' \ - '--profile=[profile to build the selected target for]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release[build artifacts in release mode, with optimizations]' \ - '--target=[target triple which compiles will be for]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - "${command_scope_spec[@]}" \ - ;; + package) + _arguments -s -S $common $parallel $features $triple $target $manifest \ + '(-l --list)'{-l,--list}'[print files included in a package without making one]' \ + '--no-metadata[ignore warnings about a lack of human-usable metadata]' \ + '--allow-dirty[allow dirty working directories to be packaged]' \ + "--no-verify[don't build to verify contents]" + ;; - rustdoc) - _arguments \ - '--color=:colorization option:(auto always never)' \ - '--features=[space-separated list of features to also build]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'=[number of parallel jobs, defaults to # of CPUs]' \ - '--manifest-path=[path to the manifest to document]: :_files -/' \ - '--no-default-features[do not build the `default` feature]' \ - '--open[open the docs in a browser after the operation]' \ - '(-p, --package)'{-p,--package}'=[package to document]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release[build artifacts in release mode, with optimizations]' \ - '--target=[build for the target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - "${command_scope_spec[@]}" \ - ;; + pkgid) + _arguments -s -S $common $manifest \ + '(-p --package)'{-p+,--package=}'[specify package to get ID specifier for]:package:_cargo_package_names' \ + '*: :_guard "^-*" "spec"' + ;; - search) - _arguments \ - '--color=:colorization option:(auto always never)' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--host=[host of a registry to search in]' \ - '--limit=[limit the number of results]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - ;; + publish) + _arguments -s -S $common $parallel $features $triple $target $manifest $registry \ + '--index=[specify registry index]:index' \ + '--allow-dirty[allow dirty working directories to be packaged]' \ + "--no-verify[don't verify the contents by building them]" \ + '--token=[specify token to use when uploading]:token' \ + '--dry-run[perform all checks without uploading]' + ;; - test) - _arguments \ - '--features=[space separated feature list]' \ - '--all-features[enable all available features]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-j, --jobs)'{-j,--jobs}'[number of parallel jobs, defaults to # of CPUs]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '--test=[test name]: :_test_names' \ - '--no-default-features[do not build the default features]' \ - '--no-fail-fast[run all tests regardless of failure]' \ - '--no-run[compile but do not run]' \ - '(-p,--package)'{-p=,--package=}'[package to run tests for]:packages:_get_package_names' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--release[build artifacts in release mode, with optimizations]' \ - '--target=[target triple]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - '1: :_test_names' \ - '(--doc --bin --example --test --bench)--lib[only test library]' \ - '(--lib --bin --example --test --bench)--doc[only test documentation]' \ - '(--lib --doc --example --test --bench)--bin=[binary name]' \ - '(--lib --doc --bin --test --bench)--example=[example name]' \ - '(--lib --doc --bin --example --bench)--test=[test name]' \ - '(--lib --doc --bin --example --test)--bench=[benchmark name]' \ - '--message-format:error format:(human json short)' \ - '--frozen[require lock and cache up to date]' \ - '--locked[require lock up to date]' - ;; + read-manifest) + _arguments -s -S $common $manifest + ;; - uninstall) - _arguments \ - '--bin=[only uninstall the binary NAME]' \ - '--color=:colorization option:(auto always never)' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-q, --quiet)'{-q,--quiet}'[less output printed to stdout]' \ - '--root=[directory to uninstall packages from]: :_files -/' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - ;; + run) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--example=[name of the bin target]:name' \ + '--bin=[name of the bin target]:name' \ + '(-p --package)'{-p+,--package=}'[specify package with the target to run]:package:_cargo_package_names' \ + '--release[build in release mode]' \ + '*: :_default' + ;; - update) - _arguments \ - '--aggressive=[force dependency update]' \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-p,--package)'{-p=,--package=}'[package to update]:packages:__get_package_names' \ - '--precise=[update single dependency to PRECISE]: :' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + rustc) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '(-p --package)'{-p+,--package=}'[specify package to build]:package:_cargo_package_names' \ + '--profile=[specify profile to build the selected target for]:profile' \ + '--release[build artifacts in release mode, with optimizations]' \ + "${command_scope_spec[@]}" \ + '*: : _dispatch rustc rustc -default-' + ;; - verify-project) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--manifest-path=[path to manifest]: :_files -/' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + rustdoc) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--document-private-items[include non-public items in the documentation]' \ + '--open[open the docs in a browser after the operation]' \ + '(-p --package)'{-p+,--package=}'[specify package to document]:package:_cargo_package_names' \ + '--release[build artifacts in release mode, with optimizations]' \ + "${command_scope_spec[@]}" \ + '*: : _dispatch rustdoc rustdoc -default-' + ;; - version) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - ;; + search) + _arguments -s -S $common $registry \ + '--index=[specify registry index]:index' \ + '--limit=[limit the number of results]:results [10]' \ + '*: :_guard "^-*" "query"' + ;; - yank) - _arguments \ - '(-h, --help)'{-h,--help}'[show help message]' \ - '--index[registry index]' \ - '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ - '--token[API token to use when authenticating]' \ - '--undo[undo a yank, putting a version back into the index]' \ - '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ - '--color=:colorization option:(auto always never)' \ - '--vers[yank version]' \ - ;; - esac - ;; -esac + test) + _arguments -s -S $common $parallel $features $msgfmt $triple $target $manifest \ + '--test=[test name]: :_cargo_test_names' \ + '--no-fail-fast[run all tests regardless of failure]' \ + '--no-run[compile but do not run]' \ + '(-p --package)'{-p+,--package=}'[package to run tests for]:package:_cargo_package_names' \ + '--all[test all packages in the workspace]' \ + '--release[build artifacts in release mode, with optimizations]' \ + '1: :_cargo_test_names' \ + '(--doc --bin --example --test --bench)--lib[only test library]' \ + '(--lib --bin --example --test --bench)--doc[only test documentation]' \ + '(--lib --doc --example --test --bench)--bin=[binary name]' \ + '(--lib --doc --bin --test --bench)--example=[example name]' \ + '(--lib --doc --bin --example --bench)--test=[test name]' \ + '(--lib --doc --bin --example --test)--bench=[benchmark name]' \ + '*: :_default' + ;; + + uninstall) + _arguments -s -S $common \ + '(-p --package)'{-p+,--package=}'[specify package to uninstall]:package:_cargo_package_names' \ + '--bin=[only uninstall the specified binary]:name' \ + '--root=[directory to uninstall packages from]: :_files -/' \ + '*:crate:_cargo_installed_crates -F line' + ;; + + update) + _arguments -s -S $common $manifest \ + '--aggressive=[force dependency update]' \ + "--dry-run[don't actually write the lockfile]" \ + '(-p --package)'{-p+,--package=}'[specify package to update]:package:_cargo_package_names' \ + '--precise=[update single dependency to precise release]:release' + ;; + + verify-project) + _arguments -s -S $common $manifest + ;; + + version) + _arguments -s -S $common + ;; + + yank) + _arguments -s -S $common $registry \ + '--vers=[specify yank version]:version' \ + '--undo[undo a yank, putting a version back into the index]' \ + '--index=[specify registry index to yank from]:registry index' \ + '--token=[specify API token to use when authenticating]:token' \ + '*: :_guard "^-*" "crate"' + ;; + *) + # allow plugins to define their own functions + if ! _call_function ret _cargo-${words[1]}; then + # fallback on default completion for unknown commands + _default && ret=0 + fi + (( ! ret )) + ;; + esac + ;; + esac } -_cargo_cmds(){ -local -a commands;commands=( -'bench:execute all benchmarks of a local package' -'build:compile the current package' -'check:check the current package without compiling' -'clean:remove generated artifacts' -'doc:build package documentation' -'fetch:fetch package dependencies' -'generate-lockfile:create lockfile' -'git-checkout:git checkout' -'help:get help for commands' -'init:create new package in current directory' -'install:install a Rust binary' -'locate-project:print "Cargo.toml" location' -'login:login to remote server' -'metadata:the metadata for a package in json' -'new:create a new package' -'owner:manage the owners of a crate on the registry' -'package:assemble local package into a distributable tarball' -'pkgid:print a fully qualified package specification' -'publish:upload package to the registry' -'read-manifest:print manifest in JSON format' -'run:run the main binary of the local package' -'rustc:compile a package and all of its dependencies' -'rustdoc:build documentation for a package' -'search:search packages on crates.io' -'test:execute all unit and tests of a local package' -'uninstall:remove a Rust binary' -'update:update dependencies' -'verify-project:check Cargo.toml' -'version:show version information' -'yank:remove pushed file from index' -) -_describe -t common-commands 'common commands' commands +_cargo_unstable_flags() { + local flags + flags=( help ${${${(M)${(f)"$(_call_program flags cargo -Z help)"}:#*--*}/ #-- #/:}##*-Z } ) + _describe -t flags 'unstable flag' flags } -_cargo_all_cmds(){ -local -a commands;commands=($(cargo --list)) -_describe -t all-commands 'all commands' commands +_cargo_installed_crates() { + local expl + _description crates expl 'crate' + compadd "$@" "$expl[@]" - ${${${(f)"$(cargo install --list)"}:# *}%% *} +} + +_cargo_cmds() { + local -a commands + # This uses Parameter Expansion Flags, which are a built-in Zsh feature. + # See more: http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags + # and http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion + # + # # How this work? + # + # First it splits the result of `cargo --list` at newline, then it removes the first line. + # Then it removes indentation (4 whitespaces) before each items. (Note the x## pattern [1]). + # Then it replaces those spaces between item and description with a `:` + # + # [1]: https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org#patterns + commands=( ${${${(M)"${(f)$(_call_program commands cargo --list)}":# *}/ ##/}/ ##/:} ) + _describe -t commands 'command' commands } #FIXME: Disabled until fixed #gets package names from the manifest file -_get_package_names() -{ -} - -#TODO:see if it makes sense to have 'locate-project' to have non-json output. -#strips package name from json stuff -_locate_manifest(){ -local manifest=`cargo locate-project 2>/dev/null` -regexp-replace manifest '\{"root":"|"\}' '' -echo $manifest +_cargo_package_names() { + _message -e packages package } # Extracts the values of "name" from the array given in $1 and shows them as # command line options for completion -_get_names_from_array() -{ - local -a filelist; - local manifest=$(_locate_manifest) +_cargo_names_from_array() { + # strip json from the path + local manifest=${${${"$(cargo locate-project)"}%\"\}}##*\"} if [[ -z $manifest ]]; then return 0 fi @@ -494,51 +372,36 @@ _get_names_from_array() local in_block=false local block_name=$1 names=() - while read line - do + while read -r line; do if [[ $last_line == "[[$block_name]]" ]]; then in_block=true else - if [[ $last_line =~ '.*\[\[.*' ]]; then + if [[ $last_line =~ '\s*\[\[.*' ]]; then in_block=false fi fi if [[ $in_block == true ]]; then - if [[ $line =~ '.*name.*=' ]]; then - regexp-replace line '^.*name *= *|"' "" - names+=$line + if [[ $line =~ '\s*name\s*=' ]]; then + regexp-replace line '^\s*name\s*=\s*|"' '' + names+=( "$line" ) fi fi last_line=$line - done < $manifest - _describe $block_name names + done < "$manifest" + _describe "$block_name" names } #Gets the test names from the manifest file -_test_names() -{ - _get_names_from_array "test" +_cargo_test_names() { + _cargo_names_from_array "test" } #Gets the bench names from the manifest file -_benchmark_names() -{ - _get_names_from_array "bench" +_cargo_benchmark_names() { + _cargo_names_from_array "bench" } -# These flags are mutually exclusive specifiers for the scope of a command; as -# they are used in multiple places without change, they are expanded into the -# appropriate command's `_arguments` where appropriate. -set command_scope_spec -command_scope_spec=( - '(--bin --example --test --lib)--bench=[benchmark name]: :_benchmark_names' - '(--bench --bin --test --lib)--example=[example name]' - '(--bench --example --test --lib)--bin=[binary name]' - '(--bench --bin --example --test)--lib=[library name]' - '(--bench --bin --example --lib)--test=[test name]' -) - _cargo diff --git a/plugins/catimg/README.md b/plugins/catimg/README.md index 2fc28a1c6..42b59a62c 100644 --- a/plugins/catimg/README.md +++ b/plugins/catimg/README.md @@ -17,10 +17,10 @@ Plugin for displaying images on the terminal using the the `catimg.sh` script pr ) ``` -2. Reload the source file or restart your Terminal session: +2. Restart the shell or restart your Terminal session: ```console - $ source ~/.zshrc + $ exec zsh $ ``` diff --git a/plugins/chruby/README.md b/plugins/chruby/README.md new file mode 100644 index 000000000..d373006a5 --- /dev/null +++ b/plugins/chruby/README.md @@ -0,0 +1,20 @@ +# chruby plugin + +This plugin loads [chruby](https://github.com/postmodern/chruby), a tool that changes the +current Ruby version, and completion and a prompt function to display the Ruby version. +Supports brew and manual installation of chruby. + +To use it, add `chruby` to the plugins array in your zshrc file: +```zsh +plugins=(... chruby) +``` + +## Usage + +If you'd prefer to specify an explicit path to load chruby from +you can set variables like so: + +``` +zstyle :omz:plugins:chruby path /local/path/to/chruby.sh +zstyle :omz:plugins:chruby auto /local/path/to/auto.sh +``` diff --git a/plugins/cloudapp/README.md b/plugins/cloudapp/README.md new file mode 100644 index 000000000..6c7f9bc6c --- /dev/null +++ b/plugins/cloudapp/README.md @@ -0,0 +1,24 @@ +# CloudApp plugin + +[CloudApp](https://www.getcloudapp.com) brings screen recording, screenshots, and GIF creation to the cloud, in an easy-to-use enterprise-level app. The CloudApp plugin allows you to upload a file to your CloadApp account from the command line. + +To use it, add `cloudapp` to the plugins array of your `~/.zshrc` file: + +``` +plugins=(... cloudapp) +``` + +## Requirements + +1. [Aaron Russell's `cloudapp_api` gem](https://github.com/aaronrussell/cloudapp_api#installation) + +2. That you set your CloudApp credentials in `~/.cloudapp` as a simple text file like below: + ``` + email + password + ``` + +## Usage + +- `cloudapp `: uploads `` to your CloudApp account, and if you're using + macOS, copies the URL to your clipboard. diff --git a/plugins/codeclimate/README.md b/plugins/codeclimate/README.md new file mode 100644 index 000000000..0d712ac63 --- /dev/null +++ b/plugins/codeclimate/README.md @@ -0,0 +1,8 @@ +# codeclimate plugin + +This plugin adds autocompletion for the [`codeclimate` CLI](https://github.com/codeclimate/codeclimate). + +To use it, add `codeclimate` to the plugins array in your zshrc file: +```zsh +plugins=(... codeclimate) +``` diff --git a/plugins/colemak/README.md b/plugins/colemak/README.md new file mode 100644 index 000000000..4da4bc126 --- /dev/null +++ b/plugins/colemak/README.md @@ -0,0 +1,48 @@ +# Colemak plugin + +This plugin remaps keys in `zsh`'s [`vi`-style navigation mode](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Keymaps) +for a [Colemak](https://colemak.com/) keyboard layout, to match the QWERTY position: + +![Colemak layout on a US keyboard](https://colemak.com/wiki/images/6/6c/Colemak2.png) + +To use it, add it to the plugins array in your `~/.zshrc` file: + +``` +plugins=(... colemak) +``` + +You will also need to enable `vi` mode, so add another line to `~/.zshrc`: +``` +bindkey -v +``` + +Restart your shell and hit the `` key to activate `vicmd` (navigation) mode, +and start navigating `zsh` with your new keybindings! + +## Key bindings for vicmd + +| Old | New | Binding | Description | +|------------|------------|---------------------------|----------------------------------------------------| +| `CTRL`+`j` | `CTRL`+`n` | accept-line | Insert new line | +| `j` | `n` | down-line-or-history | Move one line down or command history forwards | +| `k` | `e` | up-line-or-history | Move one line up or command history backwards | +| `l` | `i` | vi-forward-char | Move one character to the right | +| `n` | `k` | vi-repeat-search | Repeat command search forwards | +| `N` | `K` | vi-rev-repeat-search | Repeat command search backwards | +| `i` | `u` | vi-insert | Enter insert mode | +| `I` | `U` | vi-insert-bol | Move to first non-blank char and enter insert mode | +| `` | `l` | vi-undo-change | Undo change | +| `J` | `N` | vi-join | Join the current line with the next one | +| `e` | `j` | vi-forward-word-end | Move to the end of the next word | +| `E` | `J` | vi-forward-blank-word-end | Move to end of the current or next word | + +## Key bindings for less + +| Keyboard shortcut | `less` key binding | +|-------------------|--------------------| +| `n` | forw-line | +| `e` | back-line | +| `k` | repeat-search | +| `ESC`+`k` | repeat-search-all | +| `K` | reverse-search | +| `ESC`+`K` | reverse-search-all | diff --git a/plugins/colored-man-pages/README.md b/plugins/colored-man-pages/README.md new file mode 100644 index 000000000..d9f6acb2a --- /dev/null +++ b/plugins/colored-man-pages/README.md @@ -0,0 +1,15 @@ +# Colored man pages plugin + +This plugin adds colors to man pages. + +To use it, add `colored-man-pages` to the plugins array in your zshrc file: + +```zsh +plugins=(... colored-man-pages) +``` + +You can also try to color other pages by prefixing the respective command with `colored`: + +```zsh +colored git help clone +``` diff --git a/plugins/colored-man-pages/colored-man-pages.plugin.zsh b/plugins/colored-man-pages/colored-man-pages.plugin.zsh index 1bea536e0..f74105d40 100644 --- a/plugins/colored-man-pages/colored-man-pages.plugin.zsh +++ b/plugins/colored-man-pages/colored-man-pages.plugin.zsh @@ -16,8 +16,8 @@ EOF fi fi -function man() { - env \ +function colored() { + command env \ LESS_TERMCAP_mb=$(printf "\e[1;31m") \ LESS_TERMCAP_md=$(printf "\e[1;31m") \ LESS_TERMCAP_me=$(printf "\e[0m") \ @@ -28,5 +28,9 @@ function man() { PAGER="${commands[less]:-$PAGER}" \ _NROFF_U=1 \ PATH="$HOME/bin:$PATH" \ - man "$@" + "$@" +} + +function man() { + colored man "$@" } diff --git a/plugins/colorize/README.md b/plugins/colorize/README.md index d1f878e62..ee4ab8036 100644 --- a/plugins/colorize/README.md +++ b/plugins/colorize/README.md @@ -6,30 +6,43 @@ Colorize will highlight the content based on the filename extension. If it can't method for a given extension, it will try to find one by looking at the file contents. If no highlight method is found it will just cat the file normally, without syntax highlighting. -To use it, add colorize to the plugins array of your zshrc file: +## Setup + +To use it, add colorize to the plugins array of your `~/.zshrc` file: ``` plugins=(... colorize) ``` -## Styles +## Configuration + +### Requirements + +This plugin requires that at least one of the following tools is installed: + +* [Chroma](https://github.com/alecthomas/chroma) +* [Pygments](https://pygments.org/download/) + +### Colorize tool + +Colorize supports `pygmentize` and `chroma` as syntax highlighter. By default colorize uses `pygmentize` unless it's not installed and `chroma` is. This can be overridden by the `ZSH_COLORIZE_TOOL` environment variable: + +``` +ZSH_COLORIZE_TOOL=chroma +``` + +### Styles Pygments offers multiple styles. By default, the `default` style is used, but you can choose another theme by setting the `ZSH_COLORIZE_STYLE` environment variable: -`ZSH_COLORIZE_STYLE="colorful"` +``` +ZSH_COLORIZE_STYLE="colorful" +``` ## Usage -* `ccat [files]`: colorize the contents of the file (or files, if more than one are provided). - If no arguments are passed it will colorize the standard input or stdin. +* `ccat [files]`: colorize the contents of the file (or files, if more than one are provided). + If no files are passed it will colorize the standard input. -* `cless [files]`: colorize the contents of the file (or files, if more than one are provided) and - open less. If no arguments are passed it will colorize the standard input or stdin. - -Note that `cless` will behave as less when provided more than one file: you have to navigate files with -the commands `:n` for next and `:p` for previous. The downside is that less options are not supported. -But you can circumvent this by either using the LESS environment variable, or by running `ccat file1 file2|less --opts`. -In the latter form, the file contents will be concatenated and presented by less as a single file. - -## Requirements - -You have to install Pygments first: [pygments.org](http://pygments.org/download/) +* `cless [less-options] [files]`: colorize the contents of the file (or files, if more than one are provided) and open less. + If no files are passed it will colorize the standard input. + The LESSOPEN and LESSCLOSE will be overwritten for this to work, but only in a local scope. diff --git a/plugins/colorize/colorize.plugin.zsh b/plugins/colorize/colorize.plugin.zsh index 565ba5a36..6ed9739fa 100644 --- a/plugins/colorize/colorize.plugin.zsh +++ b/plugins/colorize/colorize.plugin.zsh @@ -1,57 +1,113 @@ -# easier alias to use the plugin -alias ccat='colorize_via_pygmentize' -alias cless='colorize_via_pygmentize_less' +# Easier alias to use the plugin +alias ccat="colorize_cat" +alias cless="colorize_less" -colorize_via_pygmentize() { - if ! (( $+commands[pygmentize] )); then - echo "package 'Pygments' is not installed!" +# '$0:A' gets the absolute path of this file +ZSH_COLORIZE_PLUGIN_PATH=$0:A + +colorize_check_requirements() { + local available_tools=("chroma" "pygmentize") + + if [ -z "$ZSH_COLORIZE_TOOL" ]; then + if (( $+commands[pygmentize] )); then + ZSH_COLORIZE_TOOL="pygmentize" + elif (( $+commands[chroma] )); then + ZSH_COLORIZE_TOOL="chroma" + else + echo "Neither 'pygments' nor 'chroma' is installed!" >&2 + return 1 + fi + fi + + if [[ ${available_tools[(Ie)$ZSH_COLORIZE_TOOL]} -eq 0 ]]; then + echo "ZSH_COLORIZE_TOOL '$ZSH_COLORIZE_TOOL' not recognized. Available options are 'pygmentize' and 'chroma'." >&2 + return 1 + elif (( $+commands["$ZSH_COLORIZE_TOOL"] )); then + echo "Package '$ZSH_COLORIZE_TOOL' is not installed!" >&2 + return 1 + fi +} + +colorize_cat() { + if ! colorize_check_requirements; then return 1 fi - # If the environment varianle ZSH_COLORIZE_STYLE + # If the environment variable ZSH_COLORIZE_STYLE # is set, use that theme instead. Otherwise, # use the default. - if [ -z $ZSH_COLORIZE_STYLE ]; then - ZSH_COLORIZE_STYLE="default" + if [ -z "$ZSH_COLORIZE_STYLE" ]; then + # Both pygmentize & chroma support 'emacs' + ZSH_COLORIZE_STYLE="emacs" fi - # pygmentize stdin if no arguments passed + # Use stdin if no arguments have been passed. if [ $# -eq 0 ]; then - pygmentize -O style="$ZSH_COLORIZE_STYLE" -g + if [[ "$ZSH_COLORIZE_TOOL" == "pygmentize" ]]; then + pygmentize -O style="$ZSH_COLORIZE_STYLE" -g + else + chroma --style="$ZSH_COLORIZE_STYLE" + fi return $? fi - # guess lexer from file extension, or - # guess it from file contents if unsuccessful - + # Guess lexer from file extension, or guess it from file contents if unsuccessful. local FNAME lexer - for FNAME in "$@" - do - lexer=$(pygmentize -N "$FNAME") - if [[ $lexer != text ]]; then - pygmentize -O style="$ZSH_COLORIZE_STYLE" -l "$lexer" "$FNAME" + for FNAME in "$@"; do + if [[ "$ZSH_COLORIZE_TOOL" == "pygmentize" ]]; then + lexer=$(pygmentize -N "$FNAME") + if [[ $lexer != text ]]; then + pygmentize -O style="$ZSH_COLORIZE_STYLE" -l "$lexer" "$FNAME" + else + pygmentize -O style="$ZSH_COLORIZE_STYLE" -g "$FNAME" + fi else - pygmentize -O style="$ZSH_COLORIZE_STYLE" -g "$FNAME" + chroma --style="$ZSH_COLORIZE_STYLE" "$FNAME" fi done } -colorize_via_pygmentize_less() ( - # this function is a subshell so tmp_files can be shared to cleanup function - declare -a tmp_files +# The less option 'F - Forward forever; like "tail -f".' will not work in this implementation +# caused by the lack of the ability to follow the file within pygmentize. +colorize_less() { + if ! colorize_check_requirements; then + return 1 + fi - cleanup () { - [[ ${#tmp_files} -gt 0 ]] && rm -f "${tmp_files[@]}" - exit + _cless() { + # LESS="-R $LESS" enables raw ANSI colors, while maintain already set options. + local LESS="-R $LESS" + + # This variable tells less to pipe every file through the specified command + # (see the man page of less INPUT PREPROCESSOR). + # 'zsh -ic "colorize_cat %s 2> /dev/null"' would not work for huge files like + # the ~/.zsh_history. For such files the tty of the preprocessor will be supended. + # Therefore we must source this file to make colorize_cat available in the + # preprocessor without the interactive mode. + # `2>/dev/null` will suppress the error for large files 'broken pipe' of the python + # script pygmentize, which will show up if less has not fully "loaded the file" + # (e.g. when not scrolled to the bottom) while already the next file will be displayed. + local LESSOPEN="| zsh -c 'source \"$ZSH_COLORIZE_PLUGIN_PATH\"; \ + ZSH_COLORIZE_TOOL=$ZSH_COLORIZE_TOOL ZSH_COLORIZE_STYLE=$ZSH_COLORIZE_STYLE \ + colorize_cat %s 2> /dev/null'" + + # LESSCLOSE will be set to prevent any errors by executing a user script + # which assumes that his LESSOPEN has been executed. + local LESSCLOSE="" + + LESS="$LESS" LESSOPEN="$LESSOPEN" LESSCLOSE="$LESSCLOSE" less "$@" } - trap 'cleanup' EXIT HUP TERM INT - while (( $# != 0 )); do #TODO: filter out less opts - tmp_file="$(mktemp -t "tmp.colorize.XXXX.$(sed 's/\//./g' <<< "$1")")" - tmp_files+=("$tmp_file") - colorize_via_pygmentize "$1" > "$tmp_file" - shift 1 - done - - less -f "${tmp_files[@]}" -) + if [ -t 0 ]; then + _cless "$@" + else + # The input is not associated with a terminal, therefore colorize_cat will + # colorize this input and pass it to less. + # Less has now to decide what to use. If any files have been provided, less + # will ignore the input by default, otherwise the colorized input will be used. + # If files have been supplied and the input has been redirected, this will + # lead to unnecessary overhead, but retains the ability to use the less options + # without checking for them inside this script. + colorize_cat | _cless "$@" + fi +} diff --git a/plugins/common-aliases/README.md b/plugins/common-aliases/README.md new file mode 100644 index 000000000..d198a29ac --- /dev/null +++ b/plugins/common-aliases/README.md @@ -0,0 +1,121 @@ +# Common Aliases Plugin + +This plugin creates helpful shortcut aliases for many commonly used commands. + +To use it add `common-aliases` to the plugins array in your zshrc file: + +```zsh +plugins=(... common-aliases) +``` + +## Aliases + +### ls command + +| Alias | Command | Description | +|-------|---------------|--------------------------------------------------------------------------------| +| l | `ls -lFh` | List files as a long list, show size, type, human-readable | +| la | `ls -lAFh` | List almost all files as a long list show size, type, human-readable | +| lr | `ls -tRFh` | List files recursively sorted by date, show type, human-readable | +| lt | `ls -ltFh` | List files as a long list sorted by date, show type, human-readable | +| ll | `ls -l` | List files as a long list | +| ldot | `ls -ld .*` | List dot files as a long list | +| lS | `ls -1FSsh` | List files showing only size and name sorted by size | +| lart | `ls -1Fcart` | List all files sorted in reverse of create/modification time (oldest first) | +| lrt | `ls -1Fcrt` | List files sorted in reverse of create/modification time(oldest first) | + +### File handling + +| Alias | Command | Description | +|-------|-----------------------|------------------------------------------------------------------------------------| +| rm | `rm -i` | Remove a file | +| cp | `cp -i` | Copy a file | +| mv | `mv -i` | Move a file | +| zshrc | `${=EDITOR} ~/.zshrc` | Quickly access the ~/.zshrc file | +| dud | `du -d 1 -h` | Display the size of files at depth 1 in current location in human-readable form | +| duf | `du -sh` | Display the size of files in current location in human-readable form | +| t | `tail -f` | Shorthand for tail which outputs the last part of a file | + +### find and grep + +| Alias | Command | Description | +|-------|-----------------------------------------------------|-----------------------------------------| +| fd | `find . -type d -name` | Find a directory with the given name | +| ff | `find . -type f -name` | Find a file with the given name | +| grep | `grep --color` | Searches for a query string | +| sgrep | `grep -R -n -H -C 5 --exclude-dir={.git,.svn,CVS}` | Useful for searching within files | + +### Other Aliases + +| Alias | Command | Description | +|-----------|---------------------|-------------------------------------------------------------| +| h | `history` | Lists all recently used commands | +| hgrep | `fc -El 0 \| grep` | Searches for a word in the list of previously used commands | +| help | `man` | Opens up the man page for a command | +| p | `ps -f` | Displays currently executing processes | +| sortnr | `sort -n -r` | Used to sort the lines of a text file | +| unexport | `unset` | Used to unset an environment variable | + +## Global aliases + +These aliases are expanded in any position in the command line, meaning you can use them even at the +end of the command you've typed. Examples: + +Quickly pipe to less: +```zsh +$ ls -l /var/log L +# will run +$ ls -l /var/log | less +``` +Silences stderr output: +```zsh +$ find . -type f NE +# will run +$ find . -type f 2>/dev/null +``` + +| Alias | Command | Description | +|-------|-----------------------------|-------------------------------------------------------------| +| H | `\| head` | Pipes output to head which outputs the first part of a file | +| T | `\| tail` | Pipes output to tail which outputs the last part of a file | +| G | `\| grep` | Pipes output to grep to search for some word | +| L | `\| less` | Pipes output to less, useful for paging | +| M | `\| most` | Pipes output to more, useful for paging | +| LL | `2>&1 \| less` | Writes stderr to stdout and passes it to less | +| CA | `2>&1 \| cat -A` | Writes stderr to stdout and passes it to cat | +| NE | `2 > /dev/null` | Silences stderr | +| NUL | `> /dev/null 2>&1` | Silences both stdout and stderr | +| P | `2>&1\| pygmentize -l pytb` | Writes stderr to stdout and passes it to pygmentize | + +## File extension aliases + +These are special aliases that are triggered when a file name is passed as the command. For example, +if the pdf file extension is aliased to `acroread` (a popular Linux pdf reader), when running `file.pdf` +that file will be open with `acroread`. + +### Reading Docs + +| Alias | Command | Description | +|-------|-------------|-------------------------------------| +| pdf | `acroread` | Opens up a document using acroread | +| ps | `gv` | Opens up a .ps file using gv | +| dvi | `xdvi` | Opens up a .dvi file using xdvi | +| chm | `xchm` | Opens up a .chm file using xchm | +| djvu | `djview` | Opens up a .djvu file using djview | + +### Listing files inside a packed file + +| Alias | Command | Description | +|---------|-------------|-------------------------------------| +| zip | `unzip -l` | Lists files inside a .zip file | +| rar | `unrar l` | Lists files inside a .rar file | +| tar | `tar tf` | Lists files inside a .tar file | +| tar.gz | `echo` | Lists files inside a .tar.gz file | +| ace | `unace l` | Lists files inside a .ace file | + +### Some other features + +- Opens urls in terminal using browser specified by the variable `$BROWSER` +- Opens C, C++, Tex and text files using editor specified by the variable `$EDITOR` +- Opens images using image viewer specified by the variable `$XIVIEWER` +- Opens videos and other media using mplayer diff --git a/plugins/common-aliases/common-aliases.plugin.zsh b/plugins/common-aliases/common-aliases.plugin.zsh index 785a09c63..ce1995c03 100644 --- a/plugins/common-aliases/common-aliases.plugin.zsh +++ b/plugins/common-aliases/common-aliases.plugin.zsh @@ -50,6 +50,7 @@ alias mv='mv -i' # zsh is able to auto-do some kungfoo # depends on the SUFFIX :) +autoload -Uz is-at-least if is-at-least 4.2.0; then # open browser on urls if [[ -n "$BROWSER" ]]; then diff --git a/plugins/compleat/README.md b/plugins/compleat/README.md new file mode 100644 index 000000000..630c91503 --- /dev/null +++ b/plugins/compleat/README.md @@ -0,0 +1,8 @@ +# compleat plugin + +This plugin looks for [compleat](https://github.com/mbrubeck/compleat) and loads its completion. + +To use it, add compleat to the plugins array in your zshrc file: +``` +plugins=(... compleat) +``` diff --git a/plugins/copybuffer/copybuffer.plugin.zsh b/plugins/copybuffer/copybuffer.plugin.zsh index cc205d40f..483ed5a5f 100644 --- a/plugins/copybuffer/copybuffer.plugin.zsh +++ b/plugins/copybuffer/copybuffer.plugin.zsh @@ -1,9 +1,9 @@ # copy the active line from the command line buffer -# onto the system clipboard (requires clipcopy plugin) +# onto the system clipboard copybuffer () { if which clipcopy &>/dev/null; then - echo $BUFFER | clipcopy + printf "%s" "$BUFFER" | clipcopy else echo "clipcopy function not found. Please make sure you have Oh My Zsh installed correctly." fi diff --git a/plugins/dash/README.md b/plugins/dash/README.md new file mode 100644 index 000000000..0ca3e4e44 --- /dev/null +++ b/plugins/dash/README.md @@ -0,0 +1,28 @@ +# Dash plugin + +This plugin adds command line functionality for [Dash](https://kapeli.com/dash), +an API Documentation Browser for macOS. This plugin requires Dash to be installed +to work. + +To use it, add `dash` to the plugins array in your zshrc file: + +```zsh +plugins=(... dash) +``` + +## Usage + +- Open and switch to the dash application. +``` +dash +``` + +- Query for something in dash app: `dash query` +``` +dash golang +``` + +- You can optionally provide a keyword: `dash [keyword:]query` +``` +dash python:tuple +``` diff --git a/plugins/dash/dash.plugin.zsh b/plugins/dash/dash.plugin.zsh index b00d4877e..ace2e33c1 100644 --- a/plugins/dash/dash.plugin.zsh +++ b/plugins/dash/dash.plugin.zsh @@ -35,36 +35,30 @@ _dash() { if [[ "$locator" == "platform" ]]; then # Since these are the only special cases right now, let's not do the # expensive processing unless we have to - if [[ "$keyword" == "python" || "$keyword" == "java" || \ - "$keyword" == "qt" || "$keyword" == "cocs2d" ]]; then + if [[ "$keyword" = (python|java|qt|cocos2d) ]]; then docsetName=`echo $doc | grep -Eo "docsetName = .*?;" | sed -e "s/docsetName = \(.*\);/\1/" -e "s/[\":]//g"` - if [[ "$keyword" == "python" ]]; then - if [[ "$docsetName" == "Python 2" ]]; then - keyword="python2" - elif [[ "$docsetName" == "Python 3" ]]; then - keyword="python3" - fi - elif [[ "$keyword" == "java" ]]; then - if [[ "$docsetName" == "Java SE7" ]]; then - keyword="java7" - elif [[ "$docsetName" == "Java SE6" ]]; then - keyword="java6" - elif [[ "$docsetName" == "Java SE8" ]]; then - keyword="java8" - fi - elif [[ "$keyword" == "qt" ]]; then - if [[ "$docsetName" == "Qt 5" ]]; then - keyword="qt5" - elif [[ "$docsetName" == "Qt 4" ]]; then - keyword="qt4" - elif [[ "$docsetName" == "Qt" ]]; then - keyword="qt4" - fi - elif [[ "$keyword" == "cocos2d" ]]; then - if [[ "$docsetName" == "Cocos3D" ]]; then - keyword="cocos3d" - fi - fi + case "$keyword" in + python) + case "$docsetName" in + "Python 2") keyword="python2" ;; + "Python 3") keyword="python3" ;; + esac ;; + java) + case "$docsetName" in + "Java SE7") keyword="java7" ;; + "Java SE6") keyword="java6" ;; + "Java SE8") keyword="java8" ;; + esac ;; + qt) + case "$docsetName" in + "Qt 5") keyword="qt5" ;; + "Qt 4"|Qt) keyword="qt4" ;; + esac ;; + cocos2d) + case "$docsetName" in + Cocos3D) keyword="cocos3d" ;; + esac ;; + esac fi fi diff --git a/plugins/debian/debian.plugin.zsh b/plugins/debian/debian.plugin.zsh index be4062ebf..68c6df1ae 100644 --- a/plugins/debian/debian.plugin.zsh +++ b/plugins/debian/debian.plugin.zsh @@ -72,7 +72,7 @@ if [[ $use_sudo -eq 1 ]]; then # commands using su ######### else alias aac="su -ls '$apt_pref autoclean' root" - abd() { + function abd() { cmd="su -lc '$apt_pref build-dep $@' root" print "$cmd" eval "$cmd" @@ -83,17 +83,17 @@ else alias adu="su -lc '$apt_pref update && aptitude dist-upgrade' root" alias afu="su -lc '$apt-file update'" alias au="su -lc '$apt_pref $apt_upgr' root" - ai() { + function ai() { cmd="su -lc 'aptitude -P install $@' root" print "$cmd" eval "$cmd" } - ap() { + function ap() { cmd="su -lc '$apt_pref -P purge $@' root" print "$cmd" eval "$cmd" } - ar() { + function ar() { cmd="su -lc '$apt_pref -P remove $@' root" print "$cmd" eval "$cmd" @@ -114,7 +114,7 @@ fi # Registers a compdef for $1 that calls $apt_pref with the commands $2 # To do that it creates a new completion function called _apt_pref_$2 # -apt_pref_compdef() { +function apt_pref_compdef() { local f fb f="_apt_pref_${2}" @@ -151,7 +151,7 @@ alias mydeb='time dpkg-buildpackage -rfakeroot -us -uc' # Functions ################################################################# # create a simple script that can be used to 'duplicate' a system -apt-copy() { +function apt-copy() { print '#!/bin/sh'"\n" > apt-copy.sh cmd='$apt_pref install' @@ -173,7 +173,7 @@ apt-copy() { # apt-history rollback # apt-history list # Based On: https://linuxcommando.blogspot.com/2008/08/how-to-show-apt-log-history.html -apt-history () { +function apt-history() { case "$1" in install) zgrep --no-filename 'install ' $(ls -rt /var/log/dpkg*) @@ -202,7 +202,7 @@ apt-history () { } # Kernel-package building shortcut -kerndeb () { +function kerndeb() { # temporarily unset MAKEFLAGS ( '-j3' will fail ) MAKEFLAGS=$( print - $MAKEFLAGS | perl -pe 's/-j\s*[\d]+//g' ) print '$MAKEFLAGS set to '"'$MAKEFLAGS'" @@ -216,10 +216,9 @@ kerndeb () { } # List packages by size -function apt-list-packages { +function apt-list-packages() { dpkg-query -W --showformat='${Installed-Size} ${Package} ${Status}\n' | \ grep -v deinstall | \ sort -n | \ awk '{print $1" "$2}' } - diff --git a/plugins/dircycle/README.md b/plugins/dircycle/README.md index 3ac162f05..3c9b3a96f 100644 --- a/plugins/dircycle/README.md +++ b/plugins/dircycle/README.md @@ -15,10 +15,10 @@ This plugin enables directory navigation similar to using back and forward on br ) ``` -2. Reload the source file or restart your Terminal session: +2. Restart the shell or restart your Terminal session: ```console - $ source ~/.zshrc + $ exec zsh $ ``` diff --git a/plugins/dirhistory/dirhistory.plugin.zsh b/plugins/dirhistory/dirhistory.plugin.zsh index 239915e48..35c43d76a 100644 --- a/plugins/dirhistory/dirhistory.plugin.zsh +++ b/plugins/dirhistory/dirhistory.plugin.zsh @@ -53,7 +53,8 @@ function push_future() { } # Called by zsh when directory changes -chpwd_functions+=(chpwd_dirhistory) +autoload -U add-zsh-hook +add-zsh-hook chpwd chpwd_dirhistory function chpwd_dirhistory() { push_past $PWD # If DIRHISTORY_CD is not set... diff --git a/plugins/dirpersist/dirpersist.plugin.zsh b/plugins/dirpersist/dirpersist.plugin.zsh index 616e2c3c6..daadc3850 100644 --- a/plugins/dirpersist/dirpersist.plugin.zsh +++ b/plugins/dirpersist/dirpersist.plugin.zsh @@ -11,7 +11,8 @@ if [[ -f ${dirstack_file} ]] && [[ ${#dirstack[*]} -eq 0 ]] ; then [[ -d $dirstack[1] ]] && cd $dirstack[1] && cd $OLDPWD fi -chpwd_functions+=(chpwd_dirpersist) +autoload -U add-zsh-hook +add-zsh-hook chpwd chpwd_dirpersist chpwd_dirpersist() { if (( $DIRSTACKSIZE <= 0 )) || [[ -z $dirstack_file ]]; then return; fi local -ax my_stack diff --git a/plugins/django/django.plugin.zsh b/plugins/django/django.plugin.zsh index 86558ff2e..c2d00c171 100644 --- a/plugins/django/django.plugin.zsh +++ b/plugins/django/django.plugin.zsh @@ -374,7 +374,8 @@ _managepy-commands() { _applist() { local line local -a apps - _call_program help-command "python -c \"import os.path as op, re, django.conf, sys;\\ + _call_program help-command "python -c \"import sys; del sys.path[0];\\ + import os.path as op, re, django.conf;\\ bn=op.basename(op.abspath(op.curdir));[sys\\ .stdout.write(str(re.sub(r'^%s\.(.*?)$' % bn, r'\1', i)) + '\n') for i in django.conf.settings.\\ diff --git a/plugins/docker/README.md b/plugins/docker/README.md index e91798485..4d9f3ae9b 100644 --- a/plugins/docker/README.md +++ b/plugins/docker/README.md @@ -1,5 +1,11 @@ -## Docker autocomplete plugin +# Docker plugin -A copy of the completion script from the -[docker/cli](https://github.com/docker/cli/blob/master/contrib/completion/zsh/_docker) -git repo. +This plugin adds auto-completion for [docker](https://www.docker.com/). + +To use it add `docker` to the plugins array in your zshrc file. +```zsh +plugins=(... docker) +``` + +A copy of the completion script from the docker/cli git repo: +https://github.com/docker/cli/blob/master/contrib/completion/zsh/_docker diff --git a/plugins/dotenv/README.md b/plugins/dotenv/README.md index cac552485..dbc02bf61 100644 --- a/plugins/dotenv/README.md +++ b/plugins/dotenv/README.md @@ -32,6 +32,8 @@ PORT=3001 ``` You can even mix both formats, although it's probably a bad idea. +## Plugin options + ### ZSH_DOTENV_FILE You can also modify the name of the file to be loaded with the variable `ZSH_DOTENV_FILE`. @@ -43,6 +45,10 @@ For example, this will make the plugin look for files named `.dotenv` and load t ZSH_DOTENV_FILE=.dotenv ``` +### ZSH_DOTENV_PROMPT + +Set `ZSH_DOTENV_PROMPT=false` in your zshrc file if you don't want the confirmation message. + ## Version Control **It's strongly recommended to add `.env` file to `.gitignore`**, because usually it contains sensitive information such as your credentials, secret keys, passwords etc. You don't want to commit this file, it's supposed to be local only. diff --git a/plugins/dotenv/dotenv.plugin.zsh b/plugins/dotenv/dotenv.plugin.zsh index 89763d0ee..54036bee3 100644 --- a/plugins/dotenv/dotenv.plugin.zsh +++ b/plugins/dotenv/dotenv.plugin.zsh @@ -1,5 +1,17 @@ source_env() { if [[ -f $ZSH_DOTENV_FILE ]]; then + if [ "$ZSH_DOTENV_PROMPT" != "false" ]; then + # confirm before sourcing file + local confirmation + # print same-line prompt and output newline character if necessary + echo -n "dotenv: source '$ZSH_DOTENV_FILE' file in the directory? (Y/n) " + read -k 1 confirmation; [[ "$confirmation" != $'\n' ]] && echo + # only bail out if confirmation character is n + if [[ "$confirmation" = [nN] ]]; then + return + fi + fi + # test .env syntax zsh -fn $ZSH_DOTENV_FILE || echo "dotenv: error when sourcing '$ZSH_DOTENV_FILE' file" >&2 diff --git a/plugins/dotnet/README.md b/plugins/dotnet/README.md new file mode 100644 index 000000000..7554b4e3c --- /dev/null +++ b/plugins/dotnet/README.md @@ -0,0 +1,23 @@ +# .NET Core CLI plugin + +This plugin provides completion and useful aliases for [.NET Core CLI](https://dotnet.microsoft.com/). + +To use it, add `dotnet` to the plugins array in your zshrc file. + +``` +plugins=(... dotnet) +``` + +## Aliases + +| Alias | Command | Description | +|-------|------------------|-------------------------------------------------------------------| +| dn | dotnet new | Create a new .NET project or file. | +| dr | dotnet run | Build and run a .NET project output. | +| dt | dotnet test | Run unit tests using the test runner specified in a .NET project. | +| dw | dotnet watch | Watch for source file changes and restart the dotnet command. | +| dwr | dotnet watch run | Watch for source file changes and restart the `run` command. | +| ds | dotnet sln | Modify Visual Studio solution files. | +| da | dotnet add | Add a package or reference to a .NET project. | +| dp | dotnet pack | Create a NuGet package. | +| dng | dotnet nuget | Provides additional NuGet commands. | diff --git a/plugins/dotnet/dotnet.plugin.zsh b/plugins/dotnet/dotnet.plugin.zsh new file mode 100644 index 000000000..6bd4b7af8 --- /dev/null +++ b/plugins/dotnet/dotnet.plugin.zsh @@ -0,0 +1,32 @@ +# This scripts is copied from (MIT License): +# https://github.com/dotnet/toolset/blob/master/scripts/register-completions.zsh + +_dotnet_zsh_complete() +{ + local completions=("$(dotnet complete "$words")") + + # If the completion list is empty, just continue with filename selection + if [ -z "$completions" ] + then + _arguments '*::arguments: _normal' + return + fi + + # This is not a variable assigment, don't remove spaces! + _values = "${(ps:\n:)completions}" +} + +compdef _dotnet_zsh_complete dotnet + +# Aliases bellow are here for backwards compatibility +# added by Shaun Tabone (https://github.com/xontab) + +alias dn='dotnet new' +alias dr='dotnet run' +alias dt='dotnet test' +alias dw='dotnet watch' +alias dwr='dotnet watch run' +alias ds='dotnet sln' +alias da='dotnet add' +alias dp='dotnet pack' +alias dng='dotnet nuget' diff --git a/plugins/eecms/README.md b/plugins/eecms/README.md new file mode 100644 index 000000000..c53835521 --- /dev/null +++ b/plugins/eecms/README.md @@ -0,0 +1,11 @@ +# eecms plugin + +This plugin adds auto-completion of console commands for [`eecms`](https://github.com/ExpressionEngine/ExpressionEngine). + +To use it, add `eecms` to the plugins array of your `.zshrc` file: +``` +plugins=(... eecms) +``` + +It also adds the alias `eecms` which finds the eecms file in the current project +and runs it with php. diff --git a/plugins/emacs/emacsclient.sh b/plugins/emacs/emacsclient.sh index 26b28d495..0aa8d6f40 100755 --- a/plugins/emacs/emacsclient.sh +++ b/plugins/emacs/emacsclient.sh @@ -20,7 +20,8 @@ _emacsfun() # tempfile. (first argument will be `--no-wait` passed in by the plugin.zsh) if [ "$#" -ge "2" -a "$2" = "-" ] then - tempfile="$(mktemp emacs-stdin-$USER.XXXXXXX --tmpdir)" + tempfile="$(mktemp --tmpdir emacs-stdin-$USER.XXXXXXX 2>/dev/null \ + || mktemp -t emacs-stdin-$USER)" # support BSD mktemp cat - > "$tempfile" _emacsfun --no-wait $tempfile else diff --git a/plugins/emoji-clock/emoji-clock.plugin.zsh b/plugins/emoji-clock/emoji-clock.plugin.zsh index 0a55528f0..bdd606f89 100644 --- a/plugins/emoji-clock/emoji-clock.plugin.zsh +++ b/plugins/emoji-clock/emoji-clock.plugin.zsh @@ -2,7 +2,7 @@ # FILE: emoji-clock.plugin.zsh # DESCRIPTION: The current time with half hour accuracy as an emoji symbol. # Inspired by Andre Torrez' "Put A Burger In Your Shell" -# http://notes.torrez.org/2013/04/put-a-burger-in-your-shell.html +# https://notes.torrez.org/2013/04/put-a-burger-in-your-shell.html # AUTHOR: Alexis Hildebrandt (afh[at]surryhill.net) # VERSION: 1.0.0 # ----------------------------------------------------------------------------- diff --git a/plugins/emotty/README.md b/plugins/emotty/README.md new file mode 100644 index 000000000..ee571705a --- /dev/null +++ b/plugins/emotty/README.md @@ -0,0 +1,39 @@ +# emotty plugin + +This plugin returns an emoji for the current $TTY number so it can be used +in a prompt. + +To use it, add emotty to the plugins array in your zshrc file: +``` +plugins=(... emotty) +``` + +**NOTE:** it requires the [emoji plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/emoji). + +## Usage + +The function `emotty` displays an emoji from the current character set (default: `emoji`), based +on the number associated to the `$TTY`. + +There are different sets of emoji characters available, to choose a different +set, set `$emotty_set` to the name of the set you would like to use, e.g.: +``` +emotty_set=nature +``` + +### Character Sets + +- emoji +- loral +- love +- nature +- stellar +- zodiac + +Use the `display_emotty` function to list the emojis in the current character set, or +the character set passed as the first argument. For example: + +``` +$ display_emotty zodiac + +``` diff --git a/plugins/encode64/README.md b/plugins/encode64/README.md index 9850da85f..66fc7cba4 100644 --- a/plugins/encode64/README.md +++ b/plugins/encode64/README.md @@ -20,10 +20,10 @@ Alias plugin for encoding or decoding using `base64` command ) ``` -2. Restart your terminal session or reload configuration by running: +2. Restart your terminal session or restart the shell: ```sh - source ~/.zshrc + exec zsh ``` ## Usage and examples diff --git a/plugins/extract/README.md b/plugins/extract/README.md index 83b878c32..81e8e1d23 100644 --- a/plugins/extract/README.md +++ b/plugins/extract/README.md @@ -25,23 +25,32 @@ plugins=(... extract) | `gz` | Gzip file | | `ipsw` | iOS firmware file | | `jar` | Java Archive | +| `lrz` | LRZ archive | +| `lz4` | LZ4 archive | | `lzma` | LZMA archive | | `rar` | WinRAR archive | +| `rpm` | RPM package | | `sublime-package` | Sublime Text package | | `tar` | Tarball | | `tar.bz2` | Tarball with bzip2 compression | | `tar.gz` | Tarball with gzip compression | +| `tar.lrz` | Tarball with lrzip compression | +| `tar.lz` | Tarball with lzip compression | +| `tar.lz4` | Tarball with lz4 compression | | `tar.xz` | Tarball with lzma2 compression | | `tar.zma` | Tarball with lzma compression | +| `tar.zst` | Tarball with zstd compression | | `tbz` | Tarball with bzip compression | | `tbz2` | Tarball with bzip2 compression | | `tgz` | Tarball with gzip compression | | `tlz` | Tarball with lzma compression | | `txz` | Tarball with lzma2 compression | +| `tzst` | Tarball with zstd compression | | `war` | Web Application archive (Java-based) | | `xpi` | Mozilla XPI module file | | `xz` | LZMA2 archive | | `zip` | Zip archive | +| `zst` | Zstandard file (zstd) | See [list of archive formats](https://en.wikipedia.org/wiki/List_of_archive_formats) for more information regarding archive formats. diff --git a/plugins/extract/_extract b/plugins/extract/_extract index 33d49fcc5..1a263a744 100644 --- a/plugins/extract/_extract +++ b/plugins/extract/_extract @@ -3,5 +3,5 @@ _arguments \ '(-r --remove)'{-r,--remove}'[Remove archive.]' \ - "*::archive file:_files -g '(#i)*.(7z|Z|apk|aar|bz2|deb|gz|ipsw|jar|lzma|rar|sublime-package|tar|tar.bz2|tar.gz|tar.xz|tar.zma|tbz|tbz2|tgz|tlz|txz|war|whl|xpi|xz|zip)(-.)'" \ + "*::archive file:_files -g '(#i)*.(7z|Z|apk|aar|bz2|deb|gz|ipsw|jar|lrz|lz4|lzma|rar|rpm|sublime-package|tar|tar.bz2|tar.gz|tar.lrz|tar.lz|tar.lz4|tar.xz|tar.zma|tar.zst|tbz|tbz2|tgz|tlz|txz|tzst|war|whl|xpi|xz|zip|zst)(-.)'" \ && return 0 diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh index 5e9b9ff24..a5594b81a 100644 --- a/plugins/extract/extract.plugin.zsh +++ b/plugins/extract/extract.plugin.zsh @@ -40,14 +40,24 @@ extract() { tar --lzma --help &> /dev/null \ && tar --lzma -xvf "$1" \ || lzcat "$1" | tar xvf - ;; + (*.tar.zst|*.tzst) + tar --zstd --help &> /dev/null \ + && tar --zstd -xvf "$1" \ + || zstdcat "$1" | tar xvf - ;; (*.tar) tar xvf "$1" ;; - (*.gz) (( $+commands[pigz] )) && pigz -d "$1" || gunzip "$1" ;; + (*.tar.lz) (( $+commands[lzip] )) && tar xvf "$1" ;; + (*.tar.lz4) lz4 -c -d "$1" | tar xvf - ;; + (*.tar.lrz) (( $+commands[lrzuntar] )) && lrzuntar "$1" ;; + (*.gz) (( $+commands[pigz] )) && pigz -dk "$1" || gunzip -k "$1" ;; (*.bz2) bunzip2 "$1" ;; (*.xz) unxz "$1" ;; + (*.lrz) (( $+commands[lrunzip] )) && lrunzip "$1" ;; + (*.lz4) lz4 -d "$1" ;; (*.lzma) unlzma "$1" ;; (*.z) uncompress "$1" ;; (*.zip|*.war|*.jar|*.sublime-package|*.ipsw|*.xpi|*.apk|*.aar|*.whl) unzip "$1" -d $extract_dir ;; (*.rar) unrar x -ad "$1" ;; + (*.rpm) mkdir "$extract_dir" && cd "$extract_dir" && rpm2cpio "../$1" | cpio --quiet -id && cd .. ;; (*.7z) 7za x "$1" ;; (*.deb) mkdir -p "$extract_dir/control" @@ -58,6 +68,7 @@ extract() { cd ..; rm *.tar.* debian-binary cd .. ;; + (*.zst) unzstd "$1" ;; (*) echo "extract: '$1' cannot be extracted" >&2 success=1 diff --git a/plugins/fabric/_fab b/plugins/fabric/_fab index 9628e1224..9102dadef 100644 --- a/plugins/fabric/_fab +++ b/plugins/fabric/_fab @@ -4,10 +4,19 @@ local curcontext=$curcontext state line declare -A opt_args -declare target_list -target_list=(`fab --shortlist 2>/dev/null`) +declare -a target_list +target_list=("${(@f)$(fab -l 2>/dev/null | awk '{ + if (NF == 0 || NR == 1) next + if (NF < 2) print $1 + else { + docstring=substr($0, index($0,$2)) + gsub(":", "\\:", docstring) + print $1":"docstring + } +}')}") -_targets() { +_fab_targets() { + [[ -n "$target_list" ]] || return _describe -t commands "fabric targets" target_list } @@ -28,7 +37,7 @@ _arguments -w -S -C \ '(-)--shortlist[print non-verbose list of possible commands and exit]: :->noargs' \ '(--reject-unknown-hosts)--reject-unknown-hosts[reject unknown hosts]' \ '(--no-pty)--no-pty[do not use pseudo-terminal in run/sudo]' \ - "(-d+ --display=-)"{-d+,--display=-}"[print detailed info about a given command]: :_targets" \ + "(-d+ --display=-)"{-d+,--display=-}"[print detailed info about a given command]: :_fab_targets" \ '(-D --disable-known-hosts)'{-D,--disable-known-hosts}'[do not load user known_hosts file]' \ '(-r --reject-unknown-hosts)'{-r,--reject-unknown-hosts}'[reject unknown hosts]' \ '(-u+ --user=-)'{-u+,--user=-}'[username to use when connecting to remote hosts]: :' \ @@ -53,7 +62,7 @@ if [[ CURRENT -ge 1 ]]; then levels) _describe -t commands "output levels" output_levels;; *) - _targets;; + _fab_targets;; esac return diff --git a/plugins/fasd/README.md b/plugins/fasd/README.md new file mode 100644 index 000000000..a5c74e5b8 --- /dev/null +++ b/plugins/fasd/README.md @@ -0,0 +1,21 @@ +# fasd + +[`Fasd`](https://github.com/clvv/fasd) (pronounced similar to "fast") is a command-line productivity booster. Fasd offers quick access to files and directories for POSIX shells. + +To use it, add `fasd` to the plugins array in your zshrc file: + +```zsh +plugins=(... fasd) +``` + +## Installation + +Please find detailed installation guide [`here`](https://github.com/clvv/fasd#install) + +## Aliases + +| Alias | Command | Description | +|-------|-------------------------------------------|-------------------------------------------------------------| +| v | `fasd -f -e "$EDITOR"` | List frequent/recent files matching the given filename. | +| o | `fasd -a -e xdg-open` | List frequent/recent files and directories matching. | +| j | `fasd_cd -d -i` | cd with interactive selection | diff --git a/plugins/fastfile/README.md b/plugins/fastfile/README.md new file mode 100644 index 000000000..37f5b2f53 --- /dev/null +++ b/plugins/fastfile/README.md @@ -0,0 +1,84 @@ +# Fastfile plugin + +This plugin adds a way to reference certain files or folders used frequently using +a global alias or shortcut. + +To use it, add `fastfile` to the plugins array in your zshrc file: +```zsh +plugins=(... fastfile) +``` + +## Usage + +Example: you access folder `/code/project/backend/database` very frequently. + +First, generate a shortcut with the name `pjdb`: +```zsh +$ fastfile pjdb /code/project/backend/database +``` + +Next time you want to access it, use `ยงpjdb`. For example: +```zsh +$ cd ยงpjdb +$ subl ยงpjdb +``` +where ยง is the fastfile prefix (see [below](#options) for how to change). + +**Note:** shortcuts with spaces in the name are assigned a global alias +where the spaces have been substituted with underscores (`_`). For example: +a shortcut named `"hello world"` corresponds with `ยงhello_world`. + + +## Functions + +- `fastfile `: generate a shortcut. + +- `fastfile_print `: prints a shortcut, with the format + ` -> `. + +- `fastfile_ls`: lists all shortcuts. + +- `fastfile_rm `: remove a shortcut. + +- `fastfile_sync`: generates the global aliases for the shortcuts. + + +### Internal functions + +- `fastfile_resolv `: resolves the location of the shortcut + file, i.e., the file in the fastfile directory where the shortcut path + is stored. + +- `fastfile_get `: get the real path of the shortcut. + + +## Aliases + +| Alias | Function | +|--------|------------------| +| ff | `fastfile` | +| ffp | `fastfile_print` | +| ffrm | `fastfile_rm` | +| ffls | `fastfile_ls` | +| ffsync | `fastfile_sync` | + + +## Options + +These are options you can set to change certain parts of the plugin. To change +them, add `=` to your zshrc file, before Oh My Zsh is sourced. +For example: `fastfile_var_prefix='@'`. + +- `fastfile_var_prefix`: prefix for the global aliases created. Controls the prefix of the + created global aliases. + **Default:** `ยง` (section sign), easy to type in a german keyboard via the combination + [`โ‡ง Shift`+`3`](https://en.wikipedia.org/wiki/German_keyboard_layout#/media/File:KB_Germany.svg), + or using `โŒฅ Option`+`6` in macOS. + +- `fastfile_dir`: directory where the fastfile shortcuts are stored. Needs to end + with a trailing slash. + **Default:** `$HOME/.fastfile/`. + +## Author + +- [Karolin Varner](https://github.com/koraa) diff --git a/plugins/fastfile/fastfile.plugin.zsh b/plugins/fastfile/fastfile.plugin.zsh index 775e9483e..a4229e4c2 100644 --- a/plugins/fastfile/fastfile.plugin.zsh +++ b/plugins/fastfile/fastfile.plugin.zsh @@ -1,15 +1,5 @@ -################################################################################ -# FILE: fastfile.plugin.zsh -# DESCRIPTION: oh-my-zsh plugin file. -# AUTHOR: Michael Varner (musikmichael@web.de) -# VERSION: 1.0.0 -# -# This plugin adds the ability to on the fly generate and access file shortcuts. -# -################################################################################ - ########################### -# Settings +# Settings # These can be overwritten any time. # If they are not set yet, they will be @@ -33,7 +23,7 @@ default fastfile_var_prefix "ยง" function fastfile() { test "$2" || 2="." file=$(readlink -f "$2") - + test "$1" || 1="$(basename "$file")" name=$(echo "$1" | tr " " "_") @@ -51,7 +41,7 @@ function fastfile() { # Arguments: # 1. name - The name of the shortcut # STDOUT: -# The path +# The path to the shortcut file # function fastfile_resolv() { echo "${fastfile_dir}${1}" @@ -88,12 +78,12 @@ function fastfile_print() { # (=> fastfle_print) for each shortcut # function fastfile_ls() { - for f in "${fastfile_dir}"/*; do - file=`basename "$f"` # To enable simpler handeling of spaces in file names - varkey=`echo "$file" | tr " " "_"` + for f in "${fastfile_dir}"/*; do + file=`basename "$f"` # To enable simpler handeling of spaces in file names + varkey=`echo "$file" | tr " " "_"` - # Special format for colums - echo "${fastfile_var_prefix}${varkey}|->|$(fastfile_get "$file")" + # Special format for colums + echo "${fastfile_var_prefix}${varkey}|->|$(fastfile_get "$file")" done | column -t -s "|" } @@ -102,7 +92,6 @@ function fastfile_ls() { # # Arguments: # 1. name - The name of the shortcut (default: name of the file) -# 2. file - The file or directory to make the shortcut for # STDOUT: # => fastfle_print # @@ -115,11 +104,11 @@ function fastfile_rm() { # Generate the aliases for the shortcuts # function fastfile_sync() { - for f in "${fastfile_dir}"/*; do - file=`basename "$f"` # To enable simpler handeling of spaces in file names - varkey=`echo "$file" | tr " " "_"` + for f in "${fastfile_dir}"/*; do + file=`basename "$f"` # To enable simpler handeling of spaces in file names + varkey=`echo "$file" | tr " " "_"` - alias -g "${fastfile_var_prefix}${varkey}"="'$(fastfile_get "$file")'" + alias -g "${fastfile_var_prefix}${varkey}"="'$(fastfile_get "$file")'" done } @@ -133,6 +122,6 @@ alias ffls=fastfile_ls alias ffsync=fastfile_sync ################################## -# Init +# Init -fastfile_sync \ No newline at end of file +fastfile_sync diff --git a/plugins/fbterm/README.md b/plugins/fbterm/README.md new file mode 100644 index 000000000..eec33d7ee --- /dev/null +++ b/plugins/fbterm/README.md @@ -0,0 +1,9 @@ +# fbterm + +This plugin automatically starts [fbterm](https://github.com/zhangyuanwei/fbterm) +if on a real TTY (`/dev/tty*`). + +To use it, add fbterm to the plugins array of your zshrc file: +``` +plugins=(... fbterm) +``` diff --git a/plugins/fedora/README.md b/plugins/fedora/README.md index 6594799b3..85d8d7dea 100644 --- a/plugins/fedora/README.md +++ b/plugins/fedora/README.md @@ -1 +1 @@ -The fedora plugin is deprecated. Use the [dnf plugin](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/dnf) instead. +The fedora plugin is deprecated. Use the [dnf plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/dnf) instead. diff --git a/plugins/firewalld/readme.md b/plugins/firewalld/README.md similarity index 100% rename from plugins/firewalld/readme.md rename to plugins/firewalld/README.md diff --git a/plugins/flutter/README.md b/plugins/flutter/README.md new file mode 100644 index 000000000..be419144f --- /dev/null +++ b/plugins/flutter/README.md @@ -0,0 +1,21 @@ +## Flutter plugin + +The Flutter plugin provides completion and useful aliases + +To use it, add flutter to the plugins array of your zshrc file: + +``` +plugins=(... flutter) +``` + +## Aliases + +| Alias | Command | Description | +| :--------- | :--------------------- | :------------------------------------------------------------------------- | +| `fl` | `flutter` | Shorthand for flutter command | +| `flr` | `flutter run` | Runs flutter app | +| `fldoc` | `flutter doctor` | Runs flutter doctor | +| `flb` | `flutter build` | Build flutter application | +| `flattach` | `flutter attach` | Attaches flutter to a running flutter application with enabled observatory | +| `flget` | `flutter packages get` | Installs dependencies | +| `flc` | `flutter clean` | Cleans flutter porject | diff --git a/plugins/flutter/_flutter b/plugins/flutter/_flutter new file mode 100644 index 000000000..ab6ce4265 --- /dev/null +++ b/plugins/flutter/_flutter @@ -0,0 +1,37 @@ +#compdef flutter +#autoload + +local -a _1st_arguments +_1st_arguments=( + "analyze":"Analyze the project's Dart code." + "assemble":"Assemble and build flutter resources." + "attach":"Attach to a running application." + "build":"Flutter build commands." + "channel":"List or switch flutter channels." + "clean":"Delete the build/ and .dart_tool/ directories." + "config":"Configure Flutter settings." + "create":"Create a new Flutter project." + "devices":"List all connected devices." + "doctor":"Show information about the installed tooling." + "drive":"Runs Flutter Driver tests for the current project." + "emulators":"List, launch and create emulators." + "format":" Format one or more dart files." + "help":"Display help information for flutter." + "install":"Install a Flutter app on an attached device." + "logs":"Show log output for running Flutter apps." + "make-host-app-editable":"Moves host apps from generated directories to non-generated directories so that they can be edited by developers." + "precache":"Populates the Flutter tool's cache of binary artifacts." + "pub":"Commands for managing Flutter packages." + "run":"Run your Flutter app on an attached device." + "screenshot":"Take a screenshot from a connected device." + "test":"Run Flutter unit tests for the current project." + "upgrade":"Upgrade your copy of Flutter." + "version":"List or switch flutter versions." +) + +_arguments -C '*:: :->subcmds' + +if (( CURRENT == 1 )); then + _describe -t commands "flutter command" _1st_arguments + return +fi diff --git a/plugins/flutter/flutter.plugin.zsh b/plugins/flutter/flutter.plugin.zsh new file mode 100644 index 000000000..01c4c9f5f --- /dev/null +++ b/plugins/flutter/flutter.plugin.zsh @@ -0,0 +1,7 @@ +alias fl="flutter" +alias flr="flutter run" +alias fldoc="flutter doctor" +alias flb="flutter build" +alias flattach="flutter attach" +alias flget="flutter packages get" +alias flc="flutter clean" diff --git a/plugins/frontend-search/README.md b/plugins/frontend-search/README.md index bf76902fd..ddcb3d72b 100644 --- a/plugins/frontend-search/README.md +++ b/plugins/frontend-search/README.md @@ -62,6 +62,10 @@ Available search contexts are: If you want to have another context, open an Issue and tell us! +## Fallback search behaviour + +The plugin will use Google as a fallback if the docs site for a search context does not have a search function. You can set the fallback search engine to DuckDuckGo by setting `FRONTEND_SEARCH_FALLBACK='duckduckgo'` in your `~/.zshrc` file before Oh My Zsh is sourced. + ## Author **Wilson Mendes (willmendesneto)** diff --git a/plugins/frontend-search/frontend-search.plugin.zsh b/plugins/frontend-search/frontend-search.plugin.zsh index 87243be13..ed19280c4 100644 --- a/plugins/frontend-search/frontend-search.plugin.zsh +++ b/plugins/frontend-search/frontend-search.plugin.zsh @@ -27,6 +27,17 @@ alias typescript='frontend typescript' alias unheap='frontend unheap' alias vuejs='frontend vuejs' +function _frontend_fallback() { + local url + if [[ "$FRONTEND_SEARCH_FALLBACK" == duckduckgo ]]; then + url="https://duckduckgo.com/?sites=$1&q=" + else + url="https://google.com/search?as_sitesearch=$1&as_q=" + fi + + echo "$url" +} + function frontend() { emulate -L zsh @@ -34,8 +45,8 @@ function frontend() { typeset -A urls urls=( angular 'https://angular.io/?search=' - angularjs 'https://google.com/search?as_sitesearch=angularjs.org&as_q=' - bem 'https://google.com/search?as_sitesearch=bem.info&as_q=' + angularjs $(_frontend_fallback 'angularjs.org') + bem $(_frontend_fallback 'bem.info') bootsnipp 'https://bootsnipp.com/search?q=' bundlephobia 'https://bundlephobia.com/result?p=' caniuse 'https://caniuse.com/#search=' @@ -43,24 +54,24 @@ function frontend() { compassdoc 'http://compass-style.org/search?q=' cssflow 'http://www.cssflow.com/search?q=' dartlang 'https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:' - emberjs 'https://www.google.com/search?as_sitesearch=emberjs.com/&as_q=' - flowtype 'https://google.com/search?as_sitesearch=flow.org/en/docs/&as_q=' + emberjs $(_frontend_fallback 'emberjs.com/') + flowtype $(_frontend_fallback 'flow.org/en/docs/') fontello 'http://fontello.com/#search=' github 'https://github.com/search?q=' html5please 'https://html5please.com/#' - jestjs 'https://www.google.com/search?as_sitesearch=jestjs.io&as_q=' + jestjs $(_frontend_fallback 'jestjs.io') jquery 'https://api.jquery.com/?s=' lodash 'https://devdocs.io/lodash/index#' mdn 'https://developer.mozilla.org/search?q=' - nodejs 'https://www.google.com/search?as_sitesearch=nodejs.org/en/docs/&as_q=' + nodejs $(_frontend_fallback 'nodejs.org/en/docs/') npmjs 'https://www.npmjs.com/search?q=' qunit 'https://api.qunitjs.com/?s=' - reactjs 'https://google.com/search?as_sitesearch=facebook.github.io/react&as_q=' - smacss 'https://google.com/search?as_sitesearch=smacss.com&as_q=' + reactjs $(_frontend_fallback 'reactjs.org/') + smacss $(_frontend_fallback 'smacss.com') stackoverflow 'https://stackoverflow.com/search?q=' - typescript 'https://google.com/search?as_sitesearch=www.typescriptlang.org/docs&as_q=' + typescript $(_frontend_fallback 'www.typescriptlang.org/docs') unheap 'http://www.unheap.com/?s=' - vuejs 'https://www.google.com/search?as_sitesearch=vuejs.org&as_q=' + vuejs $(_frontend_fallback 'vuejs.org') ) # show help for command list diff --git a/plugins/fzf/fzf.plugin.zsh b/plugins/fzf/fzf.plugin.zsh index 27e2d9246..53bdcbc97 100644 --- a/plugins/fzf/fzf.plugin.zsh +++ b/plugins/fzf/fzf.plugin.zsh @@ -1,57 +1,100 @@ -test -d "${FZF_BASE}" && fzf_base="${FZF_BASE}" +function setup_using_base_dir() { + # Declare all variables local not no mess with outside env in any way + local fzf_base + local fzf_shell + local fzfdirs + local dir -if [[ -z "${fzf_base}" ]]; then - fzfdirs=( - "${HOME}/.fzf" - "/usr/local/opt/fzf" - "/usr/share/fzf" - ) - for dir in ${fzfdirs}; do - if [[ -d "${dir}" ]]; then - fzf_base="${dir}" - break - fi - done + test -d "${FZF_BASE}" && fzf_base="${FZF_BASE}" - if [[ -z "${fzf_base}" ]]; then - if (( ${+commands[brew]} )) && dir="$(brew --prefix fzf 2>/dev/null)"; then - if [[ -d "${dir}" ]]; then - fzf_base="${dir}" - fi - fi - fi -fi + if [[ -z "${fzf_base}" ]]; then + fzfdirs=( + "${HOME}/.fzf" + "${HOME}/.nix-profile/share/fzf" + "/usr/local/opt/fzf" + "/usr/share/fzf" + "/usr/local/share/examples/fzf" + ) + for dir in ${fzfdirs}; do + if [[ -d "${dir}" ]]; then + fzf_base="${dir}" + break + fi + done -if [[ -n "${fzf_base}" ]]; then + if [[ -z "${fzf_base}" ]]; then + if (( ${+commands[brew]} )) && dir="$(brew --prefix fzf 2>/dev/null)"; then + if [[ -d "${dir}" ]]; then + fzf_base="${dir}" + fi + fi + fi + fi - # Fix fzf shell directory for Archlinux package - if [[ ! -d "${fzf_base}/shell" ]] && [[ -f /etc/arch-release ]]; then - fzf_shell="${fzf_base}" - else - fzf_shell="${fzf_base}/shell" - fi + if [[ -d "${fzf_base}" ]]; then + # Fix fzf shell directory for Arch Linux, NixOS or Void Linux packages + if [[ ! -d "${fzf_base}/shell" ]]; then + fzf_shell="${fzf_base}" + else + fzf_shell="${fzf_base}/shell" + fi - # Setup fzf - # --------- - if ! (( ${+commands[fzf]} )) && [[ ! "$PATH" == *$fzf_base/bin* ]]; then - export PATH="$PATH:$fzf_base/bin" - fi - - # Auto-completion - # --------------- - if [[ ! "$DISABLE_FZF_AUTO_COMPLETION" == "true" ]]; then - [[ $- == *i* ]] && source "${fzf_shell}/completion.zsh" 2> /dev/null - fi - - # Key bindings - # ------------ - if [[ ! "$DISABLE_FZF_KEY_BINDINGS" == "true" ]]; then - source "${fzf_shell}/key-bindings.zsh" - fi + # Setup fzf binary path + if ! (( ${+commands[fzf]} )) && [[ ! "$PATH" == *$fzf_base/bin* ]]; then + export PATH="$PATH:$fzf_base/bin" + fi -else - print "[oh-my-zsh] fzf plugin: Cannot find fzf installation directory.\n"\ - "Please add \`export FZF_BASE=/path/to/fzf/install/dir\` to your .zshrc" >&2 -fi + # Auto-completion + if [[ ! "$DISABLE_FZF_AUTO_COMPLETION" == "true" ]]; then + [[ $- == *i* ]] && source "${fzf_shell}/completion.zsh" 2> /dev/null + fi -unset fzf_base fzf_shell dir fzfdirs + # Key bindings + if [[ ! "$DISABLE_FZF_KEY_BINDINGS" == "true" ]]; then + source "${fzf_shell}/key-bindings.zsh" + fi + else + return 1 + fi +} + + +function setup_using_debian_package() { + (( $+commands[dpkg] )) && dpkg -s fzf &> /dev/null + if (( $? )); then + # Either not a debian based distro, or no fzf installed. In any case skip ahead + return 1 + fi + + # NOTE: There is no need to configure PATH for debian package, all binaries + # are installed to /usr/bin by default + + # Determine completion file path: first bullseye/sid, then buster/stretch + local completions="/usr/share/doc/fzf/examples/completion.zsh" + [[ -f "$completions" ]] || completions="/usr/share/zsh/vendor-completions/_fzf" + + local key_bindings="/usr/share/doc/fzf/examples/key-bindings.zsh" + + # Auto-completion + if [[ $- == *i* ]] && [[ ! "$DISABLE_FZF_AUTO_COMPLETION" == "true" ]]; then + source $completions 2> /dev/null + fi + + # Key bindings + if [[ ! "$DISABLE_FZF_KEY_BINDINGS" == "true" ]]; then + source $key_bindings + fi + + return 0 +} + +function indicate_error() { + print "[oh-my-zsh] fzf plugin: Cannot find fzf installation directory.\n"\ + "Please add \`export FZF_BASE=/path/to/fzf/install/dir\` to your .zshrc" >&2 +} + +# Check for debian package first, because it easy to short cut +# Indicate to user that fzf installation not found if nothing worked +setup_using_debian_package || setup_using_base_dir || indicate_error + +unset -f setup_using_debian_package setup_using_base_dir indicate_error diff --git a/plugins/gas/README.md b/plugins/gas/README.md new file mode 100644 index 000000000..cd8800e7d --- /dev/null +++ b/plugins/gas/README.md @@ -0,0 +1,9 @@ +# Gas plugin + +This plugin adds autocompletion for the [gas](http://walle.github.com/gas) command, +a utility to manage Git authors. + +To use it, add `gas` to the plugins array of your zshrc file: +```zsh +plugins=(... gas) +``` diff --git a/plugins/gcloud/README.md b/plugins/gcloud/README.md new file mode 100644 index 000000000..e7ce0e0f1 --- /dev/null +++ b/plugins/gcloud/README.md @@ -0,0 +1,24 @@ +# gcloud + +This plugin provides completion support for the +[Google Cloud SDK CLI](https://cloud.google.com/sdk/gcloud/). + +To use it, add `gcloud` to the plugins array in your zshrc file. + +```zsh +plugins=(... gcloud) +``` + +It relies on you having installed the SDK using one of the supported options +listed [here](https://cloud.google.com/sdk/install). + +## Plugin Options + +* Set `CLOUDSDK_HOME` in your `zshrc` file before you load oh-my-zsh if you have +your GCloud SDK installed in a non-standard location. The plugin will use this +as the base for your SDK if it finds it set already. + +* If you do not have a `python2` in your `PATH` you'll also need to set the +`CLOUDSDK_PYTHON` environment variable at the end of your `.zshrc`. This is +used by the SDK to call a compatible interpreter when you run one of the +SDK commands. diff --git a/plugins/gcloud/gcloud.plugin.zsh b/plugins/gcloud/gcloud.plugin.zsh new file mode 100644 index 000000000..c7aebe697 --- /dev/null +++ b/plugins/gcloud/gcloud.plugin.zsh @@ -0,0 +1,33 @@ +##################################################### +# gcloud plugin for oh-my-zsh # +# Author: Ian Chesal (github.com/ianchesal) # +##################################################### + +if [[ -z "${CLOUDSDK_HOME}" ]]; then + search_locations=( + "$HOME/google-cloud-sdk" + "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk" + "/usr/share/google-cloud-sdk" + "/snap/google-cloud-sdk/current" + "/usr/lib64/google-cloud-sdk/" + "/opt/google-cloud-sdk" + ) + + for gcloud_sdk_location in $search_locations; do + if [[ -d "${gcloud_sdk_location}" ]]; then + CLOUDSDK_HOME="${gcloud_sdk_location}" + break + fi + done +fi + +if (( ${+CLOUDSDK_HOME} )); then + if (( ! $+commands[gcloud] )); then + # Only source this if GCloud isn't already on the path + if [[ -f "${CLOUDSDK_HOME}/path.zsh.inc" ]]; then + source "${CLOUDSDK_HOME}/path.zsh.inc" + fi + fi + source "${CLOUDSDK_HOME}/completion.zsh.inc" + export CLOUDSDK_HOME +fi diff --git a/plugins/git-auto-fetch/git-auto-fetch.plugin.zsh b/plugins/git-auto-fetch/git-auto-fetch.plugin.zsh index 745c669b5..5c42c21a7 100644 --- a/plugins/git-auto-fetch/git-auto-fetch.plugin.zsh +++ b/plugins/git-auto-fetch/git-auto-fetch.plugin.zsh @@ -1,16 +1,17 @@ GIT_AUTO_FETCH_INTERVAL=${GIT_AUTO_FETCH_INTERVAL:=60} function git-fetch-all { - (`git rev-parse --is-inside-work-tree 2>/dev/null` && - dir=`git rev-parse --git-dir` && + (`command git rev-parse --is-inside-work-tree 2>/dev/null` && + dir=`command git rev-parse --git-dir` && [[ ! -f $dir/NO_AUTO_FETCH ]] && (( `date +%s` - `date -r $dir/FETCH_LOG +%s 2>/dev/null || echo 0` > $GIT_AUTO_FETCH_INTERVAL )) && - git fetch --all 2>/dev/null &>! $dir/FETCH_LOG &) + GIT_SSH_COMMAND="command ssh -o BatchMode=yes" \ + command git fetch --all 2>/dev/null &>! $dir/FETCH_LOG &) } function git-auto-fetch { - `git rev-parse --is-inside-work-tree 2>/dev/null` || return - guard="`git rev-parse --git-dir`/NO_AUTO_FETCH" + `command git rev-parse --is-inside-work-tree 2>/dev/null` || return + guard="`command git rev-parse --git-dir`/NO_AUTO_FETCH" (rm $guard 2>/dev/null && echo "${fg_bold[green]}enabled${reset_color}") || @@ -18,10 +19,18 @@ function git-auto-fetch { echo "${fg_bold[red]}disabled${reset_color}") } -eval "override-git-auto-fetch-$(declare -f zle-line-init)" - -function zle-line-init () { - git-fetch-all - override-git-auto-fetch-zle-line-init -} +# Override zle-line-init if it exists +if (( $+functions[zle-line-init] )); then + eval "override-git-auto-fetch-$(declare -f zle-line-init)" + + function zle-line-init () { + git-fetch-all + override-git-auto-fetch-zle-line-init + } +else + function zle-line-init () { + git-fetch-all + } +fi + zle -N zle-line-init diff --git a/plugins/git-escape-magic/README.md b/plugins/git-escape-magic/README.md new file mode 100644 index 000000000..7fefed39d --- /dev/null +++ b/plugins/git-escape-magic/README.md @@ -0,0 +1,16 @@ +# Git Escape Magic + +This plugin is copied from the original at +https://github.com/knu/zsh-git-escape-magic. All credit for the +functionality enabled by this plugin should go to @knu. + +An excerpt from that project's readme explains its purpose. + +> It eliminates the need for manually escaping those meta-characters. The zle function it provides is context aware and recognizes the characteristics of each subcommand of git. Every time you type one of these meta-characters on a git command line, it automatically escapes the meta-character with a backslash as necessary and as appropriate. + +## Usage + +To use this plugin, add it to your list of plugins in your `.zshrc` file. + +**NOTE**: If you use url-quote-magic, it must be included before this +plugin runs to prevent any conflicts. diff --git a/plugins/git-escape-magic/git-escape-magic b/plugins/git-escape-magic/git-escape-magic new file mode 100644 index 000000000..94a8d7b0f --- /dev/null +++ b/plugins/git-escape-magic/git-escape-magic @@ -0,0 +1,135 @@ +# -*- mode: sh -*- +# +# git-escape-magic - zle tweak for git command line arguments +# +# Copyright (c) 2011, 2012, 2014 Akinori MUSHA +# Licensed under the 2-clause BSD license. +# +# This tweak eliminates the need for manually escaping shell +# meta-characters such as [~^{}] that are used for specifying a git +# object (commit or tree). Every time you type one of these +# characters on a git command line, it is automatically escaped with a +# backslash as necessary and as appropriate. +# +# If you want to use this with url-quote-magic, make sure to enable it +# first. +# +# Usage: +# autoload -Uz git-escape-magic +# git-escape-magic +# + +git-escape-magic.self-insert() { + emulate -L zsh + setopt extendedglob + local self_insert_function + zstyle -s ':git-escape-magic' self-insert-function self_insert_function + + if [[ "$KEYS" == [{}~^]* ]] && { + local qkey="${(q)KEYS}" + [[ "$KEYS" != "$qkey" ]] + } && { + local lbuf="$LBUFFER$qkey" + [[ "${(Q)LBUFFER}$KEYS" == "${(Q)lbuf}" ]] + } && { + local -a words + words=("${(@Q)${(z)lbuf}}") + [[ "$words[(i)(*/|)git(|-[^/]##)]" -le $#words ]] + } + then + local i + i="$words[(I)([;(){\&]|\&[\&\!]|\|\||[=<>]\(*)]" + if [[ $i -gt 0 ]]; then + shift $((i-1)) words + if [[ "$words[1]" == [\=\<\>]\(* ]]; then + words[1]="${words[1]#[=<>]\(}" + else + [[ "$words[1]" == \; && $words[2] == (then|else|elif|do) ]] && shift words + shift words + fi + fi + while [[ "$words[1]" == (if|while|until|\!) ]]; do + shift words + done + while [[ "$words[1]" == [A-Za-z_][A-Za-z0-9_]#=* ]]; do + shift words + done + [[ "$words[1]" == (*/|)git(|-[^/]##) ]] && { + local subcommand + subcommand="${words[1]##*/git-}" + if [[ -z "$subcommand" ]]; then + shift words + subcommand="$words[1]" + fi + [[ $#words -ge 2 ]] + } && + case "$subcommand" in + # commands that may take pathspec but never take refspec with [{}~^] + (add|rm|am|apply|check-attr|checkout-index|clean|clone|config|diff-files|hash-object|help|index-pack|mailinfo|mailsplit|merge-file|merge-index|mergetool|mktag|mv|pack-objects|pack-redundant|relink|send-email|show-index|show-ref|stage|status|verify-pack) + false ;; + # commands that may take pathspec but rarely take refspec with [{}~^] + (for-each-ref|grep|ls-files|update-index) + false ;; + (archive|ls-tree) + ! [[ $#words -ge 3 && + "$words[-2]" == [^-]* ]] ;; + (diff-tree) + ! [[ $#words -ge 4 && + "$words[-2]" == [^-]* && + "$words[-3]" == [^-]* ]] ;; + (*) + [[ $words[(i)--] -gt $#words ]] ;; + esac && + case "${words[-1]%%"$KEYS"}" in + (*[@^]) + [[ "$KEYS" == [{~^]* ]] ;; + (*[@^]\{[^}]##) + [[ "$KEYS" == \}* ]] ;; + (?*) + [[ "$KEYS" == [~^]* ]] ;; + (*) + false ;; + esac && + LBUFFER="$LBUFFER\\" + fi + + zle "$self_insert_function" +} + +git-escape-magic.on() { + emulate -L zsh + local self_insert_function="${$(zle -lL | awk \ + '$1=="zle"&&$2=="-N"&&$3=="self-insert"{print $4;exit}'):-.self-insert}" + + [[ "$self_insert_function" == git-escape-magic.self-insert ]] && + return 0 + + # For url-quote-magic which does not zle -N itself + zle -la "$self_insert_function" || zle -N "$self_insert_function" + + zstyle ':git-escape-magic' self-insert-function "$self_insert_function" + + zle -A git-escape-magic.self-insert self-insert + return 0 +} + +git-escape-magic.off() { + emulate -L zsh + local self_insert_function + zstyle -s ':git-escape-magic' self-insert-function self_insert_function + + [[ -n "$self_insert_function" ]] && + zle -A "$self_insert_function" self-insert + return 0 +} + +zle -N git-escape-magic.self-insert +zle -N git-escape-magic.on +zle -N git-escape-magic.off + +git-escape-magic() { + git-escape-magic.on +} + +[[ -o kshautoload ]] || git-escape-magic "$@" + diff --git a/plugins/git-escape-magic/git-escape-magic.plugin.zsh b/plugins/git-escape-magic/git-escape-magic.plugin.zsh new file mode 100644 index 000000000..c021ea707 --- /dev/null +++ b/plugins/git-escape-magic/git-escape-magic.plugin.zsh @@ -0,0 +1,9 @@ +# Automatically detect and escape zsh globbing meta-characters when used with +# git refspec characters like `[^~{}]`. NOTE: This must be loaded _after_ +# url-quote-magic. +# +# This trick is detailed at https://github.com/knu/zsh-git-escape-magic and is +# what allowed this plugin to exist. + +autoload -Uz git-escape-magic +git-escape-magic diff --git a/plugins/git-prompt/git-prompt.plugin.zsh b/plugins/git-prompt/git-prompt.plugin.zsh index 76ac2e62b..da674af98 100644 --- a/plugins/git-prompt/git-prompt.plugin.zsh +++ b/plugins/git-prompt/git-prompt.plugin.zsh @@ -20,9 +20,10 @@ function precmd_update_git_vars() { fi } -chpwd_functions+=(chpwd_update_git_vars) -precmd_functions+=(precmd_update_git_vars) -preexec_functions+=(preexec_update_git_vars) +autoload -U add-zsh-hook +add-zsh-hook chpwd chpwd_update_git_vars +add-zsh-hook precmd precmd_update_git_vars +add-zsh-hook preexec preexec_update_git_vars ## Function definitions diff --git a/plugins/git-prompt/gitstatus.py b/plugins/git-prompt/gitstatus.py index 390a50a6f..300365d71 100644 --- a/plugins/git-prompt/gitstatus.py +++ b/plugins/git-prompt/gitstatus.py @@ -4,26 +4,21 @@ from __future__ import print_function import os import sys import re -import shlex from subprocess import Popen, PIPE, check_output def get_tagname_or_hash(): """return tagname if exists else hash""" - cmd = 'git log -1 --format="%h%d"' - output = check_output(shlex.split(cmd)).decode('utf-8').strip() - hash_, tagname = None, None # get hash - m = re.search('\(.*\)$', output) - if m: - hash_ = output[:m.start()-1] - # get tagname - m = re.search('tag: .*[,\)]', output) - if m: - tagname = 'tags/' + output[m.start()+len('tag: '): m.end()-1] + hash_cmd = ['git', 'rev-parse', '--short', 'HEAD'] + hash_ = check_output(hash_cmd).strip() - if tagname: - return tagname.replace(' ', '') + # get tagname + tags_cmd = ['git', 'for-each-ref', '--points-at=HEAD', '--count=2', '--sort=-version:refname', '--format=%(refname:short)', 'refs/tags'] + tags = check_output(tags_cmd).split() + + if tags: + return tags[0] + ('+' if len(tags) > 1 else '') elif hash_: return hash_ return None diff --git a/plugins/git-remote-branch/README.md b/plugins/git-remote-branch/README.md new file mode 100644 index 000000000..bd73e5dec --- /dev/null +++ b/plugins/git-remote-branch/README.md @@ -0,0 +1,14 @@ +# git-remote-branch plugin + +This plugin adds completion for [`grb`](https://github.com/webmat/git_remote_branch), +or `git_remote_branch`. + +To use it, add `git-remote-branch` to the plugins array of your `.zshrc` file: +``` +plugins=(... git-remote-branch) +``` + +## Deprecation + +[git_remote_branch was archived in 2018](https://github.com/webmat/git_remote_branch#archived), +meaning it's not actively maintained anymore. Use at your own risk. diff --git a/plugins/git/README.md b/plugins/git/README.md index fc89b27e0..009a74016 100644 --- a/plugins/git/README.md +++ b/plugins/git/README.md @@ -10,190 +10,196 @@ plugins=(... git) ## Aliases -| Alias | Command | -|:---------------------|:------------------------------------------------------------------------------------------------------------------------------| -| g | git | -| ga | git add | -| gaa | git add --all | -| gapa | git add --patch | -| gau | git add --update | -| gav | git add --verbose | -| gap | git apply | -| gb | git branch | -| gba | git branch -a | -| gbd | git branch -d | -| gbda | git branch --no-color --merged \| command grep -vE "^(\*\|\s*(master\|develop\|dev)\s*$)" \| command xargs -n 1 git branch -d | -| gbD | git branch -D | -| gbl | git blame -b -w | -| gbnm | git branch --no-merged | -| gbr | git branch --remote | -| gbs | git bisect | -| gbsb | git bisect bad | -| gbsg | git bisect good | -| gbsr | git bisect reset | -| gbss | git bisect start | -| gc | git commit -v | -| gc! | git commit -v --amend | -| gcn! | git commit -v --no-edit --amend | -| gca | git commit -v -a | -| gca! | git commit -v -a --amend | -| gcan! | git commit -v -a --no-edit --amend | -| gcans! | git commit -v -a -s --no-edit --amend | -| gcam | git commit -a -m | -| gcsm | git commit -s -m | -| gcb | git checkout -b | -| gcf | git config --list | -| gcl | git clone --recurse-submodules | -| gclean | git clean -id | -| gpristine | git reset --hard && git clean -dfx | -| gcm | git checkout master | -| gcd | git checkout develop | -| gcmsg | git commit -m | -| gco | git checkout | -| gcount | git shortlog -sn | -| gcp | git cherry-pick | -| gcpa | git cherry-pick --abort | -| gcpc | git cherry-pick --continue | -| gcs | git commit -S | -| gd | git diff | -| gdca | git diff --cached | -| gdcw | git diff --cached --word-diff | -| gdct | git describe --tags $(git rev-list --tags --max-count=1) | -| gds | git diff --staged | -| gdt | git diff-tree --no-commit-id --name-only -r | -| gdv | git diff -w $@ \| view - | -| gdw | git diff --word-diff | -| gf | git fetch | -| gfa | git fetch --all --prune | -| gfg | git ls-files \| grep | -| gfo | git fetch origin | -| gg | git gui citool | -| gga | git gui citool --amend | -| ggf | git push --force origin $(current_branch) | -| ggfl | git push --force-with-lease origin $(current_branch) | -| ggl | git pull origin $(current_branch) | -| ggp | git push origin $(current_branch) | -| ggpnp | ggl && ggp | -| ggpull | git pull origin "$(git_current_branch)" | -| ggpur | ggu | -| ggpush | git push origin "$(git_current_branch)" | -| ggsup | git branch --set-upstream-to=origin/$(git_current_branch) | -| ggu | git pull --rebase origin $(current_branch) | -| gpsup | git push --set-upstream origin $(git_current_branch) | -| ghh | git help | -| gignore | git update-index --assume-unchanged | -| gignored | git ls-files -v \| grep "^[[:lower:]]" | -| git-svn-dcommit-push | git svn dcommit && git push github master:svntrunk | -| gk | gitk --all --branches | -| gke | gitk --all $(git log -g --pretty=%h) | -| gl | git pull | -| glg | git log --stat | -| glgp | git log --stat -p | -| glgg | git log --graph | -| glgga | git log --graph --decorate --all | -| glgm | git log --graph --max-count=10 | -| glo | git log --oneline --decorate | -| glol | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' | -| glols | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --stat | -| glod | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset' | -| glods | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset' --date=short | -| glola | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --all | -| glog | git log --oneline --decorate --graph | -| gloga | git log --oneline --decorate --graph --all | -| glp | `_git_log_prettily` | -| gm | git merge | -| gmom | git merge origin/master | -| gmt | git mergetool --no-prompt | -| gmtvim | git mergetool --no-prompt --tool=vimdiff | -| gmum | git merge upstream/master | -| gma | git merge --abort | -| gp | git push | -| gpd | git push --dry-run | -| gpf | git push --force-with-lease | -| gpf! | git push --force | -| gpoat | git push origin --all && git push origin --tags | -| gpu | git push upstream | -| gpv | git push -v | -| gr | git remote | -| gra | git remote add | -| grb | git rebase | -| grba | git rebase --abort | -| grbc | git rebase --continue | -| grbd | git rebase develop | -| grbi | git rebase -i | -| grbm | git rebase master | -| grbs | git rebase --skip | -| grev | git revert | -| grh | git reset | -| grhh | git reset --hard | -| groh | git reset origin/$(git_current_branch) --hard | -| grm | git rm | -| grmc | git rm --cached | -| grmv | git remote rename | -| grrm | git remote remove | -| grset | git remote set-url | -| grt | cd "$(git rev-parse --show-toplevel \|\| echo .)" | -| gru | git reset -- | -| grup | git remote update | -| grv | git remote -v | -| gsb | git status -sb | -| gsd | git svn dcommit | -| gsh | git show | -| gsi | git submodule init | -| gsps | git show --pretty=short --show-signature | -| gsr | git svn rebase | -| gss | git status -s | -| gst | git status | -| gsta | git stash push | -| gsta | git stash save | -| gstaa | git stash apply | -| gstc | git stash clear | -| gstd | git stash drop | -| gstl | git stash list | -| gstp | git stash pop | -| gsts | git stash show --text | -| gstall | git stash --all | -| gsu | git submodule update | -| gts | git tag -s | -| gtv | git tag \| sort -V | -| gtl | gtl(){ git tag --sort=-v:refname -n -l ${1}* }; noglob gtl | -| gunignore | git update-index --no-assume-unchanged | -| gunwip | git log -n 1 \| grep -q -c "\-\-wip\-\-" && git reset HEAD~1 | -| gup | git pull --rebase | -| gupv | git pull --rebase -v | -| gupa | git pull --rebase --autostash | -| gupav | git pull --rebase --autostash -v | -| glum | git pull upstream master | -| gwch | git whatchanged -p --abbrev-commit --pretty=medium | -| gwip | git add -A; git rm $(git ls-files --deleted) 2> /dev/null; git commit --no-verify --no-gpg-sign -m "--wip-- [skip ci]" | +| Alias | Command | +|:---------------------|:---------------------------------------------------------------------------------------------------------------------------------| +| g | git | +| ga | git add | +| gaa | git add --all | +| gapa | git add --patch | +| gau | git add --update | +| gav | git add --verbose | +| gap | git apply | +| gb | git branch | +| gba | git branch -a | +| gbd | git branch -d | +| gbda | git branch --no-color --merged \| command grep -vE "^(\+|\*\|\s*(master\|develop\|dev)\s*$)" \| command xargs -n 1 git branch -d | +| gbD | git branch -D | +| gbl | git blame -b -w | +| gbnm | git branch --no-merged | +| gbr | git branch --remote | +| gbs | git bisect | +| gbsb | git bisect bad | +| gbsg | git bisect good | +| gbsr | git bisect reset | +| gbss | git bisect start | +| gc | git commit -v | +| gc! | git commit -v --amend | +| gcn! | git commit -v --no-edit --amend | +| gca | git commit -v -a | +| gca! | git commit -v -a --amend | +| gcan! | git commit -v -a --no-edit --amend | +| gcans! | git commit -v -a -s --no-edit --amend | +| gcam | git commit -a -m | +| gcsm | git commit -s -m | +| gcb | git checkout -b | +| gcf | git config --list | +| gcl | git clone --recurse-submodules | +| gclean | git clean -id | +| gpristine | git reset --hard && git clean -dfx | +| gcm | git checkout master | +| gcd | git checkout develop | +| gcmsg | git commit -m | +| gco | git checkout | +| gcount | git shortlog -sn | +| gcp | git cherry-pick | +| gcpa | git cherry-pick --abort | +| gcpc | git cherry-pick --continue | +| gcs | git commit -S | +| gd | git diff | +| gdca | git diff --cached | +| gdcw | git diff --cached --word-diff | +| gdct | git describe --tags $(git rev-list --tags --max-count=1) | +| gds | git diff --staged | +| gdt | git diff-tree --no-commit-id --name-only -r | +| gdv | git diff -w $@ \| view - | +| gdw | git diff --word-diff | +| gf | git fetch | +| gfa | git fetch --all --prune | +| gfg | git ls-files \| grep | +| gfo | git fetch origin | +| gg | git gui citool | +| gga | git gui citool --amend | +| ggf | git push --force origin $(current_branch) | +| ggfl | git push --force-with-lease origin $(current_branch) | +| ggl | git pull origin $(current_branch) | +| ggp | git push origin $(current_branch) | +| ggpnp | ggl && ggp | +| ggpull | git pull origin "$(git_current_branch)" | +| ggpur | ggu | +| ggpush | git push origin "$(git_current_branch)" | +| ggsup | git branch --set-upstream-to=origin/$(git_current_branch) | +| ggu | git pull --rebase origin $(current_branch) | +| gpsup | git push --set-upstream origin $(git_current_branch) | +| ghh | git help | +| gignore | git update-index --assume-unchanged | +| gignored | git ls-files -v \| grep "^[[:lower:]]" | +| git-svn-dcommit-push | git svn dcommit && git push github master:svntrunk | +| gk | gitk --all --branches | +| gke | gitk --all $(git log -g --pretty=%h) | +| gl | git pull | +| glg | git log --stat | +| glgp | git log --stat -p | +| glgg | git log --graph | +| glgga | git log --graph --decorate --all | +| glgm | git log --graph --max-count=10 | +| glo | git log --oneline --decorate | +| glol | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' | +| glols | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --stat | +| glod | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset' | +| glods | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset' --date=short | +| glola | git log --graph --pretty='%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --all | +| glog | git log --oneline --decorate --graph | +| gloga | git log --oneline --decorate --graph --all | +| glp | `_git_log_prettily` | +| gm | git merge | +| gmom | git merge origin/master | +| gmt | git mergetool --no-prompt | +| gmtvim | git mergetool --no-prompt --tool=vimdiff | +| gmum | git merge upstream/master | +| gma | git merge --abort | +| gp | git push | +| gpd | git push --dry-run | +| gpf | git push --force-with-lease | +| gpf! | git push --force | +| gpoat | git push origin --all && git push origin --tags | +| gpu | git push upstream | +| gpv | git push -v | +| gr | git remote | +| gra | git remote add | +| grb | git rebase | +| grba | git rebase --abort | +| grbc | git rebase --continue | +| grbd | git rebase develop | +| grbi | git rebase -i | +| grbm | git rebase master | +| grbs | git rebase --skip | +| grev | git revert | +| grh | git reset | +| grhh | git reset --hard | +| groh | git reset origin/$(git_current_branch) --hard | +| grm | git rm | +| grmc | git rm --cached | +| grmv | git remote rename | +| grrm | git remote remove | +| grs | git restore | +| grset | git remote set-url | +| grss | git restore --source | +| grt | cd "$(git rev-parse --show-toplevel \|\| echo .)" | +| gru | git reset -- | +| grup | git remote update | +| grv | git remote -v | +| gsb | git status -sb | +| gsd | git svn dcommit | +| gsh | git show | +| gsi | git submodule init | +| gsps | git show --pretty=short --show-signature | +| gsr | git svn rebase | +| gss | git status -s | +| gst | git status | +| gsta | git stash push | +| gsta | git stash save | +| gstaa | git stash apply | +| gstc | git stash clear | +| gstd | git stash drop | +| gstl | git stash list | +| gstp | git stash pop | +| gsts | git stash show --text | +| gstu | git stash --include-untracked | +| gstall | git stash --all | +| gsu | git submodule update | +| gsw | git switch | +| gswc | git switch -c | +| gts | git tag -s | +| gtv | git tag \| sort -V | +| gtl | gtl(){ git tag --sort=-v:refname -n -l ${1}* }; noglob gtl | +| gunignore | git update-index --no-assume-unchanged | +| gunwip | git log -n 1 \| grep -q -c "\-\-wip\-\-" && git reset HEAD~1 | +| gup | git pull --rebase | +| gupv | git pull --rebase -v | +| gupa | git pull --rebase --autostash | +| gupav | git pull --rebase --autostash -v | +| glum | git pull upstream master | +| gwch | git whatchanged -p --abbrev-commit --pretty=medium | +| gwip | git add -A; git rm $(git ls-files --deleted) 2> /dev/null; git commit --no-verify --no-gpg-sign -m "--wip-- [skip ci]" | ### Deprecated These are aliases that have been removed, renamed, or otherwise modified in a way that may, or may not, receive further support. -| Alias | Command | Modification | -| :----- | :----------------------------------------------------------------------------------| --------------------------------------------------------------------------------------------------- | -| gap | git add --patch | new alias `gapa` | -| gcl | git config --list | new alias `gcf` | -| gdc | git diff --cached | new alias `gdca` | -| gdt | git difftool | no replacement | -| ggpull | git pull origin $(current_branch) | new alias `ggl` (`ggpull` still exists for now though) | -| ggpur | git pull --rebase origin $(current_branch) | new alias `ggu` (`ggpur` still exists for now though) | -| ggpush | git push origin $(current_branch) | new alias `ggp` (`ggpush` still exists for now though) | -| gk | gitk --all --branches | now aliased to `gitk --all --branches` | -| glg | git log --stat --max-count = 10 | now aliased to `git log --stat --color` | -| glgg | git log --graph --max-count = 10 | now aliased to `git log --graph --color` | -| gwc | git whatchanged -p --abbrev-commit --pretty = medium | new alias `gwch` | +| Alias | Command | Modification | +| :----- | :----------------------------------------------------- | :----------------------------------------------------- | +| gap | `git add --patch` | new alias `gapa` | +| gcl | `git config --list` | new alias `gcf` | +| gdc | `git diff --cached` | new alias `gdca` | +| gdt | `git difftool` | no replacement | +| ggpull | `git pull origin $(current_branch)` | new alias `ggl` (`ggpull` still exists for now though) | +| ggpur | `git pull --rebase origin $(current_branch)` | new alias `ggu` (`ggpur` still exists for now though) | +| ggpush | `git push origin $(current_branch)` | new alias `ggp` (`ggpush` still exists for now though) | +| gk | `gitk --all --branches` | now aliased to `gitk --all --branches` | +| glg | `git log --stat --max-count = 10` | now aliased to `git log --stat --color` | +| glgg | `git log --graph --max-count = 10` | now aliased to `git log --graph --color` | +| gwc | `git whatchanged -p --abbrev-commit --pretty = medium` | new alias `gwch` | ## Functions ### Current -| Command | Description | -|:-----------------------|:----------------------------------------| -| current_branch | Return the name of the current branch | -| git_current_user_name | Returns the `user.name` config value | -| git_current_user_email | Returns the `user.email` config value | +| Command | Description | +|:-----------------------|:---------------------------------------------------------| +| `grename ` | Rename `old` branch to `new`, including in origin remote | +| current_branch | Return the name of the current branch | +| git_current_user_name | Returns the `user.name` config value | +| git_current_user_email | Returns the `user.email` config value | ### Work in Progress (WIP) diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh index e0ce27fd4..ffb3e506a 100644 --- a/plugins/git/git.plugin.zsh +++ b/plugins/git/git.plugin.zsh @@ -42,7 +42,7 @@ alias gap='git apply' alias gb='git branch' alias gba='git branch -a' alias gbd='git branch -d' -alias gbda='git branch --no-color --merged | command grep -vE "^(\*|\s*(master|develop|dev)\s*$)" | command xargs -n 1 git branch -d' +alias gbda='git branch --no-color --merged | command grep -vE "^(\+|\*|\s*(master|develop|dev)\s*$)" | command xargs -n 1 git branch -d' alias gbD='git branch -D' alias gbl='git blame -b -w' alias gbnm='git branch --no-merged' @@ -207,7 +207,9 @@ alias grm='git rm' alias grmc='git rm --cached' alias grmv='git remote rename' alias grrm='git remote remove' +alias grs='git restore' alias grset='git remote set-url' +alias grss='git restore --source' alias grt='cd "$(git rev-parse --show-toplevel || echo .)"' alias gru='git reset --' alias grup='git remote update' @@ -234,12 +236,15 @@ alias gstd='git stash drop' alias gstl='git stash list' alias gstp='git stash pop' alias gsts='git stash show --text' +alias gstu='git stash --include-untracked' alias gstall='git stash --all' alias gsu='git submodule update' +alias gsw='git switch' +alias gswc='git switch -c' alias gts='git tag -s' alias gtv='git tag | sort -V' -alias gtl='gtl(){ git tag --sort=-v:refname -n -l ${1}* }; noglob gtl' +alias gtl='gtl(){ git tag --sort=-v:refname -n -l "${1}*" }; noglob gtl' alias gunignore='git update-index --no-assume-unchanged' alias gunwip='git log -n 1 | grep -q -c "\-\-wip\-\-" && git reset HEAD~1' @@ -251,3 +256,17 @@ alias glum='git pull upstream master' alias gwch='git whatchanged -p --abbrev-commit --pretty=medium' alias gwip='git add -A; git rm $(git ls-files --deleted) 2> /dev/null; git commit --no-verify --no-gpg-sign -m "--wip-- [skip ci]"' + +function grename() { + if [[ -z "$1" || -z "$2" ]]; then + echo "Usage: $0 old_branch new_branch" + return 1 + fi + + # Rename branch locally + git branch -m "$1" "$2" + # Rename branch in origin remote + if git push origin :"$1"; then + git push --set-upstream origin "$2" + fi +} diff --git a/plugins/gitfast/README.md b/plugins/gitfast/README.md index 84e35d77c..23db5393b 100644 --- a/plugins/gitfast/README.md +++ b/plugins/gitfast/README.md @@ -11,5 +11,5 @@ plugins=(... gitfast) ## Aliases An earlier version of the plugin also loaded the git plugin. If you want to keep those -aliases enable the [git plugin](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/git) +aliases enable the [git plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git) as well. diff --git a/plugins/gitfast/_git b/plugins/gitfast/_git index 78a6dbb3d..886bf95d1 100644 --- a/plugins/gitfast/_git +++ b/plugins/gitfast/_git @@ -30,7 +30,7 @@ if [ -z "$script" ]; then local -a locations local e locations=( - "$(dirname ${funcsourcetrace[1]%:*})/git-completion.bash" + $(dirname ${funcsourcetrace[1]%:*})/git-completion.bash '/etc/bash_completion.d/git' # fedora, old debian '/usr/share/bash-completion/completions/git' # arch, ubuntu, new debian '/usr/share/bash-completion/git' # gentoo @@ -39,7 +39,7 @@ if [ -z "$script" ]; then test -f $e && script="$e" && break done fi -ZSH_VERSION='' . "$script" +GIT_SOURCING_ZSH_COMPLETION=y . "$script" __gitcomp () { @@ -93,13 +93,22 @@ __gitcomp_nl_append () compadd -Q -S "${4- }" -p "${2-}" -- ${=1} && _ret=0 } +__gitcomp_file_direct () +{ + emulate -L zsh + + local IFS=$'\n' + compset -P '*[=:]' + compadd -f -- ${=1} && _ret=0 +} + __gitcomp_file () { emulate -L zsh local IFS=$'\n' compset -P '*[=:]' - compadd -Q -p "${2-}" -f -- ${=1} && _ret=0 + compadd -p "${2-}" -f -- ${=1} && _ret=0 } __git_zsh_bash_func () @@ -223,10 +232,8 @@ _git () if (( $+functions[__${service}_zsh_main] )); then __${service}_zsh_main - elif (( $+functions[__${service}_main] )); then + else emulate ksh -c __${service}_main - elif (( $+functions[_${service}] )); then - emulate ksh -c _${service} fi let _ret && _default && _ret=0 diff --git a/plugins/gitfast/git-completion.bash b/plugins/gitfast/git-completion.bash index b6ff5dc08..e087c4bf0 100644 --- a/plugins/gitfast/git-completion.bash +++ b/plugins/gitfast/git-completion.bash @@ -29,13 +29,16 @@ # tell the completion to use commit completion. This also works with aliases # of form "!sh -c '...'". For example, "!sh -c ': git commit ; ... '". # +# Compatible with bash 3.2.57. +# # You can set the following environment variables to influence the behavior of # the completion routines: # # GIT_COMPLETION_CHECKOUT_NO_GUESS # # When set to "1", do not include "DWIM" suggestions in git-checkout -# completion (e.g., completing "foo" when "origin/foo" exists). +# and git-switch completion (e.g., completing "foo" when "origin/foo" +# exists). case "$COMP_WORDBREAKS" in *:*) : great ;; @@ -92,6 +95,70 @@ __git () ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null } +# Removes backslash escaping, single quotes and double quotes from a word, +# stores the result in the variable $dequoted_word. +# 1: The word to dequote. +__git_dequote () +{ + local rest="$1" len ch + + dequoted_word="" + + while test -n "$rest"; do + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%[\\\'\"]*}" + rest="${rest:$((${#dequoted_word}-$len))}" + + case "${rest:0:1}" in + \\) + ch="${rest:1:1}" + case "$ch" in + $'\n') + ;; + *) + dequoted_word="$dequoted_word$ch" + ;; + esac + rest="${rest:2}" + ;; + \') + rest="${rest:1}" + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%\'*}" + rest="${rest:$((${#dequoted_word}-$len+1))}" + ;; + \") + rest="${rest:1}" + while test -n "$rest" ; do + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%[\\\"]*}" + rest="${rest:$((${#dequoted_word}-$len))}" + case "${rest:0:1}" in + \\) + ch="${rest:1:1}" + case "$ch" in + \"|\\|\$|\`) + dequoted_word="$dequoted_word$ch" + ;; + $'\n') + ;; + *) + dequoted_word="$dequoted_word\\$ch" + ;; + esac + rest="${rest:2}" + ;; + \") + rest="${rest:1}" + break + ;; + esac + done + ;; + esac + done +} + # The following function is based on code from: # # bash_completion - programmable completion functions for bash 3.2+ @@ -264,9 +331,32 @@ __gitcomp () case "$cur_" in --*=) ;; + --no-*) + local c i=0 IFS=$' \t\n' + for c in $1; do + if [[ $c == "--" ]]; then + continue + fi + c="$c${4-}" + if [[ $c == "$cur_"* ]]; then + case $c in + --*=*|*.) ;; + *) c="$c " ;; + esac + COMPREPLY[i++]="${2-}$c" + fi + done + ;; *) local c i=0 IFS=$' \t\n' for c in $1; do + if [[ $c == "--" ]]; then + c="--no-...${4-}" + if [[ $c == "$cur_"* ]]; then + COMPREPLY[i++]="${2-}$c " + fi + break + fi c="$c${4-}" if [[ $c == "$cur_"* ]]; then case $c in @@ -280,6 +370,48 @@ __gitcomp () esac } +# Clear the variables caching builtins' options when (re-)sourcing +# the completion script. +if [[ -n ${ZSH_VERSION-} ]]; then + unset $(set |sed -ne 's/^\(__gitcomp_builtin_[a-zA-Z0-9_][a-zA-Z0-9_]*\)=.*/\1/p') 2>/dev/null +else + unset $(compgen -v __gitcomp_builtin_) +fi + +# This function is equivalent to +# +# __gitcomp "$(git xxx --git-completion-helper) ..." +# +# except that the output is cached. Accept 1-3 arguments: +# 1: the git command to execute, this is also the cache key +# 2: extra options to be added on top (e.g. negative forms) +# 3: options to be excluded +__gitcomp_builtin () +{ + # spaces must be replaced with underscore for multi-word + # commands, e.g. "git remote add" becomes remote_add. + local cmd="$1" + local incl="$2" + local excl="$3" + + local var=__gitcomp_builtin_"${cmd/-/_}" + local options + eval "options=\$$var" + + if [ -z "$options" ]; then + # leading and trailing spaces are significant to make + # option removal work correctly. + options=" $incl $(__git ${cmd/_/ } --git-completion-helper) " || return + + for i in $excl; do + options="${options/ $i / }" + done + eval "$var=\"$options\"" + fi + + __gitcomp "$options" +} + # Variation of __gitcomp_nl () that appends to the existing list of # completion candidates, COMPREPLY. __gitcomp_nl_append () @@ -303,6 +435,24 @@ __gitcomp_nl () __gitcomp_nl_append "$@" } +# Fills the COMPREPLY array with prefiltered paths without any additional +# processing. +# Callers must take care of providing only paths that match the current path +# to be completed and adding any prefix path components, if necessary. +# 1: List of newline-separated matching paths, complete with all prefix +# path components. +__gitcomp_file_direct () +{ + local IFS=$'\n' + + COMPREPLY=($1) + + # use a hack to enable file mode in bash < 4 + compopt -o filenames +o nospace 2>/dev/null || + compgen -f /non-existing-dir/ >/dev/null || + true +} + # Generates completion reply with compgen from newline-separated possible # completion filenames. # It accepts 1 to 3 arguments: @@ -322,7 +472,8 @@ __gitcomp_file () # use a hack to enable file mode in bash < 4 compopt -o filenames +o nospace 2>/dev/null || - compgen -f /non-existing-dir/ > /dev/null + compgen -f /non-existing-dir/ >/dev/null || + true } # Execute 'git ls-files', unless the --committable option is specified, in @@ -332,10 +483,12 @@ __gitcomp_file () __git_ls_files_helper () { if [ "$2" == "--committable" ]; then - __git -C "$1" diff-index --name-only --relative HEAD + __git -C "$1" -c core.quotePath=false diff-index \ + --name-only --relative HEAD -- "${3//\\/\\\\}*" else # NOTE: $2 is not quoted in order to support multiple options - __git -C "$1" ls-files --exclude-standard $2 + __git -C "$1" -c core.quotePath=false ls-files \ + --exclude-standard $2 -- "${3//\\/\\\\}*" fi } @@ -346,17 +499,103 @@ __git_ls_files_helper () # If provided, only files within the specified directory are listed. # Sub directories are never recursed. Path must have a trailing # slash. +# 3: List only paths matching this path component (optional). __git_index_files () { - local root="${2-.}" file + local root="$2" match="$3" - __git_ls_files_helper "$root" "$1" | - while read -r file; do - case "$file" in - ?*/*) echo "${file%%/*}" ;; - *) echo "$file" ;; - esac - done | sort | uniq + __git_ls_files_helper "$root" "$1" "$match" | + awk -F / -v pfx="${2//\\/\\\\}" '{ + paths[$1] = 1 + } + END { + for (p in paths) { + if (substr(p, 1, 1) != "\"") { + # No special characters, easy! + print pfx p + continue + } + + # The path is quoted. + p = dequote(p) + if (p == "") + continue + + # Even when a directory name itself does not contain + # any special characters, it will still be quoted if + # any of its (stripped) trailing path components do. + # Because of this we may have seen the same direcory + # both quoted and unquoted. + if (p in paths) + # We have seen the same directory unquoted, + # skip it. + continue + else + print pfx p + } + } + function dequote(p, bs_idx, out, esc, esc_idx, dec) { + # Skip opening double quote. + p = substr(p, 2) + + # Interpret backslash escape sequences. + while ((bs_idx = index(p, "\\")) != 0) { + out = out substr(p, 1, bs_idx - 1) + esc = substr(p, bs_idx + 1, 1) + p = substr(p, bs_idx + 2) + + if ((esc_idx = index("abtvfr\"\\", esc)) != 0) { + # C-style one-character escape sequence. + out = out substr("\a\b\t\v\f\r\"\\", + esc_idx, 1) + } else if (esc == "n") { + # Uh-oh, a newline character. + # We cant reliably put a pathname + # containing a newline into COMPREPLY, + # and the newline would create a mess. + # Skip this path. + return "" + } else { + # Must be a \nnn octal value, then. + dec = esc * 64 + \ + substr(p, 1, 1) * 8 + \ + substr(p, 2, 1) + out = out sprintf("%c", dec) + p = substr(p, 3) + } + } + # Drop closing double quote, if there is one. + # (There isnt any if this is a directory, as it was + # already stripped with the trailing path components.) + if (substr(p, length(p), 1) == "\"") + out = out substr(p, 1, length(p) - 1) + else + out = out p + + return out + }' +} + +# __git_complete_index_file requires 1 argument: +# 1: the options to pass to ls-file +# +# The exception is --committable, which finds the files appropriate commit. +__git_complete_index_file () +{ + local dequoted_word pfx="" cur_ + + __git_dequote "$cur" + + case "$dequoted_word" in + ?*/*) + pfx="${dequoted_word%/*}/" + cur_="${dequoted_word##*/}" + ;; + *) + cur_="$dequoted_word" + esac + + __gitcomp_file_direct "$(__git_index_files "$1" "$pfx" "$cur_")" } # Lists branches from the local repository. @@ -439,7 +678,7 @@ __git_refs () track="" ;; *) - for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD; do + for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD REBASE_HEAD; do case "$i" in $match*) if [ -e "$dir/$i" ]; then @@ -594,7 +833,7 @@ __git_is_configured_remote () __git_list_merge_strategies () { - git merge -s help 2>&1 | + LANG=C LC_ALL=C git merge -s help 2>&1 | sed -n -e '/[Aa]vailable strategies are: /,/^$/{ s/\.$// s/.*:// @@ -616,9 +855,14 @@ __git_compute_merge_strategies () __git_merge_strategies=$(__git_list_merge_strategies) } +__git_merge_strategy_options="ours theirs subtree subtree= patience + histogram diff-algorithm= ignore-space-change ignore-all-space + ignore-space-at-eol renormalize no-renormalize no-renames + find-renames find-renames= rename-threshold=" + __git_complete_revlist_file () { - local pfx ls ref cur_="$cur" + local dequoted_word pfx ls ref cur_="$cur" case "$cur_" in *..?*:*) return @@ -626,14 +870,18 @@ __git_complete_revlist_file () ?*:*) ref="${cur_%%:*}" cur_="${cur_#*:}" - case "$cur_" in + + __git_dequote "$cur_" + + case "$dequoted_word" in ?*/*) - pfx="${cur_%/*}" - cur_="${cur_##*/}" + pfx="${dequoted_word%/*}" + cur_="${dequoted_word##*/}" ls="$ref:$pfx" pfx="$pfx/" ;; *) + cur_="$dequoted_word" ls="$ref" ;; esac @@ -643,21 +891,10 @@ __git_complete_revlist_file () *) pfx="$ref:$pfx" ;; esac - __gitcomp_nl "$(__git ls-tree "$ls" \ - | sed '/^100... blob /{ - s,^.* ,, - s,$, , - } - /^120000 blob /{ - s,^.* ,, - s,$, , - } - /^040000 tree /{ - s,^.* ,, - s,$,/, - } - s/^.* //')" \ - "$pfx" "$cur_" "" + __gitcomp_file "$(__git ls-tree "$ls" \ + | sed 's/^.* // + s/$//')" \ + "$pfx" "$cur_" ;; *...*) pfx="${cur_%...*}..." @@ -675,26 +912,6 @@ __git_complete_revlist_file () esac } - -# __git_complete_index_file requires 1 argument: -# 1: the options to pass to ls-file -# -# The exception is --committable, which finds the files appropriate commit. -__git_complete_index_file () -{ - local pfx="" cur_="$cur" - - case "$cur_" in - ?*/*) - pfx="${cur_%/*}" - cur_="${cur_##*/}" - pfx="${pfx}/" - ;; - esac - - __gitcomp_file "$(__git_index_files "$1" ${pfx:+"$pfx"})" "$pfx" "$cur_" -} - __git_complete_file () { __git_complete_revlist_file @@ -726,6 +943,7 @@ __git_complete_remote_or_refspec () *) ;; esac ;; + --multiple) no_complete_refspec=1; break ;; -*) ;; *) remote="$i"; break ;; esac @@ -785,136 +1003,30 @@ __git_complete_strategy () -s|--strategy) __gitcomp "$__git_merge_strategies" return 0 + ;; + -X) + __gitcomp "$__git_merge_strategy_options" + return 0 + ;; esac case "$cur" in --strategy=*) __gitcomp "$__git_merge_strategies" "" "${cur##--strategy=}" return 0 ;; + --strategy-option=*) + __gitcomp "$__git_merge_strategy_options" "" "${cur##--strategy-option=}" + return 0 + ;; esac return 1 } -__git_commands () { - if test -n "${GIT_TESTING_COMMAND_COMPLETION:-}" - then - printf "%s" "${GIT_TESTING_COMMAND_COMPLETION}" - else - git help -a|egrep '^ [a-zA-Z0-9]' - fi -} - -__git_list_all_commands () -{ - local i IFS=" "$'\n' - for i in $(__git_commands) - do - case $i in - *--*) : helper pattern;; - *) echo $i;; - esac - done -} - __git_all_commands= __git_compute_all_commands () { test -n "$__git_all_commands" || - __git_all_commands=$(__git_list_all_commands) -} - -__git_list_porcelain_commands () -{ - local i IFS=" "$'\n' - __git_compute_all_commands - for i in $__git_all_commands - do - case $i in - *--*) : helper pattern;; - applymbox) : ask gittus;; - applypatch) : ask gittus;; - archimport) : import;; - cat-file) : plumbing;; - check-attr) : plumbing;; - check-ignore) : plumbing;; - check-mailmap) : plumbing;; - check-ref-format) : plumbing;; - checkout-index) : plumbing;; - column) : internal helper;; - commit-tree) : plumbing;; - count-objects) : infrequent;; - credential) : credentials;; - credential-*) : credentials helper;; - cvsexportcommit) : export;; - cvsimport) : import;; - cvsserver) : daemon;; - daemon) : daemon;; - diff-files) : plumbing;; - diff-index) : plumbing;; - diff-tree) : plumbing;; - fast-import) : import;; - fast-export) : export;; - fsck-objects) : plumbing;; - fetch-pack) : plumbing;; - fmt-merge-msg) : plumbing;; - for-each-ref) : plumbing;; - hash-object) : plumbing;; - http-*) : transport;; - index-pack) : plumbing;; - init-db) : deprecated;; - local-fetch) : plumbing;; - ls-files) : plumbing;; - ls-remote) : plumbing;; - ls-tree) : plumbing;; - mailinfo) : plumbing;; - mailsplit) : plumbing;; - merge-*) : plumbing;; - mktree) : plumbing;; - mktag) : plumbing;; - pack-objects) : plumbing;; - pack-redundant) : plumbing;; - pack-refs) : plumbing;; - parse-remote) : plumbing;; - patch-id) : plumbing;; - prune) : plumbing;; - prune-packed) : plumbing;; - quiltimport) : import;; - read-tree) : plumbing;; - receive-pack) : plumbing;; - remote-*) : transport;; - rerere) : plumbing;; - rev-list) : plumbing;; - rev-parse) : plumbing;; - runstatus) : plumbing;; - sh-setup) : internal;; - shell) : daemon;; - show-ref) : plumbing;; - send-pack) : plumbing;; - show-index) : plumbing;; - ssh-*) : transport;; - stripspace) : plumbing;; - symbolic-ref) : plumbing;; - unpack-file) : plumbing;; - unpack-objects) : plumbing;; - update-index) : plumbing;; - update-ref) : plumbing;; - update-server-info) : daemon;; - upload-archive) : plumbing;; - upload-pack) : plumbing;; - write-tree) : plumbing;; - var) : infrequent;; - verify-pack) : infrequent;; - verify-tag) : plumbing;; - *) echo $i;; - esac - done -} - -__git_porcelain_commands= -__git_compute_porcelain_commands () -{ - test -n "$__git_porcelain_commands" || - __git_porcelain_commands=$(__git_list_porcelain_commands) + __git_all_commands=$(__git --list-cmds=main,others,alias,nohelpers) } # Lists all set config variables starting with the given section prefix, @@ -932,11 +1044,6 @@ __git_pretty_aliases () __git_get_config_variables "pretty" } -__git_aliases () -{ - __git_get_config_variables "alias" -} - # __git_aliased_command requires 1 argument __git_aliased_command () { @@ -1072,12 +1179,14 @@ __git_count_arguments () } __git_whitespacelist="nowarn warn error error-all fix" +__git_patchformat="mbox stgit stgit-series hg mboxrd" +__git_am_inprogress_options="--skip --continue --resolved --abort --quit --show-current-patch" _git_am () { __git_find_repo_path if [ -d "$__git_repo_path"/rebase-apply ]; then - __gitcomp "--skip --continue --resolved --abort" + __gitcomp "$__git_am_inprogress_options" return fi case "$cur" in @@ -1085,13 +1194,13 @@ _git_am () __gitcomp "$__git_whitespacelist" "" "${cur##--whitespace=}" return ;; + --patch-format=*) + __gitcomp "$__git_patchformat" "" "${cur##--patch-format=}" + return + ;; --*) - __gitcomp " - --3way --committer-date-is-author-date --ignore-date - --ignore-whitespace --ignore-space-change - --interactive --keep --no-utf8 --signoff --utf8 - --whitespace= --scissors - " + __gitcomp_builtin am "" \ + "$__git_am_inprogress_options" return esac } @@ -1104,14 +1213,7 @@ _git_apply () return ;; --*) - __gitcomp " - --stat --numstat --summary --check --index - --cached --index-info --reverse --reject --unidiff-zero - --apply --no-add --exclude= - --ignore-whitespace --ignore-space-change - --whitespace= --inaccurate-eof --verbose - --recount --directory= - " + __gitcomp_builtin apply return esac } @@ -1119,11 +1221,12 @@ _git_apply () _git_add () { case "$cur" in + --chmod=*) + __gitcomp "+x -x" "" "${cur##--chmod=}" + return + ;; --*) - __gitcomp " - --interactive --refresh --patch --update --dry-run - --ignore-errors --intent-to-add --force --edit --chmod= - " + __gitcomp_builtin add return esac @@ -1182,6 +1285,8 @@ _git_bisect () esac } +__git_ref_fieldlist="refname objecttype objectsize objectname upstream push HEAD symref" + _git_branch () { local i c=1 only_local_ref="n" has_r="n" @@ -1200,13 +1305,7 @@ _git_branch () __git_complete_refs --cur="${cur##--set-upstream-to=}" ;; --*) - __gitcomp " - --color --no-color --verbose --abbrev= --no-abbrev - --track --no-track --contains --no-contains --merged --no-merged - --set-upstream-to= --edit-description --list - --unset-upstream --delete --move --copy --remotes - --column --no-column --sort= --points-at - " + __gitcomp_builtin branch ;; *) if [ $only_local_ref = "y" -a $has_r = "n" ]; then @@ -1247,11 +1346,7 @@ _git_checkout () __gitcomp "diff3 merge" "" "${cur##--conflict=}" ;; --*) - __gitcomp " - --quiet --ours --theirs --track --no-track --merge - --conflict= --orphan --patch --detach --ignore-skip-worktree-bits - --recurse-submodules --no-recurse-submodules - " + __gitcomp_builtin checkout ;; *) # check if --track, --no-track, or --no-guess was specified @@ -1266,21 +1361,22 @@ _git_checkout () esac } -_git_cherry () -{ - __git_complete_refs -} +__git_cherry_pick_inprogress_options="--continue --quit --abort" _git_cherry_pick () { __git_find_repo_path if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then - __gitcomp "--continue --quit --abort" + __gitcomp "$__git_cherry_pick_inprogress_options" return fi + + __git_complete_strategy && return + case "$cur" in --*) - __gitcomp "--edit --no-commit --signoff --strategy= --mainline" + __gitcomp_builtin cherry-pick "" \ + "$__git_cherry_pick_inprogress_options" ;; *) __git_complete_refs @@ -1292,7 +1388,7 @@ _git_clean () { case "$cur" in --*) - __gitcomp "--dry-run --quiet" + __gitcomp_builtin clean return ;; esac @@ -1305,26 +1401,7 @@ _git_clone () { case "$cur" in --*) - __gitcomp " - --local - --no-hardlinks - --shared - --reference - --quiet - --no-checkout - --bare - --mirror - --origin - --upload-pack - --template= - --depth - --single-branch - --no-tags - --branch - --recurse-submodules - --no-single-branch - --shallow-submodules - " + __gitcomp_builtin clone return ;; esac @@ -1357,16 +1434,7 @@ _git_commit () return ;; --*) - __gitcomp " - --all --author= --signoff --verify --no-verify - --edit --no-edit - --amend --include --only --interactive - --dry-run --reuse-message= --reedit-message= - --reset-author --file= --message= --template= - --cleanup= --untracked-files --untracked-files= - --verbose --quiet --fixup= --squash= - --patch --short --date --allow-empty - " + __gitcomp_builtin commit return esac @@ -1382,11 +1450,7 @@ _git_describe () { case "$cur" in --*) - __gitcomp " - --all --tags --contains --abbrev= --candidates= - --exact-match --debug --long --match --always --first-parent - --exclude --dirty --broken - " + __gitcomp_builtin describe return esac __git_complete_refs @@ -1411,7 +1475,7 @@ __git_diff_common_options="--stat --numstat --shortstat --summary --dirstat --dirstat= --dirstat-by-file --dirstat-by-file= --cumulative --diff-algorithm= - --submodule --submodule= + --submodule --submodule= --ignore-submodules " _git_diff () @@ -1439,7 +1503,8 @@ _git_diff () } __git_mergetools_common="diffuse diffmerge ecmerge emerge kdiff3 meld opendiff - tkdiff vimdiff gvimdiff xxdiff araxis p4merge bc codecompare + tkdiff vimdiff gvimdiff xxdiff araxis p4merge bc + codecompare smerge " _git_difftool () @@ -1452,11 +1517,11 @@ _git_difftool () return ;; --*) - __gitcomp "--cached --staged --pickaxe-all --pickaxe-regex - --base --ours --theirs - --no-renames --diff-filter= --find-copies-harder - --relative --ignore-submodules - --tool=" + __gitcomp_builtin difftool "$__git_diff_common_options + --base --cached --ours --theirs + --pickaxe-all --pickaxe-regex + --relative --staged + " return ;; esac @@ -1465,12 +1530,6 @@ _git_difftool () __git_fetch_recurse_submodules="yes on-demand no" -__git_fetch_options=" - --quiet --verbose --append --upload-pack --force --keep --depth= - --tags --no-tags --all --prune --dry-run --recurse-submodules= - --unshallow --update-shallow -" - _git_fetch () { case "$cur" in @@ -1478,21 +1537,21 @@ _git_fetch () __gitcomp "$__git_fetch_recurse_submodules" "" "${cur##--recurse-submodules=}" return ;; + --filter=*) + __gitcomp "blob:none blob:limit= sparse:oid=" "" "${cur##--filter=}" + return + ;; --*) - __gitcomp "$__git_fetch_options" + __gitcomp_builtin fetch return ;; esac __git_complete_remote_or_refspec } -__git_format_patch_options=" - --stdout --attach --no-attach --thread --thread= --no-thread - --numbered --start-number --numbered-files --keep-subject --signoff - --signature --no-signature --in-reply-to= --cc= --full-index --binary - --not --all --cover-letter --no-prefix --src-prefix= --dst-prefix= - --inline --suffix= --ignore-if-in-upstream --subject-prefix= - --output-directory --reroll-count --to= --quiet --notes +__git_format_patch_extra_options=" + --full-index --not --all --no-prefix --src-prefix= + --dst-prefix= --notes " _git_format_patch () @@ -1505,7 +1564,7 @@ _git_format_patch () return ;; --*) - __gitcomp "$__git_format_patch_options" + __gitcomp_builtin format-patch "$__git_format_patch_extra_options" return ;; esac @@ -1516,20 +1575,7 @@ _git_fsck () { case "$cur" in --*) - __gitcomp " - --tags --root --unreachable --cache --no-reflogs --full - --strict --verbose --lost-found --name-objects - " - return - ;; - esac -} - -_git_gc () -{ - case "$cur" in - --*) - __gitcomp "--prune --aggressive" + __gitcomp_builtin fsck return ;; esac @@ -1585,21 +1631,7 @@ _git_grep () case "$cur" in --*) - __gitcomp " - --cached - --text --ignore-case --word-regexp --invert-match - --full-name --line-number - --extended-regexp --basic-regexp --fixed-strings - --perl-regexp - --threads - --files-with-matches --name-only - --files-without-match - --max-depth - --count - --and --or --not --all-match - --break --heading --show-function --function-context - --untracked --no-index - " + __gitcomp_builtin grep return ;; esac @@ -1617,17 +1649,16 @@ _git_help () { case "$cur" in --*) - __gitcomp "--all --guides --info --man --web" + __gitcomp_builtin help return ;; esac - __git_compute_all_commands - __gitcomp "$__git_all_commands $(__git_aliases) - attributes cli core-tutorial cvs-migration - diffcore everyday gitk glossary hooks ignore modules - namespaces repository-layout revisions tutorial tutorial-2 - workflows - " + if test -n "$GIT_TESTING_ALL_COMMAND_LIST" + then + __gitcomp "$GIT_TESTING_ALL_COMMAND_LIST $(__git --list-cmds=alias,list-guide) gitk" + else + __gitcomp "$(__git --list-cmds=main,nohelpers,alias,list-guide) gitk" + fi } _git_init () @@ -1640,7 +1671,7 @@ _git_init () return ;; --*) - __gitcomp "--quiet --bare --template= --shared --shared=" + __gitcomp_builtin init return ;; esac @@ -1650,13 +1681,7 @@ _git_ls_files () { case "$cur" in --*) - __gitcomp "--cached --deleted --modified --others --ignored - --stage --directory --no-empty-directory --unmerged - --killed --exclude= --exclude-from= - --exclude-per-directory= --exclude-standard - --error-unmatch --with-tree= --full-name - --abbrev --ignored --exclude-per-directory - " + __gitcomp_builtin ls-files return ;; esac @@ -1670,7 +1695,7 @@ _git_ls_remote () { case "$cur" in --*) - __gitcomp "--heads --tags --refs --get-url --symref" + __gitcomp_builtin ls-remote return ;; esac @@ -1679,6 +1704,13 @@ _git_ls_remote () _git_ls_tree () { + case "$cur" in + --*) + __gitcomp_builtin ls-tree + return + ;; + esac + __git_complete_file } @@ -1705,8 +1737,8 @@ __git_log_shortlog_options=" --all-match --invert-grep " -__git_log_pretty_formats="oneline short medium full fuller email raw format:" -__git_log_date_formats="relative iso8601 rfc2822 short local default raw" +__git_log_pretty_formats="oneline short medium full fuller email raw format: mboxrd" +__git_log_date_formats="relative iso8601 iso8601-strict rfc2822 short local default raw unix format:" _git_log () { @@ -1794,22 +1826,13 @@ _git_log () __git_complete_revlist } -# Common merge options shared by git-merge(1) and git-pull(1). -__git_merge_options=" - --no-commit --no-stat --log --no-log --squash --strategy - --commit --stat --no-squash --ff --no-ff --ff-only --edit --no-edit - --verify-signatures --no-verify-signatures --gpg-sign - --quiet --verbose --progress --no-progress -" - _git_merge () { __git_complete_strategy && return case "$cur" in --*) - __gitcomp "$__git_merge_options - --rerere-autoupdate --no-rerere-autoupdate --abort --continue" + __gitcomp_builtin merge return esac __git_complete_refs @@ -1823,7 +1846,7 @@ _git_mergetool () return ;; --*) - __gitcomp "--tool= --prompt --no-prompt" + __gitcomp "--tool= --prompt --no-prompt --gui --no-gui" return ;; esac @@ -1833,7 +1856,7 @@ _git_merge_base () { case "$cur" in --*) - __gitcomp "--octopus --independent --is-ancestor --fork-point" + __gitcomp_builtin merge-base return ;; esac @@ -1844,7 +1867,7 @@ _git_mv () { case "$cur" in --*) - __gitcomp "--dry-run" + __gitcomp_builtin mv return ;; esac @@ -1858,19 +1881,14 @@ _git_mv () fi } -_git_name_rev () -{ - __gitcomp "--tags --all --stdin" -} - _git_notes () { - local subcommands='add append copy edit list prune remove show' + local subcommands='add append copy edit get-ref list merge prune remove show' local subcommand="$(__git_find_on_cmdline "$subcommands")" case "$subcommand,$cur" in ,--*) - __gitcomp '--ref' + __gitcomp_builtin notes ;; ,*) case "$prev" in @@ -1882,21 +1900,14 @@ _git_notes () ;; esac ;; - add,--reuse-message=*|append,--reuse-message=*|\ - add,--reedit-message=*|append,--reedit-message=*) + *,--reuse-message=*|*,--reedit-message=*) __git_complete_refs --cur="${cur#*=}" ;; - add,--*|append,--*) - __gitcomp '--file= --message= --reedit-message= - --reuse-message=' + *,--*) + __gitcomp_builtin notes_$subcommand ;; - copy,--*) - __gitcomp '--stdin' - ;; - prune,--*) - __gitcomp '--dry-run --verbose' - ;; - prune,*) + prune,*|get-ref,*) + # this command does not take a ref, do not complete it ;; *) case "$prev" in @@ -1920,12 +1931,8 @@ _git_pull () return ;; --*) - __gitcomp " - --rebase --no-rebase - --autostash --no-autostash - $__git_merge_options - $__git_fetch_options - " + __gitcomp_builtin pull + return ;; esac @@ -1976,27 +1983,36 @@ _git_push () return ;; --*) - __gitcomp " - --all --mirror --tags --dry-run --force --verbose - --quiet --prune --delete --follow-tags - --receive-pack= --repo= --set-upstream - --force-with-lease --force-with-lease= --recurse-submodules= - " + __gitcomp_builtin push return ;; esac __git_complete_remote_or_refspec } +_git_range_diff () +{ + case "$cur" in + --*) + __gitcomp " + --creation-factor= --no-dual-color + $__git_diff_common_options + " + return + ;; + esac + __git_complete_revlist +} + _git_rebase () { __git_find_repo_path if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then - __gitcomp "--continue --skip --abort --quit --edit-todo" + __gitcomp "--continue --skip --abort --quit --edit-todo --show-current-patch" return elif [ -d "$__git_repo_path"/rebase-apply ] || \ [ -d "$__git_repo_path"/rebase-merge ]; then - __gitcomp "--continue --skip --abort --quit" + __gitcomp "--continue --skip --abort --quit --show-current-patch" return fi __git_complete_strategy && return @@ -2008,7 +2024,7 @@ _git_rebase () --*) __gitcomp " --onto --merge --strategy --interactive - --preserve-merges --stat --no-stat + --rebase-merges --preserve-merges --stat --no-stat --committer-date-is-author-date --ignore-date --ignore-whitespace --whitespace= --autosquash --no-autosquash @@ -2016,6 +2032,7 @@ _git_rebase () --autostash --no-autostash --verify --no-verify --keep-empty --root --force-rebase --no-ff + --rerere-autoupdate --exec " @@ -2077,16 +2094,16 @@ _git_send_email () return ;; --*) - __gitcomp "--annotate --bcc --cc --cc-cmd --chain-reply-to + __gitcomp_builtin send-email "--annotate --bcc --cc --cc-cmd --chain-reply-to --compose --confirm= --dry-run --envelope-sender --from --identity --in-reply-to --no-chain-reply-to --no-signed-off-by-cc - --no-suppress-from --no-thread --quiet + --no-suppress-from --no-thread --quiet --reply-to --signed-off-by-cc --smtp-pass --smtp-server --smtp-server-port --smtp-encryption= --smtp-user --subject --suppress-cc= --suppress-from --thread --to --validate --no-validate - $__git_format_patch_options" + $__git_format_patch_extra_options" return ;; esac @@ -2119,11 +2136,7 @@ _git_status () return ;; --*) - __gitcomp " - --short --branch --porcelain --long --verbose - --untracked-files= --ignore-submodules= --ignored - --column= --no-column - " + __gitcomp_builtin status return ;; esac @@ -2148,6 +2161,44 @@ _git_status () __git_complete_index_file "$complete_opt" } +_git_switch () +{ + case "$cur" in + --conflict=*) + __gitcomp "diff3 merge" "" "${cur##--conflict=}" + ;; + --*) + __gitcomp_builtin switch + ;; + *) + # check if --track, --no-track, or --no-guess was specified + # if so, disable DWIM mode + local track_opt="--track" only_local_ref=n + if [ "$GIT_COMPLETION_CHECKOUT_NO_GUESS" = "1" ] || + [ -n "$(__git_find_on_cmdline "--track --no-track --no-guess")" ]; then + track_opt='' + fi + # explicit --guess enables DWIM mode regardless of + # $GIT_COMPLETION_CHECKOUT_NO_GUESS + if [ -n "$(__git_find_on_cmdline "--guess")" ]; then + track_opt='--track' + fi + if [ -z "$(__git_find_on_cmdline "-d --detach")" ]; then + only_local_ref=y + else + # --guess --detach is invalid combination, no + # dwim will be done when --detach is specified + track_opt= + fi + if [ $only_local_ref = y -a -z "$track_opt" ]; then + __gitcomp_direct "$(__git_heads "" "$cur" " ")" + else + __git_complete_refs $track_opt + fi + ;; + esac +} + __git_config_get_set_variables () { local prevword word config_file= c=$cword @@ -2170,9 +2221,24 @@ __git_config_get_set_variables () __git config $config_file --name-only --list } +__git_config_vars= +__git_compute_config_vars () +{ + test -n "$__git_config_vars" || + __git_config_vars="$(git help --config-for-completion | sort | uniq)" +} + _git_config () { - case "$prev" in + local varname + + if [ "${BASH_VERSINFO[0]:-0}" -ge 4 ]; then + varname="${prev,,}" + else + varname="$(echo "$prev" |tr A-Z a-z)" + fi + + case "$varname" in branch.*.remote|branch.*.pushremote) __gitcomp_nl "$(__git_remotes)" return @@ -2182,7 +2248,7 @@ _git_config () return ;; branch.*.rebase) - __gitcomp "false true preserve interactive" + __gitcomp "false true merges preserve interactive" return ;; remote.pushdefault) @@ -2228,7 +2294,7 @@ _git_config () return ;; diff.submodule) - __gitcomp "log short" + __gitcomp "$__git_diff_submodule_formats" return ;; help.format) @@ -2239,7 +2305,7 @@ _git_config () __gitcomp "$__git_log_date_formats" return ;; - sendemail.aliasesfiletype) + sendemail.aliasfiletype) __gitcomp "mutt mailrc pine elm gnus" return ;; @@ -2265,32 +2331,25 @@ _git_config () esac case "$cur" in --*) - __gitcomp " - --system --global --local --file= - --list --replace-all - --get --get-all --get-regexp - --add --unset --unset-all - --remove-section --rename-section - --name-only - " + __gitcomp_builtin config return ;; branch.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" - __gitcomp "remote pushremote merge mergeoptions rebase" "$pfx" "$cur_" + __gitcomp "remote pushRemote merge mergeOptions rebase" "$pfx" "$cur_" return ;; branch.*) local pfx="${cur%.*}." cur_="${cur#*.}" __gitcomp_direct "$(__git_heads "$pfx" "$cur_" ".")" - __gitcomp_nl_append $'autosetupmerge\nautosetuprebase\n' "$pfx" "$cur_" + __gitcomp_nl_append $'autoSetupMerge\nautoSetupRebase\n' "$pfx" "$cur_" return ;; guitool.*.*) local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp " - argprompt cmd confirm needsfile noconsole norescan - prompt revprompt revunmerged title + argPrompt cmd confirm needsFile noConsole noRescan + prompt revPrompt revUnmerged title " "$pfx" "$cur_" return ;; @@ -2319,14 +2378,14 @@ _git_config () local pfx="${cur%.*}." cur_="${cur##*.}" __gitcomp " url proxy fetch push mirror skipDefaultUpdate - receivepack uploadpack tagopt pushurl + receivepack uploadpack tagOpt pushurl " "$pfx" "$cur_" return ;; remote.*) local pfx="${cur%.*}." cur_="${cur#*.}" __gitcomp_nl "$(__git_remotes)" "$pfx" "$cur_" "." - __gitcomp_nl_append "pushdefault" "$pfx" "$cur_" + __gitcomp_nl_append "pushDefault" "$pfx" "$cur_" return ;; url.*.*) @@ -2334,332 +2393,14 @@ _git_config () __gitcomp "insteadOf pushInsteadOf" "$pfx" "$cur_" return ;; + *.*) + __git_compute_config_vars + __gitcomp "$__git_config_vars" + ;; + *) + __git_compute_config_vars + __gitcomp "$(echo "$__git_config_vars" | sed 's/\.[^ ]*/./g')" esac - __gitcomp " - add.ignoreErrors - advice.amWorkDir - advice.commitBeforeMerge - advice.detachedHead - advice.implicitIdentity - advice.pushAlreadyExists - advice.pushFetchFirst - advice.pushNeedsForce - advice.pushNonFFCurrent - advice.pushNonFFMatching - advice.pushUpdateRejected - advice.resolveConflict - advice.rmHints - advice.statusHints - advice.statusUoption - advice.ignoredHook - alias. - am.keepcr - am.threeWay - apply.ignorewhitespace - apply.whitespace - branch.autosetupmerge - branch.autosetuprebase - browser. - clean.requireForce - color.branch - color.branch.current - color.branch.local - color.branch.plain - color.branch.remote - color.decorate.HEAD - color.decorate.branch - color.decorate.remoteBranch - color.decorate.stash - color.decorate.tag - color.diff - color.diff.commit - color.diff.frag - color.diff.func - color.diff.meta - color.diff.new - color.diff.old - color.diff.plain - color.diff.whitespace - color.grep - color.grep.context - color.grep.filename - color.grep.function - color.grep.linenumber - color.grep.match - color.grep.selected - color.grep.separator - color.interactive - color.interactive.error - color.interactive.header - color.interactive.help - color.interactive.prompt - color.pager - color.showbranch - color.status - color.status.added - color.status.changed - color.status.header - color.status.localBranch - color.status.nobranch - color.status.remoteBranch - color.status.unmerged - color.status.untracked - color.status.updated - color.ui - commit.cleanup - commit.gpgSign - commit.status - commit.template - commit.verbose - core.abbrev - core.askpass - core.attributesfile - core.autocrlf - core.bare - core.bigFileThreshold - core.checkStat - core.commentChar - core.compression - core.createObject - core.deltaBaseCacheLimit - core.editor - core.eol - core.excludesfile - core.fileMode - core.fsyncobjectfiles - core.gitProxy - core.hideDotFiles - core.hooksPath - core.ignoreStat - core.ignorecase - core.logAllRefUpdates - core.loosecompression - core.notesRef - core.packedGitLimit - core.packedGitWindowSize - core.packedRefsTimeout - core.pager - core.precomposeUnicode - core.preferSymlinkRefs - core.preloadindex - core.protectHFS - core.protectNTFS - core.quotepath - core.repositoryFormatVersion - core.safecrlf - core.sharedRepository - core.sparseCheckout - core.splitIndex - core.sshCommand - core.symlinks - core.trustctime - core.untrackedCache - core.warnAmbiguousRefs - core.whitespace - core.worktree - credential.helper - credential.useHttpPath - credential.username - credentialCache.ignoreSIGHUP - diff.autorefreshindex - diff.external - diff.ignoreSubmodules - diff.mnemonicprefix - diff.noprefix - diff.renameLimit - diff.renames - diff.statGraphWidth - diff.submodule - diff.suppressBlankEmpty - diff.tool - diff.wordRegex - diff.algorithm - difftool. - difftool.prompt - fetch.recurseSubmodules - fetch.unpackLimit - format.attach - format.cc - format.coverLetter - format.from - format.headers - format.numbered - format.pretty - format.signature - format.signoff - format.subjectprefix - format.suffix - format.thread - format.to - gc. - gc.aggressiveDepth - gc.aggressiveWindow - gc.auto - gc.autoDetach - gc.autopacklimit - gc.logExpiry - gc.packrefs - gc.pruneexpire - gc.reflogexpire - gc.reflogexpireunreachable - gc.rerereresolved - gc.rerereunresolved - gc.worktreePruneExpire - gitcvs.allbinary - gitcvs.commitmsgannotation - gitcvs.dbTableNamePrefix - gitcvs.dbdriver - gitcvs.dbname - gitcvs.dbpass - gitcvs.dbuser - gitcvs.enabled - gitcvs.logfile - gitcvs.usecrlfattr - guitool. - gui.blamehistoryctx - gui.commitmsgwidth - gui.copyblamethreshold - gui.diffcontext - gui.encoding - gui.fastcopyblame - gui.matchtrackingbranch - gui.newbranchtemplate - gui.pruneduringfetch - gui.spellingdictionary - gui.trustmtime - help.autocorrect - help.browser - help.format - http.lowSpeedLimit - http.lowSpeedTime - http.maxRequests - http.minSessions - http.noEPSV - http.postBuffer - http.proxy - http.sslCipherList - http.sslVersion - http.sslCAInfo - http.sslCAPath - http.sslCert - http.sslCertPasswordProtected - http.sslKey - http.sslVerify - http.useragent - i18n.commitEncoding - i18n.logOutputEncoding - imap.authMethod - imap.folder - imap.host - imap.pass - imap.port - imap.preformattedHTML - imap.sslverify - imap.tunnel - imap.user - init.templatedir - instaweb.browser - instaweb.httpd - instaweb.local - instaweb.modulepath - instaweb.port - interactive.singlekey - log.date - log.decorate - log.showroot - mailmap.file - man. - man.viewer - merge. - merge.conflictstyle - merge.log - merge.renameLimit - merge.renormalize - merge.stat - merge.tool - merge.verbosity - mergetool. - mergetool.keepBackup - mergetool.keepTemporaries - mergetool.prompt - notes.displayRef - notes.rewrite. - notes.rewrite.amend - notes.rewrite.rebase - notes.rewriteMode - notes.rewriteRef - pack.compression - pack.deltaCacheLimit - pack.deltaCacheSize - pack.depth - pack.indexVersion - pack.packSizeLimit - pack.threads - pack.window - pack.windowMemory - pager. - pretty. - pull.octopus - pull.twohead - push.default - push.followTags - rebase.autosquash - rebase.stat - receive.autogc - receive.denyCurrentBranch - receive.denyDeleteCurrent - receive.denyDeletes - receive.denyNonFastForwards - receive.fsckObjects - receive.unpackLimit - receive.updateserverinfo - remote.pushdefault - remotes. - repack.usedeltabaseoffset - rerere.autoupdate - rerere.enabled - sendemail. - sendemail.aliasesfile - sendemail.aliasfiletype - sendemail.bcc - sendemail.cc - sendemail.cccmd - sendemail.chainreplyto - sendemail.confirm - sendemail.envelopesender - sendemail.from - sendemail.identity - sendemail.multiedit - sendemail.signedoffbycc - sendemail.smtpdomain - sendemail.smtpencryption - sendemail.smtppass - sendemail.smtpserver - sendemail.smtpserveroption - sendemail.smtpserverport - sendemail.smtpuser - sendemail.suppresscc - sendemail.suppressfrom - sendemail.thread - sendemail.to - sendemail.tocmd - sendemail.validate - sendemail.smtpbatchsize - sendemail.smtprelogindelay - showbranch.default - status.relativePaths - status.showUntrackedFiles - status.submodulesummary - submodule. - tar.umask - transfer.unpackLimit - url. - user.email - user.name - user.signingkey - web.browser - branch. remote. - " } _git_remote () @@ -2672,7 +2413,7 @@ _git_remote () if [ -z "$subcommand" ]; then case "$cur" in --*) - __gitcomp "--verbose" + __gitcomp_builtin remote ;; *) __gitcomp "$subcommands" @@ -2683,33 +2424,33 @@ _git_remote () case "$subcommand,$cur" in add,--*) - __gitcomp "--track --master --fetch --tags --no-tags --mirror=" + __gitcomp_builtin remote_add ;; add,*) ;; set-head,--*) - __gitcomp "--auto --delete" + __gitcomp_builtin remote_set-head ;; set-branches,--*) - __gitcomp "--add" + __gitcomp_builtin remote_set-branches ;; set-head,*|set-branches,*) __git_complete_remote_or_refspec ;; update,--*) - __gitcomp "--prune" + __gitcomp_builtin remote_update ;; update,*) - __gitcomp "$(__git_get_config_variables "remotes")" + __gitcomp "$(__git_remotes) $(__git_get_config_variables "remotes")" ;; set-url,--*) - __gitcomp "--push --add --delete" + __gitcomp_builtin remote_set-url ;; get-url,--*) - __gitcomp "--push --all" + __gitcomp_builtin remote_get-url ;; prune,--*) - __gitcomp "--dry-run" + __gitcomp_builtin remote_prune ;; *) __gitcomp_nl "$(__git_remotes)" @@ -2720,8 +2461,12 @@ _git_remote () _git_replace () { case "$cur" in + --format=*) + __gitcomp "short medium long" "" "${cur##--format=}" + return + ;; --*) - __gitcomp "--edit --graft --format= --list --delete" + __gitcomp_builtin replace return ;; esac @@ -2745,26 +2490,42 @@ _git_reset () case "$cur" in --*) - __gitcomp "--merge --mixed --hard --soft --patch --keep" + __gitcomp_builtin reset return ;; esac __git_complete_refs } +_git_restore () +{ + case "$cur" in + --conflict=*) + __gitcomp "diff3 merge" "" "${cur##--conflict=}" + ;; + --source=*) + __git_complete_refs --cur="${cur##--source=}" + ;; + --*) + __gitcomp_builtin restore + ;; + esac +} + +__git_revert_inprogress_options="--continue --quit --abort" + _git_revert () { __git_find_repo_path if [ -f "$__git_repo_path"/REVERT_HEAD ]; then - __gitcomp "--continue --quit --abort" + __gitcomp "$__git_revert_inprogress_options" return fi + __git_complete_strategy && return case "$cur" in --*) - __gitcomp " - --edit --mainline --no-edit --no-commit --signoff - --strategy= --strategy-option= - " + __gitcomp_builtin revert "" \ + "$__git_revert_inprogress_options" return ;; esac @@ -2775,7 +2536,7 @@ _git_rm () { case "$cur" in --*) - __gitcomp "--cached --dry-run --ignore-unmatch --quiet" + __gitcomp_builtin rm return ;; esac @@ -2833,12 +2594,7 @@ _git_show_branch () { case "$cur" in --*) - __gitcomp " - --all --remotes --topo-order --date-order --current --more= - --list --independent --merge-base --no-name - --color --no-color - --sha1-name --sparse --topics --reflog - " + __gitcomp_builtin show-branch return ;; esac @@ -2848,13 +2604,21 @@ _git_show_branch () _git_stash () { local save_opts='--all --keep-index --no-keep-index --quiet --patch --include-untracked' - local subcommands='push save list show apply clear drop pop create branch' - local subcommand="$(__git_find_on_cmdline "$subcommands")" + local subcommands='push list show apply clear drop pop create branch' + local subcommand="$(__git_find_on_cmdline "$subcommands save")" + if [ -n "$(__git_find_on_cmdline "-p")" ]; then + subcommand="push" + fi if [ -z "$subcommand" ]; then case "$cur" in --*) __gitcomp "$save_opts" ;; + sa*) + if [ -z "$(__git_find_on_cmdline "$save_opts")" ]; then + __gitcomp "save" + fi + ;; *) if [ -z "$(__git_find_on_cmdline "$save_opts")" ]; then __gitcomp "$subcommands" @@ -2875,6 +2639,9 @@ _git_stash () drop,--*) __gitcomp "--quiet" ;; + list,--*) + __gitcomp "--name-status --oneline --patch-with-stat" + ;; show,--*|branch,--*) ;; branch,*) @@ -2899,7 +2666,7 @@ _git_submodule () { __git_has_doubledash && return - local subcommands="add status init deinit update summary foreach sync" + local subcommands="add status init deinit update set-branch summary foreach sync absorbgitdirs" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then case "$cur" in @@ -2930,6 +2697,9 @@ _git_submodule () --force --rebase --merge --reference --depth --recursive --jobs " ;; + set-branch,--*) + __gitcomp "--default --branch" + ;; summary,--*) __gitcomp "--cached --files --summary-limit" ;; @@ -3045,7 +2815,7 @@ _git_tag () while [ $c -lt $cword ]; do i="${words[c]}" case "$i" in - -d|-v) + -d|--delete|-v|--verify) __gitcomp_direct "$(__git_tags "" "$cur" " ")" return ;; @@ -3071,11 +2841,7 @@ _git_tag () case "$cur" in --*) - __gitcomp " - --list --delete --verify --annotate --message --file - --sign --cleanup --local-user --force --column --sort= - --contains --no-contains --points-at --merged --no-merged --create-reflog - " + __gitcomp_builtin tag ;; esac } @@ -3087,23 +2853,26 @@ _git_whatchanged () _git_worktree () { - local subcommands="add list lock prune unlock" + local subcommands="add list lock move prune remove unlock" local subcommand="$(__git_find_on_cmdline "$subcommands")" if [ -z "$subcommand" ]; then __gitcomp "$subcommands" else case "$subcommand,$cur" in add,--*) - __gitcomp "--detach" + __gitcomp_builtin worktree_add ;; list,--*) - __gitcomp "--porcelain" + __gitcomp_builtin worktree_list ;; lock,--*) - __gitcomp "--reason" + __gitcomp_builtin worktree_lock ;; prune,--*) - __gitcomp "--dry-run --expire --verbose" + __gitcomp_builtin worktree_prune + ;; + remove,--*) + __gitcomp "--force" ;; *) ;; @@ -3111,6 +2880,52 @@ _git_worktree () fi } +__git_complete_common () { + local command="$1" + + case "$cur" in + --*) + __gitcomp_builtin "$command" + ;; + esac +} + +__git_cmds_with_parseopt_helper= +__git_support_parseopt_helper () { + test -n "$__git_cmds_with_parseopt_helper" || + __git_cmds_with_parseopt_helper="$(__git --list-cmds=parseopt)" + + case " $__git_cmds_with_parseopt_helper " in + *" $1 "*) + return 0 + ;; + *) + return 1 + ;; + esac +} + +__git_complete_command () { + local command="$1" + local completion_func="_git_${command//-/_}" + if ! declare -f $completion_func >/dev/null 2>/dev/null && + declare -f _completion_loader >/dev/null 2>/dev/null + then + _completion_loader "git-$command" + fi + if declare -f $completion_func >/dev/null 2>/dev/null + then + $completion_func + return 0 + elif __git_support_parseopt_helper "$command" + then + __git_complete_common "$command" + return 0 + else + return 1 + fi +} + __git_main () { local i c=1 command __git_dir __git_repo_path @@ -3164,20 +2979,24 @@ __git_main () --help " ;; - *) __git_compute_porcelain_commands - __gitcomp "$__git_porcelain_commands $(__git_aliases)" ;; + *) + if test -n "$GIT_TESTING_PORCELAIN_COMMAND_LIST" + then + __gitcomp "$GIT_TESTING_PORCELAIN_COMMAND_LIST" + else + __gitcomp "$(__git --list-cmds=list-mainporcelain,others,nohelpers,alias,list-complete,config)" + fi + ;; esac return fi - local completion_func="_git_${command//-/_}" - declare -f $completion_func >/dev/null 2>/dev/null && $completion_func && return + __git_complete_command "$command" && return local expansion=$(__git_aliased_command "$command") if [ -n "$expansion" ]; then words[1]=$expansion - completion_func="_git_${expansion//-/_}" - declare -f $completion_func >/dev/null 2>/dev/null && $completion_func + __git_complete_command "$expansion" fi } @@ -3205,7 +3024,10 @@ __gitk_main () __git_complete_revlist } -if [[ -n ${ZSH_VERSION-} ]]; then +if [[ -n ${ZSH_VERSION-} ]] && + # Don't define these functions when sourced from 'git-completion.zsh', + # it has its own implementations. + [[ -z ${GIT_SOURCING_ZSH_COMPLETION-} ]]; then echo "WARNING: this script is deprecated, please see git-completion.zsh" 1>&2 autoload -U +X compinit && compinit @@ -3254,13 +3076,22 @@ if [[ -n ${ZSH_VERSION-} ]]; then compadd -Q -S "${4- }" -p "${2-}" -- ${=1} && _ret=0 } + __gitcomp_file_direct () + { + emulate -L zsh + + local IFS=$'\n' + compset -P '*[=:]' + compadd -f -- ${=1} && _ret=0 + } + __gitcomp_file () { emulate -L zsh local IFS=$'\n' compset -P '*[=:]' - compadd -Q -p "${2-}" -f -- ${=1} && _ret=0 + compadd -p "${2-}" -f -- ${=1} && _ret=0 } _git () @@ -3315,6 +3146,6 @@ __git_complete gitk __gitk_main # when the user has tab-completed the executable name and consequently # included the '.exe' suffix. # -if [[ "$OSTYPE" = cygwin* ]]; then +if [ Cygwin = "$(uname -o 2>/dev/null)" ]; then __git_complete git.exe __git_main fi diff --git a/plugins/gitfast/git-prompt.sh b/plugins/gitfast/git-prompt.sh index fd2b049db..f7009b063 100644 --- a/plugins/gitfast/git-prompt.sh +++ b/plugins/gitfast/git-prompt.sh @@ -219,7 +219,7 @@ __git_ps1_show_upstream () if [[ -n "$count" && -n "$name" ]]; then __git_ps1_upstream_name=$(git rev-parse \ --abbrev-ref "$upstream" 2>/dev/null) - if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then + if [ "$pcmode" = yes ] && [ "$ps1_expanded" = yes ]; then p="$p \${__git_ps1_upstream_name}" else p="$p ${__git_ps1_upstream_name}" @@ -237,7 +237,7 @@ __git_ps1_show_upstream () # to build a gitstring. __git_ps1_colorize_gitstring () { - if [[ -n ${ZSH_VERSION-} ]]; then + if [[ -n "${ZSH_VERSION-}" ]]; then local c_red='%F{red}' local c_green='%F{green}' local c_lblue='%F{blue}' @@ -255,7 +255,7 @@ __git_ps1_colorize_gitstring () local flags_color="$c_lblue" local branch_color="" - if [ $detached = no ]; then + if [ "$detached" = no ]; then branch_color="$ok_color" else branch_color="$bad_color" @@ -508,13 +508,13 @@ __git_ps1 () # NO color option unless in PROMPT_COMMAND mode or it's Zsh if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then - if [ $pcmode = yes ] || [ -n "${ZSH_VERSION-}" ]; then + if [ "$pcmode" = yes ] || [ -n "${ZSH_VERSION-}" ]; then __git_ps1_colorize_gitstring fi fi b=${b##refs/heads/} - if [ $pcmode = yes ] && [ $ps1_expanded = yes ]; then + if [ "$pcmode" = yes ] && [ "$ps1_expanded" = yes ]; then __git_ps1_branch_name=$b b="\${__git_ps1_branch_name}" fi @@ -522,7 +522,7 @@ __git_ps1 () local f="$w$i$s$u" local gitstring="$c$b${f:+$z$f}$r$p" - if [ $pcmode = yes ]; then + if [ "$pcmode" = yes ]; then if [ "${__git_printf_supports_v-}" != yes ]; then gitstring=$(printf -- "$printf_format" "$gitstring") else diff --git a/plugins/glassfish/README.md b/plugins/glassfish/README.md new file mode 100644 index 000000000..1f4a8be34 --- /dev/null +++ b/plugins/glassfish/README.md @@ -0,0 +1,9 @@ +# glassfish + +The glassfish plugin adds completion for the `asadmin` utility, a command to manage +[Oracle GlassFish](https://docs.oracle.com/cd/E18930_01/html/821-2416/giobi.html) servers. + +To use it, add `glassfish` to the plugins array in your zshrc file: +```zsh +plugins=(... glassfish) +``` diff --git a/plugins/glassfish/glassfish.plugin.zsh b/plugins/glassfish/glassfish.plugin.zsh index fde2edb2a..e69de29bb 100644 --- a/plugins/glassfish/glassfish.plugin.zsh +++ b/plugins/glassfish/glassfish.plugin.zsh @@ -1,3 +0,0 @@ -# if there is a user named 'glassfish' on the system, we'll assume -# that is the user asadmin should be run as -# grep -e '^glassfish' /etc/passwd > /dev/null && alias asadmin='sudo -u glassfish asadmin' \ No newline at end of file diff --git a/plugins/gnu-utils/README.md b/plugins/gnu-utils/README.md new file mode 100644 index 000000000..f5fa81e2f --- /dev/null +++ b/plugins/gnu-utils/README.md @@ -0,0 +1,38 @@ +# gnu-utils plugin + +This plugin binds GNU coreutils to their default names, so that you don't have +to call them using their prefixed name, which starts with `g`. This is useful +in systems which don't have GNU coreutils installed by default, mainly macOS +or FreeBSD, which use BSD coreutils. + +To use it, add `gnu-utils` to the plugins array in your zshrc file: +```zsh +plugins=(... gnu-utils) +``` + +The plugin works by changing the path that the command hash points to, so +instead of `ls` pointing to `/bin/ls`, it points to wherever `gls` is +installed. + +Since `hash -rf` or `rehash` refreshes the command hashes, it also wraps +`hash` and `rehash` so that the coreutils binding is always done again +after calling these two commands. + +Look at the source code of the plugin to see which GNU coreutils are tried +to rebind. Open an issue if there are some missing. + +## Other methods + +The plugin also documents two other ways to do this: + +1. Using a function wrapper, such that, for example, there exists a function +named `ls` which calls `gls` instead. Since functions have a higher preference +than commands, this ends up calling the GNU coreutil. It has also a higher +preference over shell builtins (`gecho` is called instead of the builtin `echo`). + +2. Using an alias. This has an even higher preference than functions, but they +could be overridden because of a user setting. + +## Author + +- [Sorin Ionescu](https://github.com/sorin-ionescu). diff --git a/plugins/gnu-utils/gnu-utils.plugin.zsh b/plugins/gnu-utils/gnu-utils.plugin.zsh index b66e25d7f..967b8b4ea 100644 --- a/plugins/gnu-utils/gnu-utils.plugin.zsh +++ b/plugins/gnu-utils/gnu-utils.plugin.zsh @@ -5,79 +5,79 @@ # VERSION: 1.0.0 # ------------------------------------------------------------------------------ - -if [[ -x "${commands[gwhoami]}" ]]; then - __gnu_utils() { - emulate -L zsh - local gcmds - local gcmd - local cmd - local prefix - - # coreutils - gcmds=('g[' 'gbase64' 'gbasename' 'gcat' 'gchcon' 'gchgrp' 'gchmod' - 'gchown' 'gchroot' 'gcksum' 'gcomm' 'gcp' 'gcsplit' 'gcut' 'gdate' - 'gdd' 'gdf' 'gdir' 'gdircolors' 'gdirname' 'gdu' 'gecho' 'genv' 'gexpand' - 'gexpr' 'gfactor' 'gfalse' 'gfmt' 'gfold' 'ggroups' 'ghead' 'ghostid' - 'gid' 'ginstall' 'gjoin' 'gkill' 'glink' 'gln' 'glogname' 'gls' 'gmd5sum' - 'gmkdir' 'gmkfifo' 'gmknod' 'gmktemp' 'gmv' 'gnice' 'gnl' 'gnohup' 'gnproc' - 'god' 'gpaste' 'gpathchk' 'gpinky' 'gpr' 'gprintenv' 'gprintf' 'gptx' 'gpwd' - 'greadlink' 'grm' 'grmdir' 'gruncon' 'gseq' 'gsha1sum' 'gsha224sum' - 'gsha256sum' 'gsha384sum' 'gsha512sum' 'gshred' 'gshuf' 'gsleep' 'gsort' - 'gsplit' 'gstat' 'gstty' 'gsum' 'gsync' 'gtac' 'gtail' 'gtee' 'gtest' - 'gtimeout' 'gtouch' 'gtr' 'gtrue' 'gtruncate' 'gtsort' 'gtty' 'guname' - 'gunexpand' 'guniq' 'gunlink' 'guptime' 'gusers' 'gvdir' 'gwc' 'gwho' - 'gwhoami' 'gyes') - - # findutils - gcmds+=('gfind' 'gxargs' 'glocate') - - # Not part of either coreutils or findutils, installed separately. - gcmds+=('gsed' 'gtar' 'gtime') - - for gcmd in "${gcmds[@]}"; do - # - # This method allows for builtin commands to be primary but it's - # lost if hash -r or rehash -f is executed. Thus, those two - # functions have to be wrapped. - # - (( ${+commands[$gcmd]} )) && hash ${gcmd[2,-1]}=${commands[$gcmd]} - - # - # This method generates wrapper functions. - # It will override shell builtins. - # - # (( ${+commands[$gcmd]} )) && \ - # eval "function $gcmd[2,-1]() { \"${prefix}/${gcmd//"["/"\\["}\" \"\$@\"; }" - - # - # This method is inflexible since the aliases are at risk of being - # overridden resulting in the BSD coreutils being called. - # - # (( ${+commands[$gcmd]} )) && \ - # alias "$gcmd[2,-1]"="${prefix}/${gcmd//"["/"\\["}" - done - - return 0 - } - __gnu_utils; - - function hash() { - if [[ "$*" =~ "-(r|f)" ]]; then - builtin hash "$@" - __gnu_utils - else - builtin hash "$@" - fi - } - - function rehash() { - if [[ "$*" =~ "-f" ]]; then - builtin rehash "$@" - __gnu_utils - else - builtin rehash "$@" - fi - } +# Detect if GNU coreutils are installed by looking for gwhoami +if [[ ! -x "${commands[gwhoami]}" ]]; then + return fi +__gnu_utils() { + emulate -L zsh + local gcmds + local gcmd + local cmd + local prefix + + # coreutils + gcmds=('g[' 'gbase64' 'gbasename' 'gcat' 'gchcon' 'gchgrp' 'gchmod' + 'gchown' 'gchroot' 'gcksum' 'gcomm' 'gcp' 'gcsplit' 'gcut' 'gdate' + 'gdd' 'gdf' 'gdir' 'gdircolors' 'gdirname' 'gdu' 'gecho' 'genv' 'gexpand' + 'gexpr' 'gfactor' 'gfalse' 'gfmt' 'gfold' 'ggroups' 'ghead' 'ghostid' + 'gid' 'ginstall' 'gjoin' 'gkill' 'glink' 'gln' 'glogname' 'gls' 'gmd5sum' + 'gmkdir' 'gmkfifo' 'gmknod' 'gmktemp' 'gmv' 'gnice' 'gnl' 'gnohup' 'gnproc' + 'god' 'gpaste' 'gpathchk' 'gpinky' 'gpr' 'gprintenv' 'gprintf' 'gptx' 'gpwd' + 'greadlink' 'grm' 'grmdir' 'gruncon' 'gseq' 'gsha1sum' 'gsha224sum' + 'gsha256sum' 'gsha384sum' 'gsha512sum' 'gshred' 'gshuf' 'gsleep' 'gsort' + 'gsplit' 'gstat' 'gstty' 'gsum' 'gsync' 'gtac' 'gtail' 'gtee' 'gtest' + 'gtimeout' 'gtouch' 'gtr' 'gtrue' 'gtruncate' 'gtsort' 'gtty' 'guname' + 'gunexpand' 'guniq' 'gunlink' 'guptime' 'gusers' 'gvdir' 'gwc' 'gwho' + 'gwhoami' 'gyes') + + # findutils + gcmds+=('gfind' 'gxargs' 'glocate') + + # Not part of either coreutils or findutils, installed separately. + gcmds+=('gsed' 'gtar' 'gtime') + + for gcmd in "${gcmds[@]}"; do + # Do nothing if the command isn't found + (( ${+commands[$gcmd]} )) || continue + + # This method allows for builtin commands to be primary but it's + # lost if hash -r or rehash -f is executed. Thus, those two + # functions have to be wrapped. + # + hash ${gcmd[2,-1]}=${commands[$gcmd]} + + # This method generates wrapper functions. + # It will override shell builtins. + # + # eval "function $gcmd[2,-1]() { \"${prefix}/${gcmd//"["/"\\["}\" \"\$@\"; }" + + # This method is inflexible since the aliases are at risk of being + # overridden resulting in the BSD coreutils being called. + # + # alias "$gcmd[2,-1]"="${prefix}/${gcmd//"["/"\\["}" + done + + return 0 +} +__gnu_utils + +function hash() { + if [[ "$*" =~ "-(r|f)" ]]; then + builtin hash "$@" + __gnu_utils + else + builtin hash "$@" + fi +} + +function rehash() { + if [[ "$*" =~ "-f" ]]; then + builtin rehash "$@" + __gnu_utils + else + builtin rehash "$@" + fi +} + diff --git a/plugins/go/README.md b/plugins/go/README.md index 6ce6f4ee2..bf43b9feb 100644 --- a/plugins/go/README.md +++ b/plugins/go/README.md @@ -1 +1 @@ -The go plugin is deprecated. Use the [golang plugin](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/golang) instead. +The go plugin is deprecated. Use the [golang plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/golang) instead. diff --git a/plugins/gradle/gradle.plugin.zsh b/plugins/gradle/gradle.plugin.zsh index 8d578e27b..c651b91ca 100644 --- a/plugins/gradle/gradle.plugin.zsh +++ b/plugins/gradle/gradle.plugin.zsh @@ -7,7 +7,7 @@ gradle-or-gradlew() { echo "executing gradlew instead of gradle"; ./gradlew "$@"; else - gradle "$@"; + command gradle "$@"; fi } @@ -181,3 +181,4 @@ _gradlew_tasks () { ############################################################################ compdef _gradle_tasks gradle compdef _gradlew_tasks gradlew +compdef _gradlew_tasks gw diff --git a/plugins/history-substring-search/README.md b/plugins/history-substring-search/README.md index 7fb0fa0b6..0ffb21351 100644 --- a/plugins/history-substring-search/README.md +++ b/plugins/history-substring-search/README.md @@ -9,7 +9,7 @@ You can also use K and J in VI mode or ^P and ^N in EMACS mode for the same. [1]: https://fishshell.com [2]: https://www.zsh.org/mla/users/2009/msg00818.html [3]: https://sourceforge.net/projects/fizsh/ -[4]: https://github.com/robbyrussell/oh-my-zsh/pull/215 +[4]: https://github.com/ohmyzsh/ohmyzsh/pull/215 [5]: https://github.com/zsh-users/zsh-history-substring-search [6]: https://github.com/zsh-users/zsh-syntax-highlighting diff --git a/plugins/hitokoto/README.md b/plugins/hitokoto/README.md new file mode 100644 index 000000000..3a8758f56 --- /dev/null +++ b/plugins/hitokoto/README.md @@ -0,0 +1,15 @@ +# hitokoto plugin + +Displays a random quote taken from [hitokoto.cn](https://v1.hitokoto.cn/) + +Created by [Sinrimin](https://github.com/sinrimin) + +## Usage + +Add the plugin to the plugins array in your zshrc file and restart zsh: + +```zsh +plugins=(... hitokoto) +``` + +Then, run `hitokoto` to get a new random quote. diff --git a/plugins/hitokoto/hitokoto.plugin.zsh b/plugins/hitokoto/hitokoto.plugin.zsh new file mode 100644 index 000000000..8646ebf3b --- /dev/null +++ b/plugins/hitokoto/hitokoto.plugin.zsh @@ -0,0 +1,14 @@ +if ! (( $+commands[curl] )); then + echo "hitokoto plugin needs curl to work" >&2 + return +fi + +function hitokoto { + emulate -L zsh + Q=$(curl -s --connect-timeout 2 "https://v1.hitokoto.cn" | jq -j '.hitokoto+"\t"+.from') + + TXT=$(echo "$Q" | awk -F '\t' '{print $1}') + WHO=$(echo "$Q" | awk -F '\t' '{print $2}') + + [[ -n "$WHO" && -n "$TXT" ]] && print -P "%F{3}${WHO}%f: โ€œ%F{5}${TXT}%fโ€" +} diff --git a/plugins/homestead/homestead.plugin.zsh b/plugins/homestead/homestead.plugin.zsh index cdbc564e4..ea2803d77 100644 --- a/plugins/homestead/homestead.plugin.zsh +++ b/plugins/homestead/homestead.plugin.zsh @@ -1,6 +1,6 @@ # Homestead basic command completion _homestead_get_command_list () { - homestead --no-ansi | sed "1,/Available commands/d" | awk '/^ +[a-z]+/ { print $1 }' + homestead --no-ansi | sed -E "1,/(Available|Common) commands/d" | awk '/^ +[a-z]+/ { print $1 }' } _homestead () { diff --git a/plugins/ionic/README.md b/plugins/ionic/README.md new file mode 100644 index 000000000..3ec4fc8b7 --- /dev/null +++ b/plugins/ionic/README.md @@ -0,0 +1,30 @@ +# Ionic plugin + +This plugin adds completion for the [Ionic CLI](https://ionicframework.com/docs/cli), +as well as some aliases for common Ionic commands. + +To use it, add `ionic` to the plugins array in your zshrc file: + +```zsh +plugins=(... ionic) +``` + +## Aliases + +| Alias | Command | Description | +|-------|--------------------------------------|------------------------------------------------------------------| +| iv | `ionic --version` | Check Ionic version | +| ih | `ionic --help` | Ionic help command | +| ist | `ionic start` | Create a new project | +| ii | `ionic info` | Print system/environment info | +| is | `ionic serve` | Start a local dev server for app dev/testing | +| icba | `ionic cordova build android` | Build web assets and prepare app for android platform targets | +| icbi | `ionic cordova build ios` | Build web assets and prepare app for ios platform targets | +| icra | `ionic cordova run android` | Run an Ionic project on a connected android device | +| icri | `ionic cordova run ios` | Run an Ionic project on a connected ios device | +| icrsa | `ionic cordova resources android` | Automatically create icon and splash screen resources for android| +| icrsi | `ionic cordova resources ios` | Automatically create icon and splash screen resources for ios | +| icpaa | `ionic cordova platform add android` | Add Cordova android platform targets | +| icpai | `ionic cordova platform add ios` | Add Cordova ios platform targets | +| icpra | `ionic cordova platform rm android` | Remove Cordova platform targets | +| icpri | `ionic cordova platform rm ios` | Remove Cordova platform targets | diff --git a/plugins/ionic/ionic.plugin.zsh b/plugins/ionic/ionic.plugin.zsh new file mode 100644 index 000000000..cf388af1b --- /dev/null +++ b/plugins/ionic/ionic.plugin.zsh @@ -0,0 +1,15 @@ +alias iv="ionic --version" +alias ih="ionic --help" +alias ist="ionic start" +alias ii="ionic info" +alias is="ionic serve" +alias icba="ionic cordova build android" +alias icbi="ionic cordova build ios" +alias icra="ionic cordova run android" +alias icri="ionic cordova run ios" +alias icrsa="ionic cordova resources android" +alias icrsi="ionic cordova resources ios" +alias icpaa="ionic cordova platform add android" +alias icpai="ionic cordova platform add ios" +alias icpra="ionic cordova platform rm android" +alias icpri="ionic cordova platform rm ios" diff --git a/plugins/jenv/jenv.plugin.zsh b/plugins/jenv/jenv.plugin.zsh index 2eda8037b..b85906a0b 100644 --- a/plugins/jenv/jenv.plugin.zsh +++ b/plugins/jenv/jenv.plugin.zsh @@ -15,7 +15,7 @@ if [[ $FOUND_JENV -eq 0 ]]; then fi if [[ $FOUND_JENV -eq 1 ]]; then - export PATH="${jenvdir}/bin:$PATH" + (( $+commands[jenv] )) || export PATH="${jenvdir}/bin:$PATH" eval "$(jenv init - zsh)" function jenv_prompt_info() { jenv version-name 2>/dev/null } diff --git a/plugins/jfrog/README.md b/plugins/jfrog/README.md new file mode 100644 index 000000000..1d858620b --- /dev/null +++ b/plugins/jfrog/README.md @@ -0,0 +1,11 @@ +# JFrog CLI + +This plugin provides completion for [JFrog CLI](https://github.com/jfrog/jfrog-cli). + +JFrog CLI provides a simple interface that automates access to [Artifactory](https://jfrog.com/artifactory), [Xray](https://jfrog.com/xray), [Bintray](https://jfrog.com/bintray) and [Mission Control](https://jfrog.com/mission-control) through their respective REST APIs. + +To use it, add `jfrog` to the plugins array in your zshrc file: + +```zsh +plugins=(... jfrog) +``` diff --git a/plugins/jfrog/jfrog.plugin.zsh b/plugins/jfrog/jfrog.plugin.zsh new file mode 100644 index 000000000..064ffa2db --- /dev/null +++ b/plugins/jfrog/jfrog.plugin.zsh @@ -0,0 +1,10 @@ +_jfrog() { + local -a opts + opts=("${(@f)$(_CLI_ZSH_AUTOCOMPLETE_HACK=1 ${words[@]:0:#words[@]-1} --generate-bash-completion)}") + _describe 'values' opts + if [[ $compstate[nmatches] -eq 0 && $words[$CURRENT] != -* ]]; then + _files + fi +} + +compdef _jfrog jfrog \ No newline at end of file diff --git a/plugins/jhbuild/README.md b/plugins/jhbuild/README.md index 910526966..3220e0daf 100644 --- a/plugins/jhbuild/README.md +++ b/plugins/jhbuild/README.md @@ -1,4 +1,34 @@ -## JHBuild +# JHBuild + +This plugin adds some [JHBuild](https://developer.gnome.org/jhbuild/) aliases. + +To use it, add `jhbuild` to the plugins array of your zshrc file: + +```zsh +plugins=(... jhbuild) +``` + **Maintainer:** [Miguel Vaello](https://github.com/miguxbe) -This plugin adds some jhbuild aliases and increase the completion function provided by zsh. +## Aliases + +| Alias | Command | +|---------|---------------------------| +| `jh` | `jhbuild` | +| `jhb` | `jhbuild build` | +| `jhbo` | `jhbuild buildone` | +| `jhckb` | `jhbuild checkbranches` | +| `jhckm` | `jhbuild checkmodulesets` | +| `jhi` | `jhbuild info` | +| `jhl` | `jhbuild list` | +| `jhc` | `jhbuild clean` | +| `jhco` | `jhbuild cleanone` | +| `jhm` | `jhbuild make` | +| `jhr` | `jhbuild run` | +| `jhrd` | `jhbuild rdepends` | +| `jhsd` | `jhbuild sysdeps` | +| `jhu` | `jhbuild update` | +| `jhuo` | `jhbuild updateone` | +| `jhun` | `jhbuild uninstall` | +| `jhsh` | `jhbuild shell` | +| `jht` | `jhbuild tinderbox` | diff --git a/plugins/jhbuild/jhbuild.plugin.zsh b/plugins/jhbuild/jhbuild.plugin.zsh index fed1bc9fc..416745d27 100644 --- a/plugins/jhbuild/jhbuild.plugin.zsh +++ b/plugins/jhbuild/jhbuild.plugin.zsh @@ -1,5 +1,6 @@ -# Aliases -# +# JHBuild Aliases + +# Base alias jh='jhbuild' # Build alias jhb='jhbuild build' @@ -7,12 +8,14 @@ alias jhbo='jhbuild buildone' # Checks alias jhckb='jhbuild checkbranches' alias jhckm='jhbuild checkmodulesets' -# Info & list +# Info & List alias jhi='jhbuild info' alias jhl='jhbuild list' # Clean alias jhc='jhbuild clean' alias jhco='jhbuild cleanone' +# Make +alias jhm='jhbuild make' # Run alias jhr='jhbuild run' # Depends @@ -23,6 +26,7 @@ alias jhu='jhbuild update' alias jhuo='jhbuild updateone' # Uninstall alias jhun='jhbuild uninstall' - - - +# Shell +alias jhsh='jhbuild shell' +# Tinderbox +alias jht='jhbuild tinderbox' diff --git a/plugins/jruby/README.md b/plugins/jruby/README.md new file mode 100644 index 000000000..821a46d5e --- /dev/null +++ b/plugins/jruby/README.md @@ -0,0 +1,21 @@ +# JRuby plugin + +This plugin adds aliases for [JRuby](https://www.jruby.org/). + +To use it, add `jruby` to the plugins array in your zshrc file: + +```zsh +plugins=(... jruby) +``` + +## Requirements + +This plugin assumes you already have jruby installed and available in your [path](https://www.jruby.org/getting-started). + +## Aliases + +| Alias | Command | +| ------------ | ---------------------------------------------------------------- | +| `jrspec` | `jruby --debug -S rspec --debug` | +| `jprofile` | `jruby --profile.api -S rspec` | +| `jexec` | `jruby -S` | diff --git a/plugins/jsontools/jsontools.plugin.zsh b/plugins/jsontools/jsontools.plugin.zsh index 20d5eb1c9..912c83509 100644 --- a/plugins/jsontools/jsontools.plugin.zsh +++ b/plugins/jsontools/jsontools.plugin.zsh @@ -11,9 +11,10 @@ if [[ $(whence node) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METH alias urlencode_json='xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))"' alias urldecode_json='xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))"' elif [[ $(whence python) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METHOD" = "xpython" ) ]]; then - alias pp_json='python -mjson.tool' + alias pp_json='python -c "import sys; del sys.path[0]; import runpy; runpy._run_module_as_main(\"json.tool\")"' alias is_json='python -c " -import json, sys; +import sys; del sys.path[0]; +import json; try: json.loads(sys.stdin.read()) except ValueError, e: @@ -22,11 +23,13 @@ else: print True sys.exit(0)"' alias urlencode_json='python -c " -import urllib, json, sys; +import sys; del sys.path[0]; +import urllib, json; print urllib.quote_plus(sys.stdin.read()) sys.exit(0)"' alias urldecode_json='python -c " -import urllib, json, sys; +import sys; del sys.path[0]; +import urllib, json; print urllib.unquote_plus(sys.stdin.read()) sys.exit(0)"' elif [[ $(whence ruby) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_METHOD" = "xruby" ) ]]; then @@ -36,4 +39,4 @@ elif [[ $(whence ruby) != "" && ( "x$JSONTOOLS_METHOD" = "x" || "x$JSONTOOLS_MET alias urldecode_json='ruby -e "require \"uri\"; puts URI.unescape(STDIN.read)"' fi -unset JSONTOOLS_METHOD \ No newline at end of file +unset JSONTOOLS_METHOD diff --git a/plugins/jump/README.md b/plugins/jump/README.md index ed6415289..1b0ce68c0 100644 --- a/plugins/jump/README.md +++ b/plugins/jump/README.md @@ -17,3 +17,15 @@ plugins=(... jump) | `mark [mark-name]` | Create a mark with the given name or with the name of the current directory if none is provided | | `unmark ` | Remove the given mark | | `marks` | List the existing marks and the directories they point to | + +## Key bindings + +Pressing `CTRL`+`G` substitutes the written mark name for the full path of the mark. +For example, with a mark named `mymark` pointing to `/path/to/my/mark`: +```zsh +$ cp /tmp/file mymark +``` +will become: +```zsh +$ cp /tmp/file /path/to/my/mark +``` diff --git a/plugins/jump/jump.plugin.zsh b/plugins/jump/jump.plugin.zsh index d161a6da0..c2da1144e 100644 --- a/plugins/jump/jump.plugin.zsh +++ b/plugins/jump/jump.plugin.zsh @@ -9,33 +9,34 @@ export MARKPATH=$HOME/.marks jump() { - cd -P "$MARKPATH/$1" 2>/dev/null || {echo "No such mark: $1"; return 1} + builtin cd -P "$MARKPATH/$1" 2>/dev/null || {echo "No such mark: $1"; return 1} } mark() { - if [[ ( $# == 0 ) || ( "$1" == "." ) ]]; then - MARK=$(basename "$PWD") + if [[ $# -eq 0 || "$1" = "." ]]; then + MARK=${PWD:t} else MARK="$1" fi - if read -q \?"Mark $PWD as ${MARK}? (y/n) "; then - mkdir -p "$MARKPATH"; ln -sfn "$PWD" "$MARKPATH/$MARK" + if read -q "?Mark $PWD as ${MARK}? (y/n) "; then + command mkdir -p "$MARKPATH" + command ln -sfn "$PWD" "$MARKPATH/$MARK" fi } unmark() { - rm -i "$MARKPATH/$1" + LANG= command rm -i "$MARKPATH/$1" } marks() { - local max=0 - for link in $MARKPATH/*(@); do + local link max=0 + for link in $MARKPATH/{,.}*(@N); do if [[ ${#link:t} -gt $max ]]; then max=${#link:t} fi done local printf_markname_template="$(printf -- "%%%us " "$max")" - for link in $MARKPATH/*(@); do + for link in $MARKPATH/{,.}*(@N); do local markname="$fg[cyan]${link:t}$reset_color" local markpath="$fg[blue]$(readlink $link)$reset_color" printf -- "$printf_markname_template" "$markname" @@ -44,21 +45,15 @@ marks() { } _completemarks() { - if [[ $(ls "${MARKPATH}" | wc -l) -gt 1 ]]; then - reply=($(ls $MARKPATH/**/*(-) | grep : | sed -E 's/(.*)\/([_a-zA-Z0-9\.\-]*):$/\2/g')) - else - if readlink -e "${MARKPATH}"/* &>/dev/null; then - reply=($(ls "${MARKPATH}")) - fi - fi + reply=("${MARKPATH}"/{,.}*(@N:t)) } compctl -K _completemarks jump compctl -K _completemarks unmark _mark_expansion() { - setopt extendedglob + setopt localoptions extendedglob autoload -U modify-current-argument - modify-current-argument '$(readlink "$MARKPATH/$ARG")' + modify-current-argument '$(readlink "$MARKPATH/$ARG" || echo "$ARG")' } zle -N _mark_expansion bindkey "^g" _mark_expansion diff --git a/plugins/keychain/keychain.plugin.zsh b/plugins/keychain/keychain.plugin.zsh index af34793e7..def97d8d1 100644 --- a/plugins/keychain/keychain.plugin.zsh +++ b/plugins/keychain/keychain.plugin.zsh @@ -15,7 +15,7 @@ function _start_agent() { zstyle -a :omz:plugins:keychain options options # start keychain... - keychain ${^options:-} --agents ${agents:-gpg} ${^identities} + keychain ${^options:-} --agents ${agents:-gpg} ${^identities} --host $SHORT_HOST # Get the filenames to store/lookup the environment from _keychain_env_sh="$HOME/.keychain/$SHORT_HOST-sh" diff --git a/plugins/knife/README.md b/plugins/knife/README.md new file mode 100644 index 000000000..b167f1655 --- /dev/null +++ b/plugins/knife/README.md @@ -0,0 +1,25 @@ +# knife plugin + +This plugin adds completion for [knife](https://docs.chef.io/knife.html), a command-line tool +to interact with [Chef](https://chef.io), a platform to automate and manage infrastructure via +code. + +To use it, add `knife` to the plugins array in your zshrc file: +```zsh +plugins=(... knife) +``` + +## Options + +- `KNIFE_RELATIVE_PATH`: if set to `true`, the completion script will look for local cookbooks + under the `cookbooks` folder in the chef root directory. It has preference over the other two + options below. **Default:** empty. + +- `KNIFE_COOKBOOK_PATH`: if set, it points to the folder that contains local cookbooks, for + example: `/path/to/my/chef/cookbooks`. **Default:** `cookbook_path` field in `knife.rb` + (see below). + +- `KNIFE_CONF_PATH`: variable pointing to the `knife.rb` configuration file, for example + `/path/to/my/.chef/knife.rb`. Only used if `$KNIFE_COOKBOOK_PATH` isn't set. If it exists, + `$PWD/.chef/knife.rb` is used instead. Otherwise, if it's set, its value is used. + **Default**: `$HOME/.chef/knife.rb`. diff --git a/plugins/knife/_knife b/plugins/knife/_knife index 0d61ff15c..06b12a3b0 100644 --- a/plugins/knife/_knife +++ b/plugins/knife/_knife @@ -3,13 +3,13 @@ # You can override the path to knife.rb and your cookbooks by setting # KNIFE_CONF_PATH=/path/to/my/.chef/knife.rb # KNIFE_COOKBOOK_PATH=/path/to/my/chef/cookbooks -# If you want your local cookbooks path to be calculated relative to where you are then +# If you want your local cookbooks path to be calculated relative to where you are then # set the below option -# KNIFE_RELATIVE_PATH=true +# KNIFE_RELATIVE_PATH=true # Read around where these are used for more detail. # These flags should be available everywhere according to man knife -knife_general_flags=( --help --server-url --key --config --editor --format --log_level --logfile --no-editor --user --print-after --version --yes ) +knife_general_flags=(--help --server-url --key --config --editor --format --log_level --logfile --no-editor --user --print-after --version --yes) # knife has a very special syntax, some example calls are: # knife status @@ -25,183 +25,191 @@ _knife() { typeset -A opt_args cloudproviders=(bluebox ec2 rackspace slicehost terremark) _arguments \ - '1: :->knifecmd'\ - '2: :->knifesubcmd'\ + '1: :->knifecmd' \ + '2: :->knifesubcmd' \ '3: :->knifesubcmd2' \ '4: :->knifesubcmd3' \ '5: :->knifesubcmd4' \ '6: :->knifesubcmd5' - + case $state in knifecmd) compadd -Q "$@" bootstrap client configure cookbook "cookbook site" "data bag" diff exec environment index node recipe role search ssh status upload vault windows $cloudproviders - ;; + ;; knifesubcmd) case $words[2] in - (bluebox|ec2|rackspace|slicehost|terremark) + bluebox|ec2|rackspace|slicehost|terremark) compadd "$@" server images - ;; + ;; client) compadd -Q "$@" "bulk delete" list create show delete edit reregister - ;; + ;; configure) compadd "$@" client - ;; + ;; cookbook) compadd -Q "$@" test list create download delete "metadata from" show "bulk delete" metadata upload - ;; + ;; diff) _arguments '*:file or directory:_files -g "*"' - ;; + ;; environment) compadd -Q "$@" list create delete edit show "from file" - ;; + ;; node) - compadd -Q "$@" "from file" create show edit delete list run_list "bulk delete" - ;; + compadd -Q "$@" "from file" create show edit delete list run_list "bulk delete" + ;; recipe) - compadd "$@" list - ;; + compadd "$@" list + ;; role) compadd -Q "$@" "bulk delete" create delete edit "from file" list show - ;; + ;; upload) - _arguments '*:file or directory:_files -g "*"' - ;; + _arguments '*:file or directory:_files -g "*"' + ;; vault) compadd -Q "$@" create decrypt delete edit remove "rotate all keys" "rotate keys" show update - ;; + ;; windows) compadd "$@" bootstrap - ;; + ;; *) - _arguments '2:Subsubcommands:($(_knife_options1))' + _arguments '2:Subsubcommands:($(_knife_options1))' + ;; esac - ;; - knifesubcmd2) + ;; + knifesubcmd2) case $words[3] in - server) + server) compadd "$@" list create delete - ;; - images) + ;; + images) compadd "$@" list - ;; - site) + ;; + site) compadd "$@" vendor show share search download list unshare - ;; - (show|delete|edit) - _arguments '3:Subsubcommands:($(_chef_$words[2]s_remote))' - ;; - (upload|test) - _arguments '3:Subsubcommands:($(_chef_$words[2]s_local) --all)' - ;; + ;; + show|delete|edit) + _arguments '3:Subsubcommands:($(_chef_$words[2]s_remote))' + ;; + upload|test) + _arguments '3:Subsubcommands:($(_chef_$words[2]s_local) --all)' + ;; list) - compadd -a "$@" knife_general_flags - ;; + compadd -a "$@" knife_general_flags + ;; bag) compadd -Q "$@" show edit list "from file" create delete - ;; + ;; *) _arguments '3:Subsubcommands:($(_knife_options2))' + ;; esac - ;; - knifesubcmd3) - case $words[3] in - show) - case $words[2] in - cookbook) - versioncomp=1 - _arguments '4:Cookbookversions:($(_cookbook_versions) latest)' - ;; - (node|client|role) - compadd "$@" --attribute - esac - esac - case $words[4] in - (show|edit) - _arguments '4:Subsubsubcommands:($(_chef_$words[2]_$words[3]s_remote))' ;; - file) + knifesubcmd3) + case $words[3] in + show) + case $words[2] in + cookbook) + versioncomp=1 + _arguments '4:Cookbookversions:($(_cookbook_versions) latest)' + ;; + node|client|role) + compadd "$@" --attribute + ;; + esac + ;; + esac + case $words[4] in + show|edit) + _arguments '4:Subsubsubcommands:($(_chef_$words[2]_$words[3]s_remote))' + ;; + file) case $words[2] in environment) _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_chef_root)/environments"' - ;; + ;; node) _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_chef_root)/nodes"' - ;; + ;; role) _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_chef_root)/roles"' - ;; + ;; *) _arguments '*:Subsubcommands:($(_knife_options3))' - esac - ;; - list) - compadd -a "$@" knife_general_flags - ;; - *) - _arguments '*:Subsubcommands:($(_knife_options3))' + ;; + esac + ;; + list) + compadd -a "$@" knife_general_flags + ;; + *) + _arguments '*:Subsubcommands:($(_knife_options3))' + ;; esac ;; - knifesubcmd4) - if (( versioncomp > 0 )); then - compadd "$@" attributes definitions files libraries providers recipes resources templates - else - case $words[5] in - file) - _arguments '*:directory:_path_files -/ -W "$(_chef_root)/data_bags" -qS \ ' + knifesubcmd4) + if ((versioncomp > 0)); then + compadd "$@" attributes definitions files libraries providers recipes resources templates + else + case $words[5] in + file) + _arguments '*:directory:_path_files -/ -W "$(_chef_root)/data_bags" -qS \ ' ;; - *) _arguments '*:Subsubcommands:($(_knife_options2))' + *) _arguments '*:Subsubcommands:($(_knife_options2))' ;; esac - fi - ;; - knifesubcmd5) - case $words[5] in - file) - _arguments '*:files:_path_files -g "*.json" -W "$(_chef_root)/data_bags/$words[6]"' - ;; - *) - _arguments '*:Subsubcommands:($(_knife_options3))' - esac - esac + fi + ;; + knifesubcmd5) + case $words[5] in + file) + _arguments '*:files:_path_files -g "*.json" -W "$(_chef_root)/data_bags/$words[6]"' + ;; + *) + _arguments '*:Subsubcommands:($(_knife_options3))' + ;; + esac + ;; + esac } # Helper functions to provide the argument completion for several depths of commands _knife_options1() { - ( for line in $( knife $words[2] --help | grep -v "^knife" ); do echo $line | grep "\-\-"; done ) + (for line in $(knife $words[2] --help | grep -v "^knife"); do echo $line | grep "\-\-"; done) } _knife_options2() { - ( for line in $( knife $words[2] $words[3] --help | grep -v "^knife" ); do echo $line | grep "\-\-"; done ) + (for line in $(knife $words[2] $words[3] --help | grep -v "^knife"); do echo $line | grep "\-\-"; done) } _knife_options3() { - ( for line in $( knife $words[2] $words[3] $words[4] --help | grep -v "^knife" ); do echo $line | grep "\-\-"; done ) + (for line in $(knife $words[2] $words[3] $words[4] --help | grep -v "^knife"); do echo $line | grep "\-\-"; done) } # The chef_x_remote functions use knife to get a list of objects of type x on the server _chef_roles_remote() { - (knife role list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife role list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_clients_remote() { - (knife client list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife client list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_nodes_remote() { - (knife node list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife node list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_cookbooks_remote() { - (knife cookbook list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife cookbook list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_sitecookbooks_remote() { - (knife cookbook site list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife cookbook site list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_data_bags_remote() { - (knife data bag list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') + (knife data bag list --format json | grep \" | awk '{print $1}' | awk -F"," '{print $1}' | awk -F"\"" '{print $2}') } _chef_environments_remote() { @@ -210,14 +218,14 @@ _chef_environments_remote() { # The chef_x_local functions use the knife config to find the paths of relevant objects x to be uploaded to the server _chef_cookbooks_local() { - if [ $KNIFE_RELATIVE_PATH ]; then + if [ $KNIFE_RELATIVE_PATH ]; then local cookbook_path="$(_chef_root)/cookbooks" - else + else local knife_rb=${KNIFE_CONF_PATH:-${HOME}/.chef/knife.rb} if [ -f ./.chef/knife.rb ]; then knife_rb="./.chef/knife.rb" fi - local cookbook_path=${KNIFE_COOKBOOK_PATH:-$(grep cookbook_path $knife_rb | awk 'BEGIN {FS = "[" }; {print $2}' | sed 's/\,//g' | sed "s/'//g" | sed 's/\(.*\)]/\1/' )} + local cookbook_path=${KNIFE_COOKBOOK_PATH:-$(grep cookbook_path $knife_rb | awk 'BEGIN {FS = "[" }; {print $2}' | sed 's/\,//g' | sed "s/'//g" | sed 's/\(.*\)]/\1/')} fi (for i in $cookbook_path; do ls $i; done) } @@ -227,12 +235,11 @@ _cookbook_versions() { (knife cookbook show $words[4] | grep -v $words[4] | grep -v -E '\]|\[|\{|\}' | sed 's/ //g' | sed 's/"//g') } -# Searches up from current directory to find the closest folder that has a .chef folder -# Useful for the knife upload/from file commands -_chef_root () { +# Searches up from current directory to find the closest folder that has a .chef folder +# Useful for the knife upload/from file commands +_chef_root() { directory="$PWD" - while [ $directory != '/' ] - do + while [ $directory != '/' ]; do test -e "$directory/.chef" && echo "$directory" && return directory="${directory:h}" done diff --git a/plugins/knife_ssh/README.md b/plugins/knife_ssh/README.md new file mode 100644 index 000000000..cb836b7f3 --- /dev/null +++ b/plugins/knife_ssh/README.md @@ -0,0 +1,14 @@ +# knife_ssh plugin + +This plugin adds a `knife_ssh` function as well as completion for it, to allow +connecting via ssh to servers managed with [Chef](https://www.chef.io/). + +To use it, add `knife_ssh` to the plugins array in your zshrc file: +```zsh +plugins=(... knife_ssh) +``` + +The plugin creates a cache of the Chef node list via `knife`, and stores it +in `$HOME/.knife_comp~`, when first triggering knife_ssh completion. + +**Requirements:** `knife` has to be installed. diff --git a/plugins/knife_ssh/knife_ssh.plugin.zsh b/plugins/knife_ssh/knife_ssh.plugin.zsh index 7fdd42a1e..dc425a33e 100644 --- a/plugins/knife_ssh/knife_ssh.plugin.zsh +++ b/plugins/knife_ssh/knife_ssh.plugin.zsh @@ -1,17 +1,17 @@ function knife_ssh() { - grep -q $1 ~/.knife_comp~ 2> /dev/null || rm -f ~/.knife_comp~; + grep -q $1 ~/.knife_comp~ 2> /dev/null || rm -f ~/.knife_comp~ ssh $(knife node show $1 | awk '/IP:/{print $2}') } _knife_ssh() { if hash knife 2>/dev/null; then if [[ ! -f ~/.knife_comp~ ]]; then - echo "\nGenerating ~/.knife_comp~..." >/dev/stderr + echo "\nGenerating ~/.knife_comp~..." >&2 knife node list > ~/.knife_comp~ fi - compadd $(<~/.knife_comp~) + compadd $(< ~/.knife_comp~) else - echo "Could not find knife" > /dev/stderr; + echo "Could not find knife" >&2 fi } diff --git a/plugins/kube-ps1/README.md b/plugins/kube-ps1/README.md index 19dac42e9..fdc1a94e8 100644 --- a/plugins/kube-ps1/README.md +++ b/plugins/kube-ps1/README.md @@ -53,10 +53,13 @@ plugins=( kube-ps1 ) +# After the "source Oh My Zsh" line PROMPT=$PROMPT'$(kube_ps1) ' +# Or in double quotes, don't forget to escape +PROMPT=$PROMPT"\$(kube_ps1) " ``` -Note: the `PROMPT` example above was tested with the theme `robbyrussell` +Note: The `PROMPT` example above was tested with the theme `robbyrussell`. ## Enabling / Disabling on the current shell @@ -100,4 +103,4 @@ The default settings can be overridden in ~/.zshrc ## Contributors - Jared Yanovich -- Pedro Moranga \ No newline at end of file +- Pedro Moranga diff --git a/plugins/kubectl/kubectl.plugin.zsh b/plugins/kubectl/kubectl.plugin.zsh index 6c1696d5e..92688c53c 100644 --- a/plugins/kubectl/kubectl.plugin.zsh +++ b/plugins/kubectl/kubectl.plugin.zsh @@ -14,7 +14,7 @@ fi alias k=kubectl # Execute a kubectl command against all namespaces -alias kca='f(){ kubectl "$@" --all-namespaces; unset -f f; }; f' +alias kca='_kca(){ kubectl "$@" --all-namespaces; unset -f _kca; }; _kca' # Apply a YML file alias kaf='kubectl apply -f' @@ -37,6 +37,7 @@ alias kdelf='kubectl delete -f' # Pod management. alias kgp='kubectl get pods' +alias kgpa='kubectl get pods --all-namespaces' alias kgpw='kgp --watch' alias kgpwide='kgp -o wide' alias kep='kubectl edit pods' @@ -48,6 +49,7 @@ alias kgpl='kgp -l' # Service management. alias kgs='kubectl get svc' +alias kgsa='kubectl get svc --all-namespaces' alias kgsw='kgs --watch' alias kgswide='kgs -o wide' alias kes='kubectl edit svc' @@ -56,6 +58,7 @@ alias kdels='kubectl delete svc' # Ingress management alias kgi='kubectl get ingress' +alias kgia='kubectl get ingress --all-namespaces' alias kei='kubectl edit ingress' alias kdi='kubectl describe ingress' alias kdeli='kubectl delete ingress' @@ -69,17 +72,20 @@ alias kcn='kubectl config set-context $(kubectl config current-context) --namesp # ConfigMap management alias kgcm='kubectl get configmaps' +alias kgcma='kubectl get configmaps --all-namespaces' alias kecm='kubectl edit configmap' alias kdcm='kubectl describe configmap' alias kdelcm='kubectl delete configmap' # Secret management alias kgsec='kubectl get secret' +alias kgseca='kubectl get secret --all-namespaces' alias kdsec='kubectl describe secret' alias kdelsec='kubectl delete secret' # Deployment management. alias kgd='kubectl get deployment' +alias kgda='kubectl get deployment --all-namespaces' alias kgdw='kgd --watch' alias kgdwide='kgd -o wide' alias ked='kubectl edit deployment' @@ -98,6 +104,7 @@ alias kru='kubectl rollout undo' # Statefulset management. alias kgss='kubectl get statefulset' +alias kgssa='kubectl get statefulset --all-namespaces' alias kgssw='kgss --watch' alias kgsswide='kgss -o wide' alias kess='kubectl edit statefulset' @@ -115,7 +122,13 @@ alias kgaa='kubectl get all --all-namespaces' # Logs alias kl='kubectl logs' +alias kl1h='kubectl logs --since 1h' +alias kl1m='kubectl logs --since 1m' +alias kl1s='kubectl logs --since 1s' alias klf='kubectl logs -f' +alias klf1h='kubectl logs --since 1h -f' +alias klf1m='kubectl logs --since 1m -f' +alias klf1s='kubectl logs --since 1s -f' # File copy alias kcp='kubectl cp' @@ -128,6 +141,7 @@ alias kdelno='kubectl delete node' # PVC management. alias kgpvc='kubectl get pvc' +alias kgpvca='kubectl get pvc --all-namespaces' alias kgpvcw='kgpvc --watch' alias kepvc='kubectl edit pvc' alias kdpvc='kubectl describe pvc' diff --git a/plugins/laravel/README.md b/plugins/laravel/README.md index 44798b68d..95f590191 100644 --- a/plugins/laravel/README.md +++ b/plugins/laravel/README.md @@ -29,6 +29,12 @@ plugins=(... laravel) | `pamc` | `php artisan make:controller` | | `pams` | `php artisan make:seeder` | | `pamt` | `php artisan make:test` | +| `pamfa` | `php artisan make:factory` | +| `pamp` | `php artisan make:policy` | +| `pame` | `php artisan make:event` | +| `pamj` | `php artisan make:job` | +| `paml` | `php artisan make:listener` | +| `pamn` | `php artisan make:notification` | ## Clears @@ -38,3 +44,14 @@ plugins=(... laravel) | `pacoc` | `php artisan config:clear` | | `pavic` | `php artisan view:clear` | | `paroc` | `php artisan route:clear` | + +## Queues + +| Alias | Description | +|:-:|:-:| +| `paqf` | `php artisan queue:failed` | +| `paqft` | `php artisan queue:failed-table` | +| `paql` | `php artisan queue:listen` | +| `paqr` | `php artisan queue:retry` | +| `paqt` | `php artisan queue:table` | +| `paqw` | `php artisan queue:work` | diff --git a/plugins/laravel/laravel.plugin.zsh b/plugins/laravel/laravel.plugin.zsh index 7ddfd85ba..a8382d3c9 100644 --- a/plugins/laravel/laravel.plugin.zsh +++ b/plugins/laravel/laravel.plugin.zsh @@ -17,6 +17,13 @@ alias pamm='php artisan make:model' alias pamc='php artisan make:controller' alias pams='php artisan make:seeder' alias pamt='php artisan make:test' +alias pamfa='php artisan make:factory' +alias pamp='php artisan make:policy' +alias pame='php artisan make:event' +alias pamj='php artisan make:job' +alias paml='php artisan make:listener' +alias pamn='php artisan make:notification' +alias pampp='php artisan make:provider' # Clears @@ -24,3 +31,11 @@ alias pacac='php artisan cache:clear' alias pacoc='php artisan config:clear' alias pavic='php artisan view:clear' alias paroc='php artisan route:clear' + +# queues +alias paqf='php artisan queue:failed' +alias paqft='php artisan queue:failed-table' +alias paql='php artisan queue:listen' +alias paqr='php artisan queue:retry' +alias paqt='php artisan queue:table' +alias paqw='php artisan queue:work' diff --git a/plugins/last-working-dir/last-working-dir.plugin.zsh b/plugins/last-working-dir/last-working-dir.plugin.zsh index 53bb19e46..fd21705ae 100644 --- a/plugins/last-working-dir/last-working-dir.plugin.zsh +++ b/plugins/last-working-dir/last-working-dir.plugin.zsh @@ -2,7 +2,8 @@ typeset -g ZSH_LAST_WORKING_DIRECTORY # Updates the last directory once directory is changed -chpwd_functions+=(chpwd_last_working_dir) +autoload -U add-zsh-hook +add-zsh-hook chpwd chpwd_last_working_dir chpwd_last_working_dir() { if [ "$ZSH_SUBSHELL" = 0 ]; then local cache_file="$ZSH_CACHE_DIR/last-working-dir" diff --git a/plugins/lein/README.md b/plugins/lein/README.md new file mode 100644 index 000000000..0c4119663 --- /dev/null +++ b/plugins/lein/README.md @@ -0,0 +1,9 @@ +# Leiningen plugin + +This plugin adds completions for the [Leiningen](https://leiningen.org/) Clojure build tool. + +To use it, add `lein` to the plugins array in your zshrc file: + +```zsh +plugins=(... lein) +``` diff --git a/plugins/lol/README.md b/plugins/lol/README.md index b0e54f575..1791de493 100644 --- a/plugins/lol/README.md +++ b/plugins/lol/README.md @@ -13,10 +13,10 @@ Plugin for adding catspeak aliases, because why not ) ``` -2. Reload the source file or restart your Terminal session: +2. Restart your terminal session or restart the shell: ```console - $ source ~/.zshrc + $ exec zsh $ ``` @@ -61,7 +61,7 @@ Plugin for adding catspeak aliases, because why not | `violenz` | `git rebase` | | `visible` | `echo` | | `wtf` | `dmesg` | -| `yolo` | `git commit -m "$(curl -s https://whatthecommit.com/index.txt)"` | +| `yolo` | `git commit -m "$(curl -s http://whatthecommit.com/index.txt)"` | ## Usage Examples @@ -78,6 +78,6 @@ nowai u=r,go= some.file # ssh root@catserver.org pwned root@catserver.org -# git commit -m "$(curl -s https://whatthecommit.com/index.txt)" +# git commit -m "$(curl -s http://whatthecommit.com/index.txt)" yolo ``` diff --git a/plugins/lol/lol.plugin.zsh b/plugins/lol/lol.plugin.zsh index 585f96e4f..3c30259a1 100644 --- a/plugins/lol/lol.plugin.zsh +++ b/plugins/lol/lol.plugin.zsh @@ -45,7 +45,7 @@ alias bringz='git pull' alias chicken='git add' alias oanward='git commit -m' alias ooanward='git commit -am' -alias yolo='git commit -m "$(curl -s https://whatthecommit.com/index.txt)"' +alias yolo='git commit -m "$(curl -s http://whatthecommit.com/index.txt)"' alias letcat='git checkout' alias violenz='git rebase' diff --git a/plugins/macports/_port b/plugins/macports/_port index 06d7fb426..6a9ebe0c6 100644 --- a/plugins/macports/_port +++ b/plugins/macports/_port @@ -41,6 +41,8 @@ subcmds=( 'patch' 'pkg' 'provides' +'rdependents' +'rdeps' 'rpmpackage' 'search' 'selfupdate' diff --git a/plugins/magic-enter/README.md b/plugins/magic-enter/README.md new file mode 100644 index 000000000..78514c67d --- /dev/null +++ b/plugins/magic-enter/README.md @@ -0,0 +1,17 @@ +## Magic Enter plugin + +This plugin makes your enter key magical, by binding commonly used commands to it. + +To use it, add `magic-enter` to the plugins array in your zshrc file. You can set the +commands to be run in your .zshrc, before the line containing plugins. If no command +is specified in a git directory, `git status` is executed; in other directories, `ls`. + +```zsh +# defaults +MAGIC_ENTER_GIT_COMMAND='git status -u .' +MAGIC_ENTER_OTHER_COMMAND='ls -lh .' + +plugins=(... magic-enter) +``` + +**Maintainer:** [@dufferzafar](https://github.com/dufferzafar) diff --git a/plugins/magic-enter/Readme.md b/plugins/magic-enter/Readme.md deleted file mode 100644 index b401ab415..000000000 --- a/plugins/magic-enter/Readme.md +++ /dev/null @@ -1,14 +0,0 @@ -## Magic Enter - -**Maintainer:** [@dufferzafar](https://github.com/dufferzafar) - -Makes your enter key magical, by binding commonly used commands to it. - -You can set the commands to be run in your .zshrc, before the line containing plugins! - -```bash -MAGIC_ENTER_GIT_COMMAND='git status -u .' -MAGIC_ENTER_OTHER_COMMAND='ls -lh .' - -plugins=(magic-enter) -``` diff --git a/plugins/meteor/README.md b/plugins/meteor/README.md index 4bee87f8f..187a45a62 100644 --- a/plugins/meteor/README.md +++ b/plugins/meteor/README.md @@ -1,6 +1,6 @@ ## Introduction -The [meteor plugin](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/meteor) provides many +The [meteor plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/meteor) provides many [useful aliases](#aliases) as well as completion for the `meteor` command. Enable it by adding `meteor` to the plugins array in your zshrc file: diff --git a/plugins/microk8s/README.md b/plugins/microk8s/README.md new file mode 100644 index 000000000..2b4ea206f --- /dev/null +++ b/plugins/microk8s/README.md @@ -0,0 +1,24 @@ +# MicroK8s plugin + +This plugin provides completion and useful aliases for [MicroK8s](https://microk8s.io/). + +To use it, add `microk8s` to the plugins array in your zshrc file. + +```zsh +plugins=(... microk8s) +``` + +## Aliases + +| Alias | Command | Description | +|-------|------------------|----------------------------------------------------------------------------------------------------------| +| mco | microk8s.config | Shows the Kubernetes config file. | +| mct | microk8s.ctr | Interact with containerd CLI. | +| mdi | microk8s.disable | Disables an addon. | +| me | microk8s.enable | Enables an addon. | +| mh | microk8s.helm | Interact with Helm CLI. | +| mis | microk8s.istio | Interact with Istio CLI. | +| mk | microk8s.kubectl | Interact with Kubernetes CLI. | +| msp | microk8s.stop | Stops all Kubernetes services. | +| mst | microk8s.start | Starts MicroK8s after it is being stopped. | +| msts | microk8s.status | Provides an overview of the MicroK8s state (running / not running) as well as the set of enabled addons. | \ No newline at end of file diff --git a/plugins/microk8s/microk8s.plugin.zsh b/plugins/microk8s/microk8s.plugin.zsh new file mode 100644 index 000000000..048a9ab83 --- /dev/null +++ b/plugins/microk8s/microk8s.plugin.zsh @@ -0,0 +1,82 @@ +# ---------------------------------------------------------- # +# Aliases and Completions for MicroK8s (https://microk8s.io) # +# Author: Shaun Tabone (https://github.com/xontab) # +# ---------------------------------------------------------- # + +# Helper function to cache and load completions +_microk8s_cache_completion() { + local cache="${ZSH_CACHE_DIR}/microk8s_$(echo $1)_completion" + if [[ ! -f $cache ]]; then + $2 $cache + fi + + [[ -f $cache ]] && source $cache +} + +# ---------------------------------------------------------- # +# microk8s.enable # +# ALIAS: me # +# ---------------------------------------------------------- # +_microk8s_enable_get_command_list() { + microk8s.enable --help | tail -n +7 | awk '{$1=$1;print}' +} + +_microk8s_enable() { + compadd -X "MicroK8s Addons" $(_microk8s_enable_get_command_list) +} + +compdef _microk8s_enable microk8s.enable +alias me='microk8s.enable' + +# ---------------------------------------------------------- # +# microk8s.disable # +# ALIAS: mdi # +# ---------------------------------------------------------- # +_microk8s_disable_get_command_list() { + microk8s.disable --help | tail -n +7 | awk '{$1=$1;print}' +} + +_microk8s_disable() { + compadd -X "MicroK8s Addons" $(_microk8s_disable_get_command_list) +} + +compdef _microk8s_disable microk8s.disable +alias mdi='microk8s.disable' + +# ---------------------------------------------------------- # +# microk8s.kubectl # +# ALIAS: mk # +# ---------------------------------------------------------- # +_microk8s_kubectl_completion() { + if [ $commands[microk8s.kubectl] ]; then + microk8s.kubectl 2>/dev/null >/dev/null && microk8s.kubectl completion zsh | sed 's/__start_kubectl kubectl/__start_kubectl microk8s.kubectl/g' >$1 + fi +} + +_microk8s_cache_completion 'kubectl' _microk8s_kubectl_completion + +alias mk='microk8s.kubectl' + +# ---------------------------------------------------------- # +# microk8s.helm # +# ALIAS: mh # +# ---------------------------------------------------------- # +_microk8s_helm_completion() { + if [ $commands[microk8s.helm] ]; then + microk8s.helm completion zsh | sed 's/__start_helm helm/__start_helm microk8s.helm/g' >$1 + fi +} + +_microk8s_cache_completion 'helm' _microk8s_helm_completion + +alias mh='microk8s.helm' + +# ---------------------------------------------------------- # +# Other Aliases # +# ---------------------------------------------------------- # +alias mco='microk8s.config' +alias mct='microk8s.ctr' +alias mis='microk8s.istio' +alias mst='microk8s.start' +alias msts='microk8s.status' +alias msp='microk8s.stop' diff --git a/plugins/mvn/README.md b/plugins/mvn/README.md index 88f5be8ba..3bbba5b4f 100644 --- a/plugins/mvn/README.md +++ b/plugins/mvn/README.md @@ -55,4 +55,4 @@ has colored output, so this function will be soon removed from the plugin. ### Known bugs It has a bug where it will swallow mvn prompts for user input, _e.g._ when using -`archetype:generate`. See [#5052](https://github.com/robbyrussell/oh-my-zsh/issues/5052). +`archetype:generate`. See [#5052](https://github.com/ohmyzsh/ohmyzsh/issues/5052). diff --git a/plugins/mvn/mvn.plugin.zsh b/plugins/mvn/mvn.plugin.zsh index 01aef814d..0866e5553 100644 --- a/plugins/mvn/mvn.plugin.zsh +++ b/plugins/mvn/mvn.plugin.zsh @@ -267,6 +267,8 @@ function listMavenCompletions { stage:copy # toolchain toolchain:toolchain + #liberty + liberty:clean-server liberty:compile-jsp liberty:configure-arquillian liberty:create-server liberty:debug liberty:debug-server liberty:deploy liberty:dev liberty:display-url liberty:dump-server liberty:install-apps liberty:install-feature liberty:install-server liberty:java-dump-server liberty:package-server liberty:run liberty:run-server liberty:server-status liberty:start liberty:start-server liberty:status liberty:stop liberty:stop-server liberty:test-start-server liberty:test-stop-server liberty:undeploy liberty:uninstall-feature # options "-Dmaven.test.skip=true" -DskipTests -DskipITs -Dmaven.surefire.debug -DenableCiProfile "-Dpmd.skip=true" "-Dcheckstyle.skip=true" "-Dtycho.mode=maven" "-Dmaven.test.failure.ignore=true" "-DgroupId=" "-DartifactId=" "-Dversion=" "-Dpackaging=jar" "-Dfile=" diff --git a/plugins/mysql-macports/README.md b/plugins/mysql-macports/README.md new file mode 100644 index 000000000..a4224d9c0 --- /dev/null +++ b/plugins/mysql-macports/README.md @@ -0,0 +1,20 @@ +# MySQL-Macports plugin + +This plugin adds aliases for some of the commonly used [MySQL](https://www.mysql.com/) commands when installed using [MacPorts](https://www.macports.org/) on macOS. + +To use it, add `mysql-macports` to the plugins array in your zshrc file: + +```zsh +plugins=(... mysql-macports) +``` + +For instructions on how to install MySQL using MacPorts, read the [MacPorts wiki](https://trac.macports.org/wiki/howto/MySQL/). + +## Aliases + +| Alias | Command | Description | +| ------------ | --------------------------------------------------------- | ------------------------------------------ | +| mysqlstart | `sudo /opt/local/share/mysql5/mysql/mysql.server start` | Start the MySQL server. | +| mysqlstop | `sudo /opt/local/share/mysql5/mysql/mysql.server stop` | Stop the MySQL server. | +| mysqlrestart | `sudo /opt/local/share/mysql5/mysql/mysql.server restart` | Restart the MySQL server. | +| mysqlstatus | `mysqladmin5 -u root -p ping` | Check whether the MySQL server is running. | diff --git a/plugins/n98-magerun/README.md b/plugins/n98-magerun/README.md new file mode 100644 index 000000000..b0abe4747 --- /dev/null +++ b/plugins/n98-magerun/README.md @@ -0,0 +1,21 @@ +# n98-magerun plugin + +The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. + +The [n98-magerun plugin](https://github.com/netz98/n98-magerun) provides many +[useful aliases](#aliases) as well as completion for the `n98-magerun` command. + +Enable it by adding `n98-magerun` to the plugins array in your zshrc file: + +```zsh +plugins=(... n98-magerun) +``` + +## Aliases + +| Alias | Command | Description | +| --------- | -------------------------------------------------- | --------------------------------------------------------------------------------- | +| n98 | `n98-magerun.phar` | The N98-Magerun phar-file (Version 1) | +| n98-2 | `n98-magerun2.phar` | The N98-Magerun phar-file (Version 2) | +| mage-get | `wget https://files.magerun.net/n98-magerun.phar` | Download the latest stable N98-Magerun phar-file from the file-server (Version 1) | +| mage2-get | `wget https://files.magerun.net/n98-magerun2.phar` | Download the latest stable N98-Magerun phar-file from the file-server (Version 2) | diff --git a/plugins/n98-magerun/n98-magerun.plugin.zsh b/plugins/n98-magerun/n98-magerun.plugin.zsh index bfcf27b98..d79aee7eb 100644 --- a/plugins/n98-magerun/n98-magerun.plugin.zsh +++ b/plugins/n98-magerun/n98-magerun.plugin.zsh @@ -2,7 +2,8 @@ # FILE: n98-magerun.plugin.zsh # DESCRIPTION: oh-my-zsh n98-magerun plugin file. Adapted from composer plugin # AUTHOR: Andrew Dwyer (andrewrdwyer at gmail dot com) -# VERSION: 1.0.0 +# AUTHOR: Jisse Reitsma (jisse at yireo dot com) +# VERSION: 1.1.0 # ------------------------------------------------------------------------------ # n98-magerun basic command completion @@ -24,11 +25,18 @@ _n98_magerun () { compdef _n98_magerun n98-magerun.phar compdef _n98_magerun n98-magerun +compdef _n98_magerun n98-magerun2.phar +compdef _n98_magerun n98-magerun2 # Aliases alias n98='n98-magerun.phar' alias mage='n98-magerun.phar' -alias magefl='n98-magerun.phar cache:flush' +alias magerun='n98-magerun.phar' + +alias n98-2='n98-magerun2.phar' +alias mage2='n98-magerun2.phar' +alias magerun2='n98-magerun2.phar' # Install n98-magerun into the current directory -alias mage-get='wget https://raw.github.com/netz98/n98-magerun/master/n98-magerun.phar' +alias mage-get='wget https://files.magerun.net/n98-magerun.phar' +alias mage2-get='wget https://files.magerun.net/n98-magerun2.phar' diff --git a/plugins/ng/README.md b/plugins/ng/README.md index 86ad64041..29ac15aa4 100644 --- a/plugins/ng/README.md +++ b/plugins/ng/README.md @@ -1,37 +1,10 @@ -## NG Plugin +# ng plugin -This [ng plugin](https://github.com/robbyrussell/oh-my-zsh/tree/master/plugins/ng) - adds completion support for Angular's CLI (named ng). +This plugin adds autocompletion support for [Angular's CLI](https://github.com/angular/angular-cli) +(named `ng`). -Ng is hosted on [ng home](https://github.com/catull/angular-cli) - -It is used to generate Angular 2 app "stubs", build those apps, configure them, -test them, lint them etc. - -Ahem, "stubs" is not what Angular engineers refer to the items ng can generate -for you. - -"Stubs" can be any one of: -- class -- component -- directive -- enum -- module -- pipe -- route -- service - -At the moment, `ng completion` creates a very rough completion for Zsh and -Bash. - -It is missing most of the options and a few arguments. -In future, this plugin may be shortened to simply being +To use it, add `ng` to the plugins array of your zshrc file: ```zsh -eval `ng completion` +plugins=(... ng) ``` - -There is hope this materialises in the 21st century. - -### CONTRIBUTOR - - Carlo Dapor ([catull](https://github.com/catull)) diff --git a/plugins/nmap/README.md b/plugins/nmap/README.md index 5cd646277..0a60068c2 100644 --- a/plugins/nmap/README.md +++ b/plugins/nmap/README.md @@ -1,37 +1,27 @@ -# Nmap aliases plugin +# Nmap plugin -Adds some useful aliases for nmap similar to the profiles in zenmap. +Adds some useful aliases for [Nmap](https://nmap.org/) similar to the profiles in zenmap. -Nmap options are: - * -sS - TCP SYN scan - * -v - verbose - * -T1 - timing of scan. Options are paranoid (0), sneaky (1), polite (2), normal (3), aggressive (4), and insane (5) - * -sF - FIN scan (can sneak through non-stateful firewalls) - * -PE - ICMP echo discovery probe - * -PP - timestamp discovery probe - * -PY - SCTP init ping - * -g - use given number as source port - * -A - enable OS detection, version detection, script scanning, and traceroute (aggressive) - * -O - enable OS detection - * -sA - TCP ACK scan - * -F - fast scan - * --script=vulscan - also access vulnerabilities in target +To use it, add `nmap` to the plugins array in your zshrc file: -## Aliases explained +```zsh +plugins=(... nmap) +``` - * nmap_open_ports - Scan for open ports on target - * nmap_list_interfaces - List all network interfaces on host where the command runs - * nmap_slow - Slow scan that avoids to spam the targets logs - * nmap_fin - Scan to see if hosts are up with TCP FIN scan - * nmap_full - Aggressive full scan that scans all ports, tries to determine OS and service versions - * nmap_check_for_firewall - TCP ACK scan to check for firewall existence - * nmap_ping_through_firewall - Host discovery with SYN and ACK probes instead of just pings to avoid firewall - restrictions - * nmap_fast - Fast scan of the top 300 popular ports - * nmap_detect_versions - Detects versions of services and OS, runs on all ports - * nmap_check_for_vulns - Uses vulscan script to check target services for vulnerabilities - * nmap_full_udp - Same as full but via UDP - * nmap_traceroute - Try to traceroute using the most common ports - * nmap_full_with_scripts - Same as nmap_full but also runs all the scripts - * nmap_web_safe_osscan - Little "safer" scan for OS version as connecting to only HTTP and HTTPS ports doesn't look so attacking. +## Aliases +- `nmap_open_ports`: scan for open ports on target. +- `nmap_list_interfaces`: list all network interfaces on host where the command runs. +- `nmap_slow`: slow scan that avoids to spam the targets logs. +- `nmap_fin`: scan to see if hosts are up with TCP FIN scan. +- `nmap_full`: aggressive full scan that scans all ports, tries to determine OS and service versions. +- `nmap_check_for_firewall`: TCP ACK scan to check for firewall existence. +- `nmap_ping_through_firewall`: host discovery with SYN and ACK probes instead of just pings to avoid firewall restrictions. +- `nmap_fast`: fast scan of the top 300 popular ports. +- `nmap_detect_versions`: detects versions of services and OS, runs on all ports. +- `nmap_check_for_vulns`: uses vulscan script to check target services for vulnerabilities. +- `nmap_full_udp`: same as full but via UDP. +- `nmap_traceroute`: try to traceroute using the most common ports. +- `nmap_full_with_scripts`: same as nmap_full but also runs all the scripts. +- `nmap_web_safe_osscan`: little "safer" scan for OS version as connecting to only HTTP and HTTPS ports doesn't look so attacking. +- `nmap_ping_scan`: ICMP scan for active hosts. diff --git a/plugins/nmap/nmap.plugin.zsh b/plugins/nmap/nmap.plugin.zsh index 8c691bdaa..406870f00 100644 --- a/plugins/nmap/nmap.plugin.zsh +++ b/plugins/nmap/nmap.plugin.zsh @@ -29,4 +29,4 @@ alias nmap_full_udp="sudo nmap -sS -sU -T4 -A -v -PE -PS22,25,80 -PA21,23,80,443 alias nmap_traceroute="sudo nmap -sP -PE -PS22,25,80 -PA21,23,80,3389 -PU -PO --traceroute " alias nmap_full_with_scripts="sudo nmap -sS -sU -T4 -A -v -PE -PP -PS21,22,23,25,80,113,31339 -PA80,113,443,10042 -PO --script all " alias nmap_web_safe_osscan="sudo nmap -p 80,443 -O -v --osscan-guess --fuzzy " - +alias nmap_ping_scan="nmap -n -sP" diff --git a/plugins/npm/npm.plugin.zsh b/plugins/npm/npm.plugin.zsh index f62174a4f..87c68f3fb 100644 --- a/plugins/npm/npm.plugin.zsh +++ b/plugins/npm/npm.plugin.zsh @@ -1,14 +1,16 @@ (( $+commands[npm] )) && { - __NPM_COMPLETION_FILE="${ZSH_CACHE_DIR:-$ZSH/cache}/npm_completion" + rm -f "${ZSH_CACHE_DIR:-$ZSH/cache}/npm_completion" - if [[ ! -f $__NPM_COMPLETION_FILE ]]; then - npm completion >! $__NPM_COMPLETION_FILE 2>/dev/null - [[ $? -ne 0 ]] && rm -f $__NPM_COMPLETION_FILE - fi - - [[ -f $__NPM_COMPLETION_FILE ]] && source $__NPM_COMPLETION_FILE - - unset __NPM_COMPLETION_FILE + _npm_completion() { + local si=$IFS + compadd -- $(COMP_CWORD=$((CURRENT-1)) \ + COMP_LINE=$BUFFER \ + COMP_POINT=0 \ + npm completion -- "${words[@]}" \ + 2>/dev/null) + IFS=$si + } + compdef _npm_completion npm } # Install dependencies globally diff --git a/plugins/oc/README.md b/plugins/oc/README.md new file mode 100644 index 000000000..deae9b2d0 --- /dev/null +++ b/plugins/oc/README.md @@ -0,0 +1,13 @@ +# OC - OpenShift CLI + +This plugin provides autocompletion for [OC](https://docs.openshift.com/container-platform/3.7/cli_reference/index.html) commands, building, managing and updating operations. + +To use it, add `oc` to the plugins array of your zshrc file: + +```bash +plugins=(... oc) +``` + +## Contributors + ++ [kevinkirkup](https://github.com/kevinkirkup) - Plugin Author diff --git a/plugins/osx/README.md b/plugins/osx/README.md index 4595ee319..f3881ec6b 100644 --- a/plugins/osx/README.md +++ b/plugins/osx/README.md @@ -42,20 +42,21 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Commands -| Command | Description | -| :-------------- | :-------------------------------------------------- | -| `tab` | Open the current directory in a new tab | -| `split_tab` | Split the current terminal tab horizontally | -| `vsplit_tab` | Split the current terminal tab vertically | -| `ofd` | Open the current directory in a Finder window | -| `pfd` | Return the path of the frontmost Finder window | -| `pfs` | Return the current Finder selection | -| `cdf` | `cd` to the current Finder directory | -| `pushdf` | `pushd` to the current Finder directory | -| `quick-look` | Quick-Look a specified file | -| `man-preview` | Open a specified man page in Preview app | -| `showfiles` | Show hidden files | -| `hidefiles` | Hide the hidden files | -| `itunes` | Control iTunes. Use `itunes -h` for usage details | -| `spotify` | Control Spotify and search by artist, album, trackโ€ฆ | -| `rmdsstore` | Remove .DS\_Store files recursively in a directory | +| Command | Description | +| :-------------- | :---------------------------------------------------- | +| `tab` | Open the current directory in a new tab | +| `split_tab` | Split the current terminal tab horizontally | +| `vsplit_tab` | Split the current terminal tab vertically | +| `ofd` | Open the current directory in a Finder window | +| `pfd` | Return the path of the frontmost Finder window | +| `pfs` | Return the current Finder selection | +| `cdf` | `cd` to the current Finder directory | +| `pushdf` | `pushd` to the current Finder directory | +| `quick-look` | Quick-Look a specified file | +| `man-preview` | Open a specified man page in Preview app | +| `showfiles` | Show hidden files | +| `hidefiles` | Hide the hidden files | +| `itunes` | DEPRECATED. Use `music` from macOS Catalina on | +| `music` | Control Apple Music. Use `music -h` for usage details | +| `spotify` | Control Spotify and search by artist, album, trackโ€ฆ | +| `rmdsstore` | Remove .DS\_Store files recursively in a directory | diff --git a/plugins/osx/osx.plugin.zsh b/plugins/osx/osx.plugin.zsh index eb3c4fb7a..03e9c1c8c 100644 --- a/plugins/osx/osx.plugin.zsh +++ b/plugins/osx/osx.plugin.zsh @@ -219,7 +219,19 @@ function vncviewer() { } # iTunes control function -function itunes() { +function itunes music() { + local APP_NAME=Music + + autoload is-at-least + if is-at-least 10.15 $(sw_vers -productVersion); then + if [[ $0 = itunes ]]; then + echo >&2 The itunes function name is deprecated. Use \`music\' instead. + return 1 + fi + else + APP_NAME=iTunes + fi + local opt=$1 local playlist=$2 shift @@ -236,7 +248,7 @@ function itunes() { opt="$opt track" ;; vol) - local new_volume volume=$(osascript -e 'tell application "iTunes" to get sound volume') + local new_volume volume=$(osascript -e "tell application \"$APP_NAME\" to get sound volume") if [[ $# -eq 0 ]]; then echo "Current volume is ${volume}." return 0 @@ -251,26 +263,26 @@ function itunes() { opt="set sound volume to ${new_volume}" ;; playlist) - # Inspired by: https://gist.github.com/nakajijapan/ac8b45371064ae98ea7f -if [[ ! -z "$playlist" ]]; then - osascript -e 'tell application "iTunes"' -e "set new_playlist to \"$playlist\" as string" -e "play playlist new_playlist" -e "end tell" 2>/dev/null; + # Inspired by: https://gist.github.com/nakajijapan/ac8b45371064ae98ea7f + if [[ ! -z "$playlist" ]]; then + osascript -e "tell application \"$APP_NAME\"" -e "set new_playlist to \"$playlist\" as string" -e "play playlist new_playlist" -e "end tell" 2>/dev/null; if [[ $? -eq 0 ]]; then opt="play" else opt="stop" fi - else - opt="set allPlaylists to (get name of every playlist)" - fi - ;; + else + opt="set allPlaylists to (get name of every playlist)" + fi + ;; playing|status) - local state=`osascript -e 'tell application "iTunes" to player state as string'` + local state=`osascript -e "tell application \"$APP_NAME\" to player state as string"` if [[ "$state" = "playing" ]]; then - currenttrack=`osascript -e 'tell application "iTunes" to name of current track as string'` - currentartist=`osascript -e 'tell application "iTunes" to artist of current track as string'` + currenttrack=`osascript -e "tell application \"$APP_NAME\" to name of current track as string"` + currentartist=`osascript -e "tell application \"$APP_NAME\" to artist of current track as string"` echo -E "Listening to $fg[yellow]$currenttrack$reset_color by $fg[yellow]$currentartist$reset_color"; else - echo "iTunes is" $state; + echo "$APP_NAME is" $state; fi return 0 ;; @@ -284,7 +296,7 @@ if [[ ! -z "$playlist" ]]; then if [[ -n "$state" && ! "$state" =~ "^(on|off|toggle)$" ]] then - print "Usage: itunes shuffle [on|off|toggle]. Invalid option." + print "Usage: $0 shuffle [on|off|toggle]. Invalid option." return 1 fi @@ -305,14 +317,14 @@ EOF esac ;; ""|-h|--help) - echo "Usage: itunes