Browse Source

first commit

master
Manfraid 4 years ago
commit
56f5d70b30

+ 6
- 0
.gitignore View File

@@ -0,0 +1,6 @@
*~
*.zwc
/local
/run
/oldzsh.tar.gz
/artifacts

+ 12
- 0
.gitmodules View File

@@ -0,0 +1,12 @@
[submodule "third-party/docker-zsh-completion"]
path = third-party/docker-zsh-completion
url = git@github.com:felixr/docker-zsh-completion.git
[submodule "third-party/zsh-syntax-highlighting"]
path = third-party/zsh-syntax-highlighting
url = git@github.com:zsh-users/zsh-syntax-highlighting.git
[submodule "third-party/zsh-completions"]
path = third-party/zsh-completions
url = git@github.com:vincentbernat/zsh-completions.git
[submodule "third-party/docker-compose-zsh-completion"]
path = third-party/docker-compose-zsh-completion
url = git@github.com:sdurrheimer/docker-compose-zsh-completion.git

+ 24
- 0
.travis.yml View File

@@ -0,0 +1,24 @@
language: c
os: linux
git:
submodules: false
sudo: false
addons:
apt:
packages:
- zsh
install:
- sed -i 's+git@github.com:+https://github.com/+' .gitmodules
- git submodule update --init --recursive
script:
- ZSH=$PWD zsh -c ". rc/install.zsh && install-zsh"
- mkdir artifacts && cp run/zsh-install.sh artifacts && git reset --hard
deploy:
provider: s3
access_key_id: AKIAJWSE4LXWA33RNIYA
secret_access_key:
secure: fNGzrG9db2dgOin9A9pP1Giqjl2u44l6cOh0E9/cnjpg/0aC53fmhJ5u4MZVb05ZwgnJ56I1tc1GLNbAnTOqY+5dzm4zQ2VDpj3gzD+WPtdfaW+jkTh8cNanzWcZm3wZgmSeIzWpadfqsFZM9mPB1Ntw2CFvmrRFJpi3lb+PmTI=
bucket: vincentbernat-zshrc
acl: public_read
local_dir: artifacts
skip_cleanup: true

+ 32
- 0
README.md View File

@@ -0,0 +1,32 @@
My `.zshrc`
===========

My `.zshrc` may not suit your needs. Feel free to read and
understand. Steal anything. My opinion is that you can't have an
universal `.zshrc`. If you don't agree, take a look at
[Prezto](https://github.com/sorin-ionescu/prezto).

You need to create your own `.zshrc`. First solution is to symlink
`~/.zsh/zshrc`. The other solution is to source `~/.zsh/zshrc` from
your own `~/.zshrc`. The later case allows you to set the plugin you
want to enable.

You can copy your installation to a remote host with `install-zsh`
function.

`~/.zsh/run` contains runtime files, like history. `~/.zsh/local`
contains local files that should not be copied to a remote host.

Installation
------------

So, if you are one of those young generation not concerned about
arbitrary code execution, you can do:

curl -s https://vincentbernat-zshrc.s3.amazonaws.com/zsh-install.sh | sh

License
-------

All the code is licensed as
[CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode).

+ 1
- 0
completions/_adb View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_adb

+ 1
- 0
completions/_cabal View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_cabal

+ 50
- 0
completions/_cowbuilder View File

@@ -0,0 +1,50 @@
#compdef cowbuilder

_cowbuilder_environments() {
local -a results
local distrib
for cow in /var/cache/pbuilder/base-*.cow(N); do
distrib=${${${cow:t}%.cow}#base-}
arch=${(M)${(f)"$(dpkg-architecture -L)"}:#${distrib##*-}}
[[ -z $arch ]] || distrib=${distrib%-*}/$arch
results=($results $distrib)
done
_wanted base expl 'base path' compadd -a \
results
}

local context state state_descr line expl
typeset -A opt_args

_arguments \
'1:::_cowbuilder_environments' \
'2:action:((--create\:"create new environment"
--build\:"build a package"
--update\:"update environment"
--login\:"login into environment"
--execute\:"execute a command"))' \
'*:: :->subcmds' \
&& return 0

case "$words[2]" in
--build)
if (( CURRENT == 3 )); then
_wanted dsc expl "dsc file" _files -g "*.dsc"
fi
;;
--execute)
precommands+=($words[2])
shift 2 words
(( CURRENT -= 2 ))
_normal
;;
esac

return 0

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:

+ 19
- 0
completions/_dm View File

@@ -0,0 +1,19 @@
#compdef dm

case $CURRENT in
2)
local cmds
local -a commands
cmds=$(dm commands)
commands=(${(ps:\n:)cmds})
_wanted command expl "dm command" compadd -a commands
;;
*)
local cmd subcmds
local -a commands
cmd=${words[2]}
subcmds=$(dm completions ${words[2,$(($CURRENT - 1))]})
commands=(${(ps:\n:)subcmds})
_wanted subcommand expl "dm $cmd subcommand" compadd -a commands
;;
esac

+ 1
- 0
completions/_docker View File

@@ -0,0 +1 @@
../third-party/docker-zsh-completion/_docker

+ 1
- 0
completions/_docker-compose View File

@@ -0,0 +1 @@
../third-party/docker-compose-zsh-completion/_docker-compose

+ 14
- 0
completions/_evince View File

@@ -0,0 +1,14 @@
#compdef evince

local arguments
arguments=(
'(-p --page-label)'{-p,--page-label=}'[the page label of the document to display]'
'(-i --page-index)'{-i,--page-index=}'[the page number of the document to display]'
'(-f --fullscreen)'{-f,--fullscreen}'[run evince in fullscreen mode]'
'(-s --presentation)'{-s,--presentation}'[run evince in presentation mode]'
'(-w --preview)'{-w,--preview}'[run evince as a previewer]'
'(-l --find)'{-l,--find=}'[the word or phrase to find in the document]'
'--display=[X display to use]'
'*:PostScript, Djvu or PDF file:_files -g "*.(#i)(pdf|ps|eps|djvu)(-.)"'
)
_arguments -s $arguments

+ 1
- 0
completions/_fab View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_fab

+ 156
- 0
completions/_go View File

@@ -0,0 +1,156 @@
#compdef go

# See: http://golang.org/misc/zsh/go

