Browse Source

first commit

master
Manfraid 3 years ago
commit
56f5d70b30

+ 6
- 0
.gitignore View File

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

+ 12
- 0
.gitmodules View File

@@ -0,0 +1,12 @@
1
+[submodule "third-party/docker-zsh-completion"]
2
+	path = third-party/docker-zsh-completion
3
+	url = git@github.com:felixr/docker-zsh-completion.git
4
+[submodule "third-party/zsh-syntax-highlighting"]
5
+	path = third-party/zsh-syntax-highlighting
6
+	url = git@github.com:zsh-users/zsh-syntax-highlighting.git
7
+[submodule "third-party/zsh-completions"]
8
+	path = third-party/zsh-completions
9
+	url = git@github.com:vincentbernat/zsh-completions.git
10
+[submodule "third-party/docker-compose-zsh-completion"]
11
+	path = third-party/docker-compose-zsh-completion
12
+	url = git@github.com:sdurrheimer/docker-compose-zsh-completion.git

+ 24
- 0
.travis.yml View File

@@ -0,0 +1,24 @@
1
+language: c
2
+os: linux
3
+git:
4
+  submodules: false
5
+sudo: false
6
+addons:
7
+  apt:
8
+    packages:
9
+      - zsh
10
+install:
11
+  - sed -i 's+git@github.com:+https://github.com/+' .gitmodules
12
+  - git submodule update --init --recursive
13
+script:
14
+  - ZSH=$PWD zsh -c ". rc/install.zsh && install-zsh"
15
+  - mkdir artifacts && cp run/zsh-install.sh artifacts && git reset --hard
16
+deploy:
17
+  provider: s3
18
+  access_key_id: AKIAJWSE4LXWA33RNIYA
19
+  secret_access_key:
20
+    secure: fNGzrG9db2dgOin9A9pP1Giqjl2u44l6cOh0E9/cnjpg/0aC53fmhJ5u4MZVb05ZwgnJ56I1tc1GLNbAnTOqY+5dzm4zQ2VDpj3gzD+WPtdfaW+jkTh8cNanzWcZm3wZgmSeIzWpadfqsFZM9mPB1Ntw2CFvmrRFJpi3lb+PmTI=
21
+  bucket: vincentbernat-zshrc
22
+  acl: public_read
23
+  local_dir: artifacts
24
+  skip_cleanup: true

+ 32
- 0
README.md View File

@@ -0,0 +1,32 @@
1
+My `.zshrc`
2
+===========
3
+
4
+My `.zshrc` may not suit your needs. Feel free to read and
5
+understand. Steal anything. My opinion is that you can't have an
6
+universal `.zshrc`. If you don't agree, take a look at
7
+[Prezto](https://github.com/sorin-ionescu/prezto).
8
+
9
+You need to create your own `.zshrc`. First solution is to symlink
10
+`~/.zsh/zshrc`. The other solution is to source `~/.zsh/zshrc` from
11
+your own `~/.zshrc`. The later case allows you to set the plugin you
12
+want to enable.
13
+
14
+You can copy your installation to a remote host with `install-zsh`
15
+function.
16
+
17
+`~/.zsh/run` contains runtime files, like history. `~/.zsh/local`
18
+contains local files that should not be copied to a remote host.
19
+
20
+Installation
21
+------------
22
+
23
+So, if you are one of those young generation not concerned about
24
+arbitrary code execution, you can do:
25
+
26
+    curl -s https://vincentbernat-zshrc.s3.amazonaws.com/zsh-install.sh | sh
27
+
28
+License
29
+-------
30
+
31
+All the code is licensed as
32
+[CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/legalcode).

+ 1
- 0
completions/_adb View File

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

+ 1
- 0
completions/_cabal View File

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

+ 50
- 0
completions/_cowbuilder View File

@@ -0,0 +1,50 @@
1
+#compdef cowbuilder
2
+
3
+_cowbuilder_environments() {
4
+    local -a results
5
+    local distrib
6
+    for cow in /var/cache/pbuilder/base-*.cow(N); do
7
+        distrib=${${${cow:t}%.cow}#base-}
8
+        arch=${(M)${(f)"$(dpkg-architecture -L)"}:#${distrib##*-}}
9
+        [[ -z $arch ]] || distrib=${distrib%-*}/$arch
10
+        results=($results $distrib)
11
+    done
12
+    _wanted base expl 'base path' compadd -a \
13
+	results
14
+}
15
+
16
+local context state state_descr line expl
17
+typeset -A opt_args
18
+
19
+_arguments \
20
+    '1:::_cowbuilder_environments' \
21
+    '2:action:((--create\:"create new environment"
22
+                --build\:"build a package"
23
+                --update\:"update environment"
24
+                --login\:"login into environment"
25
+                --execute\:"execute a command"))' \
26
+    '*:: :->subcmds' \
27
+    && return 0
28
+
29
+case "$words[2]" in
30
+    --build)
31
+	if (( CURRENT == 3 )); then
32
+	    _wanted dsc expl "dsc file" _files -g "*.dsc"
33
+	fi
34
+	;;
35
+    --execute)
36
+	precommands+=($words[2])
37
+	shift 2 words
38
+	(( CURRENT -= 2 ))
39
+	_normal
40
+	;;
41
+esac
42
+
43
+return 0
44
+
45
+# Local Variables:
46
+# mode: Shell-Script
47
+# sh-indentation: 4
48
+# indent-tabs-mode: nil
49
+# sh-basic-offset: 4
50
+# End:

+ 19
- 0
completions/_dm View File

@@ -0,0 +1,19 @@
1
+#compdef dm
2
+
3
+case $CURRENT in
4
+    2)
5
+        local cmds
6
+        local -a commands
7
+        cmds=$(dm commands)
8
+        commands=(${(ps:\n:)cmds})
9
+        _wanted command expl "dm command" compadd -a commands
10
+        ;;
11
+    *)
12
+        local cmd subcmds
13
+        local -a commands
14
+        cmd=${words[2]}
15
+        subcmds=$(dm completions ${words[2,$(($CURRENT - 1))]})
16
+        commands=(${(ps:\n:)subcmds})
17
+        _wanted subcommand expl "dm $cmd subcommand" compadd -a commands
18
+        ;;
19
+esac

+ 1
- 0
completions/_docker View File

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

+ 1
- 0
completions/_docker-compose View File

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

+ 14
- 0
completions/_evince View File

@@ -0,0 +1,14 @@
1
+#compdef evince
2
+
3
+local arguments
4
+arguments=(
5
+  '(-p --page-label)'{-p,--page-label=}'[the page label of the document to display]'
6
+  '(-i --page-index)'{-i,--page-index=}'[the page number of the document to display]'
7
+  '(-f --fullscreen)'{-f,--fullscreen}'[run evince in fullscreen mode]'
8
+  '(-s --presentation)'{-s,--presentation}'[run evince in presentation mode]'
9
+  '(-w --preview)'{-w,--preview}'[run evince as a previewer]'
10
+  '(-l --find)'{-l,--find=}'[the word or phrase to find in the document]'
11
+  '--display=[X display to use]'
12
+  '*:PostScript, Djvu or PDF file:_files -g "*.(#i)(pdf|ps|eps|djvu)(-.)"'
13
+)
14
+_arguments -s $arguments

+ 1
- 0
completions/_fab View File

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

+ 156
- 0
completions/_go View File

@@ -0,0 +1,156 @@
1
+#compdef go
2
+
3
+# See: http://golang.org/misc/zsh/go
4
+
5
+# go tool
6
+__go_tool_complete() {
7
+  typeset -a commands build_flags
8
+  commands+=(
9
+    'build[compile packages and dependencies]'
10
+    'clean[remove object files]'
11
+    'doc[run godoc on package sources]'
12
+    'env[print Go environment information]'
13
+    'fix[run go tool fix on packages]'
14
+    'fmt[run gofmt on package sources]'
15
+    'get[download and install packages and dependencies]'
16
+    'help[display help]'
17
+    'install[compile and install packages and dependencies]'
18
+    'list[list packages]'
19
+    'run[compile and run Go program]'
20
+    'test[test packages]'
21
+    'tool[run specified go tool]'
22
+    'version[print Go version]'
23
+    'vet[run go tool vet on packages]'
24
+  )
25
+  if (( CURRENT == 2 )); then
26
+    # explain go commands
27
+    _values 'go tool commands' ${commands[@]}
28
+    return
29
+  fi
30
+  build_flags=(
31
+    '-a[force reinstallation of packages that are already up-to-date]'
32
+    '-n[print the commands but do not run them]'
33
+    '-p[number of parallel builds]:number'
34
+    '-race[enable data race detection]'
35
+    '-x[print the commands]'
36
+    '-work[print temporary directory name and keep it]'
37
+    '-ccflags[flags for 5c/6c/8c]:flags'
38
+    '-gcflags[flags for 5g/6g/8g]:flags'
39
+    '-ldflags[flags for 5l/6l/8l]:flags'
40
+    '-gccgoflags[flags for gccgo]:flags'
41
+    '-compiler[name of compiler to use]:name'
42
+    '-installsuffix[suffix to add to package directory]:suffix'
43
+    '-tags[list of build tags to consider satisfied]:tags'
44
+  )
45
+  __go_list() {
46
+      local expl importpaths
47
+      declare -a importpaths
48
+      importpaths=($(go list ${words[$CURRENT]}... 2>/dev/null))
49
+      _wanted importpaths expl 'import paths' compadd "$@" - "${importpaths[@]}"
50
+  }
51
+  case ${words[2]} in
52
+  clean|doc)
53
+      _arguments -s -w : '*:importpaths:__go_list'
54
+      ;;
55
+  fix|fmt|list|vet)
56
+      _alternative ':importpaths:__go_list' ':files:_path_files -g "*.go"'
57
+      ;;
58
+  install)
59
+      _arguments -s -w : ${build_flags[@]} \
60
+        "-v[show package names]" \
61
+        '*:importpaths:__go_list'
62
+      ;;
63
+  get)
64
+      _arguments -s -w : \
65
+        ${build_flags[@]}
66
+      ;;
67
+  build)
68
+      _arguments -s -w : \
69
+        ${build_flags[@]} \
70
+        "-v[show package names]" \
71
+        "-o[output file]:file:_files" \
72
+        "*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
73
+      ;;
74
+  test)
75
+      _arguments -s -w : \
76
+        ${build_flags[@]} \
77
+        "-c[do not run, compile the test binary]" \
78
+        "-i[do not run, install dependencies]" \
79
+        "-v[print test output]" \
80
+        "-x[print the commands]" \
81
+        "-short[use short mode]" \
82
+        "-parallel[number of parallel tests]:number" \
83
+        "-cpu[values of GOMAXPROCS to use]:number list" \
84
+        "-run[run tests and examples matching regexp]:regexp" \
85
+        "-bench[run benchmarks matching regexp]:regexp" \
86
+        "-benchmem[print memory allocation stats]" \
87
+        "-benchtime[run each benchmark until taking this long]:duration" \
88
+        "-blockprofile[write goroutine blocking profile to file]:file" \
89
+        "-blockprofilerate[set sampling rate of goroutine blocking profile]:number" \
90
+        "-timeout[kill test after that duration]:duration" \
91
+        "-cpuprofile[write CPU profile to file]:file:_files" \
92
+        "-memprofile[write heap profile to file]:file:_files" \
93
+        "-memprofilerate[set heap profiling rate]:number" \
94
+        "*:args:{ _alternative ':importpaths:__go_list' ':files:_path_files -g \"*.go\"' }"
95
+      ;;
96
+  help)
97
+      _values "${commands[@]}" \
98
+        'gopath[GOPATH environment variable]' \
99
+        'packages[description of package lists]' \
100
+        'remote[remote import path syntax]' \
101
+        'testflag[description of testing flags]' \
102
+        'testfunc[description of testing functions]'
103
+      ;;
104
+  run)
105
+      _arguments -s -w : \
106
+          ${build_flags[@]} \
107
+          '*:file:_path_files -g "*.go"'
108
+      ;;
109
+  tool)
110
+      if (( CURRENT == 3 )); then
111
+          _values "go tool" $(go tool)
112
+          return
113
+      fi
114
+      case ${words[3]} in
115
+      [568]g)
116
+          _arguments -s -w : \
117
+              '-I[search for packages in DIR]:includes:_path_files -/' \
118
+              '-L[show full path in file:line prints]' \
119
+              '-S[print the assembly language]' \
120
+              '-V[print the compiler version]' \
121
+              '-e[no limit on number of errors printed]' \
122
+              '-h[panic on an error]' \
123
+              '-l[disable inlining]' \
124
+              '-m[print optimization decisions]' \
125
+              '-o[file specify output file]:file' \
126
+              '-p[assumed import path for this code]:importpath' \
127
+              '-u[disable package unsafe]' \
128
+              "*:file:_files -g '*.go'"
129
+          ;;
130
+      [568]l)
131
+          local O=${words[3]%l}
132
+          _arguments -s -w : \
133
+              '-o[file specify output file]:file' \
134
+              '-L[search for packages in DIR]:includes:_path_files -/' \
135
+              "*:file:_files -g '*.[ao$O]'"
136
+          ;;
137
+      dist)
138
+          _values "dist tool" banner bootstrap clean env install version
139
+          ;;
140
+      *)
141
+          # use files by default
142
+          _files
143
+          ;;
144
+      esac
145
+      ;;
146
+  esac
147
+}
148
+
149
+__go_tool_complete "$@"
150
+
151
+# Local Variables:
152
+# mode: Shell-Script
153
+# sh-indentation: 2
154
+# indent-tabs-mode: nil
155
+# sh-basic-offset: 2
156
+# End:

