Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • rspencer/awit-zsh-superawesome
1 result
Show changes
Showing
with 0 additions and 1698 deletions
# rake-fast
Fast rake autocompletion plugin.
This script caches the output for later usage and significantly speeds it up. It generates a .rake_tasks cache file in parallel to the Rakefile. It also checks the file modification dates to see if it needs to regenerate the cache file.
This is entirely based on [this pull request by Ullrich Schäfer](https://github.com/robb/.dotfiles/pull/10/), which is inspired by [this Ruby on Rails trick from 2006](http://weblog.rubyonrails.org/2006/3/9/fast-rake-task-completion-for-zsh/).
Think about that. 2006.
## Installation
Just add the plugin to your `.zshrc`:
```bash
plugins=(foo bar rake-fast)
```
You might consider adding `.rake_tasks` to your [global .gitignore](https://help.github.com/articles/ignoring-files#global-gitignore)
## Usage
`rake`, then press tab
_rake_refresh () {
if [ -f .rake_tasks ]; then
rm .rake_tasks
fi
echo "Generating .rake_tasks..." > /dev/stderr
_rake_generate
cat .rake_tasks
}
_rake_does_task_list_need_generating () {
if [ ! -f .rake_tasks ]; then return 0;
else
if [[ "$OSTYPE" = darwin* ]]; then
accurate=$(stat -f%m .rake_tasks)
changed=$(stat -f%m Rakefile)
else
accurate=$(stat -c%Y .rake_tasks)
changed=$(stat -c%Y Rakefile)
fi
return $(expr $accurate '>=' $changed)
fi
}
_rake_generate () {
rake --silent --tasks | cut -d " " -f 2 > .rake_tasks
}
_rake () {
if [ -f Rakefile ]; then
if _rake_does_task_list_need_generating; then
echo "\nGenerating .rake_tasks..." > /dev/stderr
_rake_generate
fi
compadd `cat .rake_tasks`
fi
}
compdef _rake rake
alias rake_refresh='_rake_refresh'
# Thank you Jim for everything you contributed to the Ruby and open source community
# over the years. We will miss you dearly.
alias jimweirich="rake"
alias rake="noglob rake" # allows square brackts for rake task invocation
alias brake='noglob bundle exec rake' # execute the bundled rake gem
alias srake='noglob sudo rake' # noglob must come before sudo
alias sbrake='noglob sudo bundle exec rake' # altogether now ...
# Get a random quote fron the site http://www.quotationspage.com/random.php3
# Created by Eduardo San Martin Morote aka Posva
# http://posva.github.io
# Sun Jun 09 10:59:36 CEST 2013
# Don't remove this header, thank you
# Usage: quote
WHO_COLOR="\e[0;33m"
TEXT_COLOR="\e[0;35m"
COLON_COLOR="\e[0;35m"
END_COLOR="\e[m"
if [[ -x `which curl` ]]; then
function quote()
{
Q=$(curl -s --connect-timeout 2 "http://www.quotationspage.com/random.php3" | iconv -c -f ISO-8859-1 -t UTF-8 | grep -m 1 "dt ")
TXT=$(echo "$Q" | sed -e 's/<\/dt>.*//g' -e 's/.*html//g' -e 's/^[^a-zA-Z]*//' -e 's/<\/a..*$//g')
W=$(echo "$Q" | sed -e 's/.*\/quotes\///g' -e 's/<.*//g' -e 's/.*">//g')
if [ "$W" -a "$TXT" ]; then
echo "${WHO_COLOR}${W}${COLON_COLOR}: ${TEXT_COLOR}${TXT}${END_COLOR}"
else
quote
fi
}
#quote
else
echo "rand-quote plugin needs curl to work" >&2
fi
_homebrew-installed() {
type brew &> /dev/null
}
_rbenv-from-homebrew-installed() {
brew --prefix rbenv &> /dev/null
}
FOUND_RBENV=0
rbenvdirs=("$HOME/.rbenv" "/usr/local/rbenv" "/opt/rbenv" "/usr/local/opt/rbenv")
if _homebrew-installed && _rbenv-from-homebrew-installed ; then
rbenvdirs=($(brew --prefix rbenv) "${rbenvdirs[@]}")
fi
for rbenvdir in "${rbenvdirs[@]}" ; do
if [ -d $rbenvdir/bin -a $FOUND_RBENV -eq 0 ] ; then
FOUND_RBENV=1
if [[ $RBENV_ROOT = '' ]]; then
RBENV_ROOT=$rbenvdir
fi
export RBENV_ROOT
export PATH=${rbenvdir}/bin:$PATH
eval "$(rbenv init --no-rehash - zsh)"
alias rubies="rbenv versions"
alias gemsets="rbenv gemset list"
function current_ruby() {
echo "$(rbenv version-name)"
}
function current_gemset() {
echo "$(rbenv gemset active 2&>/dev/null | sed -e ":a" -e '$ s/\n/+/gp;N;b a' | head -n1)"
}
function gems {
local rbenv_path=$(rbenv prefix)
gem list $@ | sed -E \
-e "s/\([0-9a-z, \.]+( .+)?\)/$fg[blue]&$reset_color/g" \
-e "s|$(echo $rbenv_path)|$fg[magenta]\$rbenv_path$reset_color|g" \
-e "s/$current_ruby@global/$fg[yellow]&$reset_color/g" \
-e "s/$current_ruby$current_gemset$/$fg[green]&$reset_color/g"
}
function rbenv_prompt_info() {
if [[ -n $(current_gemset) ]] ; then
echo "$(current_ruby)@$(current_gemset)"
else
echo "$(current_ruby)"
fi
}
fi
done
unset rbenvdir
if [ $FOUND_RBENV -eq 0 ] ; then
alias rubies='ruby -v'
function gemsets() { echo 'not supported' }
function rbenv_prompt_info() { echo "system: $(ruby -v | cut -f-2 -d ' ')" }
fi
# Enables rbfu with --auto option, if available.
#
# Also provides a command to list all installed/available
# rubies. To ensure compatibility with themes, creates the
# rvm_prompt_info function to return the $RBFU_RUBY_VERSION
# version.
command -v rbfu &>/dev/null
if [[ $? -eq 0 ]]; then
eval "$(rbfu --init --auto)"
# Internal: Print ruby version details, if it's currently
# active etc.
function _rbfu_rubies_print() {
local rb rb_out
rb=$(basename $1)
rb_out="$rb"
[[ -h $1 ]] && rb_out="$rb_out${fg[green]}@${reset_color}"
[[ "x$rb" == "x$2" ]] && rb_out="${fg[red]}$rb_out ${fg[red]}*${reset_color}"
echo $rb_out
}
# Public: Provide a list with all available rubies, this basically depends
# on `ls -1` and .rfbu/rubies. Highlights the currently active ruby version
# and aliases.
function rbfu-rubies() {
local rbfu_dir active_rb
rbfu_dir=$RBFU_RUBIES
active_rb=$RBFU_RUBY_VERSION
[[ -z "$rbfu_dir" ]] && rbfu_dir="${HOME}/.rbfu/rubies"
[[ -z "$active_rb" ]] && active_rb="system"
_rbfu_rubies_print "${rbfu_dir}/system" $active_rb
for rb in $(ls -1 $rbfu_dir); do
_rbfu_rubies_print "${rbfu_dir}/${rb}" $active_rb
done
}
# Public: Create rvm_prompt_info command for themes compatibility, unless
# it has already been defined.
[ ! -x rvm_prompt_info ] && function rvm_prompt_info() { echo "${RBFU_RUBY_VERSION:=system}" }
fi
#compdef rebar
local curcontext=$curcontext state ret=1
typeset -ga _rebar_global_opts
_rebar_global_opts=(
'(--help -h)'{--help,-h}'[Show the program options]'
'(--commands -c)'{--commands,-c}'[Show available commands]'
'(--version -V)'{--version,-V}'[Show version information]'
'(-vvv -vv -v)'--verbose+'[Verbosity level. Default: 0]:verbosity level:(0 1 2 3)'
'(-vvv)-v[Slightly more verbose output]'
'(-vvv)-vv[More verbose output]'
'(-v -vv)-vvv[Most verbose output]'
'(--force -f)'{--force,-f}'[Force]'
'-D+[Define compiler macro]'
'(--jobs -j)'{--jobs+,-j+}'[Number of concurrent workers a command may use. Default: 3]:workers:(1 2 3 4 5 6 7 8 9)'
'(--config -C)'{--config,-C}'[Rebar config file to use]:files:_files'
'(--profile -p)'{--profile,-p}'[Profile this run of rebar]'
'(--keep-going -k)'{--keep-going,-k}'[Keep running after a command fails]'
)
_rebar () {
_arguments -C $_rebar_global_opts \
'*::command and variable:->cmd_and_var' \
&& return
case $state in
cmd_and_var)
_values -S = 'variables' \
'clean[Clean]' \
'compile[Compile sources]' \
'create[Create skel based on template and vars]' \
'create-app[Create simple app skel]' \
'create-node[Create simple node skel]' \
'list-template[List avaiavle templates]' \
'doc[Generate Erlang program documentation]' \
'check-deps[Display to be fetched dependencies]' \
'get-deps[Fetch dependencies]' \
'update-deps[Update fetched dependencies]' \
'delete-deps[Delete fetched dependencies]' \
'list-deps[List dependencies]' \
'generate[Build release with reltool]' \
'overlay[Run reltool overlays only]' \
'generate-appups[Generate appup files]' \
'generate-upgrade[Build an upgrade package]' \
'eunit[Run eunit tests]' \
'ct[Run common_test suites]' \
'qc[Test QuickCheck properties]' \
'xref[Run cross reference analysis]' \
'help[Show the program options]' \
'version[Show version information]' \
'apps[Application names to process]:' \
'case[Common Test case]:' \
'dump_spec[Dump reltool spec]:' \
'jobs[Number of workers]::workers:(0 1 2 3 4 5 6 7 8 9)' \
'suites[Common Test suites]::suite name:_path_files -W "(src test)" -g "*.erl(:r)"' \
'verbose[Verbosity level]::verbosity level:(0 1 2 3)' \
'appid[Application id]:' \
'previous_release[Previous release path]:' \
'nodeid[Node id]:' \
'root_dir[Reltool config root directory]::directory:_files -/' \
'skip_deps[Skip deps]::flag:(true false)' \
'skip_apps[Application names to not process]::flag:(true false)' \
'template[Template name]:' \
'template_dir[Template directory]::directory:_files -/' \
&& ret=0
;;
esac
}
_rebar
# Local variables:
# mode: shell-script
# sh-basic-offset: 2
# sh-indent-comment: t
# indent-tabs-mode: nil
# End:
# ex: sw=2 ts=2 et filetype=sh
#compdef redis-cli rec
#autoload
#redis cli completion, based off homebrew completion (ref. 2011-04-14)
local -a _1st_arguments
_1st_arguments=(
'append:append a value to a key'
'auth:authenticate to the server'
'bgrewriteeaof:asynchronously rewrite the append-only file'
'bgsave:asynchornously save the dataset to disk'
'blpop:remove and get the first element in a list, or block until one is available'
'brpop:remove and get the last element in a list, or block until one is available'
'brpoplpush:pop a value from a list, push it to another list and return it; or block until one is available'
# 'config get:get the value of a configuration parameter'
# 'config set:set a configuration parameter to the given value'
# 'config resetstat: reset the stats returned by INFO'
'dbsize:return the number of keys in the selected database'
# 'debug object:get debugging information about a key'
# 'debug setgfault:make the server crash'
'decr:decrement the integer value of a key by one'
'decrby:decrement the integet value of a key by the given number'
'del:delete a key'
'discard:discard all commands issued after MULTI'
'echo:echo the given string'
'exec:execute all commands issued after a MULTI'
'exists:determine if a key exists'
'expire:set the time to live for a key, in seconds'
'expireat:set the expiration for a key as a UNIX timestamp'
'flushall:remove all keys from all databases'
'flushdb:remove all keys from the current database'
'get:get the value of a key'
'getbit:returns the bit value at offset in the string value stored at key'
'getrange:get a substring of the string stored at a key'
'getset:set the string value of a key and return its old value'
'hdel:delete a hash field'
'hexists:determine if a hash field exists'
'hget:get the value of a hash field'
'hgetall:get all the fields and values in a hash'
'hincrby:increment the integer value of a hash field by the given number'
'hkeys:get all the fields in a hash'
'hlen:get the number of fields in a hash'
'hmget:get the values of all the given hash fields'
'hmset:set multiple hash fields to multiple values'
'hset:set the string value of a hash field'
'hsetnx:set the value of a hash field, only if the field does not exist'
'hvals:get all the values in a hash'
'incr:increment the integer value of a key by one'
'incrby:increment the integer value of a key by the given number'
'info:get information and statistics about the server'
'keys:find all keys matching the given pattern'
'lastsave:get the UNIX timestamp of the last successful save to disk'
'lindex:get an element from a list by its index'
'linsert:insert an element before or after another element in a list'
'llen:get the length of a list'
'lpop:remove and get the first element in a list'
'lpush:prepend a value to a list'
'lpushx:prepend a value to a list, only if the list exists'
'lrange:get a range of elements from a list'
'lrem:remove elements from a list'
'lset:set the value of an element in a list by its index'
'ltrim:trim a list to the specified range'
'mget:get the values of all the given keys'
'monitor:listen for all requests received by the server in real time'
'move:move a key to another database'
'mset:set multiple keys to muliple values'
'msetnx:set multiple keys tom ultiple values, only if none of the keys exist'
'multi:mark the start of a transaction block'
'object:inspect the internals of Redis objects'
'persist:remove the expiration from a key'
'ping:ping the server'
'psubscribe:listen for messages published to channels matching the given patterns'
'publish:post a message to a channel'
'punsubscribe:stop listening for messages posted to channels matching the given patterns'
'quit:close the connection'
'randomkey:return a random key from the keyspace'
'rename:rename a key'
'renamenx:rename a key, only if the new key does not exist'
'rpop:remove and get the last element in a list'
'rpoplpush:remove the last element in a list, append it to another list and return it'
'rpush:append a value to a list'
'rpushx:append a value to a list, only if the list exists'
'sadd:add a member to a set'
'save:synchronously save the dataset to disk'
'scard:get the number of members in a set'
'sdiff:subtract multiple sets'
'sdiffstore:subtract multiple sets and store the resulting set in a key'
'select:change the selected database for the current connection'
'set:set the string value of a key'
'setbit:sets or clears the bit at offset in the string value stored at key'
'setex:set the value and expiration of a key'
'setnx:set the value of a key, only if the key does not exist'
'setrange:overwrite part of a string at key starting at the specified offset'
'shutdown:synchronously save the dataset to disk and then shut down the server'
'sinter:intersect multiple sets'
'sinterstore:intersect multiple sets and store the resulting set in a key'
'sismember:determine if a given value is a member of a set'
'slaveof:make the server a slave of another instance, or promote it as master'
'smembers:get all the members in a set'
'smove:move a member from one set to another'
'sort:sort the elements in a list, set or sorted set'
'spop:remove and return a random member from a set'
'srandmember:get a random member from a set'
'srem:remove a member from a set'
'strlen:get the length of the value stored in a key'
'subscribe:listen for messages published to the given channels'
'sunion:add multiple sets'
'sunionstore:add multiple sets and store the resulting set in a key'
'ttl:get the time to live for a key'
'type:determine the type stored at key'
'unsubscribe:stop listening for messages posted to the given channels'
'unwatch:forget about all watched keys'
'watch:watch the given keys to determine execution of the MULTI/EXEC block'
'zadd:add a member to a sorted set, or update its score if it already exists'
'zcard:get the number of members in a sorted set'
'zcount:count the members in a sorted set with scores within the given values'
'zincrby:increment the score of a member in a sorted set'
'zinterstore:intersect multiple sorted sets and store the resulting sorted set in a new key'
'zrange:return a range of members in a sorted set, by index'
'zrangebyscore:return a range of members in a sorted set, by score'
'zrank:determine the index of a member in a sorted set'
'zrem:remove a member from a sorted set'
'zremrangebyrank:remove all members in a sorted set within the given indexes'
'zremrangebyscore:remove all members in a sorted set within the given scores'
'zrevrange:return a range of membrs in a sorted set, by index, with scores ordered from high to low'
'zrevrangebyscore:return a range of members in a sorted set, by score, with scores ordered from high to low'
'zrevrank:determine the index of a member in a sorted set, with scores ordered from high to low'
'zscore:get the score associated with the given member in a sorted set'
'zunionstore:add multiple sorted sets and store te resulting sorted set in a new key'
)
local expl
_arguments \
'(-v --version)'{-v,--version}'[show version]' \
'(-h --help)'{-h,--help}'[show help]' \
'*:: :->subcmds' && return 0
if (( CURRENT == 1 )); then
_describe -t commands "redis-cli subcommand" _1st_arguments
return
fi
\ No newline at end of file
## repo
**Maintainer:** [Stibbons](https://github.com/Stibbons)
This plugin mainly add support automatic completion for the repo command line tool:
http://code.google.com/p/git-repo/
* `r` aliases `repo`
#compdef repo
__git_apply_whitespace_strategies ()
{
declare -a strategies
strategies=(
'nowarn:turn off the trailing-whitespace warning'
'warn:output trailing-whitespace warning, but apply patch'
'fix:output trailing-whitespace warning and strip trailing whitespace'
'error:output trailing-whitespace warning and refuse to apply patch'
'error-all:same as "error", but output warnings for all files')
_describe -t strategies 'trailing-whitespace resolution strategy' strategies $*
}
_repo()
{
local context state state_descr line curcontext="$curcontext"
typeset -A opt_args
local ret=1
_arguments -C \
'(- 1 *)--help[show usage]'\
'1:command:->command'\
'*::args:->args' && ret=0
case $state in
(command)
repo list 2> /dev/null > /dev/null
if [[ $? == 0 ]]; then
local commands;
commands=(
'abandon:Permanently abandon a development branch'
'branch:View current topic branches'
'branches:View current topic branches'
'checkout:Checkout a branch for development'
'cherry-pick:Cherry-pick a change.'
'diff:Show changes between commit and working tree'
'download:Download and checkout a change'
'forall:execute command on several project'
'grep:Print lines matching a pattern'
'help:Display detailed help on a command'
'init:Initialize repo in the current directory'
'list:List projects and their associated directories'
'manifest:Manifest inspection utility'
'overview:Display overview of unmerged project branches'
'prune:Prune (delete) already merged topics'
'rebase:Rebase local branches on upstream branch'
'selfupdate:Update repo to the latest version'
'smartsync:Update working tree to the latest known good revision'
'stage:Stage file(s) for commit'
'start:Start a new branch for development'
'status:Show the working tree status'
'sync:Update working tree to the latest revision'
'upload:Upload changes for code review'
'version:Display the version of repo'
)
_describe -t commands 'command' commands && ret=0
else
local commands;
commands=(
'init:Install repo in the current working directory'
'help:Display detailed help on a command'
)
_describe -t commands 'command' commands && ret=0
fi
;;
(args)
case $words[1] in
(branch | branches)
# TODO : list available projects and add them in list to feed compadd with
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
': :__repo_projects' \
&& ret=0
;;
(abandon)
# TODO : list available projects and add them in list to feed compadd with
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
':branch name:__repo_branch' \
': :__repo_projects'\
&& ret=0
;;
(checkout)
# TODO : list available projects and add them in list to feed compadd with
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
':branch name:__repo_branch' \
': :__repo_projects'\
&& ret=0
;;
(init)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(-q --quiet)"{-q,--quiet}"[be quiet]" \
"(-u --manifest-url)"{-u,--manifest-url=}"[manifest repository location]":url:__repo_url_prompt \
"(-b --manifest-branch)"{-b,--manifest-branch=}"[manifest branch or revision]":branch:__repo_branch\
"(-m --manifest-name)"{-m,--manifest-name=}"[initial manifest file]":manifest_name:__repo_manifest_name\
"(--mirror)--mirror[mirror the forrest]"\
"(--reference)--reference=[location of mirror directory]":dir:_dirs\
"(--depth)--depth=[create a shallow clone with given depth; see git clone]":depth:__repo_depth_prompt\
"(-g --group=)"{-g,--group=}"[restrict manifest projects to ones with a specified group]":group:_group\
"(-p --platform=)"{-p,--platform=}"[restrict manifest projects to ones with a specified platform group(auto|all|none|linux|darwin|...)]":platform:"(auto all none linux darwin)"\
"(--repo-url)--repo-url=[repo repository location]":url:__repo_url_prompt\
"(--repo-branch)--repo-branch[repo branch or revision]":branch_or_rev:__repo__repo_branch_or_rev\
"(--no-repo-verify)--no-repo-verify[do not verify repo source code]"\
"(--config-name)--config-name[Always prompt for name/e-mail]"\
&& ret=0
;;
(start)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(--all)--all=[begin branch in all projects]"\
':branch name:__repo_new__repo_branch_name' \
':projects:__repo_projects_or_all' \
&& ret=0
;;
(rebase)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(-i --interactive)"{-i,--interactive}"[interactive rebase (single project only)]: :__repo_projects" \
"(-f --force-rebase)"{-f,--force-rebase}"[Pass --force-rebase to git rebase]" \
"(--no-ff)--no-ff=[Pass --no-ff to git rebase]"\
"(-q --quiet)"{-q,--quiet}"[Pass --quiet to git rebase]" \
"(--autosquash)--no-ff[Pass --autosquash to git rebase]"\
"(--whitespace=)--whitespace=[Pass --whitespace to git rebase]: :__git_apply_whitespace_strategies"\
"(--auto-stash)--auto-stash[Stash local modifications before starting]"\
&& ret=0
;;
(checkout)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
':branch name:__git_branch_names' \
':projects:__repo_projects' \
&& ret=0
;;
(list)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
&& ret=0
;;
(status)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(-j --jobs)"{-j,--jobs}"[number of projects to check simultaneously]" \
':projects:__repo_projects' \
&& ret=0
;;
(sync)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(--no-force-broken)--no-force-broken[stop sync if a project fails to sync (probably because of permissions)]" \
"(-l --local-only)"{-l,--local-only}"[only update working tree, don't fetch]" \
"(-n --network-only)"{-n,--network-branch}"[fetch only, don't update working tree]" \
"(-d --detach)"{-d,--detach}"[detach projects back to manifest revision]" \
"(-c --current-branch)"{-c,--current-branch}"[fetch only current branch from server]" \
"(-q --quiet)"{-q,--quiet}"[be more quiet]" \
"(-j --jobs=)"{-j,--jobs=}"[projects to fetch simultaneously (default 1) (limited to 5)]:projects to fetch simultaneously (default 1) (limited to 5)" \
"(-m --manifest-name=)"{-m,--manifest-name=}"[temporary manifest to use for this sync]:manifest xml file:_files -g *.xml" \
"(--no-clone-bundle)--no-clone-bundle[disable use of /clone.bundle on HTTP/HTTPS]" \
"(-s --smart-sync)"{-s,--smart-sync=}"[smart sync using manifest from a known tag]:tag:" \
'(--no-repo-verify)--no-repo-verify[do not verify repo source code]' \
': :__repo_projects' \
&& ret=0
;;
(upload)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(-t)-t[Send local branch name to Gerrit Code Review]" \
"(--re= --reviewers=)"{--re=,--reviewers=}"[Request reviews from these people]:Request reviews from these people:" \
"(--cc=)--cc=[Also send email to these email addresses.]:email addresses:_email_addresses" \
"(--br=)--br=[Branch to upload.]:branch:__repo_branch" \
"(--cbr --current-branch)"{--cbr,--current-branch}"[Upload current git branch]" \
"(-d --draft)"{-d,--draft}"[If specified, upload as a draft.]" \
"(--verify --no-verify)--no-verify[Do not run the upload hook.]" \
'(--verify --no-verify)--verify[Run the upload hook without prompting]' \
': :__repo_projects' \
&& ret=0
;;
(forall)
_arguments : \
"(-h --help)"{-h,--help}"[Show help]" \
"(-v --verbose)"{-v,--verbose}"[Show command error messages]" \
'(-p)-p[Show project headers before output]' \
': :__repo_projects_mandatory' \
"(-c --command -h --help -v --verbose -p)"{-c,--command}"[Command (and arguments) to execute]" \
&& ret=0
;;
*)
ret=0
esac
;;
esac
return $ret
}
__repo_reviewers()
{
# _message -e url 'reviewers'
}
__repo_url_prompt()
{
_message -e url 'url'
}
__repo_manifest_name()
{
_message -e manifest_name 'manifest name'
}
_group()
{
_message -e group 'group'
}
__repo_branch()
{
#_message -e branch 'Repo branch'
branches=($(repo branches| cut -c4- | grep '|' | cut -d' ' -f1))
_describe -t branches 'Select repo branch' branches
}
__repo__repo_branch_or_rev()
{
_message -e branch_or_rev 'repo branch or revision'
}
__repo_depth_prompt()
{
_message -e depth 'depth'
}
__repo_projects()
{
_message -e depth 'Optional option : <projects>...'
projects=($(repo list | cut -d' ' -f1))
_describe -t projects 'Select projects (keep empty for selecting all projects)' projects
}
__repo_projects_mandatory()
{
projects=($(repo list | cut -d' ' -f1))
#_describe -t projects 'Select projects to apply commands' projects
_values -s ' ' "Select projects to apply commands" $projects
}
__repo_new__repo_branch_name()
{
branches=($(repo branches| cut -c4- | grep '|' | cut -d' ' -f1))
_describe "" branches
_message -e "branch name" 'Enter new branch name or select an existing repo branch'
}
__repo_projects_or_all()
{
#_message -e depth '[--all | <project>...]'
projects=(--all $(repo list | cut -d' ' -f1))
_describe -t projects 'Select projects or --all' projects
_describe -t --all 'All projects'
}
_repo "$@"
return $?
# Aliases
alias r='repo'
compdef _repo r=repo
alias rra='repo rebase --auto-stash'
compdef _repo rra='repo rebase --auto-stash'
alias rs='repo sync'
compdef _repo rs='repo sync'
alias rsrra='repo sync ; repo rebase --auto-stash'
compdef _repo rsrra='repo sync ; repo rebase --auto-stash'
alias ru='repo upload'
compdef _repo ru='repo upload'
alias rst='repo status'
compdef _repo rst='repo status'
alias rsync-copy="rsync -avz --progress -h"
alias rsync-move="rsync -avz --progress -h --remove-source-files"
alias rsync-update="rsync -avzu --progress -h"
alias rsync-synchronize="rsync -avzu --delete --progress -h"
# TODO: Make this compatible with rvm.
# Run sudo gem on the system ruby, not the active ruby.
alias sgem='sudo gem'
# Find ruby file
alias rfind='find . -name "*.rb" | xargs grep -n'
fpath=($rvm_path/scripts/zsh/Completion $fpath)
alias rubies='rvm list rubies'
alias gemsets='rvm gemset list'
local ruby18='ruby-1.8.7'
local ruby19='ruby-1.9.3'
local ruby20='ruby-2.0.0'
local ruby21='ruby-2.1.2'
function rb18 {
if [ -z "$1" ]; then
rvm use "$ruby18"
else
rvm use "$ruby18@$1"
fi
}
_rb18() {compadd `ls -1 $rvm_path/gems | grep "^$ruby18@" | sed -e "s/^$ruby18@//" | awk '{print $1}'`}
compdef _rb18 rb18
function rb19 {
if [ -z "$1" ]; then
rvm use "$ruby19"
else
rvm use "$ruby19@$1"
fi
}
_rb19() {compadd `ls -1 $rvm_path/gems | grep "^$ruby19@" | sed -e "s/^$ruby19@//" | awk '{print $1}'`}
compdef _rb19 rb19
function rb20 {
if [ -z "$1" ]; then
rvm use "$ruby20"
else
rvm use "$ruby20@$1"
fi
}
_rb20() {compadd `ls -1 $rvm_path/gems | grep "^$ruby20@" | sed -e "s/^$ruby20@//" | awk '{print $1}'`}
compdef _rb20 rb20
function rb21 {
if [ -z "$1" ]; then
rvm use "$ruby21"
else
rvm use "$ruby21@$1"
fi
}
_rb21() {compadd `ls -1 $rvm_path/gems | grep "^$ruby21@" | sed -e "s/^$ruby21@//" | awk '{print $1}'`}
compdef _rb21 rb21
function rvm-update {
rvm get head
}
# TODO: Make this usable w/o rvm.
function gems {
local current_ruby=`rvm-prompt i v p`
local current_gemset=`rvm-prompt g`
gem list $@ | sed \
-Ee "s/\([0-9, \.]+( .+)?\)/$fg[blue]&$reset_color/g" \
-Ee "s|$(echo $rvm_path)|$fg[magenta]\$rvm_path$reset_color|g" \
-Ee "s/$current_ruby@global/$fg[yellow]&$reset_color/g" \
-Ee "s/$current_ruby$current_gemset$/$fg[green]&$reset_color/g"
}
function _rvm_completion {
source $rvm_path"/scripts/zsh/Completion/_rvm"
}
compdef _rvm_completion rvm
# Code from Mikael Magnusson: http://www.zsh.org/mla/users/2011/msg00367.html
#
# Requires xterm, urxvt, iTerm2 or any other terminal that supports bracketed
# paste mode as documented: http://www.xfree86.org/current/ctlseqs.html
# create a new keymap to use while pasting
bindkey -N paste
# make everything in this keymap call our custom widget
bindkey -R -M paste "^@"-"\M-^?" paste-insert
# these are the codes sent around the pasted text in bracketed
# paste mode.
# do the first one with both -M viins and -M vicmd in vi mode
bindkey '^[[200~' _start_paste
bindkey -M paste '^[[201~' _end_paste
# insert newlines rather than carriage returns when pasting newlines
bindkey -M paste -s '^M' '^J'
zle -N _start_paste
zle -N _end_paste
zle -N zle-line-init _zle_line_init
zle -N zle-line-finish _zle_line_finish
zle -N paste-insert _paste_insert
# switch the active keymap to paste mode
function _start_paste() {
bindkey -A paste main
}
# go back to our normal keymap, and insert all the pasted text in the
# command line. this has the nice effect of making the whole paste be
# a single undo/redo event.
function _end_paste() {
#use bindkey -v here with vi mode probably. maybe you want to track
#if you were in ins or cmd mode and restore the right one.
bindkey -e
LBUFFER+=$_paste_content
unset _paste_content
}
function _paste_insert() {
_paste_content+=$KEYS
}
function _zle_line_init() {
# Tell terminal to send escape codes around pastes.
[[ $TERM == rxvt-unicode || $TERM == xterm || $TERM = xterm-256color || $TERM = screen || $TERM = screen-256color ]] && printf '\e[?2004h'
}
function _zle_line_finish() {
# Tell it to stop when we leave zle, so pasting in other programs
# doesn't get the ^[[200~ codes around the pasted text.
[[ $TERM == rxvt-unicode || $TERM == xterm || $TERM = xterm-256color || $TERM = screen || $TERM = screen-256color ]] && printf '\e[?2004l'
}
#compdef sbt
#autoload
local -a _sbt_commands
_sbt_commands=(
'clean:delete files produced by the build'
'compile:compile sources'
'console:start the Scala REPL with project classes on the classpath'
'console-quick:start the Scala REPL with project deps on the classpath'
'console-project:start the Scala REPL w/sbt+build-def on the classpath'
'dist:generate distribution artifacts'
'dist\:clean:clean distribution artifacts'
'doc:generate API documentation'
'gen-idea:generate Intellij Idea project files'
'package:produce the main artifact, such as a binary jar'
'package-doc:produce a doc artifact, such as a jar containing API docs'
'package-src:produce a source artifact, such as a jar containing sources'
'publish:publish artifacts to a repository'
'publish-local:publish artifacts to the local repository'
'run:run a main class'
'run-main:run the main class selected by the first argument'
'test:execute all tests'
'test-only:execute the tests provided as arguments'
'test-quick:execute previously failed tests'
'update:resolve and optionally retrieve dependencies'
)
local expl
_arguments \
'(-help)-h[prints an help message]' \
'(-h)-help[prints an help message]' \
'(-verbose)-v[this runner is chattier]' \
'(-v)-verbose[this runner is chattier]' \
'(-debug)-d[set sbt log level to debug]' \
'(-d)-debug[set sbt log level to debug]' \
'-no-colors[disable ANSI color codes]' \
'-sbt-create[start even if current dir contains no sbt project]' \
'-sbt-dir[path to global settings/plugins dir (default: ~/.sbt)]' \
'-sbt-boot[path to shared boot dir (default: ~/.sbt/boot)]' \
'-ivy[path to local Ivy repository (default: ~/.ivy2)]' \
'-mem[set memory options]' \
'-no-share[use all local caches; no sharing]' \
'-no-global[use global caches, but do not use global ~/.sbt dir]' \
'-jvm-debug[turn on JVM debugging, open at the given port]' \
'-batch[disable interactive mode]' \
'-sbt-version[use the specified version of sbt]' \
'-sbt-jar[use the specified jar as the sbt launcher]' \
'(-sbt-snapshot)-sbt-rc[use an RC version of sbt]' \
'(-sbt-rc)-sbt-snapshot[use a snapshot version of sbt]' \
'-java-home[alternate JAVA_HOME]' \
'*:: :->subcmds' && return 0
_describe -t commands "sbt subcommand" _sbt_commands
return
# ------------------------------------------------------------------------------
# FILE: sbt.plugin.zsh
# DESCRIPTION: oh-my-zsh plugin file.
# AUTHOR: Mirko Caserta (mirko.caserta@gmail.com)
# VERSION: 1.0.2
# ------------------------------------------------------------------------------
# aliases - mnemonic: prefix is 'sb'
alias sbc='sbt compile'
alias sbco='sbt console'
alias sbcq='sbt console-quick'
alias sbcl='sbt clean'
alias sbcp='sbt console-project'
alias sbd='sbt doc'
alias sbdc='sbt dist:clean'
alias sbdi='sbt dist'
alias sbgi='sbt gen-idea'
alias sbp='sbt publish'
alias sbpl='sbt publish-local'
alias sbr='sbt run'
alias sbrm='sbt run-main'
alias sbu='sbt update'
alias sbx='sbt test'
#compdef scala scalac
# ------------------------------------------------------------------------------
# Copyright (c) 2012 Github zsh-users - http://github.com/zsh-users
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the zsh-users nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
# Description
# -----------
#
# Completion script for scala and scalac (http://www.scala-lang.org/).
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
# * Tony Sloane <inkytonik@gmail.com>
#
# ------------------------------------------------------------------------------
typeset -A opt_args
local context state line
_scala_features () {
compadd "postfixOps" "reflectiveCalls" "implicitConversions" "higherKinds" \
"existentials" "experimental.macros" "_"
}
_scala_phases () {
compadd "parser" "namer" "packageobjects" "typer" "patmat" "superaccessors" \
"extmethods" "pickler" "refchecks" "selectiveanf" "selectivecps" "uncurry" \
"tailcalls" "specialize" "explicitouter" "erasure" "posterasure" "lazyvals" \
"lambdalift" "constructors" "flatten" "mixin" "cleanup" "icode" "inliner" \
"inlineExceptionHandlers" "closelim" "dce" "jvm" "terminal"
}
local -a shared_opts
shared_opts=(
"-bootclasspath+[Override location of bootstrap class files]:bootstrap class directory:_files -/"
"-classpath+[Specify where to find user class files]:directory:_files -/"
"-D-[Pass -Dproperty=value directly to the runtime system]"
"-d+[Destination for generated classfiles]: directory or jar file:_files"
"-dependencyfile+[Set dependency tracking file]:dependency tracking file:_files"
"-deprecation[Emit warning and location for usages of deprecated APIs]"
"-encoding+[Specify character encoding used by source files]:encoding:"
"-explaintypes[Explain type errors in more detail]"
"-extdirs+[Override location of installed extensions]:extensions directory:_files -/"
"-g\:-[Set level of generated debugging info (default\: vars)]:debugging info level:(none source line vars notailcalls)"
"-help[Print a synopsis of standard options]"
"-J-[pass argument directly to Java runtime system]:JVM argument:"
"-javabootclasspath+[Override java boot classpath]:Java boot class path directory]:_files -/"
"-javaextdirs+[Override java extdirs classpath]:Java extdirs directory:_files -/"
"-language\:-[Enable one or more language features]:feature:_scala_features"
"-no-specialization[Ignore @specialize annotations]"
"-nobootcp[Do not use the boot classpath for the scala jars]"
"-nowarn[Generate no warnings]"
"-optimise[Generate faster bytecode by applying optimisations to the program]"
"-P\:-[Pass an option to a plugin (written plugin\:opt)]:plugin option:"
"-print[Print program with Scala-specific features removed]"
"-sourcepath+[Specify location(s) of source files]:source file directory:_files -/"
"-target\:-[Target platform for object files (default\: jvm-1.5)]:platform name:(jvm-1.5 msil)"
"-toolcp+[Add to the runner classpath]:directory:_files -/"
"-unchecked[Enable detailed unchecked (erasure) warnings]"
"-uniqid[Uniquely tag all identifiers in debugging output]"
"-usejavacp[Utilize the java.class.path in classpath resolution]"
"-verbose[Output messages about what the compiler is doing]"
"-version[Print product version and exit]"
"-X[Print a synopsis of advanced options]"
"-Y[Print a synopsis of private options]"
)
local -a X_opts
X_opts=(
"-Xcheck-null[Warn upon selection of nullable reference]"
"-Xcheckinit[Wrap field accessors to throw an exception on uninitialized access]"
"-Xdisable-assertions[Generate no assertions or assumptions]"
"-Xelide-below+[Calls to @elidable methods are omitted if method priority is lower than integer argument]"
"-Xexperimental[Enable experimental extensions]"
"-Xfatal-warnings[Fail the compilation if there are any warnings]"
"-Xfull-lubs[Retains pre 2.10 behavior of less aggressive truncation of least upper bounds]"
"-Xfuture[Turn on future language features]"
"-Xgenerate-phase-graph+[Generate the phase graphs (outputs .dot files) to fileX.dot]:output file:_files"
"-Xlint[Enable recommended additional warnings]"
"-Xlog-free-terms[Print a message when reification creates a free term]"
"-Xlog-free-types[Print a message when reification resorts to generating a free type]"
"-Xlog-implicits[Show more detail on why some implicits are not applicable]"
"-Xlog-implicit-conversions[Print a message whenever an implicit conversion is inserted]"
"-Xlog-reflective-calls[Print a message when a reflective method call is generated]"
"-Xmacro-settings\:-[Custom settings for macros]:option"
"-Xmain-class+[Class for manifest's Main-Class entry (only useful with -d jar)]:path:"
"-Xmax-classfile-name+[Maximum filename length for generated classes]"
"-Xmigration[Warn about constructs whose behavior may have changed]"
"-Xno-forwarders[Do not generate static forwarders in mirror classes]"
"-Xno-patmat-analysis[Don't perform exhaustivity/unreachability analysis. Also, ignore @switch annotation]"
"-Xno-uescape[Disable handling of \u unicode escapes]"
"-Xnojline[Do not use JLine for editing]"
"-Xoldpatmat[Use the pre-2.10 pattern matcher. Otherwise, the 'virtualizing' pattern matcher is used in 2.10]"
"-Xprint\:-[Print out program after <phase>]:phase name:_scala_phases"
"-Xprint-icode\:-[Log internal icode to *.icode files after phase (default\: icode)]:phase name:_scala_phases"
"-Xprint-pos[Print tree positions, as offsets]"
"-Xprint-types[Print tree types (debugging option)]"
"-Xprompt[Display a prompt after each error (debugging option)]"
"-Xresident[Compiler stays resident: read source filenames from standard input]"
"-Xscript+[Treat the source file as a script and wrap it in a main method]:main object name"
"-Xshow-class+[Show internal representation of class]:class name"
"-Xshow-object+[Show internal representation of object]:object name"
"-Xshow-phases[Print a synopsis of compiler phases]"
"-Xsource-reader+[Specify a class name for a custom method of reading source files]:class name"
"-Xverify[Verify generic signatures in generated bytecode]"
"-Xassem-extdirs+[List of directories containing assemblies (requires -target:msil) (default\: lib)]:assembly directory:_files -/"
"-Xassem-name+[Name of the output assembly (requires -target:msil)]:assembly name:_files"
"-Xassem-path+[List of assemblies referenced by the program (requires -target:msil)]:assembly path:_files"
"-Xsourcedir+[Mirror source folder structure in output directory (requires -target:msil)]:source directory:_files -/"
"-Xplugin\:-[Load one or more plugins from file]:plugin file:_files"
"-Xpluginsdir+[Path to search compiler plugins]:plugin directory:_files -/"
"-Xplugin-list[Print a synopsis of loaded plugins]"
"-Xplugin-disable\:-[Disable the given plugin(s)]"
"-Xplugin-require\:-[Abort unless the given plugin(s) are available]"
)
local -a Y_opts
Y_opts=(
"-Y[Print a synopsis of private options]"
"-Ybuild-manager-debug[Generate debug information for the Refined Build Manager compiler]"
"-Ybuilder-debug\:-[Compile using the specified build manager (default\: none)]:build manager:(none refined simple)"
"-Yclosure-elim[Perform closure elimination]"
"-Ycompact-trees[Use compact tree printer when displaying trees]"
"-Ydead-code[Perform dead code elimination]"
"-Ydependent-method-types[Allow dependent method types]"
"-Ydump-classes+[Dump the generated bytecode to .class files (useful for reflective compilation that utilizes in-memory classloaders)]:output directory:_files -/"
"-Yeta-expand-keeps-star[Eta-expand varargs methods to T* rather than Seq[T]. This is a temporary option to ease transition.]"
"-Ygen-javap+[Generate a parallel output directory of .javap files]:output directory:_files -/"
"-Yinfer-argument-types[Infer types for arguments of overriden methods]"
"-Yinline[Perform inlining when possible]"
"-Yinline-handlers[Perform exception handler inlining when possible]"
"-Yinline-warnings[Emit inlining warnings (normally surpressed due to high volume)]"
"-Yinvalidate+[Invalidate classpath entry before run]:classpath entry"
"-Ylinearizer\:-[Linearizer to use (default\: rpo)]:linearizer:(normal dfs rpo dump)"
"-Ylog-classpath[Output information about what classpath is being applied]"
"-Yno-adapted-args[Do not adapt an argument list (either by inserting unit or creating a tuple) to match the receiver]"
"-Ymacro-debug-lite[Trace essential macro-related activities]"
"-Ymacro-debug-verbose[Trace all macro-related activities: compilation, generation of synthetics, classloading, expansion, exceptions]"
"-Yno-completion[Disable tab-completion in the REPL]"
"-Yno-generic-signatures[Suppress generation of generic signatures for Java]"
"-Yno-imports[Compile without any implicit imports]"
"-Yno-predef[Compile without importing Predef]"
"-Yno-self-type-checks[Suppress check for self-type conformance among inherited members]"
"-Yno-squeeze[Disable creation of compact code in matching]"
"-Ynotnull[Enable (experimental and incomplete) scala.NotNull]"
"-Yoverride-objects[Allow member objects to be overridden]"
"-Yoverride-vars[Allow vars to be overridden]"
"-Ypmat-naive[Desugar matches as naively as possible]"
"-Ypresentation-delay+[Wait number of ms after typing before starting typechecking]"
"-Ypresentation-log+[Log presentation compiler events into file]:log file:_files"
"-Ypresentation-replay+[Replay presentation compiler events from file]:log file:_files"
"-Ypresentation-strict[Do not report type errors in sources with syntax errors]"
"-Ypresentation-verbose[Print information about presentation compiler tasks]"
"-Yprofile-class+[Specify name of profiler class]:profiler class name"
"-Yprofile-memory[Heap snapshot after compiler run (requires jgpagent on JVM -agentpath)]"
"-Yrangepos[Use range positions for syntax trees]"
"-Yrecursion+[Set recursion depth used when locking symbols]"
"-Yreify-copypaste[Dump the reified trees in copypasteable representation]"
"-Yrepl-sync[Do not use asynchronous code for REPL startup]"
"-Yresolve-term-conflict\:-[Resolve term conflicts (default\: error)]:resolution strategy:(package object error)"
"-Yself-in-annots[Include a \"self\" identifier inside of annotations]"
"-Yshow\:-[Show after <phase> (requires -Xshow-class or -Xshow-object)]:phase name:_scala_phases"
"-Yshow-syms[Print the AST symbol hierarchy after each phase]"
"-Yshow-symkinds[Print abbreviated symbol kinds next to symbol names]"
"-Yshow-trees[Print detailed ASTs (requires -Xprint\:phase)]"
"-Yshow-trees-compact[Print detailed ASTs in compact form (requires -Xprint\:)]"
"-Yshow-trees-stringified[Print stringifications along with detailed ASTs (requires -Xprint\:)]"
"-Ystatistics[Print compiler statistics]"
"-Ystruct-dispatch\:-[Structural method dispatch policy (default\: poly-cache)]:policy name:(no-cache mono-cache poly-cache invoke-dynamic)"
"-Ybrowse\:-[Browse the abstract syntax tree after <phase>]:phase name:_scala_phases"
"-Ycheck\:-[Check the tree at the end of <phase>]:phase name:_scala_phases"
"-Ylog\:-[Log operations during <phase>]:phase name:_scala_phases"
"-Yprofile\:-[Profile CPU usage of given phases (requires jgpagent on JVM -agentpath)]:phase name:_scala_phases"
"-Yskip\:-[Skip <phase>]:phase name:_scala_phases"
"-Ystop-after\:-[Stop after given phase <phase>]:phase name:_scala_phases"
"-Ystop-before\:-[Stop before given phase <phase>]:phase name:_scala_phases"
"-Ywarn-adapted-args[Warn if an argument list is modified to match the receiver]"
"-Ywarn-all[Enable all -Y warnings]"
"-Ywarn-dead-code[Warn when dead code is identified]"
"-Ywarn-inaccessible[Warn about inaccessible types in method signatures]"
"-Ywarn-nullary-override[Warn when non-nullary overrides nullary, e.g. def foo() over def foo]"
"-Ywarn-nullary-unit[Warn when nullary methods return Unit]"
"-Ywarn-numeric-widen[Warn when numerics are widened]"
"-Ywarn-value-discard[Warn when non-Unit expression results are unused]"
"-Ybuild-manager-debug[Generate debug information for the Refined Build Manager compiler]"
"-Ybuilder-debug\:-[Compile using the specified build manager (default\: none)]:manager:(none refined simple)"
"-Ycompletion-debug[Trace all tab completion activity]"
"-Ydebug[Increase the quantity of debugging output]"
"-Ydoc-debug[Trace all scaladoc activity]"
"-Yide-debug[Generate, validate and output trees using the interactive compiler]"
"-Yinfer-debug[Trace type inference and implicit search]"
"-Yissue-debug[Print stack traces when a context issues an error]"
"-Ypatmat-debug[Trace pattern matching translation]"
"-Ypmat-debug[Trace all pattern matcher activity]"
"-Ypos-debug[Trace position validation]"
"-Ypresentation-debug[Enable debugging output for the presentation compiler]"
"-Yreify-debug[Trace reification]"
"-Yrepl-debug[Trace all REPL activity]"
"-Ytyper-debug[Trace all type assignments]"
)
local -a scala_opts
scala_opts=(
"-e+[execute <string> as if entered in the repl]:string" \
"-howtorun+[what to run (default\: guess)]:execution mode:(script object jar guess)" \
"-i+[preload <file> before starting the repl]:file to preload:_files" \
"-nc[no compilation daemon\: do not use the fsc offline compiler]" \
"-save[save the compiled script in a jar for future use]"
)
case $words[$CURRENT] in
-X*) _arguments $X_opts;;
-Y*) _arguments $Y_opts;;
*) case $service in
scala) _arguments $scala_opts $shared_opts "*::filename:_files";;
scalac) _arguments $shared_opts "*::filename:_files";;
esac
esac
return 0
# scd - smart change of directory
Define `scd` shell function for changing to any directory with
a few keystrokes.
`scd` keeps history of the visited directories, which serves as an index of
the known paths. The directory index is updated after every `cd` command in
the shell and can be also filled manually by running `scd -a`. To switch to
some directory, `scd` needs few fragments of the desired path to match with
the index. A selection menu is displayed in case of several matches, with a
preference given to recently visited paths. `scd` can create permanent
directory aliases, which appear as named directories in zsh session.
## INSTALLATION NOTES
Besides oh-my-zsh, `scd` can be used with *bash*, *dash* or *tcsh*
shells and is also available as [Vim](http://www.vim.org/) plugin and
[IPython](http://ipython.org/) extension. For installation details, see
https://github.com/pavoljuhas/smart-change-directory.
## SYNOPSIS
```sh
scd [options] [pattern1 pattern2 ...]
```
## OPTIONS
<dl><dt>
-a, --add</dt><dd>
add specified directories to the directory index.</dd><dt>
--unindex</dt><dd>
remove current or specified directories from the index.</dd><dt>
-r, --recursive</dt><dd>
apply options <em>--add</em> or <em>--unindex</em> recursively.</dd><dt>
--alias=ALIAS</dt><dd>
create alias for the current or specified directory and save it to
<em>~/.scdalias.zsh</em>.</dd><dt>
--unalias</dt><dd>
remove ALIAS definition for the current or specified directory from
<em>~/.scdalias.zsh</em>.</dd><dt>
-A, --all</dt><dd>
include all matching directories. Disregard matching by directory
alias and filtering of less likely paths.</dd><dt>
--list</dt><dd>
show matching directories and exit.</dd><dt>
-v, --verbose</dt><dd>
display directory rank in the selection menu.</dd><dt>
-h, --help</dt><dd>
display this options summary and exit.</dd>
</dl>
## Examples
```sh
# Index recursively some paths for the very first run
scd -ar ~/Documents/
# Change to a directory path matching "doc"
scd doc
# Change to a path matching all of "a", "b" and "c"
scd a b c
# Change to a directory path that ends with "ts"
scd "ts$"
# Show selection menu and ranking of 20 most likely directories
scd -v
# Alias current directory as "xray"
scd --alias=xray
# Jump to a previously defined aliased directory
scd xray
```
# FILES
<dl><dt>
~/.scdhistory</dt><dd>
time-stamped index of visited directories.</dd><dt>
~/.scdalias.zsh</dt><dd>
scd-generated definitions of directory aliases.</dd>
</dl>
# ENVIRONMENT
<dl><dt>
SCD_HISTFILE</dt><dd>
path to the scd index file (by default ~/.scdhistory).</dd><dt>
SCD_HISTSIZE</dt><dd>
maximum number of entries in the index (5000). Index is trimmed when it
exceeds <em>SCD_HISTSIZE</em> by more than 20%.</dd><dt>
SCD_MENUSIZE</dt><dd>
maximum number of items for directory selection menu (20).</dd><dt>
SCD_MEANLIFE</dt><dd>
mean lifetime in seconds for exponential decay of directory
likelihood (86400).</dd><dt>
SCD_THRESHOLD</dt><dd>
threshold for cumulative directory likelihood. Directories with
a lower likelihood compared to the best match are excluded (0.005).
</dd><dt>
SCD_SCRIPT</dt><dd>
command script file where scd writes the final <code>cd</code>
command. This variable must be defined when scd runs in its own
process rather than as a shell function. It is up to the
scd caller to use the output in <em>SCD_SCRIPT</em>.</dd>
</dl>
#!/bin/zsh -f
emulate -L zsh
local EXIT=return
if [[ $(whence -w $0) == *:' 'command ]]; then
emulate -R zsh
local RUNNING_AS_COMMAND=1
EXIT=exit
fi
local DOC='scd -- smart change to a recently used directory
usage: scd [options] [pattern1 pattern2 ...]
Go to a directory path that contains all fixed string patterns. Prefer
recent or frequently visited directories as found in the directory index.
Display a selection menu in case of multiple matches.
Options:
-a, --add add specified directories to the directory index.
--unindex remove current or specified directories from the index.
-r, --recursive apply options --add or --unindex recursively.
--alias=ALIAS create alias for the current or specified directory and
store it in ~/.scdalias.zsh.
--unalias remove ALIAS definition for the current or specified
directory from ~/.scdalias.zsh.
-A, --all include all matching directories. Disregard matching by
directory alias and filtering of less likely paths.
--list show matching directories and exit.
-v, --verbose display directory rank in the selection menu.
-h, --help display this message and exit.
'
local SCD_HISTFILE=${SCD_HISTFILE:-${HOME}/.scdhistory}
local SCD_HISTSIZE=${SCD_HISTSIZE:-5000}
local SCD_MENUSIZE=${SCD_MENUSIZE:-20}
local SCD_MEANLIFE=${SCD_MEANLIFE:-86400}
local SCD_THRESHOLD=${SCD_THRESHOLD:-0.005}
local SCD_SCRIPT=${RUNNING_AS_COMMAND:+$SCD_SCRIPT}
local SCD_ALIAS=~/.scdalias.zsh
local ICASE a d m p i maxrank threshold
local opt_help opt_add opt_unindex opt_recursive opt_verbose
local opt_alias opt_unalias opt_all opt_list
local -A drank dalias
local dmatching
local last_directory
setopt extendedhistory extendedglob noautonamedirs brace_ccl
# If SCD_SCRIPT is defined make sure the file exists and is empty.
# This removes any previous old commands.
[[ -n "$SCD_SCRIPT" ]] && [[ -s $SCD_SCRIPT || ! -f $SCD_SCRIPT ]] && (
umask 077
: >| $SCD_SCRIPT
)
# process command line options
zmodload -i zsh/zutil
zmodload -i zsh/datetime
zparseopts -D -- a=opt_add -add=opt_add -unindex=opt_unindex \
r=opt_recursive -recursive=opt_recursive \
-alias:=opt_alias -unalias=opt_unalias \
A=opt_all -all=opt_all -list=opt_list \
v=opt_verbose -verbose=opt_verbose h=opt_help -help=opt_help \
|| $EXIT $?
if [[ -n $opt_help ]]; then
print $DOC
$EXIT
fi
# load directory aliases if they exist
[[ -r $SCD_ALIAS ]] && source $SCD_ALIAS
# Private internal functions are prefixed with _scd_Y19oug_.
# Clean them up when the scd function returns.
setopt localtraps
trap 'unfunction -m "_scd_Y19oug_*"' EXIT
# works faster than the (:a) modifier and is compatible with zsh 4.2.6
_scd_Y19oug_abspath() {
set -A $1 ${(ps:\0:)"$(
unfunction -m "*"; shift
for d; do
cd $d && print -Nr -- $PWD && cd $OLDPWD
done
)"}
}
# define directory alias
if [[ -n $opt_alias ]]; then
if [[ -n $1 && ! -d $1 ]]; then
print -u2 "'$1' is not a directory."
$EXIT 1
fi
a=${opt_alias[-1]#=}
_scd_Y19oug_abspath d ${1:-$PWD}
# alias in the current shell, update alias file if successful
hash -d -- $a=$d &&
(
umask 077
hash -dr
[[ -r $SCD_ALIAS ]] && source $SCD_ALIAS
hash -d -- $a=$d
hash -dL >| $SCD_ALIAS
)
$EXIT $?
fi
# undefine directory alias
if [[ -n $opt_unalias ]]; then
if [[ -n $1 && ! -d $1 ]]; then
print -u2 "'$1' is not a directory."
$EXIT 1
fi
_scd_Y19oug_abspath a ${1:-$PWD}
a=$(print -rD ${a})
if [[ $a != [~][^/]## ]]; then
$EXIT
fi
a=${a#[~]}
# unalias in the current shell, update alias file if successful
if unhash -d -- $a 2>/dev/null && [[ -r $SCD_ALIAS ]]; then
(
umask 077
hash -dr
source $SCD_ALIAS
unhash -d -- $a 2>/dev/null &&
hash -dL >| $SCD_ALIAS
)
fi
$EXIT $?
fi
# The "compress" function collapses repeated directories to
# one entry with a time stamp that gives equivalent-probability.
_scd_Y19oug_compress() {
awk -v epochseconds=$EPOCHSECONDS -v meanlife=$SCD_MEANLIFE '
BEGIN { FS = "[:;]"; }
length($0) < 4096 && $2 > 0 {
tau = 1.0 * ($2 - epochseconds) / meanlife;
if (tau < -6.9078) tau = -6.9078;
prob = exp(tau);
sub(/^[^;]*;/, "");
if (NF) {
dlist[last[$0]] = "";
dlist[NR] = $0;
last[$0] = NR;
ptot[$0] += prob;
}
}
END {
for (i = 1; i <= NR; ++i) {
d = dlist[i];
if (d) {
ts = log(ptot[d]) * meanlife + epochseconds;
printf(": %.0f:0;%s\n", ts, d);
}
}
}
' $*
}
# Rewrite directory index if it is at least 20% oversized
if [[ -s $SCD_HISTFILE ]] && \
(( $(wc -l <$SCD_HISTFILE) > 1.2 * $SCD_HISTSIZE )); then
# compress repeated entries
m=( ${(f)"$(_scd_Y19oug_compress $SCD_HISTFILE)"} )
# purge non-existent directories
m=( ${(f)"$(
for a in $m; do
if [[ -d ${a#*;} ]]; then print -r -- $a; fi
done
)"}
)
# cut old entries if still oversized
if [[ $#m -gt $SCD_HISTSIZE ]]; then
m=( ${m[-$SCD_HISTSIZE,-1]} )
fi
print -lr -- $m >| ${SCD_HISTFILE}
fi
# Determine the last recorded directory
if [[ -s ${SCD_HISTFILE} ]]; then
last_directory=${"$(tail -1 ${SCD_HISTFILE})"#*;}
fi
# The "record" function adds its arguments to the directory index.
_scd_Y19oug_record() {
while [[ -n $last_directory && $1 == $last_directory ]]; do
shift
done
if [[ $# -gt 0 ]]; then
( umask 077
p=": ${EPOCHSECONDS}:0;"
print -lr -- ${p}${^*} >>| $SCD_HISTFILE )
fi
}
if [[ -n $opt_add ]]; then
for d; do
if [[ ! -d $d ]]; then
print -u2 "Directory '$d' does not exist."
$EXIT 2
fi
done
_scd_Y19oug_abspath m ${*:-$PWD}
_scd_Y19oug_record $m
if [[ -n $opt_recursive ]]; then
for d in $m; do
print -n "scanning ${d} ... "
_scd_Y19oug_record ${d}/**/*(-/N)
print "[done]"
done
fi
$EXIT
fi
# take care of removing entries from the directory index
if [[ -n $opt_unindex ]]; then
if [[ ! -s $SCD_HISTFILE ]]; then
$EXIT
fi
# expand existing directories in the argument list
for i in {1..$#}; do
if [[ -d ${argv[i]} ]]; then
_scd_Y19oug_abspath d ${argv[i]}
argv[i]=${d}
fi
done
m="$(awk -v recursive=${opt_recursive} '
BEGIN {
for (i = 2; i < ARGC; ++i) {
argset[ARGV[i]] = 1;
delete ARGV[i];
}
}
1 {
d = $0; sub(/^[^;]*;/, "", d);
if (d in argset) next;
}
recursive {
for (a in argset) {
if (substr(d, 1, length(a) + 1) == a"/") next;
}
}
{ print $0 }
' $SCD_HISTFILE ${*:-$PWD} )" || $EXIT $?
: >| ${SCD_HISTFILE}
[[ ${#m} == 0 ]] || print -r -- $m >> ${SCD_HISTFILE}
$EXIT
fi
# The "action" function is called when there is just one target directory.
_scd_Y19oug_action() {
cd $1 || return $?
if [[ -z $SCD_SCRIPT && -n $RUNNING_AS_COMMAND ]]; then
print -u2 "Warning: running as command with SCD_SCRIPT undefined."
fi
if [[ -n $SCD_SCRIPT ]]; then
print -r "cd ${(q)1}" >| $SCD_SCRIPT
fi
}
# Match and rank patterns to the index file
# set global arrays dmatching and drank
_scd_Y19oug_match() {
## single argument that is an existing directory or directory alias
if [[ -z $opt_all && $# == 1 ]] && \
[[ -d ${d::=$1} || -d ${d::=${nameddirs[$1]}} ]] && [[ -x $d ]];
then
_scd_Y19oug_abspath dmatching $d
drank[${dmatching[1]}]=1
return
fi
# ignore case unless there is an argument with an uppercase letter
[[ "$*" == *[[:upper:]]* ]] || ICASE='(#i)'
# support "$" as an anchor for the directory name ending
argv=( ${argv/(#m)?[$](#e)/${MATCH[1]}(#e)} )
# calculate rank of all directories in the SCD_HISTFILE and keep it as drank
# include a dummy entry for splitting of an empty string is buggy
[[ -s $SCD_HISTFILE ]] && drank=( ${(f)"$(
print -l /dev/null -10
<$SCD_HISTFILE \
awk -v epochseconds=$EPOCHSECONDS -v meanlife=$SCD_MEANLIFE '
BEGIN { FS = "[:;]"; }
length($0) < 4096 && $2 > 0 {
tau = 1.0 * ($2 - epochseconds) / meanlife;
if (tau < -6.9078) tau = -6.9078;
prob = exp(tau);
sub(/^[^;]*;/, "");
if (NF) ptot[$0] += prob;
}
END { for (di in ptot) { print di; print ptot[di]; } }'
)"}
)
unset "drank[/dev/null]"
# filter drank to the entries that match all arguments
for a; do
p=${ICASE}"*(${a})*"
drank=( ${(kv)drank[(I)${~p}]} )
done
# require at least one argument matches the directory name
p=${ICASE}"*(${(j:|:)argv})[^/]#"
drank=( ${(kv)drank[(I)${~p}]} )
# build a list of matching directories reverse-sorted by their probabilities
dmatching=( ${(f)"$(
for d p in ${(kv)drank}; do
print -r -- "$p $d";
done | sort -grk1 | cut -d ' ' -f 2-
)"}
)
# do not match $HOME or $PWD when run without arguments
if [[ $# == 0 ]]; then
dmatching=( ${dmatching:#(${HOME}|${PWD})} )
fi
# keep at most SCD_MENUSIZE of matching and valid directories
m=( )
for d in $dmatching; do
[[ ${#m} == $SCD_MENUSIZE ]] && break
[[ -d $d && -x $d ]] && m+=$d
done
dmatching=( $m )
# find the maximum rank
maxrank=0.0
for d in $dmatching; do
[[ ${drank[$d]} -lt maxrank ]] || maxrank=${drank[$d]}
done
# discard all directories below the rank threshold
threshold=$(( maxrank * SCD_THRESHOLD ))
if [[ -n ${opt_all} ]]; then
threshold=0
fi
dmatching=( ${^dmatching}(Ne:'(( ${drank[$REPLY]} >= threshold ))':) )
}
_scd_Y19oug_match $*
## process whatever directories that remained
if [[ ${#dmatching} == 0 ]]; then
print -u2 "No matching directory."
$EXIT 1
fi
## build formatted directory aliases for selection menu or list display
for d in $dmatching; do
if [[ -n ${opt_verbose} ]]; then
dalias[$d]=$(printf "%.3g %s" ${drank[$d]} $d)
else
dalias[$d]=$(print -Dr -- $d)
fi
done
## process the --list option
if [[ -n $opt_list ]]; then
for d in $dmatching; do
print -r -- "# ${dalias[$d]}"
print -r -- $d
done
$EXIT
fi
## process single directory match
if [[ ${#dmatching} == 1 ]]; then
_scd_Y19oug_action $dmatching
$EXIT $?
fi
## here we have multiple matches - display selection menu
a=( {a-z} {A-Z} )
a=( ${a[1,${#dmatching}]} )
p=( )
for i in {1..${#dmatching}}; do
[[ -n ${a[i]} ]] || break
p+="${a[i]}) ${dalias[${dmatching[i]}]}"
done
print -c -r -- $p
if read -s -k 1 d && [[ ${i::=${a[(I)$d]}} -gt 0 ]]; then
_scd_Y19oug_action ${dmatching[i]}
$EXIT $?
fi