# go tool
__go_tool_complete() {
typeset -a commands build_flags
commands+=(
'build[compile packages and dependencies]'
'clean[remove object files]'
'doc[run godoc on package sources]'
'env[print Go environment information]'
'fix[run go tool fix on packages]'
'fmt[run gofmt on package sources]'
'get[download and install packages and dependencies]'
'help[display help]'
'install[compile and install packages and dependencies]'
'list[list packages]'
'run[compile and run Go program]'
'test[test packages]'
'tool[run specified go tool]'
'version[print Go version]'
'vet[run go tool vet on packages]'
)
if (( CURRENT == 2 )); then
# explain go commands
_values 'go tool commands' ${commands[@]}
return
fi
build_flags=(
'-a[force reinstallation of packages that are already up-to-date]'
'-n[print the commands but do not run them]'
'-p[number of parallel builds]:number'
'-race[enable data race detection]'
'-x[print the commands]'
'-work[print temporary directory name and keep it]'
'-ccflags[flags for 5c/6c/8c]:flags'
'-gcflags[flags for 5g/6g/8g]:flags'
'-ldflags[flags for 5l/6l/8l]:flags'
'-gccgoflags[flags for gccgo]:flags'
'-compiler[name of compiler to use]:name'
'-installsuffix[suffix to add to package directory]:suffix'
'-tags[list of build tags to consider satisfied]:tags'
)
__go_list() {
local expl importpaths
declare -a importpaths
importpaths=($(go list ${words[$CURRENT]}... 2>/dev/null))
_wanted importpaths expl 'import paths' compadd "$@" - "${importpaths[@]}"
}
case ${words[2]} in
clean|doc)
_arguments -s -w : '*:importpaths:__go_list'
;;
fix|fmt|list|vet)
_alternative ':importpaths:__go_list' ':files:_path_files -g "*.go"'
;;
install)
_arguments -s -w : ${build_flags[@]} \
"-v[show package names]" \
'*:importpaths:__go_list'
;;
get)
_arguments -s -w : \
${build_flags[@]}
;;
build)
_arguments -s -w : \
${build_flags[@]} \
"-v[show package names]" \
"-o[output file]:file:_files" \
"*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
;;
test)
_arguments -s -w : \
${build_flags[@]} \
"-c[do not run, compile the test binary]" \
"-i[do not run, install dependencies]" \
"-v[print test output]" \
"-x[print the commands]" \
"-short[use short mode]" \
"-parallel[number of parallel tests]:number" \
"-cpu[values of GOMAXPROCS to use]:number list" \
"-run[run tests and examples matching regexp]:regexp" \
"-bench[run benchmarks matching regexp]:regexp" \
"-benchmem[print memory allocation stats]" \
"-benchtime[run each benchmark until taking this long]:duration" \
"-blockprofile[write goroutine blocking profile to file]:file" \
"-blockprofilerate[set sampling rate of goroutine blocking profile]:number" \
"-timeout[kill test after that duration]:duration" \
"-cpuprofile[write CPU profile to file]:file:_files" \
"-memprofile[write heap profile to file]:file:_files" \
"-memprofilerate[set heap profiling rate]:number" \
"*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
;;
help)
_values "${commands[@]}" \
'gopath[GOPATH environment variable]' \
'packages[description of package lists]' \
'remote[remote import path syntax]' \
'testflag[description of testing flags]' \
'testfunc[description of testing functions]'
;;
run)
_arguments -s -w : \
${build_flags[@]} \
'*:file:_path_files -g "*.go"'
;;
tool)
if (( CURRENT == 3 )); then
_values "go tool" $(go tool)
return
fi
case ${words[3]} in
[568]g)
_arguments -s -w : \
'-I[search for packages in DIR]:includes:_path_files -/' \
'-L[show full path in file:line prints]' \
'-S[print the assembly language]' \
'-V[print the compiler version]' \
'-e[no limit on number of errors printed]' \
'-h[panic on an error]' \
'-l[disable inlining]' \
'-m[print optimization decisions]' \
'-o[file specify output file]:file' \
'-p[assumed import path for this code]:importpath' \
'-u[disable package unsafe]' \
"*:file:_files -g '*.go'"
;;
[568]l)
local O=${words[3]%l}
_arguments -s -w : \
'-o[file specify output file]:file' \
'-L[search for packages in DIR]:includes:_path_files -/' \
"*:file:_files -g '*.[ao$O]'"
;;
dist)
_values "dist tool" banner bootstrap clean env install version
;;
*)
# use files by default
_files
;;
esac
;;
esac
}

__go_tool_complete "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:

+ 47
- 0
completions/_lldpcli View File

@@ -0,0 +1,47 @@
#compdef lldpcli
#
# zsh completion for lldpcli
#
# Copyright (c) 2014 Vincent Bernat <bernat@luffy.cx>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


__lldpcli_command () {
local -a completions
completions=(${(f)"$(_call_program commands lldpcli complete ${words[1,$(($CURRENT-1))]})"})
completions=(${completions:s/ /:/})
_describe -t lldpcli-command "lldpcli completion" completions "$@"
}

_lldpcli () {
local curcontext="$curcontext" state line

_arguments -C \
'*-d[print more debugging information]' \
'(- *)-v[print version number and exit]' \
'-u[use an alternate socket with lldpd]:UNIX socket:_files' \
'-f[output format]:format:(plain xml json keyvalue)' \
'*-c[read a configuration file]:configuration file:_files' \
'(-)*::lldpcli command:__lldpcli_command'
}


_lldpcli "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:

+ 20
- 0
completions/_npm View File

@@ -0,0 +1,20 @@
#compdef npm

_npm() {
si=$IFS
compadd -- $(COMP_CWORD=$((CURRENT-1)) \
COMP_LINE=$BUFFER \
COMP_POINT=0 \
npm completion -- "${words[@]}" \
2>/dev/null)
IFS=$si
}

_npm "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:

+ 243
- 0
completions/_openssl View File

@@ -0,0 +1,243 @@
#compdef openssl
#
# Retrieved from:
# https://github.com/aschrab/zsh-completions/blob/openssl/src/_openssl

# _openssl: Start point {{{
_openssl() {
setopt nonomatch
local openssl==openssl

if [[ $openssl = '=openssl' ]]; then
_message "openssl executable not found: completion not available"
return
fi

_get_openssl_commands

if (( CURRENT > 2 )); then
_openssl_dispatch
else
_openssl_commands
fi
}
# }}}

# _get_openssl_commands: Populate arrays of subcommand names {{{
_get_openssl_commands() {
if ! (( ${+_openssl_list_cmd_list} )); then
typeset -ga _openssl_list_cmd_list
_openssl_list_cmd_list=(
list-standard-commands
list-message-digest-commands
list-cipher-commands
list-cipher-algorithms
list-message-digest-algorithms
list-public-key-algorithms
)
fi

if ! (( ${+_openssl_standard_cmd_list} )); then
typeset -ga _openssl_standard_cmd_list
_openssl_standard_cmd_list=( $(openssl list-standard-commands) )
fi

if ! (( ${+_openssl_digest_cmd_list} )); then
typeset -ga _openssl_digest_cmd_list
_openssl_digest_cmd_list=( $(openssl list-message-digest-commands) )
fi

if ! (( ${+_openssl_cipher_cmd_list} )); then
typeset -ga _openssl_cipher_cmd_list
_openssl_cipher_cmd_list=( $(openssl list-cipher-commands) )
fi
}
# }}}

# _openssl_commands: complete subcommand name {{{
_openssl_commands() {
integer ret=1
_describe -t cipher-commands 'Cipher command' _openssl_cipher_cmd_list && ret=0
_describe -t digest-commands 'Digest command' _openssl_digest_cmd_list && ret=0
_describe -t standard-commands 'Standard command' _openssl_standard_cmd_list && ret=0
_describe -t list-commands 'List commands' _openssl_list_cmd_list && ret=0

return ret
}
# }}}

# _openssl_dispatch: Dispatch to completion for subcommand {{{
_openssl_dispatch() {
integer ret=1
shift words
(( CURRENT-- ))

# Check if there's a completion function for the specific subcommand
if (( $+functions[_openssl-$words[1]] )); then
_call_function ret _openssl-$words[1]
# Digest commands can be handled by a common function
elif (( $+_openssl_digest_cmd_list )); then
_openssl_digest_command
else
_message "Can't dispatch to $words[1]"
fi

return ret
}
# }}}

# Completion for option arguments {{{
# _openssl_pass_source: Complete password source info {{{
_openssl_pass_source() {
_values -S : 'Password source' \
'pass[Direct password entry]:password:' \
'env[Get password from named environment variable]:environment:_parameters -g "*export*"' \
'file[Get password from file]:password file:_files' \
'fd[Read password from file descriptor #]:integer:' \
'stdin[Read password from standard input]'
}
# }}}

# _openssl_engine_id: Complete engine ID {{{
_openssl_engine_id() {
# TODO
}
#}}}

# _openssl_x509_name_options: Complete x509 name options {{{
_openssl_x509_name_options() {
local sep='sep_comma_plus sep_comma_plus_space sep_semi_plus_space sep_multiline'
local fname='nofname sname lname oid'

_values -s , -w 'name options' \
'compat[Use old format (default)]' \
'RFC2253[RFC2253 compatible]' \
'oneline[Single line format]' \
'multiline[Multi line format]' \
'esc_2253[Escape special characters: ,+"<>]' \
'esc_ctrl[Escape control characters]' \
'esc_msb[Escape characters with ASCII value > 127]' \
'use_quote[Surround entire string with double quote]' \
'utf8[Convert all strings to UTF8]' \
'no_type[Dump multibyte characters without conversion]' \
'show_type[Precede field content with type of ASN1 string]' \
'dump_der[Use DER encoding for hexdump]' \
'dump_nostr[dump types which are not character strings]' \
'dump_all[dump all fields]' \
'dump_unknown[dump any field with unknown OID]' \
"($sep)sep_comma_plus[use , and + as separators]" \
"($sep)sep_comma_plus_space[use , and + with following space as separators]" \
"($sep)sep_semi_plus_space[use ; and + with following space as separators]" \
"($sep)sep_multiline[use LF and + as separators]" \
'dn_rev[reverse fields of the DN]' \
"($fname)nofname[do not display field name]" \
"($fname)sname[display short field name]" \
"($fname)lname[display long field name]" \
"($fname)oid[use numerical OID for field name]" \
'align[align field values (only usable with sep_multiline)]' \
'space_eq[put spaces around = after field name]'
}
#}}}