+ 47
- 0
completions/_lldpcli View File

@@ -0,0 +1,47 @@
1
+#compdef lldpcli
2
+#
3
+# zsh completion for lldpcli
4
+#
5
+# Copyright (c) 2014 Vincent Bernat <bernat@luffy.cx>
6
+#
7
+# Permission to use, copy, modify, and/or distribute this software for any
8
+# purpose with or without fee is hereby granted, provided that the above
9
+# copyright notice and this permission notice appear in all copies.
10
+#
11
+# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17
+# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18
+
19
+
20
+__lldpcli_command () {
21
+    local -a completions
22
+    completions=(${(f)"$(_call_program commands lldpcli complete ${words[1,$(($CURRENT-1))]})"})
23
+    completions=(${completions:s/ /:/})
24
+    _describe -t lldpcli-command "lldpcli completion" completions "$@"
25
+}
26
+
27
+_lldpcli () {
28
+    local curcontext="$curcontext" state line
29
+
30
+    _arguments -C \
31
+        '*-d[print more debugging information]' \
32
+        '(- *)-v[print version number and exit]' \
33
+        '-u[use an alternate socket with lldpd]:UNIX socket:_files' \
34
+        '-f[output format]:format:(plain xml json keyvalue)' \
35
+        '*-c[read a configuration file]:configuration file:_files' \
36
+        '(-)*::lldpcli command:__lldpcli_command'
37
+}
38
+
39
+
40
+_lldpcli "$@"
41
+
42
+# Local Variables:
43
+# mode: Shell-Script
44
+# sh-indentation: 4
45
+# indent-tabs-mode: nil
46
+# sh-basic-offset: 4
47
+# End:

+ 20
- 0
completions/_npm View File

@@ -0,0 +1,20 @@
1
+#compdef npm
2
+
3
+_npm() {
4
+    si=$IFS
5
+    compadd -- $(COMP_CWORD=$((CURRENT-1)) \
6
+        COMP_LINE=$BUFFER \
7
+        COMP_POINT=0 \
8
+        npm completion -- "${words[@]}" \
9
+        2>/dev/null)
10
+    IFS=$si
11
+}
12
+
13
+_npm "$@"
14
+
15
+# Local Variables:
16
+# mode: Shell-Script
17
+# sh-indentation: 4
18
+# indent-tabs-mode: nil
19
+# sh-basic-offset: 4
20
+# End:

+ 243
- 0
completions/_openssl View File

@@ -0,0 +1,243 @@
1
+#compdef openssl
2
+#
3
+# Retrieved from:
4
+#  https://github.com/aschrab/zsh-completions/blob/openssl/src/_openssl
5
+
6
+# _openssl: Start point {{{
7
+_openssl() {
8
+  setopt nonomatch
9
+  local openssl==openssl
10
+
11
+  if [[ $openssl = '=openssl' ]]; then
12
+    _message "openssl executable not found: completion not available"
13
+    return
14
+  fi
15
+
16
+  _get_openssl_commands
17
+
18
+  if (( CURRENT > 2 )); then
19
+    _openssl_dispatch
20
+  else
21
+    _openssl_commands
22
+  fi
23
+}
24
+# }}}
25
+
26
+# _get_openssl_commands: Populate arrays of subcommand names {{{
27
+_get_openssl_commands() {
28
+  if ! (( ${+_openssl_list_cmd_list} )); then
29
+    typeset -ga _openssl_list_cmd_list
30
+    _openssl_list_cmd_list=(
31
+      list-standard-commands
32
+      list-message-digest-commands
33
+      list-cipher-commands
34
+      list-cipher-algorithms
35
+      list-message-digest-algorithms
36
+      list-public-key-algorithms
37
+    )
38
+  fi
39
+
40
+  if ! (( ${+_openssl_standard_cmd_list} )); then
41
+    typeset -ga _openssl_standard_cmd_list
42
+    _openssl_standard_cmd_list=( $(openssl list-standard-commands) )
43
+  fi
44
+
45
+  if ! (( ${+_openssl_digest_cmd_list} )); then
46
+    typeset -ga _openssl_digest_cmd_list
47
+    _openssl_digest_cmd_list=( $(openssl list-message-digest-commands) )
48
+  fi
49
+
50
+  if ! (( ${+_openssl_cipher_cmd_list} )); then
51
+    typeset -ga _openssl_cipher_cmd_list
52
+    _openssl_cipher_cmd_list=( $(openssl list-cipher-commands) )
53
+  fi
54
+}
55
+# }}}
56
+
57
+# _openssl_commands: complete subcommand name  {{{
58
+_openssl_commands() {
59
+  integer ret=1
60
+  _describe -t cipher-commands 'Cipher command' _openssl_cipher_cmd_list && ret=0
61
+  _describe -t digest-commands 'Digest command' _openssl_digest_cmd_list && ret=0
62
+  _describe -t standard-commands 'Standard command' _openssl_standard_cmd_list && ret=0
63
+  _describe -t list-commands 'List commands' _openssl_list_cmd_list && ret=0
64
+
65
+  return ret
66
+}
67
+# }}}
68
+
69
+# _openssl_dispatch: Dispatch to completion for subcommand  {{{
70
+_openssl_dispatch() {
71
+  integer ret=1
72
+  shift words
73
+  (( CURRENT-- ))
74
+
75
+  # Check if there's a completion function for the specific subcommand
76
+  if (( $+functions[_openssl-$words[1]] )); then
77
+    _call_function ret _openssl-$words[1]
78
+  # Digest commands can be handled by a common function
79
+  elif (( $+_openssl_digest_cmd_list )); then
80
+    _openssl_digest_command
81
+  else
82
+    _message "Can't dispatch to $words[1]"
83
+  fi
84
+
85
+  return ret
86
+}
87
+# }}}
88
+
89
+# Completion for option arguments {{{
90
+# _openssl_pass_source: Complete password source info {{{
91
+_openssl_pass_source() {
92
+  _values -S : 'Password source' \
93
+    'pass[Direct password entry]:password:' \
94
+    'env[Get password from named environment variable]:environment:_parameters -g "*export*"' \
95
+    'file[Get password from file]:password file:_files' \
96
+    'fd[Read password from file descriptor #]:integer:' \
97
+    'stdin[Read password from standard input]'
98
+}
99
+# }}}
100
+
101
+# _openssl_engine_id: Complete engine ID {{{
102
+_openssl_engine_id() {
103
+  # TODO
104
+}
105
+#}}}
106
+
107
+# _openssl_x509_name_options: Complete x509 name options {{{
108
+_openssl_x509_name_options() {
109
+  local sep='sep_comma_plus sep_comma_plus_space sep_semi_plus_space sep_multiline'
110
+  local fname='nofname sname lname oid'
111
+
112
+  _values -s , -w 'name options' \
113
+    'compat[Use old format (default)]' \
114
+    'RFC2253[RFC2253 compatible]' \
115
+    'oneline[Single line format]' \
116
+    'multiline[Multi line format]' \
117
+    'esc_2253[Escape special characters: ,+"<>]' \
118
+    'esc_ctrl[Escape control characters]' \
119
+    'esc_msb[Escape characters with ASCII value > 127]' \
120
+    'use_quote[Surround entire string with double quote]' \
121
+    'utf8[Convert all strings to UTF8]' \
122
+    'no_type[Dump multibyte characters without conversion]' \
123
+    'show_type[Precede field content with type of ASN1 string]' \
124
+    'dump_der[Use DER encoding for hexdump]' \
125
+    'dump_nostr[dump types which are not character strings]' \
126
+    'dump_all[dump all fields]' \
127
+    'dump_unknown[dump any field with unknown OID]' \
128
+    "($sep)sep_comma_plus[use , and + as separators]" \
129
+    "($sep)sep_comma_plus_space[use , and + with following space as separators]" \
130
+    "($sep)sep_semi_plus_space[use ; and + with following space as separators]" \
131
+    "($sep)sep_multiline[use LF and + as separators]" \
132
+    'dn_rev[reverse fields of the DN]' \
133
+    "($fname)nofname[do not display field name]" \
134
+    "($fname)sname[display short field name]" \
135
+    "($fname)lname[display long field name]" \
136
+    "($fname)oid[use numerical OID for field name]" \
137
+    'align[align field values (only usable with sep_multiline)]' \
138
+    'space_eq[put spaces around = after field name]'
139
+}
140
+#}}}
141
+
142
+# _openssl_x509_cert_options: Complete x509 certificate options {{{
143
+_openssl_x509_cert_options() {
144
+  # TODO
145
+}
146
+#}}}
147
+
148
+# _openssl_req_newkey_options: Complete options for req -newkey {{{
149
+_openssl_req_newkey_options() {
150
+  # TODO: Get list of algorithms dynamically
151
+  _values -S : 'Key options' \
152
+    'rsa[RSA key]::number of bits:' \
153
+    'param[Read paramaters from file]:parameter file:_files' \
154
+    'cmac' \
155
+    'hmac'
156
+}
157
+#}}}
158
+
159
+#}}}
160
+
161
+# _openssl_digest_command: Default completion for digest subcommands {{{
162
+_openssl_digest_command() {
163
+  _arguments : \
164
+    '-c[Print digest in two-digit groups separated by colons]' \
165
+    '-d[Print BIO debugging information]' \
166
+    '(-binary)-hex[Output digest as a hex dump]' \
167
+    '(-hex -c)-binary[Output digest or signature in binary form]' \
168
+    '-hmac[Set the HMAC key to ARG]:arg:' \
169
+    '-non-fips-allow[Allow use of non-FIPS digest]' \
170
+    '-out[Filename for output]:output file:_files' \
171
+    '-sign[Sign the digest using key in file]:key file:_files' \
172
+    '-keyform[Key format]:format:(PEM ENGINE)' \
173
+    '-engine[Use engine ID]:Engine ID:_openssl_engine_id' \
174
+    '-sigopt[Signature options]:Signature option:' \
175
+    '-passin[Private key password source]:Key source:_openssl_pass_source' \
176
+    '-verify[Verify signature with public key FILE]:Public key file:_files' \
177
+    '-prverify[Verify signature with private key FILE]:Private key file:_files' \
178
+    '-signature[Verify signature in FILE]:Signature file:_files' \
179
+    '-mac[Message Authenticate Code algorithm]:MAC algorithm:' \
180
+    '-macopt[Options to pass to MAC algorithm]:MAC options:' \
181
+    '-rand[File for random data]:Random source:_files' \
182
+    '*: :_files'
183
+}
184
+#}}}
185
+
186
+# Completion for specific subcommands {{{
187
+
188
+_openssl-req() { #{{{
189
+  local -a digests
190
+  digests=(-md5 -sha1) # FIXME generate this
191
+  _arguments : \
192
+    $digests \
193
+    '-inform[Format of the input]:input format:(DER PEM)' \
194
+    '-outform[Format to use for the output]:output format:(DER PEM)' \
195
+    '-in[Input filename]:input file:_files' \
196
+    '-passsin[Source for password of the input]:password source:_openssl_pass_source' \
197
+    '-out[Output file name]:output file:_files' \
198
+    '-passsout[Source for password of the output]:password source:_openssl_pass_source' \
199
+    '-text[Print certificate request in text form]' \
200
+    '-subject[Print request subject]' \
201
+    '-pubkey[Output the public key]' \
202
+    '-noout[Prevent output of encoded request]' \
203
+    '-modulus[Print the public key modulus]' \
204
+    '-verify[Verify request signature]' \
205
+    '-new[Generate a new certificate request]' \
206
+    '-subj[Specify subject of the request]:subject:' \
207
+    '-rand[File for random data]:Random source:_files' \
208
+    '-newkey[Create a new private key and request]:key spec:_openssl_req_newkey_options' \
209
+    '-pkeyopt[Public key option]:key option:' \
210
+    '-key[Key from which private key will be read]:private key file:_files' \
211
+    '-keyform[Format of file specified by -key option]:key format:(DER PEM)' \
212
+    '-keyout[File name to which generated key should be written]:output key file:_files' \
213
+    '-nodes[Do not encrypt generated private key]' \
214
+    '-config[Alternate configuration file]:config file:_files' \
215
+    '-multivalue-rdn[Interpret -subj argument with support for multivalued RDNs]' \
216
+    '-x509[Output a self signed certificate]' \
217
+    '-days[Number of days for which -x509 certifcate will be valid]:integer:' \
218
+    '-set_serial[Serial number for self-signed certificate]:integer:' \
219
+    {-extensions,-reqexts}'[]:section:' \
220
+    '-utf8[Interpret values as UTF8 strings]' \
221
+    '*-nameopt[Options for display of subject or issuer name]:name option:_openssl_x509_name_options' \
222
+    '-reqopt[Customise output format for -text]:request option:_openssl_x509_cert_options' \
223
+    '-asn1-kludge[Produce broken output required by some CAs]' \
224
+    '-no-asn1-kludge[Produce standard-compliant output]' \
225
+    '-newhdr[Add NEW to the PEM header and footer]' \
226
+    '-batch[Non-interactive mode]' \
227
+    '-verbose[Print extra details]' \
228
+    '-engine[Use engine ID]:Engine ID:_openssl_engine_id' \
229
+    '-keygen_engine[Use engine ID for key generation]:Engine ID:_openssl_engine_id'
230
+}
231
+#}}}
232
+
233
+#}}}
234
+
235
+_openssl "$@"
236
+
237
+# Local Variables:
238
+# mode: Shell-Script
239
+# sh-indentation: 2
240
+# indent-tabs-mode: nil
241
+# sh-basic-offset: 2
242
+# End:
243
+# vim: filetype=zsh expandtab shiftwidth=2 foldmethod=marker

