Commit 5a32f0a5 by huchi

init

parents
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
[*.sh]
indent_size = 4
indent_style = tab
# custom files
custom/
# temp files directories
cache/
log/
*.swp
.DS_Store
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at ohmyzsh@planetargon.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
# CONTRIBUTING GUIDELINES
Oh-My-Zsh is a community-driven project. Contribution is welcome, encouraged, and appreciated.
It is also essential for the development of the project.
First, please take a moment to review our [code of conduct](CODE_OF_CONDUCT.md).
These guidelines are an attempt at better addressing the huge amount of pending
issues and pull requests. Please read them closely.
Foremost, be so kind as to [search](#use-the-search-luke). This ensures any contribution
you would make is not already covered.
* [Issues](#reporting-issues)
* [You have a problem](#you-have-a-problem)
* [You have a suggestion](#you-have-a-suggestion)
* [Pull Requests](#submitting-pull-requests)
* [Getting started](#getting-started)
* [You have a solution](#you-have-a-solution)
* [You have an addition](#you-have-an-addition)
* [Information sources (_aka_ search)](#use-the-search-luke)
**BONUS:** [Volunteering](#you-have-spare-time-to-volunteer)
## Reporting Issues
### You have a problem
Please be so kind as to [search](#use-the-search-luke) for any open issue already covering
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/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.
It should include the data gathered as indicated above, along with:
1. How to reproduce the problem
2. What the correct behavior should be
3. What the actual behavior is
Please copy to anyone relevant (_eg_ plugin maintainers) by mentioning their GitHub handle
(starting with `@`) in your message.
We will do our very best to help you.
### You have a suggestion
Please be so kind as to [search](#use-the-search-luke) for any open issue already covering
your suggestion.
If you find one, comment on it so we can know there are more people supporting it.
If not, you can go ahead and create an issue. Please copy to anyone relevant (_eg_ plugin
maintainers) by mentioning their GitHub handle (starting with `@`) in your message.
## Submitting Pull Requests
### Getting started
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/ohmyzsh/ohmyzsh/wiki/Contribution-Technical-Practices).
You MUST always create PRs with _a dedicated branch_ based on the latest upstream tree.
If you create your own PR, please make sure you do it right. Also be so kind as to reference
any issue that would be solved in the PR description body,
[for instance](https://help.github.com/articles/closing-issues-via-commit-messages/)
_"Fixes #XXXX"_ for issue number XXXX.
### You have a solution
Please be so kind as to [search](#use-the-search-luke) for any open issue already covering
your [problem](#you-have-a-problem), and any pending/merged/rejected PR covering your solution.
If the solution is already reported, try it out and +1 the pull request if the
solution works ok. On the other hand, if you think your solution is better, post
it with a reference to the other one so we can have both solutions to compare.
If not, then go ahead and submit a PR. Please copy to anyone relevant (e.g. plugin
maintainers) by mentioning their GitHub handle (starting with `@`) in your message.
### You have an addition
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
covering or related to what you want to add.
If you find one, try it out and work with the author on a common solution.
If not, then go ahead and submit a PR. Please copy to anyone relevant (_eg_ plugin
maintainers) by mentioning their GitHub handle (starting with `@`) in your message.
For any extensive change, _eg_ a new plugin, you will have to find testers to +1 your PR.
----
## Use the Search, Luke
_May the Force (of past experiences) be with you_
GitHub offers [many search features](https://help.github.com/articles/searching-github/)
to help you check whether a similar contribution to yours already exists. Please search
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/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
and [create an issue](#reporting-issues) or [submit a PR](#submitting-pull-requests).
----
### You have spare time to volunteer
Very nice!! :)
Please have a look at the [Volunteer](https://github.com/ohmyzsh/ohmyzsh/wiki/Volunteers)
page for instructions on where to start and more.
MIT License
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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Bazaar integration
## Just works with the GIT integration just add $(bzr_prompt_info) to the PROMPT
function bzr_prompt_info() {
BZR_CB=`bzr nick 2> /dev/null | grep -v "ERROR" | cut -d ":" -f2 | awk -F / '{print "bzr::"$1}'`
if [ -n "$BZR_CB" ]; then
BZR_DIRTY=""
[[ -n `bzr status` ]] && BZR_DIRTY=" %{$fg[red]%} * %{$fg[green]%}"
echo "$ZSH_THEME_SCM_PROMPT_PREFIX$BZR_CB$BZR_DIRTY$ZSH_THEME_GIT_PROMPT_SUFFIX"
fi
}
\ No newline at end of file
# System clipboard integration
#
# This file has support for doing system clipboard copy and paste operations
# from the command line in a generic cross-platform fashion.
#
# This is uses essentially the same heuristic as neovim, with the additional
# special support for Cygwin.
# See: https://github.com/neovim/neovim/blob/e682d799fa3cf2e80a02d00c6ea874599d58f0e7/runtime/autoload/provider/clipboard.vim#L55-L121
#
# - pbcopy, pbpaste (macOS)
# - cygwin (Windows running Cygwin)
# - wl-copy, wl-paste (if $WAYLAND_DISPLAY is set)
# - xclip (if $DISPLAY is set)
# - xsel (if $DISPLAY is set)
# - lemonade (for SSH) https://github.com/pocke/lemonade
# - doitclient (for SSH) http://www.chiark.greenend.org.uk/~sgtatham/doit/
# - win32yank (Windows)
# - tmux (if $TMUX is set)
#
# Defines two functions, clipcopy and clippaste, based on the detected platform.
##
#
# clipcopy - Copy data to clipboard
#
# Usage:
#
# <command> | clipcopy - copies stdin to clipboard
#
# clipcopy <file> - copies a file's contents to clipboard
#
##
#
# clippaste - "Paste" data from clipboard to stdout
#
# Usage:
#
# clippaste - writes clipboard's contents to stdout
#
# clippaste | <command> - pastes contents and pipes it to another process
#
# clippaste > <file> - paste contents to a file
#
# Examples:
#
# # Pipe to another process
# clippaste | grep foo
#
# # Paste to a file
# clippaste > file.txt
#
function detect-clipboard() {
emulate -L zsh
if [[ "${OSTYPE}" == darwin* ]] && (( ${+commands[pbcopy]} )) && (( ${+commands[pbpaste]} )); then
function clipcopy() { pbcopy < "${1:-/dev/stdin}"; }
function clippaste() { pbpaste; }
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
function clipcopy() { wl-copy < "${1:-/dev/stdin}"; }
function clippaste() { wl-paste; }
elif [ -n "${DISPLAY:-}" ] && (( ${+commands[xclip]} )); then
function clipcopy() { xclip -in -selection clipboard < "${1:-/dev/stdin}"; }
function clippaste() { xclip -out -selection clipboard; }
elif [ -n "${DISPLAY:-}" ] && (( ${+commands[xsel]} )); then
function clipcopy() { xsel --clipboard --input < "${1:-/dev/stdin}"; }
function clippaste() { xsel --clipboard --output; }
elif (( ${+commands[lemonade]} )); then
function clipcopy() { lemonade copy < "${1:-/dev/stdin}"; }
function clippaste() { lemonade paste; }
elif (( ${+commands[doitclient]} )); then
function clipcopy() { doitclient wclip < "${1:-/dev/stdin}"; }
function clippaste() { doitclient wclip -r; }
elif (( ${+commands[win32yank]} )); then
function clipcopy() { win32yank -i < "${1:-/dev/stdin}"; }
function clippaste() { win32yank -o; }
elif [[ $OSTYPE == linux-android* ]] && (( $+commands[termux-clipboard-set] )); then
function clipcopy() { termux-clipboard-set "${1:-/dev/stdin}"; }
function clippaste() { termux-clipboard-get; }
elif [ -n "${TMUX:-}" ] && (( ${+commands[tmux]} )); then
function clipcopy() { tmux load-buffer "${1:--}"; }
function clippaste() { tmux save-buffer -; }
elif [[ $(uname -r) = *icrosoft* ]]; then
function clipcopy() { clip.exe < "${1:-/dev/stdin}"; }
function clippaste() { powershell.exe -noprofile -command Get-Clipboard; }
else
function _retry_clipboard_detection_or_fail() {
local clipcmd="${1}"; shift
if detect-clipboard; then
"${clipcmd}" "$@"
else
print "${clipcmd}: Platform $OSTYPE not supported or xclip/xsel not installed" >&2
return 1
fi
}
function clipcopy() { _retry_clipboard_detection_or_fail clipcopy "$@"; }
function clippaste() { _retry_clipboard_detection_or_fail clippaste "$@"; }
return 1
fi
}
# Detect at startup. A non-zero exit here indicates that the dummy clipboards were set,
# which is not really an error. If the user calls them, they will attempt to redetect
# (for example, perhaps the user has now installed xclip) and then either print an error
# or proceed successfully.
detect-clipboard || true
# Handle completions insecurities (i.e., completion-dependent directories with
# insecure ownership or permissions) by:
#
# * Human-readably notifying the user of these insecurities.
function handle_completion_insecurities() {
# List of the absolute paths of all unique insecure directories, split on
# newline from compaudit()'s output resembling:
#
# There are insecure directories:
# /usr/share/zsh/site-functions
# /usr/share/zsh/5.0.6/functions
# /usr/share/zsh
# /usr/share/zsh/5.0.6
#
# Since the ignorable first line is printed to stderr and thus not captured,
# stderr is squelched to prevent this output from leaking to the user.
local -aU insecure_dirs
insecure_dirs=( ${(f@):-"$(compaudit 2>/dev/null)"} )
# If no such directories exist, get us out of here.
[[ -z "${insecure_dirs}" ]] && return
# List ownership and permissions of all insecure directories.
print "[oh-my-zsh] Insecure completion-dependent directories detected:"
ls -ld "${(@)insecure_dirs}"
cat <<EOD
[oh-my-zsh] For safety, we will not load completions from these directories until
[oh-my-zsh] you fix their permissions and ownership and restart zsh.
[oh-my-zsh] See the above list for directories with group or other writability.
[oh-my-zsh] To fix your permissions you can do so by disabling
[oh-my-zsh] the write permission of "group" and "others" and making sure that the
[oh-my-zsh] owner of these directories is either root or your current user.
[oh-my-zsh] The following command may help:
[oh-my-zsh] compaudit | xargs chmod g-w,o-w
[oh-my-zsh] If the above didn't help or you want to skip the verification of
[oh-my-zsh] insecure directories you can set the variable ZSH_DISABLE_COMPFIX to
[oh-my-zsh] "true" before oh-my-zsh is sourced in your zshrc file.
EOD
}
# fixme - the load process here seems a bit bizarre
zmodload -i zsh/complist
WORDCHARS=''
unsetopt menu_complete # do not autoselect the first completion entry
unsetopt flowcontrol
setopt auto_menu # show completion menu on successive tab press
setopt complete_in_word
setopt always_to_end
# should this be in keybindings?
bindkey -M menuselect '^o' accept-and-infer-next-history
zstyle ':completion:*:*:*:*:*' menu select
# case insensitive (all), partial-word and substring completion
if [[ "$CASE_SENSITIVE" = true ]]; then
zstyle ':completion:*' matcher-list 'r:|=*' 'l:|=* r:|=*'
else
if [[ "$HYPHEN_INSENSITIVE" = true ]]; then
zstyle ':completion:*' matcher-list 'm:{a-zA-Z-_}={A-Za-z_-}' 'r:|=*' 'l:|=* r:|=*'
else
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'
fi
fi
unset CASE_SENSITIVE HYPHEN_INSENSITIVE
# Complete . and .. special directories
zstyle ':completion:*' special-dirs true
zstyle ':completion:*' list-colors ''
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'
if [[ "$OSTYPE" = solaris* ]]; then
zstyle ':completion:*:*:*:*:processes' command "ps -u $USER -o pid,user,comm"
else
zstyle ':completion:*:*:*:*:processes' command "ps -u $USER -o pid,user,comm -w -w"
fi
# disable named-directories autocompletion
zstyle ':completion:*:cd:*' tag-order local-directories directory-stack path-directories
# Use caching so that commands like apt and dpkg complete are useable
zstyle ':completion::complete:*' use-cache 1
zstyle ':completion::complete:*' cache-path $ZSH_CACHE_DIR
# Don't complete uninteresting users
zstyle ':completion:*:*:*:users' ignored-patterns \
adm amanda apache at avahi avahi-autoipd beaglidx bin cacti canna \
clamav daemon dbus distcache dnsmasq dovecot fax ftp games gdm \
gkrellmd gopher hacluster haldaemon halt hsqldb ident junkbust kdm \
ldap lp mail mailman mailnull man messagebus mldonkey mysql nagios \
named netdump news nfsnobody nobody nscd ntp nut nx obsrun openvpn \
operator pcap polkitd postfix postgres privoxy pulse pvm quagga radvd \
rpc rpcuser rpm rtkit scard shutdown squid sshd statd svn sync tftp \
usbmux uucp vcsa wwwrun xfs '_*'
# ... unless we really want to.
zstyle '*' single-ignored show
if [[ $COMPLETION_WAITING_DOTS = true ]]; then
expand-or-complete-with-dots() {
# toggle line-wrapping off and back on again
[[ -n "$terminfo[rmam]" && -n "$terminfo[smam]" ]] && echoti rmam
print -Pn "%{%F{red}......%f%}"
[[ -n "$terminfo[rmam]" && -n "$terminfo[smam]" ]] && echoti smam
zle expand-or-complete
zle redisplay
}
zle -N expand-or-complete-with-dots
bindkey "^I" expand-or-complete-with-dots
fi
# automatically load bash completion functions
autoload -Uz bashcompinit && bashcompinit
if [[ "$ENABLE_CORRECTION" == "true" ]]; then
alias cp='nocorrect cp'
alias ebuild='nocorrect ebuild'
alias gist='nocorrect gist'
alias heroku='nocorrect heroku'
alias hpodder='nocorrect hpodder'
alias man='nocorrect man'
alias mkdir='nocorrect mkdir'
alias mv='nocorrect mv'
alias mysql='nocorrect mysql'
alias sudo='nocorrect sudo'
setopt correct_all
fi
# Changing/making/removing directory
setopt auto_pushd
setopt pushd_ignore_dups
setopt pushdminus
alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'
alias -g ......='../../../../..'
alias -- -='cd -'
alias 1='cd -'
alias 2='cd -2'
alias 3='cd -3'
alias 4='cd -4'
alias 5='cd -5'
alias 6='cd -6'
alias 7='cd -7'
alias 8='cd -8'
alias 9='cd -9'
alias md='mkdir -p'
alias rd=rmdir
function d () {
if [[ -n $1 ]]; then
dirs "$@"
else
dirs -v | head -10
fi
}
compdef _dirs d
# List directory contents
alias lsa='ls -lah'
alias l='ls -lah'
alias ll='ls -lh'
alias la='ls -lAh'
function zsh_stats() {
fc -l 1 | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n20
}
function uninstall_oh_my_zsh() {
env ZSH="$ZSH" sh "$ZSH/tools/uninstall.sh"
}
function upgrade_oh_my_zsh() {
env ZSH="$ZSH" sh "$ZSH/tools/upgrade.sh"
command rm -rf "$ZSH/log/update.lock"
}
function take() {
mkdir -p $@ && cd ${@:$#}
}
function open_command() {
local open_cmd
# define the open command
case "$OSTYPE" in
darwin*) open_cmd='open' ;;
cygwin*) open_cmd='cygstart' ;;
linux*) [[ "$(uname -r)" != *icrosoft* ]] && open_cmd='nohup xdg-open' || {
open_cmd='cmd.exe /c start ""'
[[ -e "$1" ]] && { 1="$(wslpath -w "${1:a}")" || return 1 }
} ;;
msys*) open_cmd='start ""' ;;
*) echo "Platform $OSTYPE not supported"
return 1
;;
esac
${=open_cmd} "$@" &>/dev/null
}
#
# Get the value of an alias.
#
# Arguments:
# 1. alias - The alias to get its value from
# STDOUT:
# The value of alias $1 (if it has one).
# Return value:
# 0 if the alias was found,
# 1 if it does not exist
#
function alias_value() {
(( $+aliases[$1] )) && echo $aliases[$1]
}
#
# Try to get the value of an alias,
# otherwise return the input.
#
# Arguments:
# 1. alias - The alias to get its value from
# STDOUT:
# The value of alias $1, or $1 if there is no alias $1.
# Return value:
# Always 0
#
function try_alias_value() {
alias_value "$1" || echo "$1"
}
#
# Set variable "$1" to default value "$2" if "$1" is not yet defined.
#
# Arguments:
# 1. name - The variable to set
# 2. val - The default value
# Return value:
# 0 if the variable exists, 3 if it was set
#
function default() {
(( $+parameters[$1] )) && return 0
typeset -g "$1"="$2" && return 3
}
#
# Set environment variable "$1" to default value "$2" if "$1" is not yet defined.
#
# Arguments:
# 1. name - The env variable to set
# 2. val - The default value
# Return value:
# 0 if the env variable exists, 3 if it was set
#
function env_default() {
(( ${${(@f):-$(typeset +xg)}[(I)$1]} )) && return 0
export "$1=$2" && return 3
}
# Required for $langinfo
zmodload zsh/langinfo
# URL-encode a string
#
# Encodes a string using RFC 2396 URL-encoding (%-escaped).
# See: https://www.ietf.org/rfc/rfc2396.txt
#
# By default, reserved characters and unreserved "mark" characters are
# not escaped by this function. This allows the common usage of passing
# an entire URL in, and encoding just special characters in it, with
# the expectation that reserved and mark characters are used appropriately.
# The -r and -m options turn on escaping of the reserved and mark characters,
# respectively, which allows arbitrary strings to be fully escaped for
# embedding inside URLs, where reserved characters might be misinterpreted.
#
# Prints the encoded string on stdout.
# Returns nonzero if encoding failed.
#
# Usage:
# omz_urlencode [-r] [-m] [-P] <string>
#
# -r causes reserved characters (;/?:@&=+$,) to be escaped
#
# -m causes "mark" characters (_.!~*''()-) to be escaped
#
# -P causes spaces to be encoded as '%20' instead of '+'
function omz_urlencode() {
emulate -L zsh
zparseopts -D -E -a opts r m P
local in_str=$1
local url_str=""
local spaces_as_plus
if [[ -z $opts[(r)-P] ]]; then spaces_as_plus=1; fi
local str="$in_str"
# URLs must use UTF-8 encoding; convert str to UTF-8 if required
local encoding=$langinfo[CODESET]
local safe_encodings
safe_encodings=(UTF-8 utf8 US-ASCII)
if [[ -z ${safe_encodings[(r)$encoding]} ]]; then
str=$(echo -E "$str" | iconv -f $encoding -t UTF-8)
if [[ $? != 0 ]]; then
echo "Error converting string from $encoding to UTF-8" >&2
return 1
fi
fi
# Use LC_CTYPE=C to process text byte-by-byte
local i byte ord LC_ALL=C
export LC_ALL
local reserved=';/?:@&=+$,'
local mark='_.!~*''()-'
local dont_escape="[A-Za-z0-9"
if [[ -z $opts[(r)-r] ]]; then
dont_escape+=$reserved
fi
# $mark must be last because of the "-"
if [[ -z $opts[(r)-m] ]]; then
dont_escape+=$mark
fi
dont_escape+="]"
# Implemented to use a single printf call and avoid subshells in the loop,
# for performance (primarily on Windows).
local url_str=""
for (( i = 1; i <= ${#str}; ++i )); do
byte="$str[i]"
if [[ "$byte" =~ "$dont_escape" ]]; then
url_str+="$byte"
else
if [[ "$byte" == " " && -n $spaces_as_plus ]]; then
url_str+="+"
else
ord=$(( [##16] #byte ))
url_str+="%$ord"
fi
fi
done
echo -E "$url_str"
}
# URL-decode a string
#
# Decodes a RFC 2396 URL-encoded (%-escaped) string.
# This decodes the '+' and '%' escapes in the input string, and leaves
# other characters unchanged. Does not enforce that the input is a
# valid URL-encoded string. This is a convenience to allow callers to
# pass in a full URL or similar strings and decode them for human
# presentation.
#
# Outputs the encoded string on stdout.
# Returns nonzero if encoding failed.
#
# Usage:
# omz_urldecode <urlstring> - prints decoded string followed by a newline
function omz_urldecode {
emulate -L zsh
local encoded_url=$1
# Work bytewise, since URLs escape UTF-8 octets
local caller_encoding=$langinfo[CODESET]
local LC_ALL=C
export LC_ALL
# Change + back to ' '
local tmp=${encoded_url:gs/+/ /}
# Protect other escapes to pass through the printf unchanged
tmp=${tmp:gs/\\/\\\\/}
# Handle %-escapes by turning them into `\xXX` printf escapes
tmp=${tmp:gs/%/\\x/}
local decoded
eval "decoded=\$'$tmp'"
# Now we have a UTF-8 encoded string in the variable. We need to re-encode
# it if caller is in a non-UTF-8 locale.
local safe_encodings
safe_encodings=(UTF-8 utf8 US-ASCII)
if [[ -z ${safe_encodings[(r)$caller_encoding]} ]]; then
decoded=$(echo -E "$decoded" | iconv -f UTF-8 -t $caller_encoding)
if [[ $? != 0 ]]; then
echo "Error converting string from UTF-8 to $caller_encoding" >&2
return 1
fi
fi
echo -E "$decoded"
}
# Outputs current branch info in prompt format
function git_prompt_info() {
local ref
if [[ "$(command git config --get oh-my-zsh.hide-status 2>/dev/null)" != "1" ]]; then
ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
ref=$(command git rev-parse --short HEAD 2> /dev/null) || return 0
echo "$ZSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$(parse_git_dirty)$ZSH_THEME_GIT_PROMPT_SUFFIX"
fi
}
# Checks if working tree is dirty
function parse_git_dirty() {
local STATUS
local -a FLAGS
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
echo "$ZSH_THEME_GIT_PROMPT_DIRTY"
else
echo "$ZSH_THEME_GIT_PROMPT_CLEAN"
fi
}
# Gets the difference between the local and remote branches
function git_remote_status() {
local remote ahead behind git_remote_status git_remote_status_detailed
remote=${$(command git rev-parse --verify ${hook_com[branch]}@{upstream} --symbolic-full-name 2>/dev/null)/refs\/remotes\/}
if [[ -n ${remote} ]]; then
ahead=$(command git rev-list ${hook_com[branch]}@{upstream}..HEAD 2>/dev/null | wc -l)
behind=$(command git rev-list HEAD..${hook_com[branch]}@{upstream} 2>/dev/null | wc -l)
if [[ $ahead -eq 0 ]] && [[ $behind -eq 0 ]]; then
git_remote_status="$ZSH_THEME_GIT_PROMPT_EQUAL_REMOTE"
elif [[ $ahead -gt 0 ]] && [[ $behind -eq 0 ]]; then
git_remote_status="$ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE"
git_remote_status_detailed="$ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE_COLOR$ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE$((ahead))%{$reset_color%}"
elif [[ $behind -gt 0 ]] && [[ $ahead -eq 0 ]]; then
git_remote_status="$ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE"
git_remote_status_detailed="$ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE_COLOR$ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE$((behind))%{$reset_color%}"
elif [[ $ahead -gt 0 ]] && [[ $behind -gt 0 ]]; then
git_remote_status="$ZSH_THEME_GIT_PROMPT_DIVERGED_REMOTE"
git_remote_status_detailed="$ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE_COLOR$ZSH_THEME_GIT_PROMPT_AHEAD_REMOTE$((ahead))%{$reset_color%}$ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE_COLOR$ZSH_THEME_GIT_PROMPT_BEHIND_REMOTE$((behind))%{$reset_color%}"
fi
if [[ -n $ZSH_THEME_GIT_PROMPT_REMOTE_STATUS_DETAILED ]]; then
git_remote_status="$ZSH_THEME_GIT_PROMPT_REMOTE_STATUS_PREFIX$remote$git_remote_status_detailed$ZSH_THEME_GIT_PROMPT_REMOTE_STATUS_SUFFIX"
fi
echo $git_remote_status
fi
}
# Outputs the name of the current branch
# Usage example: git pull origin $(git_current_branch)
# Using '--quiet' with 'symbolic-ref' will not cause a fatal error (128) if
# it's not a symbolic ref, but in a Git repo.
function git_current_branch() {
local ref
ref=$(command git symbolic-ref --quiet HEAD 2> /dev/null)
local ret=$?
if [[ $ret != 0 ]]; then
[[ $ret == 128 ]] && return # no git repo.
ref=$(command git rev-parse --short HEAD 2> /dev/null) || return
fi
echo ${ref#refs/heads/}
}
# Gets the number of commits ahead from remote
function git_commits_ahead() {
if command git rev-parse --git-dir &>/dev/null; then
local commits="$(git rev-list --count @{upstream}..HEAD 2>/dev/null)"
if [[ -n "$commits" && "$commits" != 0 ]]; then
echo "$ZSH_THEME_GIT_COMMITS_AHEAD_PREFIX$commits$ZSH_THEME_GIT_COMMITS_AHEAD_SUFFIX"
fi
fi
}
# Gets the number of commits behind remote
function git_commits_behind() {
if command git rev-parse --git-dir &>/dev/null; then
local commits="$(git rev-list --count HEAD..@{upstream} 2>/dev/null)"
if [[ -n "$commits" && "$commits" != 0 ]]; then
echo "$ZSH_THEME_GIT_COMMITS_BEHIND_PREFIX$commits$ZSH_THEME_GIT_COMMITS_BEHIND_SUFFIX"
fi
fi
}
# Outputs if current branch is ahead of remote
function git_prompt_ahead() {
if [[ -n "$(command git rev-list origin/$(git_current_branch)..HEAD 2> /dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_AHEAD"
fi
}
# Outputs if current branch is behind remote
function git_prompt_behind() {
if [[ -n "$(command git rev-list HEAD..origin/$(git_current_branch) 2> /dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_BEHIND"
fi
}
# Outputs if current branch exists on remote or not
function git_prompt_remote() {
if [[ -n "$(command git show-ref origin/$(git_current_branch) 2> /dev/null)" ]]; then
echo "$ZSH_THEME_GIT_PROMPT_REMOTE_EXISTS"
else
echo "$ZSH_THEME_GIT_PROMPT_REMOTE_MISSING"
fi
}
# Formats prompt string for current git commit short SHA
function git_prompt_short_sha() {
local SHA
SHA=$(command git rev-parse --short HEAD 2> /dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# Formats prompt string for current git commit long SHA
function git_prompt_long_sha() {
local SHA
SHA=$(command git rev-parse HEAD 2> /dev/null) && echo "$ZSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$ZSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# Get the status of the working tree
function git_prompt_status() {
local INDEX STATUS
INDEX=$(command git status --porcelain -b 2> /dev/null)
STATUS=""
if $(echo "$INDEX" | command grep -E '^\?\? ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_UNTRACKED$STATUS"
fi
if $(echo "$INDEX" | grep '^A ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_ADDED$STATUS"
elif $(echo "$INDEX" | grep '^M ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_ADDED$STATUS"
elif $(echo "$INDEX" | grep '^MM ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_ADDED$STATUS"
fi
if $(echo "$INDEX" | grep '^ M ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
elif $(echo "$INDEX" | grep '^AM ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
elif $(echo "$INDEX" | grep '^MM ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
elif $(echo "$INDEX" | grep '^ T ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
fi
if $(echo "$INDEX" | grep '^R ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_RENAMED$STATUS"
fi
if $(echo "$INDEX" | grep '^ D ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
elif $(echo "$INDEX" | grep '^D ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
elif $(echo "$INDEX" | grep '^AD ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_DELETED$STATUS"
fi
if $(command git rev-parse --verify refs/stash >/dev/null 2>&1); then
STATUS="$ZSH_THEME_GIT_PROMPT_STASHED$STATUS"
fi
if $(echo "$INDEX" | grep '^UU ' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_UNMERGED$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*ahead' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_AHEAD$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*behind' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_BEHIND$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*diverged' &> /dev/null); then
STATUS="$ZSH_THEME_GIT_PROMPT_DIVERGED$STATUS"
fi
echo $STATUS
}
# Outputs the name of the current user
# Usage example: $(git_current_user_name)
function git_current_user_name() {
command git config user.name 2>/dev/null
}
# Outputs the email of the current user
# Usage example: $(git_current_user_email)
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
}
__GREP_CACHE_FILE="$ZSH_CACHE_DIR"/grep-alias
# See if there's a cache file modified in the last day
__GREP_ALIAS_CACHES=("$__GREP_CACHE_FILE"(Nm-1))
if [[ -n "$__GREP_ALIAS_CACHES" ]]; then
source "$__GREP_CACHE_FILE"
else
grep-flags-available() {
command grep "$@" "" &>/dev/null <<< ""
}
# Ignore these folders (if the necessary grep flags are available)
EXC_FOLDERS="{.bzr,CVS,.git,.hg,.svn,.idea,.tox}"
# Check for --exclude-dir, otherwise check for --exclude. If --exclude
# isn't available, --color won't be either (they were released at the same
# time (v2.5): https://git.savannah.gnu.org/cgit/grep.git/tree/NEWS?id=1236f007
if grep-flags-available --color=auto --exclude-dir=.cvs; then
GREP_OPTIONS="--color=auto --exclude-dir=$EXC_FOLDERS"
elif grep-flags-available --color=auto --exclude=.cvs; then
GREP_OPTIONS="--color=auto --exclude=$EXC_FOLDERS"
fi
if [[ -n "$GREP_OPTIONS" ]]; then
# export grep, egrep and fgrep settings
alias grep="grep $GREP_OPTIONS"
alias egrep="egrep $GREP_OPTIONS"
alias fgrep="fgrep $GREP_OPTIONS"
# write to cache file if cache directory is writable
if [[ -w "$ZSH_CACHE_DIR" ]]; then
alias -L grep egrep fgrep >| "$__GREP_CACHE_FILE"
fi
fi
# Clean up
unset GREP_OPTIONS EXC_FOLDERS
unfunction grep-flags-available
fi
unset __GREP_CACHE_FILE __GREP_ALIAS_CACHES
## History wrapper
function omz_history {
local clear list
zparseopts -E c=clear l=list
if [[ -n "$clear" ]]; then
# if -c provided, clobber the history file
echo -n >| "$HISTFILE"
echo >&2 History file deleted. Reload the session to see its effects.
elif [[ -n "$list" ]]; then
# if -l provided, run as if calling `fc' directly
builtin fc "$@"
else
# unless a number is provided, show all history events (starting from 1)
[[ ${@[-1]-} = *[0-9]* ]] && builtin fc -l "$@" || builtin fc -l "$@" 1
fi
}
# Timestamp format
case ${HIST_STAMPS-} in
"mm/dd/yyyy") alias history='omz_history -f' ;;
"dd.mm.yyyy") alias history='omz_history -E' ;;
"yyyy-mm-dd") alias history='omz_history -i' ;;
"") alias history='omz_history' ;;
*) alias history="omz_history -t '$HIST_STAMPS'" ;;
esac
## History file configuration
[ -z "$HISTFILE" ] && HISTFILE="$HOME/.zsh_history"
HISTSIZE=50000
SAVEHIST=10000
## History command configuration
setopt extended_history # record timestamp of command in HISTFILE
setopt hist_expire_dups_first # delete duplicates first when HISTFILE size exceeds HISTSIZE
setopt hist_ignore_dups # ignore duplicated commands history list
setopt hist_ignore_space # ignore commands that start with space
setopt hist_verify # show command with history expansion to user before running it
setopt inc_append_history # add commands to HISTFILE in order of execution
setopt share_history # share command history data
# http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html
# http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Builtins
# http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Standard-Widgets
# Make sure that the terminal is in application mode when zle is active, since
# only then values from $terminfo are valid
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
function zle-line-init() {
echoti smkx
}
function zle-line-finish() {
echoti rmkx
}
zle -N zle-line-init
zle -N zle-line-finish
fi
bindkey -e # Use emacs key bindings
bindkey '\ew' kill-region # [Esc-w] - Kill from the cursor to the mark
bindkey -s '\el' 'ls\n' # [Esc-l] - run command: ls
bindkey '^r' history-incremental-search-backward # [Ctrl-r] - Search backward incrementally for a specified string. The string may begin with ^ to anchor the search to the beginning of the line.
if [[ "${terminfo[kpp]}" != "" ]]; then
bindkey "${terminfo[kpp]}" up-line-or-history # [PageUp] - Up a line of history
fi
if [[ "${terminfo[knp]}" != "" ]]; then
bindkey "${terminfo[knp]}" down-line-or-history # [PageDown] - Down a line of history
fi
# start typing + [Up-Arrow] - fuzzy find history forward
if [[ "${terminfo[kcuu1]}" != "" ]]; then
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
bindkey "${terminfo[kcuu1]}" up-line-or-beginning-search
fi
# start typing + [Down-Arrow] - fuzzy find history backward
if [[ "${terminfo[kcud1]}" != "" ]]; then
autoload -U down-line-or-beginning-search
zle -N down-line-or-beginning-search
bindkey "${terminfo[kcud1]}" down-line-or-beginning-search
fi
if [[ "${terminfo[khome]}" != "" ]]; then
bindkey "${terminfo[khome]}" beginning-of-line # [Home] - Go to beginning of line
fi
if [[ "${terminfo[kend]}" != "" ]]; then
bindkey "${terminfo[kend]}" end-of-line # [End] - Go to end of line
fi
bindkey ' ' magic-space # [Space] - do history expansion
bindkey '^[[1;5C' forward-word # [Ctrl-RightArrow] - move forward one word
bindkey '^[[1;5D' backward-word # [Ctrl-LeftArrow] - move backward one word
if [[ "${terminfo[kcbt]}" != "" ]]; then
bindkey "${terminfo[kcbt]}" reverse-menu-complete # [Shift-Tab] - move through the completion menu backwards
fi
bindkey '^?' backward-delete-char # [Backspace] - delete backward
if [[ "${terminfo[kdch1]}" != "" ]]; then
bindkey "${terminfo[kdch1]}" delete-char # [Delete] - delete forward
else
bindkey "^[[3~" delete-char
bindkey "^[3;5~" delete-char
bindkey "\e[3~" delete-char
fi
# Edit the current command line in $EDITOR
autoload -U edit-command-line
zle -N edit-command-line
bindkey '\C-x\C-e' edit-command-line
# file rename magick
bindkey "^[m" copy-prev-shell-word
# consider emacs keybindings:
#bindkey -e ## emacs key bindings
#
#bindkey '^[[A' up-line-or-search
#bindkey '^[[B' down-line-or-search
#bindkey '^[^[[C' emacs-forward-word
#bindkey '^[^[[D' emacs-backward-word
#
#bindkey -s '^X^Z' '%-^M'
#bindkey '^[e' expand-cmd-path
#bindkey '^[^I' reverse-menu-complete
#bindkey '^X^N' accept-and-infer-next-history
#bindkey '^W' kill-region
#bindkey '^I' complete-word
## Fix weird sequence that rxvt produces
#bindkey -s '^[[Z' '\t'
#
autoload -Uz is-at-least
# *-magic is known buggy in some versions; disable if so
if [[ $DISABLE_MAGIC_FUNCTIONS != true ]]; then
for d in $fpath; do
if [[ -e "$d/url-quote-magic" ]]; then
if is-at-least 5.1; then
autoload -Uz bracketed-paste-magic
zle -N bracketed-paste bracketed-paste-magic
fi
autoload -Uz url-quote-magic
zle -N self-insert url-quote-magic
break
fi
done
fi
## jobs
setopt long_list_jobs
env_default 'PAGER' 'less'
env_default 'LESS' '-R'
## super user alias
alias _='sudo '
## more intelligent acking for ubuntu users
if which ack-grep &> /dev/null; then
alias afind='ack-grep -il'
else
alias afind='ack -il'
fi
# recognize comments
setopt interactivecomments
# get the node.js version
function nvm_prompt_info() {
[[ -f "$NVM_DIR/nvm.sh" ]] || return
local nvm_prompt
nvm_prompt=$(node -v 2>/dev/null)
[[ "${nvm_prompt}x" == "x" ]] && return
nvm_prompt=${nvm_prompt:1}
echo "${ZSH_THEME_NVM_PROMPT_PREFIX}${nvm_prompt}${ZSH_THEME_NVM_PROMPT_SUFFIX}"
}
# *_prompt_info functions for usage in your prompt
#
# Plugin creators, please add your *_prompt_info function to the list
# of dummy implementations to help theme creators not receiving errors
# without the need of implementing conditional clauses.
#
# See also lib/bzr.zsh, lib/git.zsh and lib/nvm.zsh for
# git_prompt_info, bzr_prompt_info and nvm_prompt_info
# Dummy implementations that return false to prevent command_not_found
# errors with themes, that implement these functions
# Real implementations will be used when the respective plugins are loaded
function chruby_prompt_info \
rbenv_prompt_info \
hg_prompt_info \
pyenv_prompt_info \
svn_prompt_info \
vi_mode_prompt_info \
virtualenv_prompt_info \
jenv_prompt_info \
{
return 1
}
# oh-my-zsh supports an rvm prompt by default
# get the name of the rvm ruby version
function rvm_prompt_info() {
[ -f $HOME/.rvm/bin/rvm-prompt ] || return 1
local rvm_prompt
rvm_prompt=$($HOME/.rvm/bin/rvm-prompt ${=ZSH_THEME_RVM_PROMPT_OPTIONS} 2>/dev/null)
[[ -z "${rvm_prompt}" ]] && return 1
echo "${ZSH_THEME_RUBY_PROMPT_PREFIX}${rvm_prompt}${ZSH_THEME_RUBY_PROMPT_SUFFIX}"
}
ZSH_THEME_RVM_PROMPT_OPTIONS="i v g"
# use this to enable users to see their ruby version, no matter which
# version management system they use
function ruby_prompt_info() {
echo $(rvm_prompt_info || rbenv_prompt_info || chruby_prompt_info)
}
#! /bin/zsh
# A script to make using 256 colors in zsh less painful.
# P.C. Shyamshankar <sykora@lucentbeing.com>
# Copied from https://github.com/sykora/etc/blob/master/zsh/functions/spectrum/
typeset -AHg FX FG BG
FX=(
reset "%{%}"
bold "%{%}" no-bold "%{%}"
italic "%{%}" no-italic "%{%}"
underline "%{%}" no-underline "%{%}"
blink "%{%}" no-blink "%{%}"
reverse "%{%}" no-reverse "%{%}"
)
for color in {000..255}; do
FG[$color]="%{[38;5;${color}m%}"
BG[$color]="%{[48;5;${color}m%}"
done
ZSH_SPECTRUM_TEXT=${ZSH_SPECTRUM_TEXT:-Arma virumque cano Troiae qui primus ab oris}
# Show all 256 colors with color number
function spectrum_ls() {
for code in {000..255}; do
print -P -- "$code: %{$FG[$code]%}$ZSH_SPECTRUM_TEXT%{$reset_color%}"
done
}
# Show all 256 colors where the background is set to specific color
function spectrum_bls() {
for code in {000..255}; do
print -P -- "$code: %{$BG[$code]%}$ZSH_SPECTRUM_TEXT%{$reset_color%}"
done
}
# Set terminal window and tab/icon title
#
# usage: title short_tab_title [long_window_title]
#
# See: http://www.faqs.org/docs/Linux-mini/Xterm-Title.html#ss3.1
# Fully supports screen, iterm, and probably most modern xterm and rxvt
# (In screen, only short_tab_title is used)
# Limited support for Apple Terminal (Terminal can't set window and tab separately)
function title {
emulate -L zsh
setopt prompt_subst
[[ "$EMACS" == *term* ]] && return
# if $2 is unset use $1 as default
# if it is set and empty, leave it as is
: ${2=$1}
case "$TERM" in
cygwin|xterm*|putty*|rxvt*|konsole*|ansi)
print -Pn "\e]2;$2:q\a" # set window name
print -Pn "\e]1;$1:q\a" # set tab name
;;
screen*|tmux*)
print -Pn "\ek$1:q\e\\" # set screen hardstatus
;;
*)
if [[ "$TERM_PROGRAM" == "iTerm.app" ]]; then
print -Pn "\e]2;$2:q\a" # set window name
print -Pn "\e]1;$1:q\a" # set tab name
else
# Try to use terminfo to set the title
# If the feature is available set title
if [[ -n "$terminfo[fsl]" ]] && [[ -n "$terminfo[tsl]" ]]; then
echoti tsl
print -Pn "$1"
echoti fsl
fi
fi
;;
esac
}
ZSH_THEME_TERM_TAB_TITLE_IDLE="%15<..<%~%<<" #15 char left truncated PWD
ZSH_THEME_TERM_TITLE_IDLE="%n@%m: %~"
# Avoid duplication of directory in terminals with independent dir display
if [[ "$TERM_PROGRAM" == Apple_Terminal ]]; then
ZSH_THEME_TERM_TITLE_IDLE="%n@%m"
fi
# Runs before showing the prompt
function omz_termsupport_precmd {
[[ "$DISABLE_AUTO_TITLE" == true ]] && return
title $ZSH_THEME_TERM_TAB_TITLE_IDLE $ZSH_THEME_TERM_TITLE_IDLE
}
# Runs before executing the command
function omz_termsupport_preexec {
[[ "$DISABLE_AUTO_TITLE" == true ]] && return
emulate -L zsh
setopt extended_glob
# split command into array of arguments
local -a cmdargs
cmdargs=("${(z)2}")
# if running fg, extract the command from the job description
if [[ "${cmdargs[1]}" = fg ]]; then
# get the job id from the first argument passed to the fg command
local job_id jobspec="${cmdargs[2]#%}"
# logic based on jobs arguments:
# http://zsh.sourceforge.net/Doc/Release/Jobs-_0026-Signals.html#Jobs
# https://www.zsh.org/mla/users/2007/msg00704.html
case "$jobspec" in
<->) # %number argument:
# use the same <number> passed as an argument
job_id=${jobspec} ;;
""|%|+) # empty, %% or %+ argument:
# use the current job, which appears with a + in $jobstates:
# suspended:+:5071=suspended (tty output)
job_id=${(k)jobstates[(r)*:+:*]} ;;
-) # %- argument:
# use the previous job, which appears with a - in $jobstates:
# suspended:-:6493=suspended (signal)
job_id=${(k)jobstates[(r)*:-:*]} ;;
[?]*) # %?string argument:
# use $jobtexts to match for a job whose command *contains* <string>
job_id=${(k)jobtexts[(r)*${(Q)jobspec}*]} ;;
*) # %string argument:
# use $jobtexts to match for a job whose command *starts with* <string>
job_id=${(k)jobtexts[(r)${(Q)jobspec}*]} ;;
esac
# override preexec function arguments with job command
if [[ -n "${jobtexts[$job_id]}" ]]; then
1="${jobtexts[$job_id]}"
2="${jobtexts[$job_id]}"
fi
fi
# cmd name only, or if this is sudo or ssh, the next cmd
local CMD=${1[(wr)^(*=*|sudo|ssh|mosh|rake|-*)]:gs/%/%%}
local LINE="${2:gs/%/%%}"
title '$CMD' '%100>...>$LINE%<<'
}
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
# Based on this answer: https://superuser.com/a/315029
# With extra fixes to handle multibyte chars and non-UTF-8 locales
if [[ "$TERM_PROGRAM" == "Apple_Terminal" ]] && [[ -z "$INSIDE_EMACS" ]]; then
# Emits the control sequence to notify Terminal.app of the cwd
# Identifies the directory using a file: URI scheme, including
# the host name to disambiguate local vs. remote paths.
function update_terminalapp_cwd() {
emulate -L zsh
# Percent-encode the host and path names.
local URL_HOST URL_PATH
URL_HOST="$(omz_urlencode -P $HOST)" || return 1
URL_PATH="$(omz_urlencode -P $PWD)" || return 1
# Undocumented Terminal.app-specific control sequence
printf '\e]7;%s\a' "file://$URL_HOST$URL_PATH"
}
# Use a precmd hook instead of a chpwd hook to avoid contaminating output
add-zsh-hook precmd update_terminalapp_cwd
# Run once to get initial cwd set
update_terminalapp_cwd
fi
# ls colors
autoload -U colors && colors
# Enable ls colors
export LSCOLORS="Gxfxcxdxbxegedabagacad"
# TODO organise this chaotic logic
if [[ "$DISABLE_LS_COLORS" != "true" ]]; then
# Find the option for using colors in ls, depending on the version
if [[ "$OSTYPE" == netbsd* ]]; then
# On NetBSD, test if "gls" (GNU ls) is installed (this one supports colors);
# otherwise, leave ls as is, because NetBSD's ls doesn't support -G
gls --color -d . &>/dev/null && alias ls='gls --color=tty'
elif [[ "$OSTYPE" == openbsd* ]]; then
# On OpenBSD, "gls" (ls from GNU coreutils) and "colorls" (ls from base,
# with color and multibyte support) are available from ports. "colorls"
# will be installed on purpose and can't be pulled in by installing
# coreutils, so prefer it to "gls".
gls --color -d . &>/dev/null && alias ls='gls --color=tty'
colorls -G -d . &>/dev/null && alias ls='colorls -G'
elif [[ "$OSTYPE" == (darwin|freebsd)* ]]; then
# this is a good alias, it works by default just using $LSCOLORS
ls -G . &>/dev/null && alias ls='ls -G'
# only use coreutils ls if there is a dircolors customization present ($LS_COLORS or .dircolors file)
# otherwise, gls will use the default color scheme which is ugly af
[[ -n "$LS_COLORS" || -f "$HOME/.dircolors" ]] && gls --color -d . &>/dev/null && alias ls='gls --color=tty'
else
# For GNU ls, we use the default ls color theme. They can later be overwritten by themes.
if [[ -z "$LS_COLORS" ]]; then
(( $+commands[dircolors] )) && eval "$(dircolors -b)"
fi
ls --color -d . &>/dev/null && alias ls='ls --color=tty' || { ls -G . &>/dev/null && alias ls='ls -G' }
# Take advantage of $LS_COLORS for completion as well.
zstyle ':completion:*' list-colors "${(s.:.)LS_COLORS}"
fi
fi
setopt auto_cd
setopt multios
setopt prompt_subst
[[ -n "$WINDOW" ]] && SCREEN_NO="%B$WINDOW%b " || SCREEN_NO=""
# git theming default: Variables for theming the git info prompt
ZSH_THEME_GIT_PROMPT_PREFIX="git:(" # Prefix at the very beginning of the prompt, before the branch name
ZSH_THEME_GIT_PROMPT_SUFFIX=")" # At the very end of the prompt
ZSH_THEME_GIT_PROMPT_DIRTY="*" # Text to display if the branch is dirty
ZSH_THEME_GIT_PROMPT_CLEAN="" # Text to display if the branch is clean
ZSH_THEME_RUBY_PROMPT_PREFIX="("
ZSH_THEME_RUBY_PROMPT_SUFFIX=")"
# Set ZSH_CACHE_DIR to the path where cache files should be created
# or else we will use the default cache/
if [[ -z "$ZSH_CACHE_DIR" ]]; then
ZSH_CACHE_DIR="$ZSH/cache"
fi
# Migrate .zsh-update file to $ZSH_CACHE_DIR
if [ -f ~/.zsh-update ] && [ ! -f ${ZSH_CACHE_DIR}/.zsh-update ]; then
mv ~/.zsh-update ${ZSH_CACHE_DIR}/.zsh-update
fi
# Check for updates on initial load...
if [ "$DISABLE_AUTO_UPDATE" != "true" ]; then
env ZSH=$ZSH ZSH_CACHE_DIR=$ZSH_CACHE_DIR DISABLE_UPDATE_PROMPT=$DISABLE_UPDATE_PROMPT zsh -f $ZSH/tools/check_for_upgrade.sh
fi
# Initializes Oh My Zsh
# add a function path
fpath=($ZSH/functions $ZSH/completions $fpath)
# Load all stock functions (from $fpath files) called below.
autoload -U compaudit compinit
# Set ZSH_CUSTOM to the path where your custom config files
# and plugins exists, or else we will use the default custom/
if [[ -z "$ZSH_CUSTOM" ]]; then
ZSH_CUSTOM="$ZSH/custom"
fi
is_plugin() {
local base_dir=$1
local name=$2
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
# before running compinit.
for plugin ($plugins); do
if is_plugin $ZSH_CUSTOM $plugin; then
fpath=($ZSH_CUSTOM/plugins/$plugin $fpath)
elif is_plugin $ZSH $plugin; then
fpath=($ZSH/plugins/$plugin $fpath)
else
echo "[oh-my-zsh] plugin '$plugin' not found"
fi
done
# Figure out the SHORT hostname
if [[ "$OSTYPE" = darwin* ]]; then
# macOS's $HOST changes with dhcp, etc. Use ComputerName if possible.
SHORT_HOST=$(scutil --get ComputerName 2>/dev/null) || SHORT_HOST=${HOST/.*/}
else
SHORT_HOST=${HOST/.*/}
fi
# Save the location of the current completion dump file.
if [ -z "$ZSH_COMPDUMP" ]; then
ZSH_COMPDUMP="${ZDOTDIR:-${HOME}}/.zcompdump-${SHORT_HOST}-${ZSH_VERSION}"
fi
if [[ $ZSH_DISABLE_COMPFIX != true ]]; then
source $ZSH/lib/compfix.zsh
# If completion insecurities exist, warn the user
handle_completion_insecurities
# Load only from secure directories
compinit -i -C -d "${ZSH_COMPDUMP}"
else
# If the user wants it, load from all found directories
compinit -u -C -d "${ZSH_COMPDUMP}"
fi
# Load all of the config files in ~/oh-my-zsh that end in .zsh
# TIP: Add files you don't want in git to .gitignore
for config_file ($ZSH/lib/*.zsh); do
custom_config_file="${ZSH_CUSTOM}/lib/${config_file:t}"
[ -f "${custom_config_file}" ] && config_file=${custom_config_file}
source $config_file
done
# Load all of the plugins that were defined in ~/.zshrc
for plugin ($plugins); do
if [ -f $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh
elif [ -f $ZSH/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH/plugins/$plugin/$plugin.plugin.zsh
fi
done
# Load all of your custom configurations from custom/
for config_file ($ZSH_CUSTOM/*.zsh(N)); do
source $config_file
done
unset config_file
# Load the 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
source "$ZSH/themes/$ZSH_THEME.zsh-theme"
fi
fi
# adb autocomplete plugin
* Adds autocomplete options for all adb commands.
* Add autocomplete for `adb -s`
## Requirements
In order to make this work, you will need to have the Android adb tools set up in your path.
#compdef adb
#autoload
# in order to make this work, you will need to have the android adb tools
# adb zsh completion, based on homebrew completion
local -a _1st_arguments
_1st_arguments=(
'bugreport:return all information from the device that should be included in a bug report.'
'connect:connect to a device via TCP/IP Port 5555 is default.'
'devices:list all connected devices'
'disconnect:disconnect from a TCP/IP device. Port 5555 is default.'
'emu:run emulator console command'
'forward:forward socket connections'
'get-devpath:print the device path'
'get-serialno:print the serial number of the device'
'get-state:print the current state of the device: offline | bootloader | device'
'help:show the help message'
'install:push this package file to the device and install it'
'jdwp:list PIDs of processes hosting a JDWP transport'
'keygen:generate adb public/private key'
'kill-server:kill the server if it is running'
'logcat:view device log'
'pull:copy file/dir from device'
'push:copy file/dir to device'
'reboot:reboots the device, optionally into the bootloader or recovery program'
'reboot-bootloader:reboots the device into the bootloader'
'remount:remounts the partitions on the device read-write'
'root:restarts the adbd daemon with root permissions'
'sideload:push a ZIP to device and install it'
'shell:run remote shell interactively'
'sync:copy host->device only if changed (-l means list but dont copy)'
'start-server:ensure that there is a server running'
'tcpip:restart host adb in tcpip mode'
'uninstall:remove this app package from the device'
'usb:restart the adbd daemon listing on USB'
'version:show version num'
'wait-for-device:block until device is online'
)
local expl
local -a pkgs installed_pkgs
_arguments \
'-s[devices]:specify device:->specify_device' \
'*:: :->subcmds' && return 0
case "$state" in
specify_device)
_values -C 'devices' ${$(adb devices -l|awk 'NR>1&& $1 \
{sub(/ +/," ",$0); \
gsub(":","\\:",$1); \
for(i=1;i<=NF;i++) {
if($i ~ /model:/) { split($i,m,":") } \
else if($i ~ /product:/) { split($i,p,":") } } \
printf "%s[%s(%s)] ",$1, p[2], m[2]}'):-""}
return
;;
esac
if (( CURRENT == 1 )); then
_describe -t commands "adb subcommand" _1st_arguments
return
fi
_files
# 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'
```
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
# ansible plugin
## Introduction
The `ansible plugin` adds several aliases for useful [ansible](https://docs.ansible.com/ansible/latest/index.html) commands and [aliases](#aliases).
To use it, add `ansible` to the plugins array of your zshrc file:
```
plugins=(... ansible)
```
## Aliases
| Command | Description |
|:-------------------------------------------|:--------------------------------------------------------------------|
| `ansible-version` / `aver` | Show the version on ansible installed in this host |
| `ansible-role-init <role name>` / `arinit` | Creates the Ansible Role as per Ansible Galaxy standard |
| `a` | command `ansible` |
| `aconf` | command `ansible-config` |
| `acon` | command `ansible-console` |
| `ainv` | command `ansible-inventory` |
| `aplaybook` | command `ansible-playbook` |
| `ainv` | command `ansible-inventory` |
| `adoc` | command `ansible-doc` |
| `agal` | command `ansible-galaxy` |
| `apull` | command `ansible-pull` |
| `aval` | command `ansible-vault` |
## Maintainer
### [Deepankumar](https://github.com/deepan10)
[https://github.com/deepan10/oh-my-zsh/tree/features/ansible-plugin](https://github.com/deepan10/oh-my-zsh/tree/features/ansible-plugin)
# Functions
function ansible-version(){
ansible --version
}
function ansible-role-init(){
if ! [ -z $1] ; then
echo "Ansible Role : $1 Creating...."
ansible-galaxy init $1
tree $1
else
echo "Usage : ansible-role-init <role name>"
echo "Example : ansible-role-init role1"
fi
}
# Alias
alias a='ansible '
alias aconf='ansible-config '
alias acon='ansible-console '
alias aver='ansible-version'
alias arinit='ansible-role-init'
alias aplaybook='ansible-playbook '
alias ainv='ansible-inventory '
alias adoc='ansible-doc '
alias agal='ansible-galaxy '
alias apull='ansible-pull '
alias aval='ansible-vault'
\ No newline at end of file
# Ant
This plugin provides completion for [Ant](https://ant.apache.org/).
To use it add ant to the plugins array in your zshrc file.
```bash
plugins=(... ant)
```
It caches ant targets in a file named `.ant_targets`, you might want to add that to
your `.gitignore` file.
_ant_does_target_list_need_generating () {
[ ! -f .ant_targets ] && return 0;
[ build.xml -nt .ant_targets ] && return 0;
return 1;
}
_ant () {
if [ -f build.xml ]; then
if _ant_does_target_list_need_generating; then
ant -p | awk -F " " 'NR > 5 { print lastTarget }{lastTarget = $1}' > .ant_targets
fi
compadd -- `cat .ant_targets`
fi
}
compdef _ant ant
## APACHE2 MACPORTS PLUGIN
---
### FEATURES
| Alias | Function | Description |
|:--------------:|:-------------------------------------------------------------------------------|----------------------:|
| apache2restart | sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper restart | Restart apache daemon |
| apache2start | sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start | Start apache daemon |
| apache2stop | sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper stop | Stop apache daemon |
---
### CONTRIBUTORS
- Alexander Rinass (alex@rinass.net)
---
# commands to control local apache2 server installation
# paths are for osx installation via macports
alias apache2start='sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start'
alias apache2stop='sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper stop'
alias apache2restart='sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper restart'
## arcanist
This plugin adds many useful aliases for [arcanist](https://github.com/phacility/arcanist).
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` |
| ardp | `arc diff --preview` |
| 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` |
## Functions
The following functions make copy pasting revision ids from the URL bar of your browser
easier, as they allow for copy pasting the whole URL. For example: `ardu` accepts
both `https://arcanist-url.com/<REVISION>` as well as `<REVISION>`.
| Function | Command |
| ------------------------- | --------------------------------- |
| ardu [URL or revision_id] | `arc diff --update` [revision_id] |
| arpa [URL or revision_id] | `arc patch` [revision_id] |
#
# Aliases
# (sorted alphabetically)
#
alias ara='arc amend'
alias arb='arc branch'
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'
alias ardp='arc diff --preview' # creates a new diff in the phab interface
alias are='arc export'
alias arh='arc help'
alias arl='arc land'
alias arli='arc lint'
alias arls='arc list'
#
# Functions
# (sorted alphabetically)
#
ardu() {
# Both `ardu https://arcanist-url.com/<REVISION>`, and `ardu <REVISION>` work.
arc diff --update "${1:t}"
}
arpa() {
# Both `arpa https://arcanist-url.com/<REVISION>`, and `arpa <REVISION>` work.
arc patch "${1:t}"
}
if (( $+commands[trizen] )); then
alias trconf='trizen -C'
alias trupg='trizen -Syua'
alias trsu='trizen -Syua --noconfirm'
alias trin='trizen -S'
alias trins='trizen -U'
alias trre='trizen -R'
alias trrem='trizen -Rns'
alias trrep='trizen -Si'
alias trreps='trizen -Ss'
alias trloc='trizen -Qi'
alias trlocs='trizen -Qs'
alias trlst='trizen -Qe'
alias trorph='trizen -Qtd'
alias trinsd='trizen -S --asdeps'
alias trmir='trizen -Syy'
if (( $+commands[abs] && $+commands[aur] )); then
alias trupd='trizen -Sy && sudo abs && sudo aur'
elif (( $+commands[abs] )); then
alias trupd='trizen -Sy && sudo abs'
elif (( $+commands[aur] )); then
alias trupd='trizen -Sy && sudo aur'
else
alias trupd='trizen -Sy'
fi
fi
if (( $+commands[yaourt] )); then
alias yaconf='yaourt -C'
alias yaupg='yaourt -Syua'
alias yasu='yaourt -Syua --noconfirm'
alias yain='yaourt -S'
alias yains='yaourt -U'
alias yare='yaourt -R'
alias yarem='yaourt -Rns'
alias yarep='yaourt -Si'
alias yareps='yaourt -Ss'
alias yaloc='yaourt -Qi'
alias yalocs='yaourt -Qs'
alias yalst='yaourt -Qe'
alias yaorph='yaourt -Qtd'
alias yainsd='yaourt -S --asdeps'
alias yamir='yaourt -Syy'
if (( $+commands[abs] && $+commands[aur] )); then
alias yaupd='yaourt -Sy && sudo abs && sudo aur'
elif (( $+commands[abs] )); then
alias yaupd='yaourt -Sy && sudo abs'
elif (( $+commands[aur] )); then
alias yaupd='yaourt -Sy && sudo aur'
else
alias yaupd='yaourt -Sy'
fi
fi
if (( $+commands[yay] )); then
alias yaconf='yay -Pg'
alias yaupg='yay -Syu'
alias yasu='yay -Syu --noconfirm'
alias yain='yay -S'
alias yains='yay -U'
alias yare='yay -R'
alias yarem='yay -Rns'
alias yarep='yay -Si'
alias yareps='yay -Ss'
alias yaloc='yay -Qi'
alias yalocs='yay -Qs'
alias yalst='yay -Qe'
alias yaorph='yay -Qtd'
alias yainsd='yay -S --asdeps'
alias yamir='yay -Syy'
if (( $+commands[abs] && $+commands[aur] )); then
alias yaupd='yay -Sy && sudo abs && sudo aur'
elif (( $+commands[abs] )); then
alias yaupd='yay -Sy && sudo abs'
elif (( $+commands[aur] )); then
alias yaupd='yay -Sy && sudo aur'
else
alias yaupd='yay -Sy'
fi
fi
if (( $+commands[pacaur] )); then
alias paupg='pacaur -Syu'
alias pasu='pacaur -Syu --noconfirm'
alias pain='pacaur -S'
alias pains='pacaur -U'
alias pare='pacaur -R'
alias parem='pacaur -Rns'
alias parep='pacaur -Si'
alias pareps='pacaur -Ss'
alias paloc='pacaur -Qi'
alias palocs='pacaur -Qs'
alias palst='pacaur -Qe'
alias paorph='pacaur -Qtd'
alias painsd='pacaur -S --asdeps'
alias pamir='pacaur -Syy'
if (( $+commands[abs] && $+commands[aur] )); then
alias paupd='pacaur -Sy && sudo abs && sudo aur'
elif (( $+commands[abs] )); then
alias paupd='pacaur -Sy && sudo abs'
elif (( $+commands[aur] )); then
alias paupd='pacaur -Sy && sudo aur'
else
alias paupd='pacaur -Sy'
fi
fi
if (( $+commands[trizen] )); then
function upgrade() {
trizen -Syu
}
elif (( $+commands[pacaur] )); then
function upgrade() {
pacaur -Syu
}
elif (( $+commands[yaourt] )); then
function upgrade() {
yaourt -Syu
}
elif (( $+commands[yay] )); then
function upgrade() {
yay -Syu
}
else
function upgrade() {
sudo pacman -Syu
}
fi
# Pacman - https://wiki.archlinux.org/index.php/Pacman_Tips
alias pacupg='sudo pacman -Syu'
alias pacin='sudo pacman -S'
alias pacins='sudo pacman -U'
alias pacre='sudo pacman -R'
alias pacrem='sudo pacman -Rns'
alias pacrep='pacman -Si'
alias pacreps='pacman -Ss'
alias pacloc='pacman -Qi'
alias paclocs='pacman -Qs'
alias pacinsd='sudo pacman -S --asdeps'
alias pacmir='sudo pacman -Syy'
alias paclsorphans='sudo pacman -Qdt'
alias pacrmorphans='sudo pacman -Rs $(pacman -Qtdq)'
alias pacfileupg='sudo pacman -Fy'
alias pacfiles='pacman -Fs'
alias pacls='pacman -Ql'
alias pacown='pacman -Qo'
if (( $+commands[abs] && $+commands[aur] )); then
alias pacupd='sudo pacman -Sy && sudo abs && sudo aur'
elif (( $+commands[abs] )); then
alias pacupd='sudo pacman -Sy && sudo abs'
elif (( $+commands[aur] )); then
alias pacupd='sudo pacman -Sy && sudo aur'
else
alias pacupd='sudo pacman -Sy'
fi
function paclist() {
# Source: https://bbs.archlinux.org/viewtopic.php?id=93683
LC_ALL=C pacman -Qei $(pacman -Qu | cut -d " " -f 1) | \
awk 'BEGIN {FS=":"} /^Name/{printf("\033[1;36m%s\033[1;37m", $2)} /^Description/{print $2}'
}
function pacdisowned() {
emulate -L zsh
tmp=${TMPDIR-/tmp}/pacman-disowned-$UID-$$
db=$tmp/db
fs=$tmp/fs
mkdir "$tmp"
trap 'rm -rf "$tmp"' EXIT
pacman -Qlq | sort -u > "$db"
find /bin /etc /lib /sbin /usr ! -name lost+found \
\( -type d -printf '%p/\n' -o -print \) | sort > "$fs"
comm -23 "$fs" "$db"
}
function pacmanallkeys() {
emulate -L zsh
curl -s https://www.archlinux.org/people/{developers,trustedusers}/ | \
awk -F\" '(/pgp.mit.edu/) { sub(/.*search=0x/,""); print $1}' | \
xargs sudo pacman-key --recv-keys
}
function pacmansignkeys() {
emulate -L zsh
for key in $*; do
sudo pacman-key --recv-keys $key
sudo pacman-key --lsign-key $key
printf 'trust\n3\n' | sudo gpg --homedir /etc/pacman.d/gnupg \
--no-permission-warning --command-fd 0 --edit-key $key
done
}
if (( $+commands[xdg-open] )); then
function pacweb() {
pkg="$1"
infos="$(pacman -Si "$pkg")"
if [[ -z "$infos" ]]; then
return
fi
repo="$(grep '^Repo' <<< "$infos" | grep -oP '[^ ]+$')"
arch="$(grep '^Arch' <<< "$infos" | grep -oP '[^ ]+$')"
xdg-open "https://www.archlinux.org/packages/$repo/$arch/$pkg/" &>/dev/null
}
fi
## asdf
**Maintainer:** [@RobLoach](https://github.com/RobLoach)
Adds integration with [asdf](https://github.com/asdf-vm/asdf), the extendable version manager, with support for Ruby, Node.js, Elixir, Erlang and more.
### Installation
1. Enable the plugin by adding it to your `plugins` definition in `~/.zshrc`.
```
plugins=(asdf)
```
2. [Install asdf](https://github.com/asdf-vm/asdf#setup) by running the following:
```
git clone https://github.com/asdf-vm/asdf.git ~/.asdf
```
### Usage
See the [asdf usage documentation](https://github.com/asdf-vm/asdf#usage) for information on how to use asdf:
```
asdf plugin-add nodejs git@github.com:asdf-vm/asdf-nodejs.git
asdf install nodejs 5.9.1
```
# Find where asdf should be installed
ASDF_DIR="${ASDF_DIR:-$HOME/.asdf}"
ASDF_COMPLETIONS="$ASDF_DIR/completions"
# If not found, check for Homebrew package
if [[ ! -f "$ASDF_DIR/asdf.sh" ]] && (( $+commands[brew] )); then
ASDF_DIR="$(brew --prefix asdf)"
ASDF_COMPLETIONS="$ASDF_DIR/etc/bash_completion.d"
fi
# Load command
if [[ -f "$ASDF_DIR/asdf.sh" ]]; then
. "$ASDF_DIR/asdf.sh"
# Load completions
if [[ -f "$ASDF_COMPLETIONS/asdf.bash" ]]; then
. "$ASDF_COMPLETIONS/asdf.bash"
fi
fi
# 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
# Activates autoenv or reports its failure
() {
if ! type autoenv_init >/dev/null; then
for d (~/.autoenv ~/.local/bin /usr/local/opt/autoenv /usr/local/bin); do
if [[ -e $d/activate.sh ]]; then
autoenv_dir=$d
break
fi
done
if [[ -z $autoenv_dir ]]; then
cat <<END >&2
-------- AUTOENV ---------
Could not locate autoenv installation.
Please check if autoenv is correctly installed.
In the meantime the autoenv plugin is DISABLED.
--------------------------
END
return 1
fi
source $autoenv_dir/activate.sh
fi
}
[[ $? != 0 ]] && return $?
# The use_env call below is a reusable command to activate/create a new Python
# virtualenv, requiring only a single declarative line of code in your .env files.
# It only performs an action if the requested virtualenv is not the current one.
use_env() {
typeset venv
venv="$1"
if [[ "${VIRTUAL_ENV:t}" != "$venv" ]]; then
if workon | grep -q "$venv"; then
workon "$venv"
else
echo -n "Create virtualenv $venv now? (Yn) "
read answer
if [[ "$answer" == "Y" ]]; then
mkvirtualenv "$venv"
fi
fi
fi
}
# Autojump plugin
This plugin loads the [autojump navigation tool](https://github.com/wting/autojump).
To use it, add `autojump` to the plugins array in your zshrc file:
```zsh
plugins=(... autojump)
```
More info on the usage: https://github.com/wting/autojump
declare -a autojump_paths
autojump_paths=(
$HOME/.autojump/etc/profile.d/autojump.zsh # manual installation
$HOME/.autojump/share/autojump/autojump.zsh # manual installation
$HOME/.nix-profile/etc/profile.d/autojump.sh # NixOS installation
/run/current-system/sw/share/autojump/autojump.zsh # NixOS installation
/usr/share/autojump/autojump.zsh # Debian and Ubuntu package
/etc/profile.d/autojump.zsh # manual installation
/etc/profile.d/autojump.sh # Gentoo installation
/usr/local/share/autojump/autojump.zsh # FreeBSD installation
/opt/local/etc/profile.d/autojump.sh # macOS with MacPorts
/usr/local/etc/profile.d/autojump.sh # macOS with Homebrew (default)
)
for file in $autojump_paths; do
if [[ -f "$file" ]]; then
source "$file"
found=1
break
fi
done
# if no path found, try Homebrew
if (( ! found && $+commands[brew] )); then
file=$(brew --prefix)/etc/profile.d/autojump.sh
if [[ -f "$file" ]]; then
source "$file"
found=1
fi
fi
(( ! found )) && echo '[oh-my-zsh] autojump script not found'
unset autojump_paths file found
# autopep8 plugin
This plugin adds completion for [autopep8](https://pypi.org/project/autopep8/), a tool that automatically formats Python code to conform to the [PEP 8](http://www.python.org/dev/peps/pep-0008/) style guide.
To use it, add autopep8 to the plugins array of your zshrc file:
```
plugins=(... autopep8)
```
#compdef autopep8
#
# this is zsh completion function file.
# generated by genzshcomp(ver: 0.5.1)
#
typeset -A opt_args
local context state line
_arguments -s -S \
"--help[show this help message and exit]:" \
"-h[show this help message and exit]:" \
"--version[show program's version number and exit]:" \
"--verbose[print verbose messages; multiple -v result in more verbose messages]" \
"-v[print verbose messages; multiple -v result in more verbose messages]" \
"--diff[print the diff for the fixed source]" \
"-d[print the diff for the fixed source]" \
"--in-place[make changes to files in place]" \
"-i[make changes to files in place]" \
"--recursive[run recursively; must be used with --in-place or --diff]" \
"-r[run recursively; must be used with --in-place or --diff]" \
"--jobs[number of parallel jobs; match CPU count if value is less than 1]::n number of parallel jobs; match CPU count if value is:_files" \
"-j[number of parallel jobs; match CPU count if value is less than 1]::n number of parallel jobs; match CPU count if value is:_files" \
"--pep8-passes[maximum number of additional pep8 passes (default: 100)]::n:_files" \
"-p[maximum number of additional pep8 passes (default: 100)]::n:_files" \
"-a[-a result in more aggressive changes]::result:_files" \
"--exclude[exclude files/directories that match these comma- separated globs]::globs:_files" \
"--list-fixes[list codes for fixes; used by --ignore and --select]" \
"--ignore[do not fix these errors/warnings (default E226,E24)]::errors:_files" \
"--select[fix only these errors/warnings (e.g. E4,W)]::errors:_files" \
"--max-line-length[set maximum allowed line length (default: 79)]::n:_files" \
"*::args:_files"
# aws
This plugin provides completion support for [awscli](https://docs.aws.amazon.com/cli/latest/reference/index.html)
and a few utilities to manage AWS profiles and display them in the prompt.
To use it, add `aws` to the plugins array in your zshrc file.
```zsh
plugins=(... aws)
```
## Plugin commands
* `asp [<profile>]`: sets `$AWS_PROFILE` and `$AWS_DEFAULT_PROFILE` (legacy) to `<profile>`.
It also sets `$AWS_EB_PROFILE` to `<profile>` for the Elastic Beanstalk CLI.
Run `asp` without arguments to clear the profile.
* `agp`: gets the current value of `$AWS_PROFILE`.
* `aws_change_access_key`: changes the AWS access key of a profile.
* `aws_profiles`: lists the available profiles in the `$AWS_CONFIG_FILE` (default: `~/.aws/config`).
Used to provide completion for the `asp` function.
## Plugin options
* Set `SHOW_AWS_PROMPT=false` in your zshrc file if you want to prevent the plugin from modifying your RPROMPT.
Some themes might overwrite the value of RPROMPT instead of appending to it, so they'll need to be fixed to
see the AWS profile prompt.
## Theme
The plugin creates an `aws_prompt_info` function that you can use in your theme, which displays
the current `$AWS_PROFILE`. It uses two variables to control how that is shown:
- ZSH_THEME_AWS_PREFIX: sets the prefix of the AWS_PROFILE. Defaults to `<aws:`.
- ZSH_THEME_AWS_SUFFIX: sets the suffix of the AWS_PROFILE. Defaults to `>`.
function agp() {
echo $AWS_PROFILE
}
# AWS profile selection
function asp() {
if [[ -z "$1" ]]; then
unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE
echo AWS profile cleared.
return
fi
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
return 1
fi
export AWS_DEFAULT_PROFILE=$1
export AWS_PROFILE=$1
export AWS_EB_PROFILE=$1
}
function aws_change_access_key() {
if [[ -z "$1" ]]; then
echo "usage: $0 <profile>"
return 1
fi
echo Insert the credentials when asked.
asp "$1" || return 1
aws iam create-access-key
aws configure --profile "$1"
echo You can now safely delete the old access key running \`aws iam delete-access-key --access-key-id ID\`
echo Your current keys are:
aws iam list-access-keys
}
function aws_profiles() {
[[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1
grep '\[profile' "${AWS_CONFIG_FILE:-$HOME/.aws/config}"|sed -e 's/.*profile \([a-zA-Z0-9_\.-]*\).*/\1/'
}
function _aws_profiles() {
reply=($(aws_profiles))
}
compctl -K _aws_profiles asp aws_change_access_key
# AWS prompt
function aws_prompt_info() {
[[ -z $AWS_PROFILE ]] && return
echo "${ZSH_THEME_AWS_PREFIX:=<aws:}${AWS_PROFILE}${ZSH_THEME_AWS_SUFFIX:=>}"
}
if [ "$SHOW_AWS_PROMPT" != false ]; then
RPROMPT='$(aws_prompt_info)'"$RPROMPT"
fi
# Load awscli completions
# AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back
if [[ -x /usr/local/bin/aws_completer ]]; then
autoload -Uz bashcompinit && bashcompinit
complete -C aws_completer aws
else
function _awscli-homebrew-installed() {
# check if Homebrew is installed
(( $+commands[brew] )) || return 1
# speculatively check default brew prefix
if [ -h /usr/local/opt/awscli ]; then
_brew_prefix=/usr/local/opt/awscli
else
# ok, it is not in the default prefix
# this call to brew is expensive (about 400 ms), so at least let's make it only once
_brew_prefix=$(brew --prefix awscli)
fi
}
# get aws_zsh_completer.sh location from $PATH
_aws_zsh_completer_path="$commands[aws_zsh_completer.sh]"
# otherwise check common locations
if [[ -z $_aws_zsh_completer_path ]]; then
# Homebrew
if _awscli-homebrew-installed; then
_aws_zsh_completer_path=$_brew_prefix/libexec/bin/aws_zsh_completer.sh
# Ubuntu
elif [[ -e /usr/share/zsh/vendor-completions/_awscli ]]; then
_aws_zsh_completer_path=/usr/share/zsh/vendor-completions/_awscli
# RPM
else
_aws_zsh_completer_path=/usr/share/zsh/site-functions/aws_zsh_completer.sh
fi
fi
[[ -r $_aws_zsh_completer_path ]] && source $_aws_zsh_completer_path
unset _aws_zsh_completer_path _brew_prefix
fi
# Battery Plugin
This plugin adds some functions you can use to display battery information in your custom theme.
To use, add `battery` to the list of plugins in your `.zshrc` file:
`plugins=(... battery)`
Then, add the `battery_pct_prompt` function to your custom theme. For example:
```
RPROMPT='$(battery_pct_prompt)'
```
###########################################
# Battery plugin for oh-my-zsh #
# Original Author: Peter hoeg (peterhoeg) #
# Email: peter@speartail.com #
###########################################
# Author: Sean Jones (neuralsandwich) #
# Email: neuralsandwich@gmail.com #
# Modified to add support for Apple Mac #
###########################################
# Author: J (927589452) #
# Modified to add support for FreeBSD #
###########################################
if [[ "$OSTYPE" = darwin* ]]; then
function battery_is_charging() {
ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ Yes'
}
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 battery_is_charging; then
echo "External Power"
else
battery_pct
fi
}
function battery_time_remaining() {
local smart_battery_status="$(ioreg -rc "AppleSmartBattery")"
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))"
fi
else
echo "∞"
fi
}
function battery_pct_prompt () {
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 [[ $battery_pct -gt 20 ]]; then
color='yellow'
else
color='red'
fi
echo "%{$fg[$color]%}[${battery_pct}%%]%{$reset_color%}"
else
echo "∞"
fi
}
elif [[ "$OSTYPE" = freebsd* ]]; then
function battery_is_charging() {
[[ $(sysctl -n hw.acpi.battery.state) -eq 2 ]]
}
function battery_pct() {
if (( $+commands[sysctl] )); then
sysctl -n hw.acpi.battery.life
fi
}
function battery_pct_remaining() {
if ! battery_is_charging; then
battery_pct
else
echo "External Power"
fi
}
function battery_time_remaining() {
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() {
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
}
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_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:-$(( 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 filled empty gauge_color
if [[ $battery_remaining_percentage =~ [0-9]+ ]]; then
filled=$(( ($battery_remaining_percentage * $gauge_slots) / 100 ))
empty=$(( $gauge_slots - $filled ))
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
filled=$gauge_slots
empty=0
filled_symbol=${BATTERY_UNKNOWN_SYMBOL:-'.'}
fi
local charging=' '
battery_is_charging && charging=$charging_symbol
# Charging status and prefix
printf ${charging_color//\%/\%\%}$charging${color_reset//\%/\%\%}${battery_prefix//\%/\%\%}${gauge_color//\%/\%\%}
# 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//\%/\%\%}
}
## bbedit
Plugin for BBEdit, an HTML and text editor for Mac OS X
### Requirements
* [BBEdit](https://www.barebones.com/products/bbedit/)
* [BBEdit Command-Line Tools](https://www.barebones.com/support/bbedit/cmd-line-tools.html)
### Usage
* If the `bb` command is called without an argument, launch BBEdit
* If `bb` is passed a directory, cd to it and open it in BBEdit
* If `bb` is passed a file, open it in BBEdit
* If `bbpb` create a new BBEdit document with the contents of the clipboard
* If `bbd` alias for BBEdit diff tool
alias bbpb='pbpaste | bbedit --clean --view-top'
alias bbd=bbdiff
#
# If the bb command is called without an argument, launch BBEdit
# If bb is passed a directory, cd to it and open it in BBEdit
# If bb is passed a file, open it in BBEdit
#
function bb() {
if [[ -z "$1" ]]
then
bbedit --launch
else
bbedit "$1"
if [[ -d "$1" ]]
then
cd "$1"
fi
fi
}
# bgnotify zsh plugin
cross-platform background notifications for long running commands! Supports OSX and Ubuntu linux.
Standalone homepage: [t413/zsh-background-notify](https://github.com/t413/zsh-background-notify)
----------------------------------
## How to use!
Just add bgnotify to your plugins list in your `.zshrc`
- On OS X you'll need [terminal-notifier](https://github.com/alloy/terminal-notifier)
* `brew install terminal-notifier` (or `gem install terminal-notifier`)
- On ubuntu you're already all set!
- On windows you can use [notifu](https://www.paralint.com/projects/notifu/) or the Cygwin Ports libnotify package
## Screenshots
**Linux**
![screenshot from 2014-11-07 15 58 36](https://cloud.githubusercontent.com/assets/326829/4962187/256b465c-66da-11e4-927d-cc2fc105e31f.png)
**OS X**
![screenshot 2014-11-08 14 15 12](https://cloud.githubusercontent.com/assets/326829/4965780/19fa3eac-6795-11e4-8ed6-0355711123a9.png)
**Windows**
![screenshot from 2014-11-07 15 55 00](https://cloud.githubusercontent.com/assets/326829/4962159/a2625ca0-66d9-11e4-9e91-c5834913190e.png)
## Configuration
One can configure a few things:
- `bgnotify_threshold` sets the notification threshold time (default 6 seconds)
- `function bgnotify_formatted` lets you change the notification
Use these by adding a function definition before the your call to source. Example:
~~~ sh
bgnotify_threshold=4 ## set your own notification threshold
function bgnotify_formatted {
## $1=exit_status, $2=command, $3=elapsed_time
[ $1 -eq 0 ] && title="Holy Smokes Batman!" || title="Holy Graf Zeppelin!"
bgnotify "$title -- after $3 s" "$2";
}
plugins=(git bgnotify) ## add to plugins list
source $ZSH/oh-my-zsh.sh ## existing source call
~~~
#!/usr/bin/env zsh
## setup ##
[[ -o interactive ]] || return #interactive only!
zmodload zsh/datetime || { print "can't load zsh/datetime"; return } # faster than date()
autoload -Uz add-zsh-hook || { print "can't add zsh hook!"; return }
(( ${+bgnotify_threshold} )) || bgnotify_threshold=5 #default 10 seconds
## definitions ##
if ! (type bgnotify_formatted | grep -q 'function'); then ## allow custom function override
function bgnotify_formatted { ## args: (exit_status, command, elapsed_seconds)
elapsed="$(( $3 % 60 ))s"
(( $3 >= 60 )) && elapsed="$((( $3 % 3600) / 60 ))m $elapsed"
(( $3 >= 3600 )) && elapsed="$(( $3 / 3600 ))h $elapsed"
[ $1 -eq 0 ] && bgnotify "#win (took $elapsed)" "$2" || bgnotify "#fail (took $elapsed)" "$2"
}
fi
currentWindowId () {
if hash osascript 2>/dev/null; then #osx
osascript -e 'tell application (path to frontmost application as text) to id of front window' 2&> /dev/null || echo "0"
elif (hash notify-send 2>/dev/null || hash kdialog 2>/dev/null); then #ubuntu!
xprop -root 2> /dev/null | awk '/NET_ACTIVE_WINDOW/{print $5;exit} END{exit !$5}' || echo "0"
else
echo $EPOCHSECONDS #fallback for windows
fi
}
bgnotify () { ## args: (title, subtitle)
if hash terminal-notifier 2>/dev/null; then #osx
[[ "$TERM_PROGRAM" == 'iTerm.app' ]] && term_id='com.googlecode.iterm2';
[[ "$TERM_PROGRAM" == 'Apple_Terminal' ]] && term_id='com.apple.terminal';
## now call terminal-notifier, (hopefully with $term_id!)
[ -z "$term_id" ] && terminal-notifier -message "$2" -title "$1" >/dev/null ||
terminal-notifier -message "$2" -title "$1" -activate "$term_id" -sender "$term_id" >/dev/null
elif hash growlnotify 2>/dev/null; then #osx growl
growlnotify -m "$1" "$2"
elif hash notify-send 2>/dev/null; then #ubuntu gnome!
notify-send "$1" "$2"
elif hash kdialog 2>/dev/null; then #ubuntu kde!
kdialog --title "$1" --passivepopup "$2" 5
elif hash notifu 2>/dev/null; then #cygwyn support!
notifu /m "$2" /p "$1"
fi
}
## Zsh hooks ##
bgnotify_begin() {
bgnotify_timestamp=$EPOCHSECONDS
bgnotify_lastcmd="$1"
bgnotify_windowid=$(currentWindowId)
}
bgnotify_end() {
didexit=$?
elapsed=$(( EPOCHSECONDS - bgnotify_timestamp ))
past_threshold=$(( elapsed >= bgnotify_threshold ))
if (( bgnotify_timestamp > 0 )) && (( past_threshold )); then
if [ $(currentWindowId) != "$bgnotify_windowid" ]; then
print -n "\a"
bgnotify_formatted "$didexit" "$bgnotify_lastcmd" "$elapsed"
fi
fi
bgnotify_timestamp=0 #reset it to 0!
}
## only enable if a local (non-ssh) connection
if [ -z "$SSH_CLIENT" ] && [ -z "$SSH_TTY" ]; then
add-zsh-hook preexec bgnotify_begin
add-zsh-hook precmd bgnotify_end
fi
## Boot2docker autocomplete plugin
- Adds autocomplete options for all boot2docker commands.
Maintainer : Manfred Touron ([@moul](https://github.com/moul))
#compdef boot2docker
# Boot2docker autocompletion for oh-my-zsh
# Requires: Boot2docker installed
# Author: Manfred Touron (@moul)
local -a _1st_arguments
_1st_arguments=(
"init":"Create a new Boot2Docker VM."
"up":"Start VM from any states."
"start":"Start VM from any states."
"boot":"Start VM from any states."
"ssh":"[ssh-command] Login to VM via SSH."
"save":"Suspend VM and save state to disk."
"suspend":"Suspend VM and save state to disk."
"down":"Gracefully shutdown the VM."
"stop":"Gracefully shutdown the VM."
"halt":"Gracefully shutdown the VM."
"restart":"Gracefully reboot the VM."
"poweroff":"Forcefully power off the VM (may corrupt disk image)."
"reset":"Forcefully power cycle the VM (may corrupt disk image)."
"delete":"Delete Boot2Docker VM and its disk image."
"destroy":"Delete Boot2Docker VM and its disk image."
"config":"Show selected profile file settings."
"cfg":"Show selected profile file settings."
"info":"Display detailed information of VM."
"ip":"Display the IP address of the VM's Host-only network."
"socket":"Display the DOCKER_HOST socket to connect to."
"shellinit":"Display the shell command to set up the Docker client."
"status":"Display current state of VM."
"download":"Download Boot2Docker ISO image."
"upgrade":"Upgrade the Boot2Docker ISO image (restart if running)."
"version":"Display version information."
)
_arguments \
'(--basevmdk)--basevmdk[Path to VMDK to use as base for persistent partition]' \
'(--cpus)'{-c,--cpus}'[number of CPUs for boot2docker.]' \
'(--clobber)--clobber[overwrite Docker client binary on boot2docker upgrade]' \
'(--dhcp)--dhcp[enable VirtualBox host-only network DHCP.]' \
'(--dhcpip)--dhcpip[VirtualBox host-only network DHCP server address.]' \
'(-s --disksize)'{-s,--disksize}'[boot2docker disk image size (in MB).]' \
'(--dockerport)--dockerport[host Docker port (forward to port 2376 in VM). (deprecated - use with care)]' \
'(--driver)--driver[hypervisor driver.]' \
'(--force-upgrade-download)--force-upgrade-download[always download on boot2docker upgrade, never skip.]' \
'(--hostip)--hostip[VirtualBox host-only network IP address.]' \
'(--iso)--iso[path to boot2docker ISO image.]' \
'(--iso-url)--iso-url[/api.github.com/repos/boot2docker/boot2docker/releases": source URL to provision the boot2docker ISO image.]' \
'(--lowerip)--lowerip[VirtualBox host-only network DHCP lower bound.]' \
'(--memory)'{-m,--memory}'[virtual machine memory size (in MB).]' \
'(--netmask)--netmask[VirtualBox host-only network mask.]' \
'(--no-dummy)--no-dummy[Example parameter for the dummy driver.]' \
'(--retries)--retries[number of port knocking retries during 'start']' \
'(--serial)--serial[try serial console to get IP address (experimental)]' \
'(--serialfile)--serialfile[path to the serial socket/pipe.]' \
'(--ssh)--ssh[path to SSH client utility.]' \
'(--ssh-keygen)--ssh-keygen[path to ssh-keygen utility.]' \
'(--sshkey)--sshkey[path to SSH key to use.]' \
'(--sshport)--sshport[host SSH port (forward to port 22 in VM).]' \
'(--upperip)--upperip[VirtualBox host-only network DHCP upper bound.]' \
'(--vbm)--vbm[path to VirtualBox management utility.]' \
'(--vbox-share)--vbox-share[(defaults to "/Users=Users" if no shares are specified; use "disable" to explicitly prevent any shares from being created) List of directories to share during "up|start|boot" via VirtualBox Guest Additions, with optional labels]' \
'(--verbose)'{-v,--verbose}'[display verbose command invocations.]' \
'(--vm)--vm[virtual machine name.]' \
'(--waittime)--waittime[Time in milliseconds to wait between port knocking retries during 'start']' \
'*:: :->subcmds' && return 0
#_arguments '*:: :->command'
if (( CURRENT == 1 )); then
_describe -t commands "boot2docker command" _1st_arguments
return
fi
# Bower plugin
This plugin adds completion for [Bower](https://bower.io/) and a few useful aliases for common Bower commands.
To use it, add `bower` to the plugins array in your zshrc file:
```
plugins=(... bower)
```
## Aliases
| Alias | Command | Description |
|-------|-----------------|--------------------------------------------------------|
| bi | `bower install` | Installs the project dependencies listed in bower.json |
| bl | `bower list` | List local packages and possible updates |
| bs | `bower search` | Finds all packages or a specific package. |
# Credits to npm's awesome completion utility.
#
# Bower completion script, based on npm completion script.
###-begin-bower-completion-###
#
# Installation: bower completion >> ~/.bashrc (or ~/.zshrc)
# Or, maybe: bower completion > /usr/local/etc/bash_completion.d/bower
#
COMP_WORDBREAKS=${COMP_WORDBREAKS/=/}
COMP_WORDBREAKS=${COMP_WORDBREAKS/@/}
export COMP_WORDBREAKS
if type complete &>/dev/null; then
_bower_completion () {
local si="$IFS"
IFS=$'\n' COMPREPLY=($(COMP_CWORD="$COMP_CWORD" \
COMP_LINE="$COMP_LINE" \
COMP_POINT="$COMP_POINT" \
bower completion -- "${COMP_WORDS[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
complete -F _bower_completion bower
elif type compdef &>/dev/null; then
_bower_completion() {
si=$IFS
compadd -- $(COMP_CWORD=$((CURRENT-1)) \
COMP_LINE=$BUFFER \
COMP_POINT=0 \
bower completion -- "${words[@]}" \
2>/dev/null)
IFS=$si
}
compdef _bower_completion bower
elif type compctl &>/dev/null; then
_bower_completion () {
local cword line point words si
read -Ac words
read -cn cword
let cword-=1
read -l line
read -ln point
si="$IFS"
IFS=$'\n' reply=($(COMP_CWORD="$cword" \
COMP_LINE="$line" \
COMP_POINT="$point" \
bower completion -- "${words[@]}" \
2>/dev/null)) || return $?
IFS="$si"
}
compctl -K _bower_completion bower
fi
###-end-bower-completion-###
alias bi="bower install"
alias bl="bower list"
alias bs="bower search"
_bower_installed_packages () {
bower_package_list=$(bower ls --no-color 2>/dev/null| awk 'NR>3{print p}{p=$0}'| cut -d ' ' -f 2|sed 's/#.*//')
}
_bower ()
{
local -a _1st_arguments _no_color _dopts _save_dev _force_lastest _production
local expl
typeset -A opt_args
_no_color=('--no-color[Do not print colors (available in all commands)]')
_dopts=(
'(--save)--save[Save installed packages into the project"s bower.json dependencies]'
'(--force)--force[Force fetching remote resources even if a local copy exists on disk]'
)
_save_dev=('(--save-dev)--save-dev[Save installed packages into the project"s bower.json devDependencies]')
_force_lastest=('(--force-latest)--force-latest[Force latest version on conflict]')
_production=('(--production)--production[Do not install project devDependencies]')
_1st_arguments=(
'cache-clean:Clean the Bower cache, or the specified package caches' \
'help:Display help information about Bower' \
'info:Version info and description of a particular package' \
'init:Interactively create a bower.json file' \
'install:Install a package locally' \
'link:Symlink a package folder' \
'lookup:Look up a package URL by name' \
'register:Register a package' \
'search:Search for a package by name' \
'uninstall:Remove a package' \
'update:Update a package' \
{ls,list}:'[List all installed packages]'
)
_arguments \
$_no_color \
'*:: :->subcmds' && return 0
if (( CURRENT == 1 )); then
_describe -t commands "bower subcommand" _1st_arguments
return
fi
case "$words[1]" in
install)
_arguments \
$_dopts \
$_save_dev \
$_force_lastest \
$_no_color \
$_production
;;
update)
_arguments \
$_dopts \
$_no_color \
$_force_lastest
_bower_installed_packages
compadd "$@" $(echo $bower_package_list)
;;
uninstall)
_arguments \
$_no_color \
$_dopts
_bower_installed_packages
compadd "$@" $(echo $bower_package_list)
;;
*)
_arguments \
$_no_color \
;;
esac
}
compdef _bower bower
# Branch
Displays the current Git or Mercurial branch fast.
## Speed test
### Mercurial
```shell
$ time hg branch
0.11s user 0.14s system 70% cpu 0.355 total
```
### Branch plugin
```shell
$ time zsh /tmp/branch_prompt_info_test.zsh
0.00s user 0.01s system 78% cpu 0.014 total
```
## Usage
Edit your theme file (eg.: `~/.oh-my-zsh/theme/robbyrussell.zsh-theme`)
adding `$(branch_prompt_info)` in your prompt like this:
```diff
- PROMPT='${ret_status}%{$fg_bold[green]%}%p %{$fg[cyan]%}%c %{$fg_bold[blue]%}$(git_prompt_info)%{$fg_bold[blue]%} % %{$reset_color%}'
+ PROMPT='${ret_status}%{$fg_bold[green]%}%p %{$fg[cyan]%}%c %{$fg_bold[blue]%}$(git_prompt_info)$(branch_prompt_info)%{$fg_bold[blue]%} % %{$reset_color%}'
```
## Maintainer
Victor Torres (<vpaivatorres@gmail.com>)
# Branch: displays the current Git or Mercurial branch fast.
# Victor Torres <vpaivatorres@gmail.com>
# Oct 2, 2015
function branch_prompt_info() {
# Defines path as current directory
local current_dir=$PWD
# While current path is not root path
while [[ $current_dir != '/' ]]
do
# Git repository
if [[ -d "${current_dir}/.git" ]]
then
echo '±' ${"$(<"$current_dir/.git/HEAD")"##*/}
return;
fi
# Mercurial repository
if [[ -d "${current_dir}/.hg" ]]
then
if [[ -f "$current_dir/.hg/branch" ]]
then
echo '☿' $(<"$current_dir/.hg/branch")
else
echo '☿ default'
fi
return;
fi
# Defines path as parent directory and keeps looking for :)
current_dir="${current_dir:h}"
done
}
# brew plugin
The plugin adds several aliases for common [brew](https://brew.sh) commands.
To use it, add `brew` to the plugins array of your zshrc file:
```
plugins=(... brew)
```
## Aliases
| Alias | Command | Description |
|--------|----------------------|---------------|
| brewp | `brew pin` | Pin a specified formulae, preventing them from being upgraded when issuing the brew upgrade <formulae> command. |
| brews | `brew list -1` | List installed formulae, one entry per line, or the installed files for a given formulae. |
| brewsp | `brew list --pinned` | Show the versions of pinned formulae, or only the specified (pinned) formulae if formulae are given. |
| bubo | `brew update && brew outdated` | Fetch the newest version of Homebrew and all formulae, then list outdated formulae. |
| bubc | `brew upgrade && brew cleanup` | Upgrade outdated, unpinned brews (with existing install options), then removes stale lock files and outdated downloads for formulae and casks, and removes old versions of installed formulae. |
| bubu | `bubo && bubc` | Updates Homebrew, lists outdated formulae, upgrades oudated and unpinned formulae, and removes stale and outdated downloads and versions. |
| bcubo | `brew update && brew cask outdated` | Fetch the newest version of Homebrew and all formulae, then list outdated casks. |
| bcubc | `brew cask reinstall $(brew cask outdated) && brew cleanup` | Updates outdated casks, then runs cleanup. |
\ No newline at end of file
alias brewp='brew pin'
alias brews='brew list -1'
alias brewsp='brew list --pinned'
alias bubo='brew update && brew outdated'
alias bubc='brew upgrade && brew cleanup'
alias bubu='bubo && bubc'
alias bcubo='brew update && brew cask outdated'
alias bcubc='brew cask reinstall $(brew cask outdated) && brew cleanup'
if command mkdir "$ZSH_CACHE_DIR/.brew-completion-message" 2>/dev/null; then
print -P '%F{yellow}'Oh My Zsh brew plugin:
cat <<-'EOF'
With the advent of their 1.0 release, Homebrew has decided to bundle
the zsh completion as part of the brew installation, so we no longer
ship it with the brew plugin; now it only has brew aliases.
If you find that brew completion no longer works, make sure you have
your Homebrew installation fully up to date.
You will only see this message once.
EOF
print -P '%f'
fi
# Bundler
- adds completion for basic bundler commands
- adds short aliases for common bundler commands
- `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`
- `bo` aliased to `bundle open`
- `bout` aliased to `bundle outdated`
- `bu` aliased to `bundle update`
- `bi` aliased to `bundle install --jobs=<cpu core count>` (only for bundler `>= 1.4.0`)
- adds a wrapper for common gems:
- looks for a binstub under `./bin/` and executes it (if present)
- calls `bundle exec <gem executable>` 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`, `rubocop`, `shotgun`, `sidekiq`, `spec`, `spork`, `spring`, `strainer`, `tailor`, `taps`, `thin`, `thor`, `unicorn` and `unicorn_rails`.
## Configuration
Please use the exact name of the executable and not the gem name.
### Add additional gems to be wrapped
Add this before the plugin-list in your `.zshrc`:
```sh
BUNDLED_COMMANDS=(rubocop)
plugins=(... bundler ...)
```
This will add the wrapper for the `rubocop` gem (i.e. the executable).
### Exclude gems from being wrapped
Add this before the plugin-list in your `.zshrc`:
```sh
UNBUNDLED_COMMANDS=(foreman spin)
plugins=(... bundler ...)
```
This will exclude the `foreman` and `spin` gems (i.e. their executable) from being wrapped.
## Excluded gems
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`
`mailcatcher`
`rails`
`ruby`
`spin`
#compdef bundle
local curcontext="$curcontext" state line _gems _opts ret=1
_arguments -C -A "-v" -A "--version" \
'(- 1 *)'{-v,--version}'[display version information]' \
'1: :->cmds' \
'*:: :->args' && ret=0
case $state in
cmds)
_values "bundle command" \
"install[Install the gems specified by the Gemfile or Gemfile.lock]" \
"update[Update dependencies to their latest versions]" \
"package[Package the .gem files required by your application]" \
"exec[Execute a script in the context of the current bundle]" \
"config[Specify and read configuration options for bundler]" \
"check[Determine whether the requirements for your application are installed]" \
"list[Show all of the gems in the current bundle]" \
"show[Show the source location of a particular gem in the bundle]" \
"outdated[Show all of the outdated gems in the current bundle]" \
"console[Start an IRB session in the context of the current bundle]" \
"open[Open an installed gem in the editor]" \
"viz[Generate a visual representation of your dependencies]" \
"init[Generate a simple Gemfile, placed in the current directory]" \
"gem[Create a simple gem, suitable for development with bundler]" \
"platform[Displays platform compatibility information]" \
"clean[Cleans up unused gems in your bundler directory]" \
"help[Describe available tasks or one specific task]"
ret=0
;;
args)
case $line[1] in
help)
_values 'commands' \
'install' \
'update' \
'package' \
'exec' \
'config' \
'check' \
'list' \
'show' \
'outdated' \
'console' \
'open' \
'viz' \
'init' \
'gem' \
'platform' \
'help' && ret=0
;;
install)
_arguments \
'(--no-color)--no-color[disable colorization in output]' \
'(--local)--local[do not attempt to connect to rubygems.org]' \
'(--quiet)--quiet[only output warnings and errors]' \
'(--gemfile)--gemfile=-[use the specified gemfile instead of Gemfile]:gemfile' \
'(--system)--system[install to the system location]' \
'(--deployment)--deployment[install using defaults tuned for deployment environments]' \
'(--frozen)--frozen[do not allow the Gemfile.lock to be updated after this install]' \
'(--path)--path=-[specify a different path than the system default]:path:_files' \
'(--binstubs)--binstubs=-[generate bin stubs for bundled gems to ./bin]:directory:_files' \
'(--without)--without=-[exclude gems that are part of the specified named group]:groups'
ret=0
;;
exec)
_normal && ret=0
;;
clean)
_arguments \
'(--force)--force[forces clean even if --path is not set]' \
'(--dry-run)--dry-run[only print out changes, do not actually clean gems]' \
'(--no-color)--no-color[Disable colorization in output]' \
'(--verbose)--verbose[Enable verbose output mode]'
ret=0
;;
outdated)
_arguments \
'(--pre)--pre[Check for newer pre-release gems]' \
'(--source)--source[Check against a specific source]' \
'(--local)--local[Do not attempt to fetch gems remotely and use the gem cache instead]' \
'(--no-color)--no-color[Disable colorization in output]' \
'(--verbose)--verbose[Enable verbose output mode]'
ret=0
;;
(open|show)
_gems=( $(bundle show 2> /dev/null | sed -e '/^ \*/!d; s/^ \* \([^ ]*\) .*/\1/') )
if [[ $_gems != "" ]]; then
_values 'gems' $_gems && ret=0
fi
;;
*)
_opts=( $(bundle help $line[1] | sed -e '/^ \[-/!d; s/^ \[\(-[^=]*\)=.*/\1/') )
_opts+=( $(bundle help $line[1] | sed -e '/^ -/!d; s/^ \(-.\), \[\(-[^=]*\)=.*/\1 \2/') )
if [[ $_opts != "" ]]; then
_values 'options' $_opts && ret=0
fi
;;
esac
;;
esac
return ret
alias be="bundle exec"
alias bl="bundle list"
alias bp="bundle package"
alias bo="bundle open"
alias bout="bundle outdated"
alias bu="bundle update"
alias bi="bundle_install"
alias bcn="bundle clean"
bundled_commands=(
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
unicorn_rails
)
# Remove $UNBUNDLED_COMMANDS from the bundled_commands list
for cmd in $UNBUNDLED_COMMANDS; do
bundled_commands=(${bundled_commands#$cmd});
done
# Add $BUNDLED_COMMANDS to the bundled_commands list
for cmd in $BUNDLED_COMMANDS; do
bundled_commands+=($cmd);
done
## Functions
bundle_install() {
if ! _bundler-installed; then
echo "Bundler is not installed"
elif ! _within-bundled-project; then
echo "Can't 'bundle install' outside a bundled project"
else
local bundler_version=`bundle version | cut -d' ' -f3`
if [[ $bundler_version > '1.4.0' || $bundler_version = '1.4.0' ]]; then
if [[ "$OSTYPE" = (darwin|freebsd)* ]]
then
local cores_num="$(sysctl -n hw.ncpu)"
else
local cores_num="$(nproc)"
fi
bundle install --jobs=$cores_num $@
else
bundle install $@
fi
fi
}
_bundler-installed() {
which bundle > /dev/null 2>&1
}
_within-bundled-project() {
local check_dir="$PWD"
while [ "$check_dir" != "/" ]; do
[ -f "$check_dir/Gemfile" -o -f "$check_dir/gems.rb" ] && return
check_dir="$(dirname $check_dir)"
done
false
}
_binstubbed() {
[ -f "./bin/${1}" ]
}
_run-with-bundler() {
if _bundler-installed && _within-bundled-project; then
if _binstubbed $1; then
./bin/${^^@}
else
bundle exec $@
fi
else
$@
fi
}
## Main program
for cmd in $bundled_commands; do
eval "function unbundled_$cmd () { $cmd \$@ }"
eval "function bundled_$cmd () { _run-with-bundler $cmd \$@}"
alias $cmd=bundled_$cmd
if which _$cmd > /dev/null 2>&1; then
compdef _$cmd bundled_$cmd=$cmd
fi
done
# Cabal
This plugin provides completion for [Cabal](https://www.haskell.org/cabal/), a build tool for Haskell. It
also provides a function `cabal_sandbox_info` that prints whether the current working directory is in a sandbox.
To use it, add cabal to the plugins array of your zshrc file:
```
plugins=(... cabal)
```
function cabal_sandbox_info() {
cabal_files=(*.cabal(N))
if [ $#cabal_files -gt 0 ]; then
if [ -f cabal.sandbox.config ]; then
echo "%{$fg[green]%}sandboxed%{$reset_color%}"
else
echo "%{$fg[red]%}not sandboxed%{$reset_color%}"
fi
fi
}
function _cabal_commands() {
local ret=1 state
_arguments ':subcommand:->subcommand' && ret=0
case $state in
subcommand)
subcommands=(
"bench:Run the benchmark, if any (configure with UserHooks)"
"build:Compile all targets or specific target."
"check:Check the package for common mistakes"
"clean:Clean up after a build"
"copy:Copy the files into the install locations"
"configure:Prepare to build the package"
"exec:Run a command with the cabal environment"
"fetch:Downloads packages for later installation"
"freeze:Freeze dependencies."
"get:Gets a package's source code"
"haddock:Generate Haddock HTML documentation"
"help:Help about commands"
"hscolour:Generate HsColour colourised code, in HTML format"
"info:Display detailed information about a particular package"
"init:Interactively create a .cabal file"
"install:Installs a list of packages"
"list:List packages matching a search string"
"register:Register this package with the compiler"
"repl:Open an interpreter session for the given target"
"report:Upload build reports to a remote server"
"run:Runs the compiled executable"
"sandbox:Create/modify/delete a sandbox"
"sdist:Generate a source distribution file (.tar.gz)"
"test:Run the test suite, if any (configure with UserHooks)"
"unpack:Unpacks packages for user inspection"
"update:Updates list of known packages"
"upload:Uploads source packages to Hackage"
)
_describe -t subcommands 'cabal subcommands' subcommands && ret=0
esac
return ret
}
compdef _cabal_commands cabal
function _cab_commands() {
local ret=1 state
_arguments ':subcommand:->subcommand' && ret=0
case $state in
subcommand)
subcommands=(
"sync:Fetch the latest package index"
"install:Install packages"
"uninstall:Uninstall packages"
"installed:List installed packages"
"configure:Configure a cabal package"
"build:Build a cabal package"
"clean:Clean up a build directory"
"outdated:Display outdated packages"
"info:Display information of a package"
"sdist:Make tar.gz for source distribution"
"upload:Uploading tar.gz to HackageDB"
"get:Untar a package in the current directory"
"deps:Show dependencies of this package"
"revdeps:Show reverse dependencies of this package"
"check:Check consistency of packages"
"genpaths:Generate Paths_<pkg>.hs"
"search:Search available packages by package name"
"add:Add a source directory"
"test:Run tests"
"bench:Run benchmarks"
"doc:Generate manuals"
"ghci:Run GHCi (with a sandbox)"
"init:Initialize a sandbox"
"help:Display the help message of the command"
)
_describe -t subcommands 'cab subcommands' subcommands && ret=0
esac
return ret
}
command -v cab >/dev/null 2>&1 && { compdef _cab_commands cab }
# Cake
This plugin provides completion for [CakePHP](https://cakephp.org/).
To use it add cake to the plugins array in your zshrc file.
```bash
plugins=(... cake)
```
## Note
This plugin generates a cache file of the cake tasks found, named `.cake_task_cache`, in the current working directory.
It is regenerated when the Cakefile is newer than the cache file. It is advised that you add the cake file to your
`.gitignore` files.
# Set this to 1 if you want to cache the tasks
_cake_cache_task_list=1
# Cache filename
_cake_task_cache_file='.cake_task_cache'
_cake_get_target_list () {
cake | grep '^cake ' | sed -e "s/cake \([^ ]*\) .*/\1/" | grep -v '^$'
}
_cake_does_target_list_need_generating () {
if [ ${_cake_cache_task_list} -eq 0 ]; then
return 1;
fi
[ ! -f ${_cake_task_cache_file} ] && return 0;
[ Cakefile -nt ${_cake_task_cache_file} ] && return 0;
return 1;
}
_cake () {
if [ -f Cakefile ]; then
if _cake_does_target_list_need_generating; then
_cake_get_target_list > ${_cake_task_cache_file}
compadd `cat ${_cake_task_cache_file}`
else
compadd `_cake_get_target_list`
fi
fi
}
compdef _cake cake
# 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` |
# CakePHP 3 basic command completion
_cakephp3_get_command_list () {
bin/cake Completion commands
}
_cakephp3_get_sub_command_list () {
bin/cake Completion subcommands ${words[2]}
}
_cakephp3_get_3rd_argument () {
bin/cake ${words[2]} ${words[3]} | \grep '\-\ '| \awk '{print $2}'
}
_cakephp3 () {
local -a has3rdargument
has3rdargument=("all" "controller" "fixture" "model" "template")
if [ -f bin/cake ]; then
if (( CURRENT == 2 )); then
compadd $(_cakephp3_get_command_list)
fi
if (( CURRENT == 3 )); then
compadd $(_cakephp3_get_sub_command_list)
fi
if (( CURRENT == 4 )); then
if [[ ${has3rdargument[(i)${words[3]}]} -le ${#has3rdargument} ]]; then
compadd $(_cakephp3_get_3rd_argument)
fi
fi
fi
}
compdef _cakephp3 bin/cake
compdef _cakephp3 cake
#Alias
alias c3='bin/cake'
alias c3cache='bin/cake orm_cache clear'
alias c3migrate='bin/cake migrations migrate'
# Capistrano
This plugin provides completion for [Capistrano](https://capistranorb.com/).
To use it add capistrano to the plugins array in your zshrc file.
```bash
plugins=(... capistrano)
```
For a working completion use the `capit` command instead of `cap`, because cap is a
[reserved word in zsh](http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcap-Module).
`capit` automatically runs cap with bundler if a Gemfile is found.
#compdef capit
#autoload
# Added `capit` because `cap` is a reserved word. `cap` completion doesn't work.
# http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcap-Module
local curcontext="$curcontext" state line ret=1
local -a _configs
_arguments -C \
'1: :->cmds' \
'2:: :->args' && ret=0
_cap_tasks() {
if [[ -f config/deploy.rb || -f Capfile ]]; then
if [[ ! -f .cap_tasks~ ]]; then
capit --tasks | sed 's/\(\[\)\(.*\)\(\]\)/\2:/' | awk '{command=$2; $1=$2=$3=""; gsub(/^[ \t\r\n]+/, "", $0); gsub(":", "\\:", command); print command"["$0"]"}' > .cap_tasks~
fi
OLD_IFS=$IFS
IFS=$'\n'
_values 'cap commands' $(< .cap_tasks~)
IFS=$OLD_IFS
# zmodload zsh/mapfile
# _values ${(f)mapfile[.cap_tasks~]}
fi
}
_cap_stages() {
compadd $(find config/deploy -name \*.rb | cut -d/ -f3 | sed s:.rb::g)
}
case $state in
cmds)
# check if it uses multistage
if [[ -d config/deploy ]]; then
_cap_stages
else
_cap_tasks
fi
ret=0
;;
args)
_cap_tasks
ret=0
;;
esac
return ret
# Added `capit` because `cap` is a reserved word. `cap` completion doesn't work.
# http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcap-Module
function capit() {
if [ -f Gemfile ]
then
bundle exec cap $*
else
cap $*
fi
}
# cargo
This plugin adds completion for the Rust build tool [`Cargo`](https://github.com/rust-lang/cargo).
To use it, add `cargo` to the plugins array in your zshrc file:
```zsh
plugins=(... cargo)
```
Updated on March 3rd, 2019, from [Cargo 0.34.0](https://github.com/rust-lang/cargo/releases/tag/0.34.0).
# Cask plugin
[Cask](https://github.com/cask/cask) is a project management tool for Emacs that helps
automate the package development cycle; development, dependencies, testing, building,
packaging and more.
This plugin loads `cask` completion from non-standard locations, such as if installed
via Homebrew or others. To enable it, add `cask` to your plugins array:
```zsh
plugins=(... cask)
```
Make sure you have the `cask` directory in your `$PATH` before loading Oh My Zsh,
otherwise you'll get a "command not found" error.
() {
emulate -L zsh
if ! (( $+commands[cask] )); then
print "zsh cask plugin: cask command not found" >&2
return
fi
cask_base=${commands[cask]:h:h}
# Plain cask installation location (for Cask 0.7.2 and earlier)
comp_files=($cask_base/etc/cask_completion.zsh)
# Mac Homebrew installs the completion in a different location
if (( $+commands[brew] )); then
comp_files+=($(brew --prefix)/share/zsh/site-functions/cask_completion.zsh)
fi
# Load first found file
for f in $comp_files; do
if [[ -f "$f" ]]; then
source "$f"
break
fi
done
}
# catimg
Plugin for displaying images on the terminal using the the `catimg.sh` script provided by [posva](https://github.com/posva/catimg)
## Requirements
- `convert` (ImageMagick)
## Enabling the plugin
1. Open your `.zshrc` file and add `catimg` in the plugins section:
```zsh
plugins=(
# all your enabled plugins
catimg
)
```
2. Restart the shell or restart your Terminal session:
```console
$ exec zsh
$
```
## Functions
| Function | Description |
| -------- | ---------------------------------------- |
| `catimg` | Displays the given image on the terminal |
## Usage examples
[![asciicast](https://asciinema.org/a/204702.png)](https://asciinema.org/a/204702)
################################################################################
# catimg script by Eduardo San Martin Morote aka Posva #
# https://posva.net #
# #
# Ouput the content of an image to the stdout using the 256 colors of the #
# terminal. #
# GitHub: https://github.com/posva/catimg #
################################################################################
function catimg() {
if [[ -x `which convert` ]]; then
zsh $ZSH/plugins/catimg/catimg.sh $@
else
echo "catimg need convert (ImageMagick) to work)"
fi
}
################################################################################
# catimg script by Eduardo San Martin Morote aka Posva #
# https://posva.net #
# #
# Ouput the content of an image to the stdout using the 256 colors of the #
# terminal. #
# GitHub: https://github.com/posva/catimg #
################################################################################
function help() {
echo "Usage catimg [-h] [-w width] [-c char] img"
echo "By default char is \" \" and w is the terminal width"
}
# VARIABLES
COLOR_FILE=$(dirname $0)/colors.png
CHAR=" "
WIDTH=""
IMG=""
while getopts qw:c:h opt; do
case "$opt" in
w) WIDTH="$OPTARG" ;;
c) CHAR="$OPTARG" ;;
h) help; exit ;;
*) help ; exit 1;;
esac
done
while [ "$1" ]; do
IMG="$1"
shift
done
if [ "$IMG" = "" -o ! -f "$IMG" ]; then
help
exit 1
fi
if [ ! "$WIDTH" ]; then
COLS=$(expr $(tput cols) "/" $(echo -n "$CHAR" | wc -c))
else
COLS=$(expr $WIDTH "/" $(echo -n "$CHAR" | wc -c))
fi
WIDTH=$(convert "$IMG" -print "%w\n" /dev/null)
if [ "$WIDTH" -gt "$COLS" ]; then
WIDTH=$COLS
fi
REMAP=""
if convert "$IMG" -resize $COLS\> +dither -remap $COLOR_FILE /dev/null ; then
REMAP="-remap $COLOR_FILE"
else
echo "The version of convert is too old, don't expect good results :(" >&2
#convert "$IMG" -colors 256 PNG8:tmp.png
#IMG="tmp.png"
fi
# Display the image
I=0
convert "$IMG" -resize $COLS\> +dither `echo $REMAP` txt:- 2>/dev/null |
sed -e 's/.*none.*/NO NO NO/g' -e '1d;s/^.*(\(.*\)[,)].*$/\1/g;y/,/ /' |
while read R G B f; do
if [ ! "$R" = "NO" ]; then
if [ "$R" -eq "$G" -a "$G" -eq "$B" ]; then
((
I++,
IDX = 232 + R * 23 / 255
))
else
((
I++,
IDX = 16
+ R * 5 / 255 * 36
+ G * 5 / 255 * 6
+ B * 5 / 255
))
fi
#echo "$R,$G,$B: $IDX"
echo -ne "\e[48;5;${IDX}m${CHAR}"
else
(( I++ ))
echo -ne "\e[0m${CHAR}"
fi
# New lines
(( $I % $WIDTH )) || echo -e "\e[0m"
done
# Celery
This plugin provides completion for [Celery](http://www.celeryproject.org/).
To use it add celery to the plugins array in your zshrc file.
```bash
plugins=(... celery)
```
#compdef celery
#autoload
#celery zsh completion
_celery () {
local -a _1st_arguments ifargs dopts controlargs
typeset -A opt_args
_1st_arguments=('worker' 'events' 'beat' 'shell' 'multi' 'amqp' 'status' 'inspect' \
'control' 'purge' 'list' 'migrate' 'call' 'result' 'report')
ifargs=('--app=' '--broker=' '--loader=' '--config=' '--version')
dopts=('--detach' '--umask=' '--gid=' '--uid=' '--pidfile=' '--logfile=' '--loglevel=')
controlargs=('--timeout' '--destination')
_arguments \
'(-A --app=)'{-A,--app}'[app instance to use (e.g. module.attr_name):APP]' \
'(-b --broker=)'{-b,--broker}'[url to broker. default is "amqp://guest@localhost//":BROKER]' \
'(--loader)--loader[name of custom loader class to use.:LOADER]' \
'(--config)--config[Name of the configuration module:CONFIG]' \
'(--workdir)--workdir[Optional directory to change to after detaching.:WORKING_DIRECTORY]' \
'(-q --quiet)'{-q,--quiet}'[Don"t show as much output.]' \
'(-C --no-color)'{-C,--no-color}'[Don"t display colors.]' \
'(--version)--version[show program"s version number and exit]' \
'(- : *)'{-h,--help}'[show this help message and exit]' \
'*:: :->subcmds' && return 0
if (( CURRENT == 1 )); then
_describe -t commands "celery subcommand" _1st_arguments
return
fi
case "$words[1]" in
worker)
_arguments \
'(-C --concurrency=)'{-C,--concurrency=}'[Number of child processes processing the queue. The default is the number of CPUs.]' \
'(--pool)--pool=:::(processes eventlet gevent threads solo)' \
'(--purge --discard)'{--discard,--purge}'[Purges all waiting tasks before the daemon is started.]' \
'(-f --logfile=)'{-f,--logfile=}'[Path to log file. If no logfile is specified, stderr is used.]' \
'(--loglevel=)--loglevel=:::(critical error warning info debug)' \
'(-N --hostname=)'{-N,--hostname=}'[Set custom hostname, e.g. "foo.example.com".]' \
'(-B --beat)'{-B,--beat}'[Also run the celerybeat periodic task scheduler.]' \
'(-s --schedule=)'{-s,--schedule=}'[Path to the schedule database if running with the -B option. Defaults to celerybeat-schedule.]' \
'(-S --statedb=)'{-S,--statedb=}'[Path to the state database.Default: None]' \
'(-E --events)'{-E,--events}'[Send events that can be captured by monitors like celeryev, celerymon, and others.]' \
'(--time-limit=)--time-limit=[nables a hard time limit (in seconds int/float) for tasks]' \
'(--soft-time-limit=)--soft-time-limit=[Enables a soft time limit (in seconds int/float) for tasks]' \
'(--maxtasksperchild=)--maxtasksperchild=[Maximum number of tasks a pool worker can execute before it"s terminated and replaced by a new worker.]' \
'(-Q --queues=)'{-Q,--queues=}'[List of queues to enable for this worker, separated by comma. By default all configured queues are enabled.]' \
'(-I --include=)'{-I,--include=}'[Comma separated list of additional modules to import.]' \
'(--pidfile=)--pidfile=[Optional file used to store the process pid.]' \
'(--autoscale=)--autoscale=[Enable autoscaling by providing max_concurrency, min_concurrency.]' \
'(--autoreload)--autoreload[Enable autoreloading.]' \
'(--no-execv)--no-execv[Don"t do execv after multiprocessing child fork.]'
compadd -a ifargs
;;
inspect)
_values -s \
'active[dump active tasks (being processed)]' \
'active_queues[dump queues being consumed from]' \
'ping[ping worker(s)]' \
'registered[dump of registered tasks]' \
'report[get bugreport info]' \
'reserved[dump reserved tasks (waiting to be processed)]' \
'revoked[dump of revoked task ids]' \
'scheduled[dump scheduled tasks (eta/countdown/retry)]' \
'stats[dump worker statistics]'
compadd -a controlargs ifargs
;;
control)
_values -s \
'add_consumer[tell worker(s) to start consuming a queue]' \
'autoscale[change autoscale settings]' \
'cancel_consumer[tell worker(s) to stop consuming a queue]' \
'disable_events[tell worker(s) to disable events]' \
'enable_events[tell worker(s) to enable events]' \
'pool_grow[start more pool processes]' \
'pool_shrink[use less pool processes]' \
'rate_limit[tell worker(s) to modify the rate limit for a task type]' \
'time_limit[tell worker(s) to modify the time limit for a task type.]'
compadd -a controlargs ifargs
;;
multi)
_values -s \
'--nosplash[Don"t display program info.]' \
'--verbose[Show more output.]' \
'--no-color[Don"t display colors.]' \
'--quiet[Don"t show as much output.]' \
'start' 'restart' 'stopwait' 'stop' 'show' \
'names' 'expand' 'get' 'kill'
compadd -a ifargs
;;
amqp)
_values -s \
'queue.declare' 'queue.purge' 'exchange.delete' 'basic.publish' \
'exchange.declare' 'queue.delete' 'queue.bind' 'basic.get'
;;
list)
_values -s, 'bindings'
;;
shell)
_values -s \
'--ipython[force iPython.]' \
'--bpython[force bpython.]' \
'--python[force default Python shell.]' \
'--without-tasks[don"t add tasks to locals.]' \
'--eventlet[use eventlet.]' \
'--gevent[use gevent.]'
compadd -a ifargs
;;
beat)
_arguments \
'(-s --schedule=)'{-s,--schedule=}'[Path to the schedule database. Defaults to celerybeat-schedule.]' \
'(-S --scheduler=)'{-S,--scheduler=}'[Scheduler class to use. Default is celery.beat.PersistentScheduler.]' \
'(--max-interval)--max-interval[]'
compadd -a dopts fargs
;;
events)
_arguments \
'(-d --dump)'{-d,--dump}'[Dump events to stdout.]' \
'(-c --camera=)'{-c,--camera=}'[Take snapshots of events using this camera.]' \
'(-F --frequency=)'{-F,--frequency=}'[Camera: Shutter frequency. Default is every 1.0 seconds.]' \
'(-r --maxrate=)'{-r,--maxrate=}'[Camera: Optional shutter rate limit (e.g. 10/m).]'
compadd -a dopts fargs
;;
*)
;;
esac
}
# 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
```
#
# INSTRUCTIONS
#
# With either a manual or brew installed chruby things should just work.
#
# 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
#
# TODO
# - autodetermine correct source path on non OS X systems
# - completion if ruby-install exists
# rvm and rbenv plugins also provide this alias
alias rubies='chruby'
_homebrew-installed() {
whence brew &> /dev/null
_xit=$?
if [ $_xit -eq 0 ];then
# ok , we have brew installed
# speculatively we check default brew prefix
if [ -h /usr/local/opt/chruby ];then
_brew_prefix="/usr/local/opt/chruby"
else
# ok , it is not default prefix
# this call to brew is expensive ( about 400 ms ), so at least let's make it only once
_brew_prefix=$(brew --prefix chruby)
fi
return 0
else
return $_xit
fi
}
_chruby-from-homebrew-installed() {
[ -r _brew_prefix ] &> /dev/null
}
_ruby-build_installed() {
whence ruby-build &> /dev/null
}
_ruby-install-installed() {
whence ruby-install &> /dev/null
}
# Simple definition completer for ruby-build
if _ruby-build_installed; then
_ruby-build() { compadd $(ruby-build --definitions) }
compdef _ruby-build ruby-build
fi
_source_from_omz_settings() {
local _chruby_path
local _chruby_auto
zstyle -s :omz:plugins:chruby path _chruby_path
zstyle -s :omz:plugins:chruby auto _chruby_auto
if [[ -r ${_chruby_path} ]]; then
source ${_chruby_path}
fi
if [[ -r ${_chruby_auto} ]]; then
source ${_chruby_auto}
fi
}
_chruby_dirs() {
chrubydirs=($HOME/.rubies/ $PREFIX/opt/rubies)
for dir in chrubydirs; do
if [[ -d $dir ]]; then
RUBIES+=$dir
fi
done
}
if _homebrew-installed && _chruby-from-homebrew-installed ; then
source $_brew_prefix/share/chruby/chruby.sh
source $_brew_prefix/share/chruby/auto.sh
_chruby_dirs
elif [[ -r "/usr/local/share/chruby/chruby.sh" ]] ; then
source /usr/local/share/chruby/chruby.sh
source /usr/local/share/chruby/auto.sh
_chruby_dirs
else
_source_from_omz_settings
_chruby_dirs
fi
function ensure_chruby() {
$(whence chruby)
}
function current_ruby() {
local _ruby
_ruby="$(chruby |grep \* |tr -d '* ')"
if [[ $(chruby |grep -c \*) -eq 1 ]]; then
echo ${_ruby}
else
echo "system"
fi
}
function chruby_prompt_info() {
echo "$(current_ruby)"
}
# complete on installed rubies
_chruby() {
compadd $(chruby | tr -d '* ')
local default_path='/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin'
if PATH=${default_path} type ruby &> /dev/null; then
compadd system
fi
}
compdef _chruby chruby
fortunes/chucknorris.dat
# chucknorris
Chuck Norris fortunes plugin for oh-my-zsh
**Maintainers**: [apjanke](https://github.com/apjanke) [maff](https://github.com/maff)
To use it add `chucknorris` to the plugins array in you zshrc file.
```zsh
plugins=(... chucknorris)
```
Depends on fortune (and cowsay if using chuck_cow) being installed (available via homebrew, apt, ...). Perfectly suitable as MOTD.
| Command | Description |
| ----------- | ------------------------------- |
| `chuck` | Print random Chuck Norris quote |
| `chuck_cow` | Print quote in cowthink |
# chucknorris: Chuck Norris fortunes
# Automatically generate or update Chuck's compiled fortune data file
# $0 must be used outside a local function. This variable name is unlikly to collide.
CHUCKNORRIS_PLUGIN_DIR=${0:h}
() {
local DIR=$CHUCKNORRIS_PLUGIN_DIR/fortunes
if [[ ! -f $DIR/chucknorris.dat ]] || [[ $DIR/chucknorris.dat -ot $DIR/chucknorris ]]; then
# For some reason, Cygwin puts strfile in /usr/sbin, which is not on the path by default
local strfile=strfile
if ! which strfile &>/dev/null && [[ -f /usr/sbin/strfile ]]; then
strfile=/usr/sbin/strfile
fi
if which $strfile &> /dev/null; then
$strfile $DIR/chucknorris $DIR/chucknorris.dat >/dev/null
else
echo "[oh-my-zsh] chucknorris depends on strfile, which is not installed" >&2
echo "[oh-my-zsh] strfile is often provided as part of the 'fortune' package" >&2
fi
fi
# Aliases
alias chuck="fortune -a $DIR"
alias chuck_cow="chuck | cowthink"
}
unset CHUCKNORRIS_PLUGIN_DIR
This source diff could not be displayed because it is too large. You can view the blob instead.
# 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 <filename>`: uploads `<filename>` to your CloudApp account, and if you're using
macOS, copies the URL to your clipboard.
alias cloudapp="${0:a:h}/cloudapp.rb"
# Ensure only the owner can access the credentials file
if [[ -f ~/.cloudapp ]]; then
chmod 600 ~/.cloudapp
fi
#!/usr/bin/env ruby
#
# cloudapp
# Zach Holman / @holman
#
# Uploads a file from the command line to CloudApp, drops it into your
# clipboard (on a Mac, at least).
#
# Example:
#
# cloudapp drunk-blake.png
#
# This requires Aaron Russell's cloudapp_api gem:
#
# gem install cloudapp_api
#
# Requires you set your CloudApp credentials in ~/.cloudapp as a simple file of:
#
# email
# password
require 'rubygems'
begin
require 'cloudapp_api'
rescue LoadError
puts "You need to install cloudapp_api: gem install cloudapp_api"
exit!(1)
end
config_file = "#{ENV['HOME']}/.cloudapp"
unless File.exist?(config_file)
puts "You need to type your email and password (one per line) into "+
"`~/.cloudapp`"
exit!(1)
end
email,password = File.read(config_file).split("\n")
class HTTParty::Response
# Apparently HTTPOK.ok? IS NOT OKAY WTFFFFFFFFFFUUUUUUUUUUUUUU
# LETS MONKEY PATCH IT I FEEL OKAY ABOUT IT
def ok? ; true end
end
if ARGV[0].nil?
puts "You need to specify a file to upload."
exit!(1)
end
CloudApp.authenticate(email,password)
url = CloudApp::Item.create(:upload, {:file => ARGV[0]}).url
# Say it for good measure.
puts "Uploaded to #{url}."
# Get the embed link.
url = "#{url}/#{ARGV[0].split('/').last}"
# Copy it to your (Mac's) clipboard.
`echo '#{url}' | tr -d "\n" | pbcopy`
# Cloudfoundry Plugin
This plugin is intended to offer a few simple aliases for regular users of the [Cloud Foundry Cli][1]. Most are just simple aliases that will save a bit of typing. Others include mini functions and or accept parameters. Take a look at the table below for details.
| Alias | Command | Description |
|----------|-----------------------------|--------------------------------------------------------------------------|
| cfl | `cf login` | Login to Cloud Foundry |
| cft | `cf target` | Target the cli at a specific Org/Space in Cloud Foundry |
| cfa | `cf apps` | List all applications in the current Org/Space |
| cfs | `cf services` | List all services in the current Org/Space |
| cfm | `cf marketplace` | List the services available in the Marketplace |
| cfp | `cf push` | Push your application code to Cloud Foundry |
| cfcs | `cf create-service` | Create a service based on a Marketplace offering |
| cfbs | `cf bind-service` | Bind an application to a service you created |
| cfus | `cf unbind-service` | Unbind a service from an application |
| cfds | `cf delete-service` | Delete a service you no longer have bound |
| cfup | `cf cups` | Create a "user-provided-service" |
| cflg | `cf logs` | Tail the logs of an application (requires <APP_NAME>) |
| cfr | `cf routes` | List all the routes in the current Space |
| cfe | `cf env` | Show the environment variables for an application (requires <APP_NAME>) |
| cfsh | `cf ssh` | Attach to a running container (requires an <APP_NAME> etc.) |
| cfsc | `cf scale` | Scale an application (requires an <APP_NAME> etc.) |
| cfev | `cf events` | Show the application events (requires <APP_NAME>) |
| cfdor | `cf delete-orphaned-routes` | Delete routes that are no longer bound to applications |
| cfbpk | `cf buildpacks` | List the available buildpacks |
| cfdm | `cf domains` | List the domains associates with this Cloud Foundry foundation |
| cfsp | `cf spaces` | List all the Spaces in the current Org |
| cfap | `cf app` | Show the details of a deployed application (requires <APP_NAME>) |
| cfh. | `export CF_HOME=$PWD/.cf` | Set the current directory as CF_HOME |
| cfh~ | `export CF_HOME=~/.cf` | Set the user's root directory as CF_HOME |
| cfhu | `unset CF_HOME` | Unsets CF_HOME |
| cfpm | `cf push -f` | Push an application using a manifest (requires <MANIFEST_FILE> location) |
| cflr | `cf logs --recent` | Show the recent logs (requires <APP_NAME>) |
| cfsrt | `cf start` | Start an application (requires <APP_NAME>) |
| cfstp | `cf stop` | Stop an application (requires <APP_NAME>) |
| cfstg | `cf restage` | Restage an application (requires <APP_NAME>) |
| cfdel | `cf delete` | Delete an application (requires <APP_NAME>) |
| cfsrtall | - | Start all apps that are currently in the "Stopped" state |
| cfstpall | - | Stop all apps that are currently in the "Started" state |
For help and advice on what any of the commands does, consult the built in `cf` help functions as follows:-
```bash
cf help # List the most popular and commonly used commands
cf help -a # Complete list of all possible commands
cf <COMMAND_NAME> --help # Help on a specific command including arguments and examples
```
Alternatively, seek out the [online documentation][3]. And don't forget, there are loads of great [community plugins for the cf-cli][4] command line tool that can greatly extend its power and usefulness.
## Contributors
Contributed to `oh_my_zsh` by [benwilcock][2].
[1]: https://docs.cloudfoundry.org/cf-cli/install-go-cli.html
[2]: https://github.com/benwilcock
[3]: https://docs.cloudfoundry.org/cf-cli/getting-started.html
[4]: https://plugins.cloudfoundry.org/
# Some Useful CloudFoundry Aliases & Functions
alias cfl="cf login"
alias cft="cf target"
alias cfa="cf apps"
alias cfs="cf services"
alias cfm="cf marketplace"
alias cfp="cf push"
alias cfcs="cf create-service"
alias cfbs="cf bind-service"
alias cfus="cf unbind-service"
alias cfds="cf delete-service"
alias cfup="cf cups"
alias cflg="cf logs"
alias cfr="cf routes"
alias cfe="cf env"
alias cfsh="cf ssh"
alias cfsc="cf scale"
alias cfev="cf events"
alias cfdor="cf delete-orphaned-routes"
alias cfbpk="cf buildpacks"
alias cfdm="cf domains"
alias cfsp="cf spaces"
function cfap() { cf app $1 }
function cfh.() { export CF_HOME=$PWD/.cf }
function cfh~() { export CF_HOME=~/.cf }
function cfhu() { unset CF_HOME }
function cfpm() { cf push -f $1 }
function cflr() { cf logs $1 --recent }
function cfsrt() { cf start $1 }
function cfstp() { cf stop $1 }
function cfstg() { cf restage $1 }
function cfdel() { cf delete $1 }
function cfsrtall() {cf apps | awk '/stopped/ { system("cf start " $1)}'}
function cfstpall() {cf apps | awk '/started/ { system("cf stop " $1)}'}
# 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)
```
#compdef codeclimate
_codeclimate_all_engines() {
engines_all=(`codeclimate engines:list | tail -n +2 | gawk '{ print $2 }' | gawk -F: '{ print $1 }'`)
}
_codeclimate_installed_engines() {
_codeclimate_all_engines
engines_installed=()
if [ -e .codeclimate.yml ]
then
for engine in $engines_all
do
if grep -q $engine ".codeclimate.yml"
then
engines_installed+=$engine
fi
done
fi
}
_codeclimate_not_installed_engines() {
_codeclimate_all_engines
engines_not_installed=()
if [ -e .codeclimate.yml ]
then
for engine in $engines_all
do
if ! grep -q $engine ".codeclimate.yml"
then
engines_not_installed+=$engine
fi
done
fi
}
local curcontext="$curcontext" state line ret=1
local expl
local -a engines_all engines_installed engines_not_installed
_arguments \
'1: :->cmds' \
'*:: :->args' && ret=0
case $state in
cmds)
_values "bundle command" \
"analyze[Analyze all relevant files in the current working directory]" \
"console[Start an interactive session providing access to the classes within the CLI]" \
"engines\:disable[Prevents the engine from being used in this project]" \
"engines\:enable[This engine will be run the next time your project is analyzed]" \
"engines\:install[Compares the list of engines in your .codeclimate.yml file to those that are currently installed, then installs any missing engines]" \
"engines\:list[Lists all available engines in the Code Climate Docker Hub]" \
"engines\:remove[Removes an engine from your .codeclimate.yml file]" \
"help[Displays a list of commands that can be passed to the Code Climate CLI]" \
"init[Generates a new .codeclimate.yml file in the current working directory]" \
"validate-config[Validates the .codeclimate.yml file in the current working directory]" \
"version[Displays the current version of the Code Climate CLI]"
ret=0
;;
args)
case $line[1] in
engines:enable)
_codeclimate_not_installed_engines
_wanted engines_not_installed expl 'not installed engines' compadd -a engines_not_installed ;;
engines:disable|engines:remove)
_codeclimate_installed_engines
_wanted engines_installed expl 'installed engines' compadd -a engines_installed ;;
analyze)
_arguments \
'-f:Output Format:(text json)'
ret=0
;;
esac
;;
esac
return ret
## Coffeescript Plugin
This plugin provides aliases for quickly compiling and previewing your
coffeescript code.
When writing Coffeescript it's very common to want to preview the output of a
certain snippet of code, either because you want to test the output or because
you'd like to execute it in a browser console which doesn't accept Coffeescript.
Preview the compiled result of your coffeescript with `cf "code"` as per the
following:
```zsh
$ cf 'if a then b else c'
if (a) {
b;
} else {
c;
}
```
Also provides the following aliases:
* **cfc:** Copies the compiled JS to your clipboard. Very useful when you want
to run the code in a JS console.
* **cfp:** Compiles from your currently copied clipboard. Useful when you want
to compile large/multi-line snippets
* **cfpc:** Paste coffeescript from clipboard, compile to JS, then copy the
the result back to clipboard.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论