# _openssl_x509_cert_options: Complete x509 certificate options {{{
_openssl_x509_cert_options() {
# TODO
}
#}}}

# _openssl_req_newkey_options: Complete options for req -newkey {{{
_openssl_req_newkey_options() {
# TODO: Get list of algorithms dynamically
_values -S : 'Key options' \
'rsa[RSA key]::number of bits:' \
'param[Read paramaters from file]:parameter file:_files' \
'cmac' \
'hmac'
}
#}}}

#}}}

# _openssl_digest_command: Default completion for digest subcommands {{{
_openssl_digest_command() {
_arguments : \
'-c[Print digest in two-digit groups separated by colons]' \
'-d[Print BIO debugging information]' \
'(-binary)-hex[Output digest as a hex dump]' \
'(-hex -c)-binary[Output digest or signature in binary form]' \
'-hmac[Set the HMAC key to ARG]:arg:' \
'-non-fips-allow[Allow use of non-FIPS digest]' \
'-out[Filename for output]:output file:_files' \
'-sign[Sign the digest using key in file]:key file:_files' \
'-keyform[Key format]:format:(PEM ENGINE)' \
'-engine[Use engine ID]:Engine ID:_openssl_engine_id' \
'-sigopt[Signature options]:Signature option:' \
'-passin[Private key password source]:Key source:_openssl_pass_source' \
'-verify[Verify signature with public key FILE]:Public key file:_files' \
'-prverify[Verify signature with private key FILE]:Private key file:_files' \
'-signature[Verify signature in FILE]:Signature file:_files' \
'-mac[Message Authenticate Code algorithm]:MAC algorithm:' \
'-macopt[Options to pass to MAC algorithm]:MAC options:' \
'-rand[File for random data]:Random source:_files' \
'*: :_files'
}
#}}}

# Completion for specific subcommands {{{

_openssl-req() { #{{{
local -a digests
digests=(-md5 -sha1) # FIXME generate this
_arguments : \
$digests \
'-inform[Format of the input]:input format:(DER PEM)' \
'-outform[Format to use for the output]:output format:(DER PEM)' \
'-in[Input filename]:input file:_files' \
'-passsin[Source for password of the input]:password source:_openssl_pass_source' \
'-out[Output file name]:output file:_files' \
'-passsout[Source for password of the output]:password source:_openssl_pass_source' \
'-text[Print certificate request in text form]' \
'-subject[Print request subject]' \
'-pubkey[Output the public key]' \
'-noout[Prevent output of encoded request]' \
'-modulus[Print the public key modulus]' \
'-verify[Verify request signature]' \
'-new[Generate a new certificate request]' \
'-subj[Specify subject of the request]:subject:' \
'-rand[File for random data]:Random source:_files' \
'-newkey[Create a new private key and request]:key spec:_openssl_req_newkey_options' \
'-pkeyopt[Public key option]:key option:' \
'-key[Key from which private key will be read]:private key file:_files' \
'-keyform[Format of file specified by -key option]:key format:(DER PEM)' \
'-keyout[File name to which generated key should be written]:output key file:_files' \
'-nodes[Do not encrypt generated private key]' \
'-config[Alternate configuration file]:config file:_files' \
'-multivalue-rdn[Interpret -subj argument with support for multivalued RDNs]' \
'-x509[Output a self signed certificate]' \
'-days[Number of days for which -x509 certifcate will be valid]:integer:' \
'-set_serial[Serial number for self-signed certificate]:integer:' \
{-extensions,-reqexts}'[]:section:' \
'-utf8[Interpret values as UTF8 strings]' \
'*-nameopt[Options for display of subject or issuer name]:name option:_openssl_x509_name_options' \
'-reqopt[Customise output format for -text]:request option:_openssl_x509_cert_options' \
'-asn1-kludge[Produce broken output required by some CAs]' \
'-no-asn1-kludge[Produce standard-compliant output]' \
'-newhdr[Add NEW to the PEM header and footer]' \
'-batch[Non-interactive mode]' \
'-verbose[Print extra details]' \
'-engine[Use engine ID]:Engine ID:_openssl_engine_id' \
'-keygen_engine[Use engine ID for key generation]:Engine ID:_openssl_engine_id'
}
#}}}

#}}}

_openssl "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 2
# indent-tabs-mode: nil
# sh-basic-offset: 2
# End:
# vim: filetype=zsh expandtab shiftwidth=2 foldmethod=marker

+ 20
- 0
completions/_pip View File

@@ -0,0 +1,20 @@
#compdef pip

function _pip {
local -a reply
reply=( $( COMP_WORDS="$words[*]" \
COMP_CWORD=$CURRENT \
PIP_AUTO_COMPLETE=1 _call_program commands pip ) )
_describe "pip completion" reply
}

_pip "$@"

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:
# vim: ft=zsh sw=4 ts=4 et


+ 1
- 0
completions/_rfkill View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_rfkill

+ 154
- 0
completions/_snmpcmd View File

@@ -0,0 +1,154 @@
#compdef snmpwalk=snmpcmd snmpget=snmpcmd snmpbulkwalk=snmpcmd snmpbulkget=snmpcmd
#
# Completion for snmp* cmd. Stolen from:
# 2006 Andrew J Cosgriff
# http://polydistortion.net/
# http://polydistortion.net/sw/zsh/_snmpcmd
# http://polydistortion.net/monkey/archives/2006/07/16/003735.html
#
# With some other modifications