+ 20
- 0
completions/_pip View File

@@ -0,0 +1,20 @@
1
+#compdef pip
2
+
3
+function _pip {
4
+    local -a reply
5
+    reply=( $( COMP_WORDS="$words[*]" \
6
+        COMP_CWORD=$CURRENT \
7
+        PIP_AUTO_COMPLETE=1 _call_program commands pip ) )
8
+    _describe "pip completion" reply
9
+}
10
+
11
+_pip "$@"
12
+
13
+# Local Variables:
14
+# mode: Shell-Script
15
+# sh-indentation: 4
16
+# indent-tabs-mode: nil
17
+# sh-basic-offset: 4
18
+# End:
19
+# vim: ft=zsh sw=4 ts=4 et
20
+

+ 1
- 0
completions/_rfkill View File

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

+ 154
- 0
completions/_snmpcmd View File

@@ -0,0 +1,154 @@
1
+#compdef snmpwalk=snmpcmd snmpget=snmpcmd snmpbulkwalk=snmpcmd snmpbulkget=snmpcmd
2
+#
3
+# Completion for snmp* cmd. Stolen from:
4
+#    2006 Andrew J Cosgriff
5
+#    http://polydistortion.net/
6
+#    http://polydistortion.net/sw/zsh/_snmpcmd
7
+#    http://polydistortion.net/monkey/archives/2006/07/16/003735.html
8
+#
9
+# With some other modifications
10
+
11
+_snmp_get_mibs () {
12
+    local -a mibs
13
+    local -a mib
14
+    local mibdirs
15
+    local dir
16
+
17
+    mibdirs=$(snmptranslate -Dinit_mib 2>&1 | \
18
+	sed -n "s/^init_mib: Seen MIBDIRS: Looking in '\(.*\)' for mib dirs ...$/\1/p")
19
+    for dir in ${(ws+:+)mibdirs}; do
20
+	mibs=($mibs $dir/*(.))
21
+    done
22
+
23
+    compadd "$@" -- ${mibs[@]:t:r}
24
+}
25
+
26
+_snmp_get_object() {
27
+    local obj
28
+    local arg
29
+    local next
30
+    local -a additional
31
+    next=0
32
+    for arg in $words; do
33
+	case $arg in
34
+	    "-m")
35
+		next=1
36
+		additional=($additional "-m")
37
+		;;
38
+	    *)
39
+		if (( next == 1 )); then
40
+		    additional=($additional $arg)
41
+		    next=0
42
+		fi
43
+		;;
44
+	esac
45
+    done
46
+    for obj in ${(@f)"$(snmptranslate $additional -Ta 2> /dev/null)"}; do
47
+	case ${${(s: :)obj}[2]} in
48
+	    OBJECT)
49
+		;;
50
+	    *) continue
51
+		;;
52
+	esac
53
+	compadd "$@" -- ${${(s: :)obj}[1]}
54
+    done
55
+}
56
+
57
+_snmpcmd () {
58
+    local context state line
59
+    typeset -A opt_args
60
+
61
+    _arguments -A \
62
+	{-h,--help}'[show help]' \
63
+	'-H[display configuration file directives understood]' \
64
+	'-v[SNMP version to use]:version:(1 2c 3)' \
65
+	{-V,--version}'[display package version number]' \
66
+	'-c[set the community string]:community string: ' \
67
+	'-a[set authentcation protocol]:protocol:(MD5 SHA)' \
68
+	'-A[set authentication protocol pass phrase]:passphrase: ' \
69
+	'-e[set security engine ID]:engine-id: ' \
70
+	'-E[set context engine ID]:engine-id: ' \
71
+	'-l[set security level]:security level:(noAuthNoPriv authNoPriv authPriv)' \
72
+	'-n[set context name]:context: ' \
73
+	'-u[set security name]:user:_users' \
74
+	'-x[set privacy protocol]:protocol:(DES AES)' \
75
+	'-X[set privacy protocol pass phrase]:passphrase: ' \
76
+	'-Z[set destination engine boots/time]:boots,time: ' \
77
+	'-r[set the number of retries]:retries: ' \
78
+	'-t[set the request timeout (in seconds)]:timeout: ' \
79
+	'-d[dump input/output packets in hexadecimal]' \
80
+	'-D[turn on debugging output for the specified tokens]:token: ' \
81
+	'-m[MIB file to use]:mib:->mib' \
82
+	'-M[directory to search for MIBs]:directory:_files -/' \
83
+	'-Pu[allow the use of underlines in MIB symbols]' \
84
+	'-Pc[disallow the use of "--" to terminate comments in MIBs]' \
85
+	'-Pd[save the DESCRIPTIONs of the MIB objects]' \
86
+	'-Pe[disable errors when MIB symbols conflict]' \
87
+	'-Pw[enable warnings when MIB symbols conflict]' \
88
+	'-PW[enable detailed warnings when MIB symbols conflict]' \
89
+	'-PR[replace MIB symbols from latest module]' \
90
+	'-O0[print leading 0 for single-digit hex characters]' \
91
+	'-Oa[print all strings in ascii format]' \
92
+	'-Ob[do not break OID indexes down]' \
93
+	'-Oe[print enums numerically]' \
94
+	'-OE[escape quotes in string indices]' \
95
+	'-Of[print full OIDs on output]' \
96
+	'-On[print OIDs numerically]' \
97
+	'-Oq[quick print for easier parsing]' \
98
+	'-OQ[quick print with equal-signs]' \
99
+	'-Os[print only last symbolic element of OID]' \
100
+	'-OS[print MIB module-id plus last element]' \
101
+	'-Ot[print timeticks unparsed as numeric integers]' \
102
+	'-OT[print human-readable text along with hex strings]' \
103
+	'-Ou[print OIDs using UCD-style prefix suppression]' \
104
+	"-OU[don't print units]" \
105
+	'-Ov[print values only (not OID = value)]' \
106
+	'-Ox[print all strings in hex format]' \
107
+	'-OX[extended index format]' \
108
+	'-Ib[do best/regex matching to find a MIB node]' \
109
+	"-Ih[don't apply DISPLAY-HINTs]" \
110
+	'-Ir[do not check values for range/type legality]' \
111
+	'-IR[do random access to OID labels]' \
112
+	'-Iu[top-level OIDs must have '.' prefix (UCD-style)]' \
113
+	'-Is[Append all textual OIDs with suffix before parsing]:suffix: ' \
114
+	'-IS[Append all textual OIDs with prefix before parsing]:prefix: ' \
115
+	'-Le[log to standard error]' \
116
+	'-Lo[log to standard output]' \
117
+	"-Ln[don't log at all]" \
118
+	'-Lf[log to the specified file]:file:_files' \
119
+	'-Ls[log to the syslog (via the specified facility)]:facility: ' \
120
+	'-Cp[print the number of variables found]' \
121
+	'-Ci[include given OID in the search range]' \
122
+	"-CI[don't include the given OID, even if no results are returned]" \
123
+	'-Ic[do not check returned OIDs are increasing]' \
124
+	'-It[Display wall-clock time to complete the request]' \
125
+	':hosts:_hosts' \
126
+	':object:->object'
127
+
128
+    while [[ -n "$state" ]]; do
129
+	lstate="$state"
130
+	state=''
131
+
132
+	case "$lstate" in
133
+	    mib)
134
+		if compset -P '*+'; then
135
+		    _snmp_get_mibs
136
+		elif compset -P '*:'; then
137
+		    _snmp_get_mibs
138
+		else
139
+		    _snmp_get_mibs
140
+		fi
141
+		;;
142
+	    object)
143
+		_snmp_get_object
144
+		;;
145
+	esac
146
+    done
147
+}
148
+
149
+# Local Variables:
150
+# mode: Shell-Script
151
+# sh-indentation: 4
152
+# indent-tabs-mode: t
153
+# sh-basic-offset: 4
154
+# End:

+ 1
- 0
completions/_socat View File

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

+ 11
- 0
completions/_tmux-cssh View File

@@ -0,0 +1,11 @@
1
+#compdef tmux-cssh
2
+
3
+_arguments \
4
+    '*::arguments: _hosts' && return 0
5
+
6
+# Local Variables:
7
+# mode: Shell-Script
8
+# sh-indentation: 4
9
+# indent-tabs-mode: nil
10
+# sh-basic-offset: 4
11
+# End:

+ 1
- 0
completions/_vagrant View File

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

+ 1
- 0
completions/_virsh View File

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

+ 29
- 0
completions/_workon View File

@@ -0,0 +1,29 @@
1
+#compdef workon
2
+
3
+_environments() {
4
+    local -a virtualenvs images containers
5
+    local expl
6
+
7
+    virtualenvs=( ${WORKON_HOME}/*/bin/activate(.N:h:h:t) - )
8
+    _wanted environments expl 'virtualenv environment' compadd \
9
+        -a virtualenvs
10
+
11
+    (( $+commands[docker] )) && [[ -w /var/run/docker.sock ]] && {
12
+        images=(${(f)"$(docker images 2> /dev/null | awk '(NR > 1 && $1 !~ /^</){printf("%s:%s\n", $1,$2)}')"})
13
+        _wanted images expl 'docker images' compadd \
14
+            -a images
15
+
16
+        containers=(${(f)"$(docker ps 2> /dev/null | awk '(NR > 1) { split($NF,names,/,/); for (i in names) printf("%s:%7s\n",names[i],$2)}')"})
17
+        _describe -t containers-active "running containers" containers
18
+    }
19
+}
20
+
21
+_arguments \
22
+    '1:::_environments' && return 0
23
+
24
+# Local Variables:
25
+# mode: Shell-Script
26
+# sh-indentation: 4
27
+# indent-tabs-mode: nil
28
+# sh-basic-offset: 4
29
+# End:

+ 90
- 0
dir_colors View File

@@ -0,0 +1,90 @@
1
+# /etc/dir_colors ou ~/.dir_colors
2
+# Fichier de configuration des couleurs pour la commande 'ls'
3
+# Formation Debian GNU/Linux par Alexis de Lattre
4
+# http://www.via.ecp.fr/~alexis/formation-linux/
5
+
6
+# Les couleurs sont exprimées sous forme d'une liste de numéros
7
+# séparés par des points-virgules, sachant qu'il ne doit pas y
8
+# avoir plus d'un numéro par catégorie.
9
+
10
+# Il existe 3 catégories :
11
+# - Type :
12
+#   00=normal 01=gras 04=souligné 05=clignotant 07=inversé caractères/fond
13
+#   08=invisible (?)
14
+# - Couleur des caractères :
15
+#   30=noir 31=rouge 32=vert 33=jaune 34=bleu 35=magenta 36=cyan 37=blanc
16
+# - Couleur du fond
17
+#   40=noir 41=rouge 42=vert 43=marron 44=bleu 45=magenta 46=cyan 47=gris
18
+
19
+# Couleur par défaut globale
20
+NORMAL 00
21
+# Couleur par défaut pour les fichiers
22
+FILE 00
23
+# Couleur pour les répertoires
24
+DIR 01;32
25
+# Couleur pour les liens symboliques
26
+LINK 36
27
+# Couleur pour les FIFOs
28
+FIFO 33
29
+# Couleur pour les sockets
30
+SOCK 01;35
31
+# Couleur pour les block device drivers
32
+BLK 01;33
33
+# Couleur pour les character device drivers
34
+CHR 01;33
35
+# Couleur pour les fichiers ayant les permissions d'exécution
36
+EXEC 01;31
37
+
38
+# Couleur pour les fichiers selon leur extension
39
+
40
+# Fichiers de configuration
41
+.conf 01;33;41
42
+# Fichiers exécutables
43
+.sh   01;31
44
+.pl   01;31
45
+.php3 01;31
46
+.php  01;31
47
+.py   01;31
48
+# Fichiers compressés
49
+.tar  36
50
+.tgz  36
51
+.arj  36
52
+.taz  36
53
+.lzh  36
54
+.zip  36
55
+.gz   36
56
+.bz2  36
57
+.rar  36
58
+.tar.gz 36
59
+# Packages
60
+.deb  33
61
+.rpm  33
62
+# Fichiers images
63
+.jpg  35
64
+.JPG  35
65
+.jpeg 35
66
+.eps  35
67
+.gif  35
68
+.png  35
69
+.bmp  35
70
+.xpm  35
71
+.tif  35
72
+.tiff 35
73
+.tga  35
74
+.pcx  35
75
+.cr2  35
76
+.CR2  35
77
+# Fichiers audio/vidéo
78
+.avi  32
79
+.mpg  32
80
+.mpeg 32
81
+.vob  32
82
+.au   32
83
+.wav  32
84
+.mp3  32
85
+.ogg  32
86
+.mp4  32
87
+.mkv  32
88
+.webm 32
89
+.flv  32
90
+