_snmp_get_mibs () {
local -a mibs
local -a mib
local mibdirs
local dir

mibdirs=$(snmptranslate -Dinit_mib 2>&1 | \
sed -n "s/^init_mib: Seen MIBDIRS: Looking in '\(.*\)' for mib dirs ...$/\1/p")
for dir in ${(ws+:+)mibdirs}; do
mibs=($mibs $dir/*(.))
done

compadd "$@" -- ${mibs[@]:t:r}
}

_snmp_get_object() {
local obj
local arg
local next
local -a additional
next=0
for arg in $words; do
case $arg in
"-m")
next=1
additional=($additional "-m")
;;
*)
if (( next == 1 )); then
additional=($additional $arg)
next=0
fi
;;
esac
done
for obj in ${(@f)"$(snmptranslate $additional -Ta 2> /dev/null)"}; do
case ${${(s: :)obj}[2]} in
OBJECT)
;;
*) continue
;;
esac
compadd "$@" -- ${${(s: :)obj}[1]}
done
}

_snmpcmd () {
local context state line
typeset -A opt_args

_arguments -A \
{-h,--help}'[show help]' \
'-H[display configuration file directives understood]' \
'-v[SNMP version to use]:version:(1 2c 3)' \
{-V,--version}'[display package version number]' \
'-c[set the community string]:community string: ' \
'-a[set authentcation protocol]:protocol:(MD5 SHA)' \
'-A[set authentication protocol pass phrase]:passphrase: ' \
'-e[set security engine ID]:engine-id: ' \
'-E[set context engine ID]:engine-id: ' \
'-l[set security level]:security level:(noAuthNoPriv authNoPriv authPriv)' \
'-n[set context name]:context: ' \
'-u[set security name]:user:_users' \
'-x[set privacy protocol]:protocol:(DES AES)' \
'-X[set privacy protocol pass phrase]:passphrase: ' \
'-Z[set destination engine boots/time]:boots,time: ' \
'-r[set the number of retries]:retries: ' \
'-t[set the request timeout (in seconds)]:timeout: ' \
'-d[dump input/output packets in hexadecimal]' \
'-D[turn on debugging output for the specified tokens]:token: ' \
'-m[MIB file to use]:mib:->mib' \
'-M[directory to search for MIBs]:directory:_files -/' \
'-Pu[allow the use of underlines in MIB symbols]' \
'-Pc[disallow the use of "--" to terminate comments in MIBs]' \
'-Pd[save the DESCRIPTIONs of the MIB objects]' \
'-Pe[disable errors when MIB symbols conflict]' \
'-Pw[enable warnings when MIB symbols conflict]' \
'-PW[enable detailed warnings when MIB symbols conflict]' \
'-PR[replace MIB symbols from latest module]' \
'-O0[print leading 0 for single-digit hex characters]' \
'-Oa[print all strings in ascii format]' \
'-Ob[do not break OID indexes down]' \
'-Oe[print enums numerically]' \
'-OE[escape quotes in string indices]' \
'-Of[print full OIDs on output]' \
'-On[print OIDs numerically]' \
'-Oq[quick print for easier parsing]' \
'-OQ[quick print with equal-signs]' \
'-Os[print only last symbolic element of OID]' \
'-OS[print MIB module-id plus last element]' \
'-Ot[print timeticks unparsed as numeric integers]' \
'-OT[print human-readable text along with hex strings]' \
'-Ou[print OIDs using UCD-style prefix suppression]' \
"-OU[don't print units]" \
'-Ov[print values only (not OID = value)]' \
'-Ox[print all strings in hex format]' \
'-OX[extended index format]' \
'-Ib[do best/regex matching to find a MIB node]' \
"-Ih[don't apply DISPLAY-HINTs]" \
'-Ir[do not check values for range/type legality]' \
'-IR[do random access to OID labels]' \
'-Iu[top-level OIDs must have '.' prefix (UCD-style)]' \
'-Is[Append all textual OIDs with suffix before parsing]:suffix: ' \
'-IS[Append all textual OIDs with prefix before parsing]:prefix: ' \
'-Le[log to standard error]' \
'-Lo[log to standard output]' \
"-Ln[don't log at all]" \
'-Lf[log to the specified file]:file:_files' \
'-Ls[log to the syslog (via the specified facility)]:facility: ' \
'-Cp[print the number of variables found]' \
'-Ci[include given OID in the search range]' \
"-CI[don't include the given OID, even if no results are returned]" \
'-Ic[do not check returned OIDs are increasing]' \
'-It[Display wall-clock time to complete the request]' \
':hosts:_hosts' \
':object:->object'

while [[ -n "$state" ]]; do
lstate="$state"
state=''

case "$lstate" in
mib)
if compset -P '*+'; then
_snmp_get_mibs
elif compset -P '*:'; then
_snmp_get_mibs
else
_snmp_get_mibs
fi
;;
object)
_snmp_get_object
;;
esac
done
}

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: t
# sh-basic-offset: 4
# End:

+ 1
- 0
completions/_socat View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_socat

+ 11
- 0
completions/_tmux-cssh View File

@@ -0,0 +1,11 @@
#compdef tmux-cssh

_arguments \
'*::arguments: _hosts' && return 0

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:

+ 1
- 0
completions/_vagrant View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_vagrant

+ 1
- 0
completions/_virsh View File

@@ -0,0 +1 @@
../third-party/zsh-completions/src/_virsh

+ 29
- 0
completions/_workon View File

@@ -0,0 +1,29 @@
#compdef workon

_environments() {
local -a virtualenvs images containers
local expl

virtualenvs=( ${WORKON_HOME}/*/bin/activate(.N:h:h:t) - )
_wanted environments expl 'virtualenv environment' compadd \
-a virtualenvs

(( $+commands[docker] )) && [[ -w /var/run/docker.sock ]] && {
images=(${(f)"$(docker images 2> /dev/null | awk '(NR > 1 && $1 !~ /^</){printf("%s:%s\n", $1,$2)}')"})
_wanted images expl 'docker images' compadd \
-a images

containers=(${(f)"$(docker ps 2> /dev/null | awk '(NR > 1) { split($NF,names,/,/); for (i in names) printf("%s:%7s\n",names[i],$2)}')"})
_describe -t containers-active "running containers" containers
}
}

_arguments \
'1:::_environments' && return 0

# Local Variables:
# mode: Shell-Script
# sh-indentation: 4
# indent-tabs-mode: nil
# sh-basic-offset: 4
# End:

+ 90
- 0
dir_colors View File

@@ -0,0 +1,90 @@
# /etc/dir_colors ou ~/.dir_colors
# Fichier de configuration des couleurs pour la commande 'ls'
# Formation Debian GNU/Linux par Alexis de Lattre
# http://www.via.ecp.fr/~alexis/formation-linux/

# Les couleurs sont exprimées sous forme d'une liste de numéros
# séparés par des points-virgules, sachant qu'il ne doit pas y
# avoir plus d'un numéro par catégorie.

# Il existe 3 catégories :
# - Type :
# 00=normal 01=gras 04=souligné 05=clignotant 07=inversé caractères/fond
# 08=invisible (?)
# - Couleur des caractères :
# 30=noir 31=rouge 32=vert 33=jaune 34=bleu 35=magenta 36=cyan 37=blanc
# - Couleur du fond
# 40=noir 41=rouge 42=vert 43=marron 44=bleu 45=magenta 46=cyan 47=gris

# Couleur par défaut globale
NORMAL 00
# Couleur par défaut pour les fichiers
FILE 00
# Couleur pour les répertoires
DIR 01;32
# Couleur pour les liens symboliques
LINK 36
# Couleur pour les FIFOs
FIFO 33
# Couleur pour les sockets
SOCK 01;35
# Couleur pour les block device drivers
BLK 01;33
# Couleur pour les character device drivers
CHR 01;33
# Couleur pour les fichiers ayant les permissions d'exécution
EXEC 01;31

# Couleur pour les fichiers selon leur extension

# Fichiers de configuration
.conf 01;33;41
# Fichiers exécutables
.sh 01;31
.pl 01;31
.php3 01;31
.php 01;31
.py 01;31
# Fichiers compressés
.tar 36
.tgz 36
.arj 36
.taz 36
.lzh 36
.zip 36
.gz 36
.bz2 36
.rar 36
.tar.gz 36
# Packages
.deb 33
.rpm 33
# Fichiers images
.jpg 35
.JPG 35
.jpeg 35
.eps 35
.gif 35
.png 35
.bmp 35
.xpm 35
.tif 35
.tiff 35
.tga 35
.pcx 35
.cr2 35
.CR2 35
# Fichiers audio/vidéo
.avi 32
.mpg 32
.mpeg 32
.vob 32
.au 32
.wav 32
.mp3 32
.ogg 32
.mp4 32
.mkv 32
.webm 32
.flv 32


+ 10
- 0
env View File

@@ -0,0 +1,10 @@
# -*- sh -*-
# Could be sourced by simple POSIX shell

# No timeout
unset TMOUT

# Debian email address
[ x"$USER" != x"bernat" ] || export DEBEMAIL=$USER@debian.org

export GOPATH=$HOME/src/gocode

+ 225
- 0
functions/workon View File

@@ -0,0 +1,225 @@
# -*- sh -*-
# Description
# ===========
#
# Switch to another environment.
#
# An environment is either a virtualenv-based environment, a Docker
# image or a Docker container. Virtualenv-based environments are
# expected to be in $WORKON_HOME.

local env=$1
local -a venv dimages dcontainers
venv=($WORKON_HOME/*/bin/activate(.N:h:h:ft))
(( $+commands[docker] )) && [[ -w /var/run/docker.sock ]] && {
dimages=( $(docker images | awk '(NR > 1 && $1 !~ /^</){printf("%s:%s\n", $1,$2)}') )
dcontainers=( $(docker ps | awk '(NR > 1){split($NF,names,/,/); for (i in names) printf("%s\n",names[i])}') )
}

# No parameters, list available environment
[[ -n $env ]] || {
print "INFO: List of available environments:"
for env in $venv; do
print " - [virtualenv] $env"
done
for image in $dimages; do
print " - [docker ] $image"
done
for container in $dcontainers; do
print " - [docker ] $container"
done
return 0
}

[[ $env == "." ]] && env=${PWD:t}

# Docker stuff
local setupuser="
if ! id $USER > /dev/null 2> /dev/null; then
echo $(getent passwd $(id -u)) >> /etc/passwd
echo $(getent group $(id -g)) >> /etc/group
# Put sudo configuration even when no sudo (in case it gets installed later)
mkdir -p /etc/sudoers.d
echo \"$USER ALL=(ALL) NOPASSWD: ALL\" > /etc/sudoers.d/$USER
chmod 0440 /etc/sudoers.d/$USER
[ -x /usr/bin/sudo ] || {
cp /usr/sbin/chroot /usr/bin/_root
chown root:$(id -gn) /usr/bin/_root
chmod 4750 /usr/bin/_root
cat <<'EOF' > /usr/bin/sudo
#!/bin/sh
export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin

escape() {
echo \"\$1\" | sed s/\\'/\\'\\\"\\'\\\"\\'/g
}
args=
for arg in \"\$@\"; do
qarg=\$(escape \"\$arg\")
args=\"\$args '\$qarg'\"
done

exec /usr/bin/_root --userspec=root:root / /bin/sh -c \"cd '\$(escape \"\$PWD\")'; \$args\"
EOF
chmod +x /usr/bin/sudo
}
fi
"

# Docker images
[[ ${dimages[(r)$env]} == $env ]] && {
local image=${env}
local tmp=$(mktemp -d)
<<EOF > $tmp/start
#!/bin/sh
for SHELL in ${SHELL}-static $SHELL /bin/bash /bin/sh; do
[ ! -x \$SHELL ] || break
done
$setupuser
exec chroot --userspec=$(id -u):$(id -g) / \
env HOME=$HOME TERM=$TERM DOCKER_CHROOT_NAME=$env \
sh -c "[ -d '\$PWD' ] && cd '\$PWD' ; exec \$SHELL -i -l"
EOF
docker run -t -i \
$([[ -d /usr/share/zsh ]] && print -- -v /usr/share/zsh:/usr/share/zsh-static:ro) \
$([[ -x ${SHELL}-static ]] && print -- -v ${SHELL}-static:${SHELL}-static:ro) \
-v $HOME:$HOME \
-v $tmp:$tmp \
-w $PWD \
-u root \
--rm \
-h ${${${image##*/}:gs/:/-}:gs/./-} \
--entrypoint /bin/sh \
$image $tmp/start
local ret=$?
rm -f $tmp/start && rmdir $tmp
return $ret
}

# Docker containers
[[ ${dcontainers[(r)$env]} == $env ]] && {
local id=$(docker inspect --format '{{.State.Pid}}' $env)

# We need to mount $HOME inside the container, that's quite
# hacky: we get the device we need to mount, we mount it
# somewhere, then bind mount the home directory in the right
# place. All this with elevated privileges. We also create our
# user, with sudo rights. Most inspiration comes from here:
# http://blog.dehacked.net/lxc-getting-mounts-into-a-running-container/
#
# Also, from Docker 0.9, see:
# http://jpetazzo.github.io/2014/03/23/lxc-attach-nsinit-nsenter-docker-0-9/
# http://www.sebastien-han.fr/blog/2014/01/27/access-a-container-without-ssh/
#
# From Docker 1.3, see `docker exec'.
#
# So, this needs nsenter which needs a recent util-linux.
local homemnt=${${(f)"$(df --output=target $HOME)"}[-1]}
local homedev=$(readlink -f ${${(f)"$(df --output=source $HOME)"}[-1]})
local enter=/tmp/nsenter-$RANDOM-$$-$UID
${(%):-%(!..sudo)} =nsenter -m -t $id -- /bin/sh -e <<EOF
#!/bin/sh
if ! mountpoint $HOME > /dev/null 2>/dev/null; then
tmp=\$(mktemp -d)
mkdir -p ${HOME}
[ -b /dev/home-directory ] || mknod /dev/home-directory b $(stat -c "0x%t 0x%T" ${homedev})
mount -n /dev/home-directory \$tmp
rm /dev/home-directory
mount -n --bind \$tmp/${HOME#$homemnt} $HOME
umount -n \$tmp 2> /dev/null
rmdir \$tmp
fi

# Shell to use
for SHELL in $SHELL /bin/bash /bin/sh; do
[ ! -x \$SHELL ] || break
done

$setupuser

# Setup a command to enter this environment
> $enter echo exec 'chroot --userspec=$(id -u):$(id -g) / \
env HOME=$HOME TERM=$TERM DOCKER_CHROOT_NAME=$env \
sh -c "[ -d '"'"'$PWD'"'"' ] && cd '"'"'$PWD'"'"' ; exec '\$SHELL' -i -l"'

EOF
local ret=$?
[[ $ret -eq 0 ]] && {
${(%):-%(!..sudo)} =nsenter -m -u -i -n -p -w$HOME -t $id -- /bin/sh $enter
ret=$?
}
return $ret
}

function save() {
local v
for v ($@) {
_saved_environment[$v]=${${(e):-\$$v}}
}
}

function restore() {
local v
for v (${(k)_saved_environment}) {
unset $v
[[ -z ${_saved_environment[$v]} ]] || export $v=${_saved_environment[$v]}
}
}

# If in another virtualenv, call deactivate
(( $+functions[deactivate_node] )) && deactivate_node
(( $+functions[deactivate] )) && {
deactivate
restore
}

# Virtualenv
[[ ${venv[(r)$env]} == $env ]] && {
local activate="$WORKON_HOME/$env/bin/activate"
local VIRTUAL_ENV_DISABLE_PROMPT=1
local NODE_VIRTUAL_ENV_DISABLE_PROMPT=1
source $activate

typeset -Ag _saved_environment

# Gems.
# GEM_HOME is where gems will be installed.
# GEM_PATH is where gems are searched
save GEM_HOME GEM_PATH
export GEM_HOME=$VIRTUAL_ENV/gems
export GEM_PATH=$GEM_HOME
path=( $GEM_HOME/bin $path )

# Go
save GOPATH
export GOPATH=$VIRTUAL_ENV/go
path=( $GOPATH/bin $path)

# C (install with ./configure --prefix=$VIRTUAL_ENV)
save LD_LIBRARY_PATH PKG_CONFIG_PATH
export LD_LIBRARY_PATH=$VIRTUAL_ENV/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig
path=( $VIRTUAL_ENV/sbin $path )

# OCaml (through OPAM)
(( $+commands[opam] )) && {
save OPAMROOT MANPATH PERL5LIB CAML_LD_LIBRARY_PATH OCAML_TOPLEVEL_PATH
export OPAMROOT=$VIRTUAL_ENV/opam
[[ -d $OPAMROOT ]] && \
eval $(opam config env)
}

# node.js workaround
[[ -z $NPM_CONFIG_PREFIX ]] || {
save npm_config_prefix
export npm_config_prefix=$NPM_CONFIG_PREFIX
}

rehash
return
}

[[ $env == "-" ]] || {
print "ERROR: environment $env does not exist"
return 2
}

+ 69
- 0
plugins/battery.plugin.zsh View File

@@ -0,0 +1,69 @@
# -*- sh -*-

# acpi -b output
#
# Battery X: YYYYYY, ZZ%
# Battery X: YYYYYY, ZZ%, rate information unavailable
# Battery X: YYYYYY, ZZ%, charging at zero rate
# Battery X: YYYYYY, ZZ%, discharging at zero rate
# Battery X: YYYYYY, ZZ%, HH:MM:SS remaining
# Battery X: YYYYYY, ZZ%, HH:MM:SS until charged
#
# YYYYYY = charging
# YYYYYY = discharging

_vbe_battery () {
(( $+commands[acpi] )) || return
local cache=$ZSH/run/u/$HOST-$UID/acpi
zmodload zsh/stat
zmodload zsh/datetime
if [[ -f $cache ]] && \
(( $EPOCHSECONDS - $(stat +mtime $cache) < 240 )); then
print -n $(<$cache)
return
fi

local acpi
local percent
local state
acpi=(${(f)$(acpi -b)})
percent=${(L)${${acpi[1]}#*, }%\%, *}
state=${(L)${${acpi[1]}#*: }%%, *}
[[ $state == (dis|)charging ]] || {
: > $cache
return
}

local -a gauge
local size=4
local full
local g
local i j
_vbe_can_do_unicode && gauge=(▲ ▼ △ ▽) || gauge=('#' '#' '-' '-')
full=$(( (${percent}*${size}+49)/100 ))
if (( $percent < 10 )); then
g=red
elif (( $percent < 30 )); then
g=yellow
else
g=green
fi
i=1
[[ $state == "discharging" ]] && i=2
local gg
(( $full >= 1 )) && for j in {1..$full}; do gg=$gg$gauge[$i]; done
i=$(( $i + 2 ))
(( $full < $size )) && \
for j in {$(( $full + 1 ))..$size}; do gg=$gg$gauge[$i]; done
print -n $g $gg > $cache
print $g $gg
}

_vbe_add_prompt_battery () {
local v="$(_vbe_battery)"
local color=${v% *}
local gauge="${v#* }"

[[ -n $gauge ]] && \
_vbe_prompt_segment $color black %B$gauge
}

+ 24
- 0
plugins/hebex.plugin.zsh View File

@@ -0,0 +1,24 @@
# -*- sh -*-

# Telnet through HNM
telnet() {
_vbe_title "$*"
case "$1" in
*.net.b?.p.fti.net|swbg*)
host=bgadm
;;
*.net.s?.p.fti.net)
host=soadm
;;
*.net.m?.p.fti.net)
host=mtadm
;;
*)
# Don't know how to handle, let's just use normal telnet
command telnet "$@"
return
;;
esac
LANG=C LC_MESSAGES=C command ssh -t $host \
telnet $1
}

+ 39
- 0
plugins/vcs.plugin.zsh View File

@@ -0,0 +1,39 @@
# -*- sh -*-

# Incorporate git and svn information into prompt

(( $+functions[add-zsh-hook] )) && {

autoload -Uz vcs_info

zstyle ':vcs_info:*' enable git svn
__() {
local common='${PRCH[branch]} %b%c%u'
zstyle ':vcs_info:*:*' formats $common
zstyle ':vcs_info:*:*' actionformats ${common}'%{${fg[default]}%} ${PRCH[sep]} %{${fg[green]}%}'%a
zstyle ':vcs_info:svn:*' branchformat '%b:%r'
zstyle ':vcs_info:hg*:*' hgrevformat '%r'
zstyle ':vcs_info:*:*' stagedstr %{${fg[green]}%}${PRCH[circle]}
zstyle ':vcs_info:*:*' unstagedstr %{${fg[yellow]}%}${PRCH[circle]}
zstyle ':vcs_info:*:*' check-for-changes true
zstyle ':vcs_info:hg*:*' get-revision true

zstyle ':vcs_info:git*+set-message:*' hooks git-untracked

+vi-git-untracked(){
if [[ $(git rev-parse --is-inside-work-tree 2> /dev/null) == 'true' ]] && \
git status --porcelain | grep '??' &> /dev/null ; then
hook_com[staged]+='%{${fg[black]}%}${PRCH[circle]}'
fi
}

} && __

_vbe_vcs_precmd () {
vcs_info
}
add-zsh-hook precmd _vbe_vcs_precmd
_vbe_add_prompt_vcs () {
_vbe_prompt_segment cyan default ${(e)vcs_info_msg_0_}
}
}

+ 28
- 0
rc/00-helpers.zsh View File

@@ -0,0 +1,28 @@
# -*- sh -*-

_vbe_autoload () {
# Like autoload but actually load and fail silently if not able to load
(( $+functions[$1] )) && return 0
autoload +X $1 2> /dev/null || {
unset -f $1
return 1
}
return 0
}

_vbe_autoload is-at-least || is-at-least() { return 0 }

# Test for unicode support
_vbe_can_do_unicode () {
if is-at-least 4.3.4 && \
[[ -o multibyte ]] && (( ${#${:-↵}} == 1 )); then
case $TERM in
screen*) ;;
xterm*) ;;
rxvt*) ;;
*) return 1 ;;
esac
return 0
fi
return 0
}