+ 10
- 0
env View File

@@ -0,0 +1,10 @@
1
+# -*- sh -*-
2
+# Could be sourced by simple POSIX shell
3
+
4
+# No timeout
5
+unset TMOUT
6
+
7
+# Debian email address
8
+[ x"$USER" != x"bernat" ] || export DEBEMAIL=$USER@debian.org
9
+
10
+export GOPATH=$HOME/src/gocode

+ 225
- 0
functions/workon View File

@@ -0,0 +1,225 @@
1
+# -*- sh -*-
2
+# Description
3
+# ===========
4
+#
5
+# Switch to another environment.
6
+#
7
+# An environment is either a virtualenv-based environment, a Docker
8
+# image or a Docker container. Virtualenv-based environments are
9
+# expected to be in $WORKON_HOME.
10
+
11
+local env=$1
12
+local -a venv dimages dcontainers
13
+venv=($WORKON_HOME/*/bin/activate(.N:h:h:ft))
14
+(( $+commands[docker] )) && [[ -w /var/run/docker.sock ]] && {
15
+    dimages=( $(docker images | awk '(NR > 1 && $1 !~ /^</){printf("%s:%s\n", $1,$2)}') )
16
+    dcontainers=( $(docker ps | awk '(NR > 1){split($NF,names,/,/); for (i in names) printf("%s\n",names[i])}') )
17
+}
18
+
19
+# No parameters, list available environment
20
+[[ -n $env ]] || {
21
+    print "INFO: List of available environments:"
22
+    for env in $venv; do
23
+        print " - [virtualenv] $env"
24
+    done
25
+    for image in $dimages; do
26
+        print " - [docker    ] $image"
27
+    done
28
+    for container in $dcontainers; do
29
+        print " - [docker    ] $container"
30
+    done
31
+    return 0
32
+}
33
+
34
+[[ $env == "." ]] && env=${PWD:t}
35
+
36
+# Docker stuff
37
+local setupuser="
38
+if ! id $USER > /dev/null 2> /dev/null; then
39
+    echo $(getent passwd $(id -u)) >> /etc/passwd
40
+    echo $(getent group $(id -g)) >> /etc/group
41
+    # Put sudo configuration even when no sudo (in case it gets installed later)
42
+    mkdir -p /etc/sudoers.d
43
+    echo \"$USER ALL=(ALL) NOPASSWD: ALL\" > /etc/sudoers.d/$USER
44
+    chmod 0440 /etc/sudoers.d/$USER
45
+    [ -x /usr/bin/sudo ] || {
46
+        cp /usr/sbin/chroot /usr/bin/_root
47
+        chown root:$(id -gn) /usr/bin/_root
48
+        chmod 4750 /usr/bin/_root
49
+        cat <<'EOF' > /usr/bin/sudo
50
+#!/bin/sh
51
+export PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
52
+
53
+escape() {
54
+  echo \"\$1\" | sed s/\\'/\\'\\\"\\'\\\"\\'/g
55
+}
56
+args=
57
+for arg in \"\$@\"; do
58
+    qarg=\$(escape \"\$arg\")
59
+    args=\"\$args '\$qarg'\"
60
+done
61
+
62
+exec /usr/bin/_root --userspec=root:root / /bin/sh -c \"cd '\$(escape \"\$PWD\")'; \$args\"
63
+EOF
64
+        chmod +x /usr/bin/sudo
65
+    }
66
+fi
67
+"
68
+
69
+# Docker images
70
+[[ ${dimages[(r)$env]} == $env ]] && {
71
+    local image=${env}
72
+    local tmp=$(mktemp -d)
73
+    <<EOF > $tmp/start
74
+#!/bin/sh
75
+for SHELL in ${SHELL}-static $SHELL /bin/bash /bin/sh; do
76
+    [ ! -x \$SHELL ] || break
77
+done
78
+$setupuser
79
+exec chroot --userspec=$(id -u):$(id -g) / \
80
+     env HOME=$HOME TERM=$TERM DOCKER_CHROOT_NAME=$env \
81
+     sh -c "[ -d '\$PWD' ] && cd '\$PWD' ; exec \$SHELL -i -l"
82
+EOF
83
+    docker run -t -i \
84
+           $([[ -d /usr/share/zsh ]] && print -- -v /usr/share/zsh:/usr/share/zsh-static:ro) \
85
+           $([[ -x ${SHELL}-static ]] && print -- -v ${SHELL}-static:${SHELL}-static:ro) \
86
+           -v $HOME:$HOME \
87
+           -v $tmp:$tmp \
88
+           -w $PWD \
89
+           -u root \
90
+           --rm \
91
+           -h ${${${image##*/}:gs/:/-}:gs/./-} \
92
+           --entrypoint /bin/sh \
93
+           $image $tmp/start
94
+    local ret=$?
95
+    rm -f $tmp/start && rmdir $tmp
96
+    return $ret
97
+}
98
+
99
+# Docker containers
100
+[[ ${dcontainers[(r)$env]} == $env ]] && {
101
+    local id=$(docker inspect --format '{{.State.Pid}}' $env)
102
+
103
+    # We need to mount $HOME inside the container, that's quite
104
+    # hacky: we get the device we need to mount, we mount it
105
+    # somewhere, then bind mount the home directory in the right
106
+    # place. All this with elevated privileges. We also create our
107
+    # user, with sudo rights. Most inspiration comes from here:
108
+    #  http://blog.dehacked.net/lxc-getting-mounts-into-a-running-container/
109
+    #
110
+    # Also, from Docker 0.9, see:
111
+    #  http://jpetazzo.github.io/2014/03/23/lxc-attach-nsinit-nsenter-docker-0-9/
112
+    #  http://www.sebastien-han.fr/blog/2014/01/27/access-a-container-without-ssh/
113
+    #
114
+    # From Docker 1.3, see `docker exec'.
115
+    #
116
+    # So, this needs nsenter which needs a recent util-linux.
117
+    local homemnt=${${(f)"$(df --output=target $HOME)"}[-1]}
118
+    local homedev=$(readlink -f ${${(f)"$(df --output=source $HOME)"}[-1]})
119
+    local enter=/tmp/nsenter-$RANDOM-$$-$UID
120
+    ${(%):-%(!..sudo)} =nsenter -m -t $id -- /bin/sh -e <<EOF
121
+#!/bin/sh
122
+if ! mountpoint $HOME > /dev/null 2>/dev/null; then
123
+    tmp=\$(mktemp -d)
124
+    mkdir -p ${HOME}
125
+    [ -b /dev/home-directory ] || mknod /dev/home-directory b $(stat -c "0x%t 0x%T" ${homedev})
126
+    mount -n /dev/home-directory \$tmp
127
+    rm /dev/home-directory
128
+    mount -n --bind \$tmp/${HOME#$homemnt} $HOME
129
+    umount -n \$tmp 2> /dev/null
130
+    rmdir \$tmp
131
+fi
132
+
133
+# Shell to use
134
+for SHELL in $SHELL /bin/bash /bin/sh; do
135
+    [ ! -x \$SHELL ] || break
136
+done
137
+
138
+$setupuser
139
+
140
+# Setup a command to enter this environment
141
+> $enter echo exec 'chroot --userspec=$(id -u):$(id -g) / \
142
+env HOME=$HOME TERM=$TERM DOCKER_CHROOT_NAME=$env \
143
+sh -c "[ -d '"'"'$PWD'"'"' ] && cd '"'"'$PWD'"'"' ; exec '\$SHELL' -i -l"'
144
+
145
+EOF
146
+    local ret=$?
147
+    [[ $ret -eq 0 ]] && {
148
+        ${(%):-%(!..sudo)} =nsenter -m -u -i -n -p -w$HOME -t $id -- /bin/sh $enter
149
+        ret=$?
150
+    }
151
+    return $ret
152
+}
153
+
154
+function save() {
155
+    local v
156
+    for v ($@) {
157
+            _saved_environment[$v]=${${(e):-\$$v}}
158
+        }
159
+}
160
+
161
+function restore() {
162
+    local v
163
+    for v (${(k)_saved_environment}) {
164
+            unset $v
165
+            [[ -z ${_saved_environment[$v]} ]] || export $v=${_saved_environment[$v]}
166
+        }
167
+}
168
+
169
+# If in another virtualenv, call deactivate
170
+(( $+functions[deactivate_node] )) && deactivate_node
171
+(( $+functions[deactivate] )) && {
172
+    deactivate
173
+    restore
174
+}
175
+
176
+# Virtualenv
177
+[[ ${venv[(r)$env]} == $env ]] && {
178
+    local activate="$WORKON_HOME/$env/bin/activate"
179
+    local VIRTUAL_ENV_DISABLE_PROMPT=1
180
+    local NODE_VIRTUAL_ENV_DISABLE_PROMPT=1
181
+    source $activate
182
+
183
+    typeset -Ag _saved_environment
184
+
185
+    # Gems.
186
+    # GEM_HOME is where gems will be installed.
187
+    # GEM_PATH is where gems are searched
188
+    save GEM_HOME GEM_PATH
189
+    export GEM_HOME=$VIRTUAL_ENV/gems
190
+    export GEM_PATH=$GEM_HOME
191
+    path=( $GEM_HOME/bin $path )
192
+
193
+    # Go
194
+    save GOPATH
195
+    export GOPATH=$VIRTUAL_ENV/go
196
+    path=( $GOPATH/bin $path)
197
+
198
+    # C (install with ./configure --prefix=$VIRTUAL_ENV)
199
+    save LD_LIBRARY_PATH PKG_CONFIG_PATH
200
+    export LD_LIBRARY_PATH=$VIRTUAL_ENV/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
201
+    export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig
202
+    path=( $VIRTUAL_ENV/sbin $path )
203
+
204
+    # OCaml (through OPAM)
205
+    (( $+commands[opam] )) && {
206
+        save OPAMROOT MANPATH PERL5LIB CAML_LD_LIBRARY_PATH OCAML_TOPLEVEL_PATH
207
+        export OPAMROOT=$VIRTUAL_ENV/opam
208
+        [[ -d $OPAMROOT ]] && \
209
+            eval $(opam config env)
210
+    }
211
+
212
+    # node.js workaround
213
+    [[ -z $NPM_CONFIG_PREFIX ]] || {
214
+        save npm_config_prefix
215
+        export npm_config_prefix=$NPM_CONFIG_PREFIX
216
+    }
217
+
218
+    rehash
219
+    return
220
+}
221
+
222
+[[ $env == "-" ]] || {
223
+    print "ERROR: environment $env does not exist"
224
+    return 2
225
+}

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

@@ -0,0 +1,69 @@
1
+# -*- sh -*-
2
+
3
+# acpi -b output
4
+#
5
+# Battery X: YYYYYY, ZZ%
6
+# Battery X: YYYYYY, ZZ%, rate information unavailable
7
+# Battery X: YYYYYY, ZZ%, charging at zero rate
8
+# Battery X: YYYYYY, ZZ%, discharging at zero rate
9
+# Battery X: YYYYYY, ZZ%, HH:MM:SS remaining
10
+# Battery X: YYYYYY, ZZ%, HH:MM:SS until charged
11
+#
12
+# YYYYYY = charging
13
+# YYYYYY = discharging
14
+
15
+_vbe_battery () {
16
+    (( $+commands[acpi] )) || return
17
+    local cache=$ZSH/run/u/$HOST-$UID/acpi
18
+    zmodload zsh/stat
19
+    zmodload zsh/datetime
20
+    if [[ -f $cache ]] && \
21
+	(( $EPOCHSECONDS - $(stat +mtime $cache) < 240 )); then
22
+	print -n $(<$cache)
23
+	return
24
+    fi
25
+
26
+    local acpi
27
+    local percent
28
+    local state
29
+    acpi=(${(f)$(acpi -b)})
30
+    percent=${(L)${${acpi[1]}#*, }%\%, *}
31
+    state=${(L)${${acpi[1]}#*: }%%, *}
32
+    [[ $state == (dis|)charging ]] || {
33
+	: > $cache
34
+	return
35
+    }
36
+
37
+    local -a gauge
38
+    local size=4
39
+    local full
40
+    local g
41
+    local i j
42
+    _vbe_can_do_unicode && gauge=(▲ ▼ △ ▽) || gauge=('#' '#' '-' '-')
43
+    full=$(( (${percent}*${size}+49)/100 ))
44
+    if (( $percent < 10 )); then
45
+	g=red
46
+    elif (( $percent < 30 )); then
47
+	g=yellow
48
+    else
49
+	g=green
50
+    fi
51
+    i=1
52
+    [[ $state == "discharging" ]] && i=2
53
+    local gg
54
+    (( $full >= 1 )) && for j in {1..$full}; do gg=$gg$gauge[$i]; done
55
+    i=$(( $i + 2 ))
56
+    (( $full < $size )) && \
57
+	for j in {$(( $full + 1 ))..$size}; do gg=$gg$gauge[$i]; done
58
+    print -n $g $gg > $cache
59
+    print $g $gg
60
+}
61
+
62
+_vbe_add_prompt_battery () {
63
+    local v="$(_vbe_battery)"
64
+    local color=${v% *}
65
+    local gauge="${v#* }"
66
+
67
+    [[ -n $gauge ]] && \
68
+        _vbe_prompt_segment $color black %B$gauge
69
+}

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

@@ -0,0 +1,24 @@
1
+# -*- sh -*-
2
+
3
+# Telnet through HNM
4
+telnet() {
5
+    _vbe_title "$*"
6
+    case "$1" in
7
+	*.net.b?.p.fti.net|swbg*)
8
+	    host=bgadm
9
+	    ;;
10
+	*.net.s?.p.fti.net)
11
+	    host=soadm
12
+	    ;;
13
+	*.net.m?.p.fti.net)
14
+	    host=mtadm
15
+	    ;;
16
+	*)
17
+	    # Don't know how to handle, let's just use normal telnet
18
+	    command telnet "$@"
19
+	    return
20
+	    ;;
21
+    esac
22
+    LANG=C LC_MESSAGES=C command ssh -t $host \
23
+	telnet $1
24
+}

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

@@ -0,0 +1,39 @@
1
+# -*- sh -*-
2
+
3
+# Incorporate git and svn information into prompt
4
+
5
+(( $+functions[add-zsh-hook] )) && {
6
+
7
+    autoload -Uz vcs_info
8
+
9
+    zstyle ':vcs_info:*' enable git svn
10
+    __() {
11
+        local common='${PRCH[branch]} %b%c%u'
12
+	zstyle ':vcs_info:*:*'   formats $common
13
+	zstyle ':vcs_info:*:*'   actionformats ${common}'%{${fg[default]}%} ${PRCH[sep]} %{${fg[green]}%}'%a
14
+	zstyle ':vcs_info:svn:*' branchformat '%b:%r'
15
+	zstyle ':vcs_info:hg*:*' hgrevformat '%r'
16
+	zstyle ':vcs_info:*:*'   stagedstr     %{${fg[green]}%}${PRCH[circle]}
17
+	zstyle ':vcs_info:*:*'   unstagedstr   %{${fg[yellow]}%}${PRCH[circle]}
18
+	zstyle ':vcs_info:*:*'   check-for-changes true
19
+        zstyle ':vcs_info:hg*:*' get-revision true
20
+
21
+        zstyle ':vcs_info:git*+set-message:*' hooks git-untracked
22
+
23
+        +vi-git-untracked(){
24
+            if [[ $(git rev-parse --is-inside-work-tree 2> /dev/null) == 'true' ]] && \
25
+                git status --porcelain | grep '??' &> /dev/null ; then
26
+                hook_com[staged]+='%{${fg[black]}%}${PRCH[circle]}'
27
+            fi
28
+        }
29
+
30
+    } && __
31
+
32
+    _vbe_vcs_precmd () {
33
+	vcs_info
34
+    }
35
+    add-zsh-hook precmd _vbe_vcs_precmd
36
+    _vbe_add_prompt_vcs () {
37
+	_vbe_prompt_segment cyan default ${(e)vcs_info_msg_0_}
38
+    }
39
+}

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

@@ -0,0 +1,28 @@
1
+# -*- sh -*-
2
+
3
+_vbe_autoload () {
4
+    # Like autoload but actually load and fail silently if not able to load
5
+    (( $+functions[$1] )) && return 0
6
+    autoload +X $1 2> /dev/null || {
7
+        unset -f $1
8
+        return 1
9
+    }
10
+    return 0
11
+}
12
+
13
+_vbe_autoload is-at-least || is-at-least() { return 0 }
14
+
15
+# Test for unicode support
16
+_vbe_can_do_unicode () {
17
+    if is-at-least 4.3.4 && \
18
+           [[ -o multibyte ]] && (( ${#${:-↵}} == 1 )); then
19
+        case $TERM in
20
+            screen*) ;;
21
+            xterm*) ;;
22
+            rxvt*) ;;
23
+            *) return 1 ;;
24
+        esac
25
+        return 0
26
+    fi
27
+    return 0
28
+}

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