+ 17
- 0
rc/00-hostname.zsh View File

@@ -0,0 +1,17 @@
# -*- sh -*-

# Export HOSTNAME variable
__() {
local -a hostnames
local host
hostnames=($(hostname -f)
$(hostname)
$(</etc/hostname)
$HOST
$HOST.$(</etc/mailname))
for host ($hostnames); do
HOSTNAME=${host%%.}
[[ $HOSTNAME == *.* ]] && break
done
export HOSTNAME
} && __ 2> /dev/null

+ 12
- 0
rc/00-path.zsh View File

@@ -0,0 +1,12 @@
# -*- sh -*-

__() {
local wanted
local p
wanted=(/usr/local/sbin /usr/sbin /sbin /usr/local/bin /usr/bin /bin /usr/lib/ccache ~/bin)
for p in $wanted; do
(( ${${path[(r)$p]}:+1} )) || {
[ -d $p ] && path=($p $path)
}
done
} && __

+ 19
- 0
rc/01-locale.zsh View File

@@ -0,0 +1,19 @@
# -*- sh -*-

(( $+commands[locale] )) && __() {
local available
local locales
local locale
locales=( "LANG fr_FR.utf8 fr_FR.UTF-8 en_US.utf8 en_US.UTF-8 C.utf8 C.UTF-8 C" \
"LC_MESSAGES en_US.utf8 en_US.UTF-8 fr_FR.utf8 fr_FR.UTF-8 C.utf8 C.UTF-8 C" )
available=("${(f)$(locale -a)}")
for locale in $locales; do
for l in $=locale[(w)2,-1]; do
if (( ${available[(i)$l]} <= ${#available} )); then
export $locale[(w)1]=$l
break
fi
done
done
unset LC_ALL
} && __ 2> /dev/null

+ 19
- 0
rc/01-run.zsh View File

@@ -0,0 +1,19 @@
# -*- sh -*-

# Create $ZSH/run/u if it doesn't exist
[[ -d $ZSH/run/u ]] || {
mkdir -p $ZSH/run/u
chmod 1777 $ZSH/run/u
}

# Create per-UID directory and do migration
[[ -d $ZSH/run/u/$HOST-$UID ]] || {
mkdir -p $ZSH/run/u/$HOST-$UID
for f in $ZSH/run/{acpi,history,editor,zcompdump,bookmarks}-$HOST-$UID(N); do
mv $f $ZSH/run/u/$HOST-$UID/${${f##*/}%-$HOST-$UID}
done
for f in $ZSH/run/u/$UID/{acpi,history,editor,zcompdump,bookmarks}-$HOST(N); do
mv $f $ZSH/run/u/$HOST-$UID/${${f##*/}%-$HOST}
done
rmdir $ZSH/run/u/$UID 2> /dev/null
}

+ 76
- 0
rc/02-terminfo.zsh View File

@@ -0,0 +1,76 @@
# -*- sh -*-

# Update TERM if we have LC__ORIGINALTERM variable
# Also, try a sensible term where we have terminfo stuff
autoload -U zsh/terminfo zsh/termcap
__() {
local term

case $COLORTERM,$TERM in
vbeterm,xterm | xfce4-terminal,xterm )
TERM=xterm-256color
;;
esac

for term in $LC__ORIGINALTERM $TERM ${TERM/-256color} xterm-256color xterm; do
TERM=$term 2> /dev/null
if (( ${terminfo[colors]:-0} >= 8 )) || \
(zmodload zsh/termcap 2> /dev/null) && \
(( ${termcap[Co]:-0} >= 8)); then
if _vbe_autoload colors; then
colors
else
# Minimal version with what we need
local -A color
color=(none 00
fg-black 30 bg-black 40
fg-red 31 bg-red 41
fg-green 32 bg-green 42
fg-yellow 33 bg-yellow 43
fg-blue 34 bg-blue 44
fg-magenta 35 bg-magenta 45
fg-cyan 36 bg-cyan 46
fg-white 37 bg-white 47
fg-default 39 bg-default 49)
local lc=$'\e[' rc=m
local k
typeset -AHg fg bg
for k in ${(k)color[(I)fg-*]}; do
fg[${k#fg-}]="$lc${color[$k]}$rc"
done
for k in ${(k)color[(I)bg-*]}; do
bg[${k#bg-}]="$lc${color[$k]}$rc"
done
typeset -Hg reset_color
reset_color="$lc${color[none]}$rc"
fi
break
fi
done
unset LC__ORIGINALTERM
unset COLORTERM
export TERM
} && __


typeset -gA PRCH
if _vbe_can_do_unicode; then
PRCH=(
sep "\uE0B1" end "\uE0B0"
retb "" reta " ↵"
circle "●" branch "\uE0A0"
ok "✔" ellipsis "…"
eol "⏎" running "↻"
)
else
PRCH=(
sep "/" end ""
retb "<" reta ">"
circle "*" branch "±"
ok ">" ellipsis ".."
eol "~~" running "> "
)
fi

# Freeze the terminal
ttyctl -f

+ 71
- 0
rc/02-title.zsh View File

@@ -0,0 +1,71 @@
# -*- sh -*-

# Alter window title
_vbe_title () {
[ -t 1 ] || return
emulate -L zsh
local title
title=${1//[^[:alnum:]\/>< ._~:=?@-]/ }
shorttitle=${2:-$1}
case $TERM in
screen*)
print -n "\ek$shorttitle\e\\"
print -n "\e]1;$title\a"
print -n "\e]2;$title\a"
;;
rxvt*|xterm*)
print -n "\e]1;$title\a"
print -n "\e]2;$title\a"
;;
esac
}

# Current running program as title
_title_preexec () {
emulate -L zsh
setopt extended_glob
local t tt
local -a cmd
cmd=(${(z)1})
case $cmd[1] in
fg)
case $#cmd in
1)
t=${jobtexts[${(k)jobstates[(R)*+*]}]}
;;
*)
t=${jobtexts[${cmd[2]#%}]}
;;
esac
;;
%*)
t=${jobtexts[${cmd[1]#%}]}
;;
*=*|exec|sudo|\()
(( ${#cmd} > 1 )) && shift cmd
;&
*)
case $cmd[1] in
less|more|v|e|vi|vim|emacs|ssh)
# Display filename
t=$cmd[*]
tt=${${${(R)cmd:#-*}[2]}:t}
;;
*)
t=$cmd[*]
tt=$cmd[1]:t
;;
esac
;;
esac
# _vbe_title "${SSH_TTY+${(%):-%M} }\> $t" "${SSH_TTY+${(%):-%M} }${PRCH[running]}${tt:-${t%% *}}"
_vbe_title "$t" "${PRCH[running]}${tt:-${t%% *}}"

}
if (( $+functions[add-zsh-hook] )); then
add-zsh-hook preexec _title_preexec
else
preexec () {
_title_preexec
}
fi

+ 5
- 0
rc/03-temp.zsh View File

@@ -0,0 +1,5 @@
# -*- sh -*-

# Create a temporary directory
[ ! -h ~/tmp ] && [ ! -d ~/tmp ] && [ -w ~ ] && \
mkdir ~/tmp

+ 66
- 0
rc/05-completion.zsh View File

@@ -0,0 +1,66 @@
# -*- sh -*-

autoload -U zutil

_vbe_autoload compinit && {
autoload -U complist
compinit -i -d $ZSH/run/u/$HOST-$UID/zcompdump
}

setopt auto_menu
setopt auto_remove_slash
setopt complete_in_word
setopt always_to_end
setopt glob_complete
unsetopt list_beep

zstyle ':completion:*' completer _complete _match _approximate
zstyle ':completion:*' list-colors ''
zstyle ':completion:*' list-prompt ''
zstyle ':completion:*' group-name ''
zstyle ':completion:*' menu select
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'
zstyle ':completion:*:kill:*' force-list always
zstyle ':completion:*:processes' command "ps -eo pid,user,comm,cmd -w -w"
zstyle ':completion::complete:*' use-cache 1
zstyle ':completion::complete:*' cache-path $ZSH/run/u/$HOST-$UID/cache/
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:match:*' original only
zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'

# Host completion
_custom_hosts() {
# Complete ~/.zsh/local/hosts.*
local host
for host in $ZSH/local/hosts.*(N-.); do
_wanted hosts expl host compadd "$@" $(<$host)
done

# And /etc/hosts
_wanted hosts expl host \
compadd "$@" ${(s: :)${(ps:\t:)${${(f)~~"$(</etc/hosts)"}%%\#*}##[:blank:]#[^[:blank:]]#}}

# Now, try LDAP
[[ -z $LDAPHOST ]] || {
_wanted hosts expl host \
compadd "$@" ${$(ldapsearch -h $LDAPHOST \
-b "ou=hosts,dc=fti,dc=net" -LLL -s sub -z 100 \
-x "cn=${words[CURRENT]}*" cn 2> /dev/null)%* }
}
}

zstyle -e ':completion:*' hosts _custom_hosts

# In menu, select items with +
zmodload -i zsh/complist
bindkey -M menuselect "+" accept-and-menu-complete

# Display dots when completion is in progress
expand-or-complete-with-dots() {
echo -n "\e[31m...\e[0m"
zle expand-or-complete
zle redisplay
}
zle -N expand-or-complete-with-dots
bindkey "^I" expand-or-complete-with-dots

+ 371
- 0
rc/alias.zsh View File

@@ -0,0 +1,371 @@
# -*- sh -*-

# Some generic aliases
alias df='df -h'
alias du='du -h'
alias rm='rm -i'
alias ll='ls -l'
alias s='cd ..'
__() {
local dmesg_version=${${${:-"$(dmesg --version 2> /dev/null)"}##* }:-0.0}
if is-at-least 2.23 $dmesg_version; then
alias dmesg='dmesg -H -P'
elif is-at-least 0.1 $dmesg_version; then
alias dmesg='dmesg -T'
fi
} && __

# ls colors
(( ${terminfo[colors]:-0} >= 8 )) && {
export LSCOLORS="Gxfxcxdxbxegedabagacad"
ls --color -d . &>/dev/null && alias ls='ls --color=tty' || {
ls -G &> /dev/null && alias ls='ls -G'
}
}
# alias de ls
alias ls='ls --classify --tabsize=0 --literal --color=auto --show-control-chars --human-readable'

alias l='ls -lh'
alias ll='ls -l'
alias la='ls -a'
alias lla='ls -la'
# ls pour voir que les fichiers par .
alias lsa='ls -ld .*'

alias sl=ls # pour les ceussent qui pensent à la fin avant le début ;-)

alias grep='grep --color=always'

# ip aliases
alias ip6='ip -6'
alias ipr='ip -r'
alias ip6r='ip -6 -r'
alias ipm='ip -r monitor'

# Setting up less colors
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;38;5;74m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[7;32;5;246m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[04;38;5;146m'

# grep
__() {
local cmd
local -A greps
greps=(grep ""
rgrep r
egrep E
fgrep F
zgrep "")
for cmd in ${(k)greps}; do
if (( $+commands[$cmd] )); then
alias $cmd="$cmd --color=auto"
else
[[ -n ${greps[$cmd]} ]] &&
alias $cmd='command grep -${greps[$cmd]} --color=auto'
fi
done
} && __

# smv like scp
alias smv='rsync -P --remove-source-files'
(( $+functions[compdef] )) && compdef _ssh smv=scp

# Less generic aliases
susu() {
command sudo -H -u ${1:-root} \
env ZDOTDIR=${ZDOTDIR:-$HOME} \
ZSH=$ZSH ${DISPLAY+DISPLAY=$DISPLAY} \
${SSH_TTY+SSH_TTY=$SSH_TTY} \
${SSH_AUTH_SOCK+SSH_AUTH_SOCK=$SSH_AUTH_SOCK} \
zsh -i -l
}
alias please='sudo $(fc -ln -1)'

# Aliases as a function
evince() { command evince ${*:-*.(djvu|dvi|pdf)(om[1])} }
md() { command mkdir -p $1 && cd $1 }

# JSON pretty-printing.
#
# Many programs have a flag to enable unbuffered output. For example,
# `curl -N`. Most programs can be forced to use unbuffered output with
# `stdbuf -o L`.
json() {
PATH=/usr/bin:$PATH python -u -c '#!/usr/bin/env python

# Pretty-print files containing JSON lines. Reads from stdin when no
# argument is provided, otherwise pretty print each argument. This
# script should be invoked with "-u" to disable buffering. The shebang
# above is just for syntax highlighting to work correctly.

import sys
import re
import json
import subprocess
import errno
try:
import pygments
from pygments.lexers import JavascriptLexer
from pygments.formatters import TerminalFormatter
except ImportError:
pygments = None

jsonre = re.compile(r"(?P<prefix>.*?)(?P<json>\{.*\})(?P<suffix>.*)")


def display(f):
pager = None
out = sys.stdout
if out.isatty() and f != sys.stdin:
pager = subprocess.Popen(["less", "-RFX"], stdin=subprocess.PIPE)
out = pager.stdin
while True:
line = f.readline()
if line == "":
break
mo = None
try:
mo = jsonre.match(line)
if not mo:
raise ValueError("No JSON string found")
j = json.loads(mo.group("json"))
pretty = json.dumps(j, indent=2)
if pygments and sys.stdout.isatty():
pretty = pygments.highlight(pretty,
JavascriptLexer(),
TerminalFormatter())
output = (mo.group("prefix") + pretty.strip() +
mo.group("suffix") + "\n")
except:
output = line
try:
out.write(output)
except IOError as e:
if e.errno == errno.EPIPE or e.errno == errno.EINVAL:
break
raise
if pager is not None:
pager.stdin.close()
pager.wait()

if len(sys.argv) == 1:
files = [sys.stdin]
else:
files = sys.argv[1:]

for f in files:
try:
if type(f) != file:
with file(f) as f:
display(f)
else:
display(f)
except KeyboardInterrupt:
sys.exit(1)
' "$@"
}

# Other pretty-printing functions
if (( $+commands[pygmentize] )); then
__pygmentize() {
PATH=/usr/bin:$PATH python -u -c "#!/usr/bin/env python
import sys
import errno
import pygments.cmdline
try:
sys.exit(pygments.cmdline.main(sys.argv))
except KeyboardInterrupt:
sys.exit(1)
except IOError as e:
if e.errno == errno.EPIPE:
sys.exit(1)
raise
" "$@"
}

xml() {
cat "$@" | xmllint --format - | __pygmentize -l xml
}

v() {
local formatter
if (( ${terminfo[colors]:-0} >= 256 )); then
formatter=console256
else
formatter=terminal
fi

local lexer
lexer=$(__pygmentize -N "${1%.gz}")

local -a args
args=(-P style=monokai -f $formatter)
case $lexer in
text)
args=(-g $args)
;;
*)
args=(-l $lexer)
;;
esac

zcat -f "$@" | __pygmentize $args | less -RFX
}
else
xml() {
cat "$@" | xmllint --format -
}

alias v=zless -FX
fi

# Record a video
screenrecord() {
(
eval $(xdotool selectwindow getwindowgeometry --shell) &&
command ffmpeg -f x11grab \
-draw_mouse 0 \
-r 25 \
-s ${WIDTH}x${HEIGHT} \
-i ${DISPLAY}.${SCREEN:-0}+${X:-0},${Y:-0} \
-dcodec copy \
-pix_fmt yuv420p \
-c:v libx264 \
-preset ultrafast \
$@
)
}

# Reimplementation of an xterm tool
resize() {
printf '\033[18t'

local width
local height
local state
local char

state=0
while read -r -s -k 1 -t 1 char; do
case "$state,$char" in
"0,;")
# End of CSI
state=1
;;
"1,;")
# End of height
stty rows $height
state=2
;;
"1,"*)
height="$height$char"
;;
"2,t")
# End of width
stty columns $width
state=3
;;
"2,"*)
width="$width$char"
;;
esac
(( $state == 3 )) && break
done
# tmux <= 1.9.1 is buggy and doesn't end its answer with 't'
(( $state == 2 )) && stty columns $width
}

# Simple calculator
function c() {
echo $(($@))
}
alias c='noglob c'

# Currency conversion (with Google)
function currency() {
local -a amounts
local -a currencies
for ((i=1; i<=$#; i++)); do
case ${@[i]} in
[0-9.]*)
amounts=($amounts ${@[i]})
;;
*)
currencies=($currencies ${@[i]})
;;
esac
done
(( $#currencies > 1 )) || currencies=($currencies chf eur usd)
local from=${currencies[1]}
for amount in $amounts; do
for to in $currencies; do
[[ ${to:u} != ${from:u} ]] || continue
#echo "Convert $amount ${from:u} to ${to:u}"
curl -s "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to" | \
sed '/res/!d;s/<[^>]*>//g'
done
done
}

# Allow to prefix commands with `$` to help copy/paste operations.
function \$() {
"$@"
}

# Get my own external IP
function myip() {
for v in 4 6 ; do
echo IPv$v $(false || \
curl -$v -s ip.appspot.com || \
curl -$v -s eth0.me || \
curl -$v -s ipecho.net/plain ||
dig -$v +short myip.opendns.com @resolver1.opendns.com)
done
}

# Display a color testcard
# From: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
colortest() {
local T='gYw' # The test text

local fg
local bg
printf "%12s" ""
for fg in {40..47}; do
printf "%7sm" ${fg}
done
printf "\n"
for fg in 0 1 $(for i in {30..37}; do echo $i 1\;$i; done); do
printf " %5s \e[%s %s " ${fg}m ${fg}m ${T}
for bg in {40..47}m; do
printf " \e[%s\e[%s %s \e[0m" ${fg}m ${bg} ${T}
done
printf "\n"
done
printf "\n"

printf "Color cube: 6x6x6:\n"
local red
local green
local blue
for red in {0..5}; do
for green in {0..5}; do
for blue in {0..5}; do
bg=$((16 + red * 36 + green * 6 + blue))
printf "\e[48;5;%dm " bg
done
printf "\e[0m "
done
printf "\n"
done

printf "\nGrayscale ramp:\n"
for bg in {232..255}; do
printf "\e[48;5;%dm " bg
done
printf "\e[0m\n"
}

+ 61
- 0
rc/bookmarks.zsh View File

@@ -0,0 +1,61 @@
# -*- sh -*-

# Handle bookmarks. This uses the static named directories feature of
# zsh. Such directories are declared with `hash -d
# name=directory`. Both prompt expansion and completion know how to
# handle them. We populate the hash with directories.
#
# With autocd, you can just type `~-bookmark`. Since this can be
# cumbersome to type, you can also type `@@` and this will be turned
# into `~-` by ZLE.

is-at-least 4.3.12 && __() {
MARKPATH=$ZSH/run/marks

# Add some static entries
hash -d log=/var/log
hash -d doc=/usr/share/doc

# Populate the hash
for link ($MARKPATH/*(N@)) {
hash -d -- -${link:t}=${link:A}
}

vbe-insert-bookmark() {
emulate -L zsh
LBUFFER=${LBUFFER}"~-"
}
zle -N vbe-insert-bookmark
bindkey '@@' vbe-insert-bookmark

# Manage bookmarks
bookmark() {
[[ -d $MARKPATH ]] || mkdir -p $MARKPATH
if (( $# == 0 )); then
# When no arguments are provided, just display existing
# bookmarks
for link in $MARKPATH/*(N@); do
local markname="$fg[green]${link:t}$reset_color"
local markpath="$fg[blue]${link:A}$reset_color"
printf "%-30s -> %s\n" $markname $markpath
done
else
# Otherwise, we may want to add a bookmark or delete an
# existing one.
local -a delete
zparseopts -D d=delete
if (( $+delete[1] )); then
# With `-d`, we delete an existing bookmark
command rm $MARKPATH/$1
else
# Otherwise, add a bookmark to the current
# directory. The first argument is the bookmark
# name. `.` is special and means the bookmark should
# be named after the current directory.
local name=$1
[[ $name == "." ]] && name=${PWD:t}
ln -s $PWD $MARKPATH/$name
fi
fi