@@ -0,0 +1,17 @@
1
+# -*- sh -*-
2
+
3
+# Export HOSTNAME variable
4
+__() {
5
+    local -a hostnames
6
+    local host
7
+    hostnames=($(hostname -f)
8
+	$(hostname)
9
+	$(</etc/hostname)
10
+	$HOST
11
+	$HOST.$(</etc/mailname))
12
+    for host ($hostnames); do
13
+	HOSTNAME=${host%%.}
14
+	[[ $HOSTNAME == *.* ]] && break
15
+    done
16
+    export HOSTNAME
17
+} && __ 2> /dev/null

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

@@ -0,0 +1,12 @@
1
+# -*- sh -*-
2
+
3
+__() {
4
+    local wanted
5
+    local p
6
+    wanted=(/usr/local/sbin /usr/sbin /sbin /usr/local/bin /usr/bin /bin /usr/lib/ccache ~/bin)
7
+    for p in $wanted; do
8
+	(( ${${path[(r)$p]}:+1} )) || {
9
+	    [ -d $p ] && path=($p $path)
10
+	}
11
+    done
12
+} && __

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

@@ -0,0 +1,19 @@
1
+# -*- sh -*-
2
+
3
+(( $+commands[locale] )) && __() {
4
+    local available
5
+    local locales
6
+    local locale
7
+    locales=( "LANG fr_FR.utf8 fr_FR.UTF-8 en_US.utf8 en_US.UTF-8 C.utf8 C.UTF-8 C" \
8
+	      "LC_MESSAGES en_US.utf8 en_US.UTF-8 fr_FR.utf8 fr_FR.UTF-8 C.utf8 C.UTF-8 C" )
9
+    available=("${(f)$(locale -a)}")
10
+    for locale in $locales; do
11
+	for l in $=locale[(w)2,-1]; do
12
+            if (( ${available[(i)$l]} <= ${#available} )); then
13
+		export $locale[(w)1]=$l
14
+		break
15
+	    fi
16
+	done
17
+    done
18
+    unset LC_ALL
19
+} && __ 2> /dev/null

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

@@ -0,0 +1,19 @@
1
+# -*- sh -*-
2
+
3
+# Create $ZSH/run/u if it doesn't exist
4
+[[ -d $ZSH/run/u ]] || {
5
+    mkdir -p $ZSH/run/u
6
+    chmod 1777 $ZSH/run/u
7
+}
8
+
9
+# Create per-UID directory and do migration
10
+[[ -d $ZSH/run/u/$HOST-$UID ]] || {
11
+    mkdir -p $ZSH/run/u/$HOST-$UID
12
+    for f in $ZSH/run/{acpi,history,editor,zcompdump,bookmarks}-$HOST-$UID(N); do
13
+        mv $f $ZSH/run/u/$HOST-$UID/${${f##*/}%-$HOST-$UID}
14
+    done
15
+    for f in $ZSH/run/u/$UID/{acpi,history,editor,zcompdump,bookmarks}-$HOST(N); do
16
+        mv $f $ZSH/run/u/$HOST-$UID/${${f##*/}%-$HOST}
17
+    done
18
+    rmdir $ZSH/run/u/$UID 2> /dev/null
19
+}

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

@@ -0,0 +1,76 @@
1
+# -*- sh -*-
2
+
3
+# Update TERM if we have LC__ORIGINALTERM variable
4
+# Also, try a sensible term where we have terminfo stuff
5
+autoload -U zsh/terminfo zsh/termcap
6
+__() {
7
+    local term
8
+
9
+    case $COLORTERM,$TERM in
10
+        vbeterm,xterm | xfce4-terminal,xterm )
11
+            TERM=xterm-256color
12
+            ;;
13
+    esac
14
+
15
+    for term in $LC__ORIGINALTERM $TERM ${TERM/-256color} xterm-256color xterm; do
16
+        TERM=$term 2> /dev/null
17
+        if (( ${terminfo[colors]:-0} >= 8 )) || \
18
+            (zmodload zsh/termcap 2> /dev/null) && \
19
+            (( ${termcap[Co]:-0} >= 8)); then
20
+            if _vbe_autoload colors; then
21
+                colors
22
+            else
23
+                # Minimal version with what we need
24
+                local -A color
25
+                color=(none 00
26
+                       fg-black 30 bg-black 40
27
+                       fg-red 31 bg-red 41
28
+                       fg-green 32 bg-green 42
29
+                       fg-yellow 33 bg-yellow 43
30
+                       fg-blue 34 bg-blue 44
31
+                       fg-magenta 35 bg-magenta 45
32
+                       fg-cyan 36 bg-cyan 46
33
+                       fg-white 37 bg-white 47
34
+                       fg-default 39 bg-default 49)
35
+                local lc=$'\e[' rc=m
36
+                local k
37
+                typeset -AHg fg bg
38
+                for k in ${(k)color[(I)fg-*]}; do
39
+                    fg[${k#fg-}]="$lc${color[$k]}$rc"
40
+                done
41
+                for k in ${(k)color[(I)bg-*]}; do
42
+                    bg[${k#bg-}]="$lc${color[$k]}$rc"
43
+                done
44
+                typeset -Hg reset_color
45
+                reset_color="$lc${color[none]}$rc"
46
+            fi
47
+            break
48
+        fi
49
+    done
50
+    unset LC__ORIGINALTERM
51
+    unset COLORTERM
52
+    export TERM
53
+} && __
54
+
55
+
56
+typeset -gA PRCH
57
+if _vbe_can_do_unicode; then
58
+    PRCH=(
59
+        sep "\uE0B1" end "\uE0B0"
60
+        retb "" reta " ↵"
61
+        circle "●" branch "\uE0A0"
62
+        ok "✔" ellipsis "…"
63
+        eol "⏎" running "↻"
64
+    )
65
+else
66
+    PRCH=(
67
+        sep "/" end ""
68
+        retb "<" reta ">"
69
+        circle "*" branch "±"
70
+        ok ">" ellipsis ".."
71
+        eol "~~" running "> "
72
+    )
73
+fi
74
+
75
+# Freeze the terminal
76
+ttyctl -f

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

@@ -0,0 +1,71 @@
1
+# -*- sh -*-
2
+
3
+# Alter window title
4
+_vbe_title () {
5
+    [ -t 1 ] || return
6
+    emulate -L zsh
7
+    local title
8
+    title=${1//[^[:alnum:]\/>< ._~:=?@-]/ }
9
+    shorttitle=${2:-$1}
10
+    case $TERM in
11
+	screen*)
12
+	    print -n "\ek$shorttitle\e\\"
13
+	    print -n "\e]1;$title\a"
14
+	    print -n "\e]2;$title\a"
15
+	    ;;
16
+	rxvt*|xterm*)
17
+	    print -n "\e]1;$title\a"
18
+	    print -n "\e]2;$title\a"
19
+	    ;;
20
+    esac
21
+}
22
+
23
+# Current running program as title
24
+_title_preexec () {
25
+    emulate -L zsh
26
+    setopt extended_glob
27
+    local t tt
28
+    local -a cmd
29
+    cmd=(${(z)1})
30
+    case $cmd[1] in
31
+        fg)
32
+            case $#cmd in
33
+                1)
34
+                    t=${jobtexts[${(k)jobstates[(R)*+*]}]}
35
+                    ;;
36
+                *)
37
+                    t=${jobtexts[${cmd[2]#%}]}
38
+                    ;;
39
+            esac
40
+            ;;
41
+        %*)
42
+	    t=${jobtexts[${cmd[1]#%}]}
43
+	    ;;
44
+	*=*|exec|sudo|\()
45
+	    (( ${#cmd} > 1 )) && shift cmd
46
+	    ;&
47
+	*)
48
+            case $cmd[1] in
49
+                less|more|v|e|vi|vim|emacs|ssh)
50
+                    # Display filename
51
+                    t=$cmd[*]
52
+                    tt=${${${(R)cmd:#-*}[2]}:t}
53
+                    ;;
54
+                *)
55
+	            t=$cmd[*]
56
+                    tt=$cmd[1]:t
57
+	            ;;
58
+            esac
59
+            ;;
60
+    esac
61
+#    _vbe_title "${SSH_TTY+${(%):-%M} }\> $t" "${SSH_TTY+${(%):-%M} }${PRCH[running]}${tt:-${t%% *}}"
62
+    _vbe_title "$t" "${PRCH[running]}${tt:-${t%% *}}"
63
+
64
+}
65
+if (( $+functions[add-zsh-hook] )); then
66
+    add-zsh-hook preexec _title_preexec
67
+else
68
+    preexec () {
69
+	_title_preexec
70
+    }
71
+fi

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

@@ -0,0 +1,5 @@
1
+# -*- sh -*-
2
+
3
+# Create a temporary directory
4
+[ ! -h ~/tmp ] && [ ! -d ~/tmp ] && [ -w ~ ] && \
5
+    mkdir ~/tmp

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

@@ -0,0 +1,66 @@
1
+# -*- sh -*-
2
+
3
+autoload -U zutil
4
+
5
+_vbe_autoload compinit && {
6
+    autoload -U complist
7
+    compinit -i -d $ZSH/run/u/$HOST-$UID/zcompdump
8
+}
9
+
10
+setopt auto_menu
11
+setopt auto_remove_slash
12
+setopt complete_in_word
13
+setopt always_to_end
14
+setopt glob_complete
15
+unsetopt list_beep
16
+
17
+zstyle ':completion:*' completer _complete _match _approximate
18
+zstyle ':completion:*' list-colors ''
19
+zstyle ':completion:*' list-prompt ''
20
+zstyle ':completion:*' group-name ''
21
+zstyle ':completion:*' menu select
22
+zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#) ([0-9a-z-]#)*=01;34=0=01'
23
+zstyle ':completion:*:kill:*' force-list always
24
+zstyle ':completion:*:processes' command "ps -eo pid,user,comm,cmd -w -w"
25
+zstyle ':completion::complete:*' use-cache 1
26
+zstyle ':completion::complete:*' cache-path $ZSH/run/u/$HOST-$UID/cache/
27
+zstyle ':completion:*:descriptions' format '%B%d%b'
28
+zstyle ':completion:*:functions' ignored-patterns '_*'
29
+zstyle ':completion:*:match:*' original only
30
+zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX + $#SUFFIX) / 3 )) )'
31
+
32
+# Host completion
33
+_custom_hosts() {
34
+    # Complete ~/.zsh/local/hosts.*
35
+    local host
36
+    for host in $ZSH/local/hosts.*(N-.); do
37
+	_wanted hosts expl host compadd "$@" $(<$host)
38
+    done
39
+
40
+    # And /etc/hosts
41
+    _wanted hosts expl host \
42
+	compadd "$@" ${(s: :)${(ps:\t:)${${(f)~~"$(</etc/hosts)"}%%\#*}##[:blank:]#[^[:blank:]]#}}
43
+
44
+    # Now, try LDAP
45
+    [[ -z $LDAPHOST ]] || {
46
+	_wanted hosts expl host \
47
+	    compadd "$@" ${$(ldapsearch -h $LDAPHOST \
48
+	    -b "ou=hosts,dc=fti,dc=net" -LLL -s sub -z 100 \
49
+	    -x "cn=${words[CURRENT]}*" cn 2> /dev/null)%* }
50
+    }
51
+}
52
+
53
+zstyle -e ':completion:*' hosts _custom_hosts
54
+
55
+# In menu, select items with +
56
+zmodload -i zsh/complist
57
+bindkey -M menuselect "+" accept-and-menu-complete
58
+
59
+# Display dots when completion is in progress
60
+expand-or-complete-with-dots() {
61
+    echo -n "\e[31m...\e[0m"
62
+    zle expand-or-complete
63
+    zle redisplay
64
+}
65
+zle -N expand-or-complete-with-dots
66
+bindkey "^I" expand-or-complete-with-dots

+ 371
- 0
rc/alias.zsh View File

@@ -0,0 +1,371 @@
1
+# -*- sh -*-
2
+
3
+# Some generic aliases
4
+alias df='df -h'
5
+alias du='du -h'
6
+alias rm='rm -i'
7
+alias ll='ls -l'
8
+alias s='cd ..'
9
+__() {
10
+  local dmesg_version=${${${:-"$(dmesg --version 2> /dev/null)"}##* }:-0.0}
11
+  if is-at-least 2.23 $dmesg_version; then
12
+      alias dmesg='dmesg -H -P'
13
+  elif is-at-least 0.1 $dmesg_version; then
14
+    alias dmesg='dmesg -T'
15
+  fi
16
+} && __
17
+
18
+# ls colors
19
+(( ${terminfo[colors]:-0} >= 8 )) && {
20
+    export LSCOLORS="Gxfxcxdxbxegedabagacad"
21
+    ls --color -d . &>/dev/null && alias ls='ls --color=tty' || {
22
+        ls -G &> /dev/null && alias ls='ls -G'
23
+    }
24
+}
25
+#  alias de ls
26
+alias ls='ls --classify --tabsize=0 --literal --color=auto --show-control-chars --human-readable'
27
+
28
+alias l='ls -lh'
29
+alias ll='ls -l'
30
+alias la='ls -a'
31
+alias lla='ls -la'
32
+# ls pour voir que les fichiers par .
33
+alias lsa='ls -ld .*'
34
+
35
+alias sl=ls # pour les ceussent qui pensent à la fin avant le début ;-)
36
+
37
+alias grep='grep --color=always'
38
+
39
+# ip aliases
40
+alias ip6='ip -6'
41
+alias ipr='ip -r'
42
+alias ip6r='ip -6 -r'
43
+alias ipm='ip -r monitor'
44
+
45
+# Setting up less colors
46
+export LESS_TERMCAP_mb=$'\E[01;31m'
47
+export LESS_TERMCAP_md=$'\E[01;38;5;74m'
48
+export LESS_TERMCAP_me=$'\E[0m'
49
+export LESS_TERMCAP_se=$'\E[0m'
50
+export LESS_TERMCAP_so=$'\E[7;32;5;246m'
51
+export LESS_TERMCAP_ue=$'\E[0m'
52
+export LESS_TERMCAP_us=$'\E[04;38;5;146m'
53
+
54
+# grep
55
+__() {
56
+  local cmd
57
+  local -A greps
58
+  greps=(grep ""
59
+         rgrep r
60
+         egrep E
61
+         fgrep F
62
+         zgrep "")
63
+  for cmd in ${(k)greps}; do
64
+    if (( $+commands[$cmd] )); then
65
+        alias $cmd="$cmd --color=auto"
66
+    else
67
+      [[ -n ${greps[$cmd]} ]] &&
68
+          alias $cmd='command grep -${greps[$cmd]} --color=auto'
69
+    fi
70
+  done
71
+} && __
72
+
73
+# smv like scp
74
+alias smv='rsync -P --remove-source-files'
75
+(( $+functions[compdef] )) && compdef _ssh smv=scp
76
+
77
+# Less generic aliases
78
+susu() {
79
+  command sudo -H -u ${1:-root} \
80
+          env ZDOTDIR=${ZDOTDIR:-$HOME} \
81
+              ZSH=$ZSH ${DISPLAY+DISPLAY=$DISPLAY} \
82
+              ${SSH_TTY+SSH_TTY=$SSH_TTY} \
83
+              ${SSH_AUTH_SOCK+SSH_AUTH_SOCK=$SSH_AUTH_SOCK} \
84
+          zsh -i -l
85
+}
86
+alias please='sudo $(fc -ln -1)'
87
+
88
+# Aliases as a function
89
+evince() { command evince ${*:-*.(djvu|dvi|pdf)(om[1])} }
90
+md() { command mkdir -p $1 && cd $1 }
91
+
92
+# JSON pretty-printing.
93
+#
94
+# Many programs have a flag to enable unbuffered output. For example,
95
+# `curl -N`. Most programs can be forced to use unbuffered output with
96
+# `stdbuf -o L`.
97
+json() {
98
+  PATH=/usr/bin:$PATH python -u -c '#!/usr/bin/env python
99
+
100
+# Pretty-print files containing JSON lines. Reads from stdin when no
101
+# argument is provided, otherwise pretty print each argument. This
102
+# script should be invoked with "-u" to disable buffering. The shebang
103
+# above is just for syntax highlighting to work correctly.
104
+
105
+import sys
106
+import re
107
+import json
108
+import subprocess
109
+import errno
110
+try:
111
+    import pygments
112
+    from pygments.lexers import JavascriptLexer
113
+    from pygments.formatters import TerminalFormatter
114
+except ImportError:
115
+    pygments = None
116
+
117
+jsonre = re.compile(r"(?P<prefix>.*?)(?P<json>\{.*\})(?P<suffix>.*)")
118
+
119
+
120
+def display(f):
121
+    pager = None
122
+    out = sys.stdout
123
+    if out.isatty() and f != sys.stdin:
124
+        pager = subprocess.Popen(["less", "-RFX"], stdin=subprocess.PIPE)
125
+        out = pager.stdin
126
+    while True:
127
+        line = f.readline()
128
+        if line == "":
129
+            break
130
+        mo = None
131
+        try:
132
+            mo = jsonre.match(line)
133
+            if not mo:
134
+                raise ValueError("No JSON string found")
135
+            j = json.loads(mo.group("json"))
136
+            pretty = json.dumps(j, indent=2)
137
+            if pygments and sys.stdout.isatty():
138
+                pretty = pygments.highlight(pretty,
139
+                                            JavascriptLexer(),
140
+                                            TerminalFormatter())
141
+            output = (mo.group("prefix") + pretty.strip() +
142
+                      mo.group("suffix") + "\n")
143
+        except:
144
+            output = line
145
+        try:
146
+            out.write(output)
147
+        except IOError as e:
148
+            if e.errno == errno.EPIPE or e.errno == errno.EINVAL:
149
+                break
150
+            raise
151
+    if pager is not None:
152
+        pager.stdin.close()
153
+        pager.wait()
154
+
155
+if len(sys.argv) == 1:
156
+    files = [sys.stdin]
157
+else:
158
+    files = sys.argv[1:]
159
+
160
+for f in files:
161
+    try:
162
+        if type(f) != file:
163
+            with file(f) as f:
164
+                display(f)
165
+        else:
166
+            display(f)
167
+    except KeyboardInterrupt:
168
+        sys.exit(1)
169
+' "$@"
170
+}
171
+
172
+# Other pretty-printing functions
173
+if (( $+commands[pygmentize] )); then
174
+  __pygmentize() {
175
+    PATH=/usr/bin:$PATH python -u -c "#!/usr/bin/env python
176
+import sys
177
+import errno
178
+import pygments.cmdline
179
+try:
180
+    sys.exit(pygments.cmdline.main(sys.argv))
181
+except KeyboardInterrupt:
182
+    sys.exit(1)
183
+except IOError as e:
184
+    if e.errno == errno.EPIPE:
185
+        sys.exit(1)
186
+    raise
187
+" "$@"
188
+  }
189
+
190
+  xml() {
191
+    cat "$@" | xmllint --format - | __pygmentize -l xml
192
+  }
193
+
194
+  v() {
195
+    local formatter
196
+    if (( ${terminfo[colors]:-0} >= 256 )); then
197
+      formatter=console256
198
+    else
199
+      formatter=terminal
200
+    fi
201
+
202
+    local lexer
203
+    lexer=$(__pygmentize -N "${1%.gz}")
204
+
205
+    local -a args
206
+    args=(-P style=monokai -f $formatter)
207
+    case $lexer in
208
+      text)
209
+        args=(-g $args)
210
+        ;;
211
+      *)
212
+        args=(-l $lexer)
213
+        ;;
214
+    esac
215
+
216
+    zcat -f "$@" | __pygmentize $args | less -RFX
217
+  }
218
+else
219
+  xml() {
220
+    cat "$@" | xmllint --format -
221
+  }
222
+
223
+  alias v=zless -FX
224
+fi
225
+
226
+# Record a video
227
+screenrecord() {
228
+  (
229
+    eval $(xdotool selectwindow getwindowgeometry --shell) &&
230
+    command ffmpeg -f x11grab \
231
+      -draw_mouse 0 \
232
+      -r 25 \
233
+      -s ${WIDTH}x${HEIGHT} \
234
+      -i ${DISPLAY}.${SCREEN:-0}+${X:-0},${Y:-0} \
235
+      -dcodec copy \
236
+      -pix_fmt yuv420p \
237
+      -c:v libx264 \
238
+      -preset ultrafast \
239
+      $@
240
+  )
241
+}
242
+
243
+# Reimplementation of an xterm tool
244
+resize() {
245
+  printf '\033[18t'
246
+
247
+  local width
248
+  local height
249
+  local state
250
+  local char
251
+
252
+  state=0
253
+  while read -r -s -k 1 -t 1 char; do
254
+    case "$state,$char" in
255
+      "0,;")
256
+        # End of CSI
257
+        state=1
258
+        ;;
259
+      "1,;")
260
+        # End of height
261
+        stty rows $height
262
+        state=2
263
+        ;;
264
+      "1,"*)
265
+        height="$height$char"
266
+        ;;
267
+      "2,t")
268
+        # End of width
269
+        stty columns $width
270
+        state=3
271
+        ;;
272
+      "2,"*)
273
+        width="$width$char"
274
+        ;;
275
+    esac
276
+    (( $state == 3 )) && break
277
+  done
278
+  # tmux <= 1.9.1 is buggy and doesn't end its answer with 't'
279
+  (( $state == 2 )) && stty columns $width
280
+}
281
+
282
+# Simple calculator
283
+function c() {
284
+  echo $(($@))
285
+}
286
+alias c='noglob c'
287
+
288
+# Currency conversion (with Google)
289
+function currency() {
290
+  local -a amounts
291
+  local -a currencies
292
+  for ((i=1; i<=$#; i++)); do
293
+    case ${@[i]} in
294
+      [0-9.]*)
295
+        amounts=($amounts ${@[i]})
296
+        ;;
297
+      *)
298
+        currencies=($currencies ${@[i]})
299
+        ;;
300
+    esac
301
+  done
302
+  (( $#currencies > 1 )) || currencies=($currencies chf eur usd)
303
+  local from=${currencies[1]}
304
+  for amount in $amounts; do
305
+    for to in $currencies; do
306
+      [[ ${to:u} != ${from:u} ]] || continue
307
+      #echo "Convert $amount ${from:u} to ${to:u}"
308
+      curl -s "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to" | \
309
+          sed '/res/!d;s/<[^>]*>//g'
310
+    done
311
+  done
312
+}
313
+
314
+# Allow to prefix commands with `$` to help copy/paste operations.
315
+function \$() {
316
+  "$@"
317
+}
318
+
319
+# Get my own external IP
320
+function myip() {
321
+  for v in 4 6 ; do
322
+    echo IPv$v $(false || \
323
+        curl -$v -s ip.appspot.com || \
324
+        curl -$v -s eth0.me || \
325
+        curl -$v -s ipecho.net/plain ||
326
+        dig -$v +short myip.opendns.com @resolver1.opendns.com)
327
+  done
328
+}
329
+
330
+# Display a color testcard
331
+# From: http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
332
+colortest() {
333
+    local T='gYw'   # The test text
334
+
335
+    local fg
336
+    local bg
337
+    printf "%12s" ""
338
+    for fg in {40..47}; do
339
+	printf "%7sm" ${fg}
340
+    done
341
+    printf "\n"
342
+    for fg in 0 1 $(for i in {30..37}; do echo $i 1\;$i; done); do
343
+	printf " %5s \e[%s  %s  " ${fg}m ${fg}m ${T}
344
+	for bg in {40..47}m; do
345
+	    printf " \e[%s\e[%s  %s  \e[0m" ${fg}m ${bg} ${T}
346
+	done
347
+	printf "\n"
348
+    done
349
+    printf "\n"
350
+
351
+    printf "Color cube: 6x6x6:\n"
352
+    local red
353
+    local green
354
+    local blue
355
+    for red in {0..5}; do
356
+        for green in {0..5}; do
357
+            for blue in {0..5}; do
358
+                bg=$((16 + red * 36 + green * 6 + blue))
359
+                printf "\e[48;5;%dm  " bg
360
+            done
361
+            printf "\e[0m "
362
+        done
363
+        printf "\n"
364
+    done
365
+
366
+    printf "\nGrayscale ramp:\n"
367
+    for bg in {232..255}; do
368
+      printf "\e[48;5;%dm  " bg
369
+    done
370
+    printf "\e[0m\n"
371
+}

+ 61
- 0
rc/bookmarks.zsh View File

@@ -0,0 +1,61 @@
1
+# -*- sh -*-
2
+
3
+# Handle bookmarks. This uses the static named directories feature of
4
+# zsh. Such directories are declared with `hash -d
5
+# name=directory`. Both prompt expansion and completion know how to
6
+# handle them. We populate the hash with directories.
7
+#
8
+# With autocd, you can just type `~-bookmark`. Since this can be
9
+# cumbersome to type, you can also type `@@` and this will be turned
10
+# into `~-` by ZLE.
11
+
12
+is-at-least 4.3.12 && __() {
13
+    MARKPATH=$ZSH/run/marks
14
+
15
+    # Add some static entries
16
+    hash -d log=/var/log
17
+    hash -d doc=/usr/share/doc
18
+
19
+    # Populate the hash
20
+    for link ($MARKPATH/*(N@)) {
21
+        hash -d -- -${link:t}=${link:A}
22
+    }
23
+
24
+    vbe-insert-bookmark() {
25
+        emulate -L zsh
26
+        LBUFFER=${LBUFFER}"~-"
27
+    }
28
+    zle -N vbe-insert-bookmark
29
+    bindkey '@@' vbe-insert-bookmark
30
+
31
+    # Manage bookmarks
32
+    bookmark() {
33
+        [[ -d $MARKPATH ]] || mkdir -p $MARKPATH
34
+        if (( $# == 0 )); then
35
+            # When no arguments are provided, just display existing
36
+            # bookmarks
37
+            for link in $MARKPATH/*(N@); do
38
+                local markname="$fg[green]${link:t}$reset_color"
39
+                local markpath="$fg[blue]${link:A}$reset_color"
40
+                printf "%-30s -> %s\n" $markname $markpath
41
+            done
42
+        else
43
+            # Otherwise, we may want to add a bookmark or delete an
44
+            # existing one.
45
+            local -a delete
46
+            zparseopts -D d=delete
47
+            if (( $+delete[1] )); then
48
+                # With `-d`, we delete an existing bookmark
49
+                command rm $MARKPATH/$1
50
+            else
51
+                # Otherwise, add a bookmark to the current
52
+                # directory. The first argument is the bookmark
53
+                # name. `.` is special and means the bookmark should
54
+                # be named after the current directory.
55
+                local name=$1
56
+                [[ $name == "." ]] && name=${PWD:t}
57
+                ln -s $PWD $MARKPATH/$name
58
+            fi
59
+        fi
60
+    }
61
+} && __

+ 18
- 0
rc/dircolors.zsh View File

@@ -0,0 +1,18 @@
1
+
2
+# couleurs personnalisées pour le LS
3
+if [ -x /usr/bin/dircolors ]
4
+then
5
+   if [ -r ~/.dir_colors ]
6
+   then
7
+        eval "`/usr.bin/dircolors ~/.dir_colors`"
8
+   elif [ -r ~/.zsh/dir_colors ]
9
+   then
10
+        eval "`/usr/bin/dircolors ~/.zsh/dir_colors`"
11
+   elif [ -r /etc/dir_colors ]
12
+   then
13
+        eval "`/usr/bin/dircolors /etc/dir_colors`"
14
+   else
15
+        eval "`/usr/bin/dircolors`"
16
+   fi
17
+fi
18
+

+ 46
- 0
rc/editor.zsh View File

@@ -0,0 +1,46 @@
1
+# -*- sh -*-
2
+
3
+# Setup EDITOR
4
+__() {
5
+    local -a editors
6
+    local editor
7
+    editors=(
8
+	"emacs-snapshot -nw ${(%):-%(!.-q --eval='(global-font-lock-mode 1)'.)}" # emacs
9
+	"emacs24        -nw ${(%):-%(!.-q --eval='(global-font-lock-mode 1)'.)}" # emacs
10
+	"emacs23        -nw ${(%):-%(!.-q --eval='(global-font-lock-mode 1)'.)}" # emacs
11
+	"emacs22        -nw ${(%):-%(!.-q --eval='(global-font-lock-mode 1)'.)}" # emacs
12
+	"zile"		  # Emacs clone
13
+	"jove" "mg" "jed" # Emacs clone
14
+	"vim" "vi"	  # vi
15
+	"editor")	  # fallback
16
+    for editor in $editors; do
17
+	(( $+commands[$editor[(w)1]] )) && {
18
+	    # Some programs may not like to have arguments
19
+	    if [[ $editor == *\ * ]]; then
20
+		export EDITOR=$ZSH/run/u/$HOST-$UID/editor
21
+		cat <<EOF > $EDITOR
22
+#!/bin/sh
23
+exec $editor "\$@"
24
+EOF
25
+		chmod +x $EDITOR
26
+	    else
27
+		export EDITOR=$editor
28
+	    fi
29
+	    break
30
+	}
31
+    done
32
+    [[ -z $EDITOR ]] || {
33
+        alias e=$EDITOR
34
+        # Maybe use emacsclient?
35
+        [[ $editor == emacs* ]] && (( $+commands[emacsclient] )) && {
36
+	    export ALTERNATE_EDITOR=$EDITOR
37
+	    export EDITOR="emacsclient"
38
+            local ecargs='${=${DISPLAY:+-n}:--t -c}'
39
+	    alias e="emacsclient $ecargs"
40
+        }
41
+    }
42
+
43
+} && __
44
+
45
+
46
+unset VISUAL

+ 13
- 0
rc/history.zsh View File

@@ -0,0 +1,13 @@
1
+# -*- sh -*-
2
+
3
+setopt extended_history	        # save timestamps
4
+setopt share_history            # share history accross zsh sessions
5
+setopt hist_ignore_all_dups	# ignores duplicates
6
+
7
+HISTFILE=$ZSH/run/u/$HOST-$UID/history
8
+HISTSIZE=20000
9
+SAVEHIST=20000
10
+
11
+# Ctrl-r search in the history with patterns
12
+(( $+widgets[history-incremental-pattern-search-backward] )) &&	\
13
+    bindkey '^r' history-incremental-pattern-search-backward

+ 16
- 0
rc/keys.zsh View File

@@ -0,0 +1,16 @@
1
+# -*- sh -*-
2
+
3
+# Use emacs keybindings
4
+bindkey -e
5
+
6
+# Some systems misses the appropriate /etc/inputrc for this
7
+bindkey "\e[3~" delete-char        # Delete
8
+
9
+# Replace insert-last-word by a smart version
10
+autoload -U smart-insert-last-word
11
+zle -N insert-last-word smart-insert-last-word
12
+
13
+# Also copy previous word
14
+autoload -U copy-earlier-word
15
+zle -N copy-earlier-word
16
+bindkey "\e," copy-earlier-word

+ 17
- 0
rc/options.zsh View File

@@ -0,0 +1,17 @@
1
+# -*- sh -*-
2
+
3
+setopt rmstarsilent             # Don't ask for confirmation on rm *
4
+setopt interactivecomments	# Allow comments inside commands
5
+setopt autopushd		# Maintain directories in a heap
6
+setopt autocd			# Don't need to use `cd`
7
+setopt extendedglob             # Enable extended globbing
8
+
9
+# meta-h will invoke man for the current command
10
+autoload run-help
11
+# When the command is {sudo,git,openssl} something, get help on something
12
+autoload run-help-sudo
13
+autoload run-help-git
14
+autoload run-help-openssl
15
+autoload -U zmv
16
+# Remove / from WORDCHARS (more like bash)
17
+WORDCHARS=${WORDCHARS:s#/#}

+ 61
- 0
rc/paste.zsh View File

@@ -0,0 +1,61 @@
1
+# -*- sh -*-
2
+# Code from Mikael Magnusson: http://www.zsh.org/mla/users/2011/msg00367.html
3
+#
4
+# Requires xterm, urxvt, iTerm2 or any other terminal that supports
5
+# bracketed paste mode as documented: http://www.xfree86.org/current/ctlseqs.html.
6
+#
7
+# This is enabled by default in Zsh 5.1+.
8
+#
9
+# By default, tmux doesn't paste using this mode. It's possible to
10
+# force it to do so:
11
+#
12
+#    bind ] paste-buffer -p
13
+
14
+(( $+zle_bracketed_paste == 0 )) && [[  $TERM == rxvt-unicode || \
15
+    $TERM == rxvt-unicode-256color || \
16
+    $TERM == xterm || \
17
+    $TERM == xterm-256color || \
18
+    $TERM == screen-256color ]] && __() {
19
+
20
+    # create a new keymap to use while pasting
21
+    bindkey -N paste
22
+    bindkey -R -M paste "^@"-"\M-^?" paste-insert
23
+    bindkey '^[[200~' _start_paste
24
+    bindkey -M paste '^[[201~' _end_paste
25
+    bindkey -M paste -s '^M' '^J'
26
+
27
+    zle -N _start_paste
28
+    zle -N _end_paste
29
+    zle -N zle-line-init _zle_line_init
30
+    zle -N zle-line-finish _zle_line_finish
31
+    zle -N paste-insert _paste_insert
32
+
33
+    # switch the active keymap to paste mode
34
+    function _start_paste() {
35
+        bindkey -A paste main
36
+    }
37
+
38
+    # go back to our normal keymap, and insert all the pasted text in the
39
+    # command line. this has the nice effect of making the whole paste be
40
+    # a single undo/redo event.
41
+    function _end_paste() {
42
+        bindkey -e
43
+        LBUFFER+=$_paste_content
44
+        unset _paste_content
45
+    }
46
+
47
+    function _paste_insert() {
48
+        _paste_content+=$KEYS
49
+    }
50
+
51
+    function _zle_line_init() {
52
+        # Tell terminal to send escape codes around pastes.
53
+        printf '\e[?2004h'
54
+    }
55
+
56
+    function _zle_line_finish() {
57
+        # Tell it to stop when we leave zle, so pasting in other programs
58
+        # doesn't get the ^[[200~ codes around the pasted text.
59
+        printf '\e[?2004l'
60
+    }
61
+} && __

+ 68
- 0
rc/profiles.zsh View File

@@ -0,0 +1,68 @@
1
+# -*- sh -*-
2
+
3
+# Definition of profiles is quite personal, protect them
4
+[[ $USER != "bernat" ]] || {
5
+    zstyle ':chpwd:profiles:/home/*/code/debian(|/|/*)'    profile debian
6
+    zstyle ':chpwd:profiles:/home/*/code/exoscale(|/|/*)'  profile exoscale
7
+
8
+    chpwd_profile_debian() {
9
+        [[ ${profile} == ${CHPWD_PROFILE} ]] && return 1
10
+        export DEBEMAIL=$USER@debian.org
11
+        export GIT_AUTHOR_EMAIL=$DEBEMAIL
12
+        export GIT_COMMITTER_EMAIL=$DEBEMAIL
13
+    }
14
+
15
+    chpwd_profile_exoscale() {
16
+        [[ ${profile} == ${CHPWD_PROFILE} ]] && return 1
17
+        export DEBEMAIL=Vincent.${(C)USER}@exoscale.ch
18
+        export GIT_AUTHOR_EMAIL=$DEBEMAIL
19
+        export GIT_COMMITTER_EMAIL=$DEBEMAIL
20
+    }
21
+
22
+    chpwd_profile_default() {
23
+        [[ ${profile} == ${CHPWD_PROFILE} ]] && return 1
24
+        export DEBEMAIL=$USER@debian.org
25
+        unset GIT_AUTHOR_EMAIL
26
+        unset GIT_COMMITTER_EMAIL
27
+    }
28
+}
29
+
30
+# Stolen from: http://git.grml.org/?p=grml-etc-core.git;f=etc/zsh/zshrc;hb=HEAD#l1558
31
+#
32
+# chpwd_profiles(): Directory Profiles, Quickstart:
33
+#
34
+# In .zshrc.local:
35
+#
36
+#   zstyle ':chpwd:profiles:/usr/src/grml(|/|/*)'   profile grml
37
+#   zstyle ':chpwd:profiles:/usr/src/debian(|/|/*)' profile debian
38
+#   chpwd_profiles
39
+#
40
+# For details see the `grmlzshrc.5' manual page.
41
+function chpwd_profiles() {
42
+    local profile context
43
+    local -i reexecute
44
+
45
+    context=":chpwd:profiles:$PWD"
46
+    zstyle -s "$context" profile profile || profile='default'
47
+    zstyle -T "$context" re-execute && reexecute=1 || reexecute=0
48
+
49
+    if (( ${+parameters[CHPWD_PROFILE]} == 0 )); then
50
+        typeset -g CHPWD_PROFILE
51
+        local CHPWD_PROFILES_INIT=1
52
+        (( ${+functions[chpwd_profiles_init]} )) && chpwd_profiles_init
53
+    elif [[ $profile != $CHPWD_PROFILE ]]; then
54
+        (( ${+functions[chpwd_leave_profile_$CHPWD_PROFILE]} )) \
55
+            && chpwd_leave_profile_${CHPWD_PROFILE}
56
+    fi
57
+    if (( reexecute )) || [[ $profile != $CHPWD_PROFILE ]]; then
58
+        (( ${+functions[chpwd_profile_$profile]} )) && chpwd_profile_${profile}
59
+    fi
60
+
61
+    CHPWD_PROFILE="${profile}"
62
+    return 0
63
+}
64
+
65
+chpwd_functions=(${chpwd_functions} chpwd_profiles)
66
+
67
+# Init
68
+chpwd_profiles

+ 127
- 0
rc/prompt.zsh View File

@@ -0,0 +1,127 @@
1
+# -*- sh -*-
2
+# Mostly taken from:
3
+#  - https://github.com/robbyrussell/oh-my-zsh/blob/master/themes/jonathan.zsh-theme
4
+#  - https://github.com/robbyrussell/oh-my-zsh/blob/master/themes/agnoster.zsh-theme
5
+
6
+zmodload zsh/datetime
7
+_vbe_prompt_precmd () {
8
+    _vbe_title "${SSH_TTY+${(%):-%M}:}${(%):-%50<..<%~}" "${SSH_TTY+${(%):-%M}:}${(%):-%20<..<%~}"
9
+}
10
+_vbe_prompt_preexec () {
11
+    _vbe_cmd_timestamp=$EPOCHSECONDS
12
+}
13
+if (( $+functions[add-zsh-hook] )); then
14
+    add-zsh-hook precmd _vbe_prompt_precmd
15
+    add-zsh-hook preexec _vbe_prompt_preexec
16
+else
17
+    precmd () {
18
+	_vbe_prompt_precmd
19
+    }
20
+fi
21
+
22
+# Stolen from https://github.com/sindresorhus/pure/blob/master/pure.zsh
23
+_vbe_human_time () {
24
+    local tmp=$1
25
+    local days=$(( tmp / 60 / 60 / 24 ))
26
+    local hours=$(( tmp / 60 / 60 % 24 ))
27
+    local minutes=$(( tmp / 60 % 60 ))
28
+    local seconds=$(( tmp % 60 ))
29
+    local -a result
30
+    (( $days    > 0 )) && result=( "${days}d" )
31
+    (( $hours   > 0 )) && result=( $result "${hours}h" )
32
+    (( $minutes > 0 )) && result=( $result "${minutes}m" )
33
+    (( $seconds > 0 )) && result=( $result "${seconds}s" )
34
+    print -n "${result[1,2]}"
35
+}
36
+
37
+CURRENT_BG=NONE
38
+_vbe_prompt_segment() {
39
+  local b f
40
+  [[ -n $1 ]] && b="$bg[$1]" || b="$bg[default]"
41
+  [[ -n $2 ]] && f="$fg[$2]" || f="$fg[default]"
42
+  [[ -n $3 ]] || return
43
+  if [[ $CURRENT_BG != 'NONE' && $1 != $CURRENT_BG ]]; then
44
+      print -n " %{%b$b$fg[$CURRENT_BG]%}${PRCH[end]}%{$f%} "
45
+  elif [[ $1 == $CURRENT_BG ]]; then
46
+      print -n " %{%b$b$f%}${PRCH[sep]} "
47
+  else
48
+      print -n "%{%b$b$f%} "
49
+  fi
50
+  CURRENT_BG=$1
51
+  print -n $3
52
+}
53
+_vbe_prompt_end() {
54
+  if [[ -n $CURRENT_BG ]]; then
55
+    print -n " %{%b$fg[$CURRENT_BG]%}${PRCH[end]}"
56
+  else
57
+    print -n "%{%b%}"
58
+  fi
59
+  print -n "%{${reset_color}%}"
60
+  CURRENT_BG=''
61
+}
62
+
63
+_vbe_prompt () {
64
+    local retval=$?
65
+    local fond="ligh_blue"
66
+    # user@host
67
+    local f=${(%):-%(!.red.${${SSH_TTY:+magenta}:-green})}
68
+    _vbe_prompt_segment black $f \
69
+        %B%n%b%{${fg[cyan]}%}${${(%):-%n}:+@}%B%{${bg[black]}${fg[$f]}%}%M
70
+
71
+    # Directory
72
+    local -a segs
73
+    local len=$(($COLUMNS - ${#${(%):-%n@%M}} - 7 - ${#${${(%):-%~}//[^\/]/}} * 2))
74
+    segs=(${(s./.)${(%):-%${len}<${PRCH[ellipsis]}<%~}})
75
+    [[ ${#segs} == 0 ]] && segs=(/)
76
+    if [[ -w $PWD ]]; then
77
+      fond="cyan"
78
+    else
79
+      fond="red"
80
+    fi
81
+
82
+    for seg in ${segs[1,-2]}; do
83
+        _vbe_prompt_segment $fond black $seg
84
+    done
85
+    _vbe_prompt_segment $fond black ${segs[-1]}
86
+    _vbe_prompt_end
87
+
88
+    # New line
89
+    print
90
+    CURRENT_BG=NONE
91
+
92
+    # Additional info
93
+    _vbe_add_prompt
94
+
95
+    # Time elapsed
96
+    local now=$EPOCHSECONDS
97
+    local elapsed=$(($now - ${_vbe_cmd_timestamp:-$now}))
98
+    (($elapsed >= 5)) && \
99
+        _vbe_prompt_segment white black "$(_vbe_human_time $elapsed)"
100
+
101
+    # Error code
102
+    (( $retval )) && \
103
+        _vbe_prompt_segment red default %B${PRCH[retb]}'%?'${PRCH[reta]} || \
104
+        _vbe_prompt_segment green white %B${PRCH[ok]}
105
+
106
+    _vbe_prompt_end
107
+}
108
+
109
+# Collect additional information from functions matching _vbe_add_prompt_*
110
+_vbe_add_prompt () {
111
+    for f in ${(M)${(k)functions}:#_vbe_add_prompt_*}; do
112
+	$f
113
+    done
114
+}
115
+_vbe_prompt_ps2 () {
116
+    for seg in ${${(s. .)${1}}[1,-2]}; do
117
+        _vbe_prompt_segment cyan default $seg
118
+    done
119
+    _vbe_prompt_end
120
+}
121
+_vbe_setprompt () {
122
+    setopt prompt_subst
123
+    PROMPT='$(_vbe_prompt) '
124
+    PS2='$(_vbe_prompt_ps2 ${(%):-%_}) '
125
+    PROMPT_EOL_MARK='%B${PRCH[eol]}%b'
126
+    unset RPROMPT
127
+}

+ 85
- 0
rc/ssh.zsh View File

@@ -0,0 +1,85 @@
1
+# -*- sh -*-
2
+
3
+ssh() {
4
+    # TERM is one of the variables that is usually allowed to be
5
+    # transmitted to the remote session. The remote host should have
6
+    # the appropriate termcap or terminfo file to handle the TERM you
7
+    # provided. When connecting to random hosts, this may not be the
8
+    # case if your TERM is somewhat special. A good fallback is
9
+    # xterm. Most terminals are compatible with xterm and all hosts
10
+    # have a termcap or terminfo file to handle xterm. Therefore, for
11
+    # some values of TERM, we fallback to xterm.
12
+    #
13
+    # Now, you may connect to a host where your current TERM is fully
14
+    # supported and you will get xterm instead (which means 8 base
15
+    # colors only). There is no clean solution for this. You may want
16
+    # to reexport the appropriate TERM when logged on the remote host
17
+    # or use commands like this:
18
+    #     ssh -t XXXXX env TERM=$TERM emacsclient -t -c
19
+    #
20
+    # If the remote host uses the same zshrc than this one, there is
21
+    # something in `$ZSH/rc/00-terminfo.zsh` to restore the
22
+    # appropriate terminal (saved in `LC__ORIGINALTERM`).
23
+    #
24
+    # The problem is quite similar for LANG and LC_MESSAGES. We reset
25
+    # them to C to avoid any problem with hosts not having your
26
+    # locally installed locales. See this post for more details on
27
+    # this:
28
+    #    http://vincent.bernat.im/en/blog/2011-zsh-zshrc.html
29
+    #
30
+    # Also, when the same ZSH configuration is used on the remote
31
+    # host, the locale is reset with the help of
32
+    # `$ZSH/rc/01-locale.zsh`.
33
+    case "$TERM" in
34
+	rxvt-256color|rxvt-unicode*)
35
+	    LC__ORIGINALTERM=$TERM TERM=rxvt LANG=C LC_MESSAGES=C command ssh "$@"
36
+	    ;;
37
+	screen-256color)
38
+	    LC__ORIGINALTERM=$TERM TERM=screen LANG=C LC_MESSAGES=C command ssh "$@"
39
+	    ;;
40
+	*)
41
+	    LANG=C LC_MESSAGES=C command ssh "$@"
42
+	    ;;
43
+    esac
44
+}
45
+
46
+# The following command implements a reverse SSH connection. This is
47
+# to connect to hosts behind a firewall, which can connect to your
48
+# machine but you cannot connect directly. The idea is that they issue
49
+# a TCP connection that you will use as a tunnel to access their SSH
50
+# port.
51
+#
52
+# I am using this to connect to VM using user-mode network (QEMU, KVM,
53
+# UML, ...).
54
+rssh() {
55
+    # We should probe for a free port, but is it easy?
56
+    local port
57
+    port=$((21422 + $RANDOM % 1000))
58
+
59
+    print "On remote host, use \`socat TCP:10.0.2.2:$port TCP:127.0.0.1:22\` to allow SSH access... "
60
+    ssh -oProxyCommand="socat TCP-LISTEN:$port,bind=127.0.0.1,reuseaddr STDIO" \
61
+        "$@"
62
+}
63
+
64
+(( $+commands[tmux] )) && [[ -n $TMUX ]] && {
65
+
66
+    # Execute a command in a new pane and synchronise all panes. This
67
+    # is a replacement of cluster-ssh. Here is how to execute it:
68
+    #
69