summaryrefslogtreecommitdiffstats
path: root/.zshrc
blob: 30e8af36fd58ebc5dceaf6c1517416f4c7ccce12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# Author: Florian Pritz <bluewind@xinu.at>

# Don't show input while loading
stty -echo

ZDOTDIR="$HOME/.zsh"

export LANG=en_US.UTF-8
export TZ=Europe/Vienna

if [[ $TERM = "xterm-termite" ]]; then
	export TERM=xterm-256color
fi

# ruby gems
for _dir in $HOME/.gem/ruby/*/bin; do
	export PATH=$_dir:$PATH
done

# add extra dirs/symlinks to path. allows to separate script bundles into dirs
for _dir in $HOME/bin/extra/*(/N,@N); do
	export PATH=$_dir:$PATH
done

export PATH=$HOME/bin:$PATH
if [ $UID -eq 0 ]; then
  export PATH=/root/bin:$PATH
fi

# Exports {{{

# TODO: move these to file and load in .xinitrc?
# XDG directories
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_CACHE_HOME="$HOME/.cache"
export XDG_DATA_HOME="$HOME/.local/share"

#export MPV_HOME="$XDG_CONFIG_HOME/mpv"

# Work around pssh hanging due to multiplexer not closing stdin
export PSSH_OPTIONS='ControlPersist=no'

# }}}
# Colors {{{
#use these in functions/shell scripts
export NC='\e[0m'
export white='\e[0;30m'
export WHITE='\e[1;30m'
export red='\e[0;31m'
export RED='\e[1;31m'
export green='\e[0;32m'
export GREEN='\e[1;32m'
export yellow='\e[0;33m'
export YELLOW='\e[1;33m'
export blue='\e[0;34m'
export BLUE='\e[1;34m'
export magenta='\e[0;35m'
export MAGENTA='\e[1;35m'
export cyan='\e[0;36m'
export CYAN='\e[1;36m'
export black='\e[0;37m'
export BLACK='\e[1;37m'

# these are for use in PROMPT
p_nc=$'%{\e[0m%}'
p_white=$'%{\e[0;30m%}'
p_WHITE=$'%{\e[1;30m%}'
p_red=$'%{\e[0;31m%}'
p_RED=$'%{\e[1;31m%}'
p_green=$'%{\e[0;32m%}'
p_GREEN=$'%{\e[1;32m%}'
p_yellow=$'%{\e[0;33m%}'
p_YELLOW=$'%{\e[1;33m%}'
p_blue=$'%{\e[0;34m%}'
p_BLUE=$'%{\e[1;34m%}'
p_magenta=$'%{\e[0;35m%}'
p_MAGENTA=$'%{\e[1;35m%}'
p_cyan=$'%{\e[0;36m%}'
p_CYAN=$'%{\e[1;36m%}' 
p_black=$'%{\e[0;37m%}'
p_white=$'%{\e[1;37m%}'

# colors in framebuffer!
if [[ $TERM = "linux" ]]; then
  ${HOME}/bin/parse_xdefaults.sh  
  clear #for background artifacting
fi

# some better colors for ls
eval "`dircolors ~/.dircolors`"

# }}}
# Keybindings {{{
bindkey -e
bindkey '\e[1~' beginning-of-line
bindkey '\e[4~' end-of-line
bindkey '\e[3~' delete-char
bindkey '\e[2~' overwrite-mode
bindkey "^[[7~" beginning-of-line # Pos1
bindkey "^[[8~" end-of-line # End
bindkey "${terminfo[khome]}" beginning-of-line
bindkey "${terminfo[kend]}" end-of-line
bindkey '\e[H' beginning-of-line
bindkey '\e[F' end-of-line
bindkey "^[[A" history-beginning-search-backward
bindkey "^[[B" history-beginning-search-forward

# HOWTO make your own:
# bindkey '<crtl+v key>' action
# for some actions run `bindkey`

# "cd......" ;)
_rationalise-dot() {
  if [[ $LBUFFER = "cd "* ]]; then
    if [[ $LBUFFER = *.. ]]; then
      LBUFFER+=/..
    else
      LBUFFER+=.
    fi
  else
    LBUFFER+=.
  fi
}
zle -N _rationalise-dot
bindkey . _rationalise-dot

# add edit command line feature ("alt-e")
autoload edit-command-line
zle -N edit-command-line
bindkey '\ee' edit-command-line

# source: http://github.com/xfire/dotfiles/blob/master/.zsh/abbrev_expansion
# power completion / abbreviation expansion / buffer expansion
# see http://zshwiki.org/home/examples/zleiab for details
# less risky than the global aliases but powerful as well
# just type the abbreviation key and afterwards ',' to expand it
typeset -Ag abbreviations
abbreviations=(
#    'M'         '| most'
    'dn'        '&>/dev/null '
    'dn1'       '1>/dev/null '
    'dn2'       '2>/dev/null '
#    'NULL'      '>/dev/null 2>&1'
    '21'        '2>&1 '
    'l'         '| less'
    'll'        '|& less'
    'g'         '| grep '
    'gi'        '| grep -i '
    'eg'        '| egrep '
    'h'         '| head '
    'hh'        '|& head '
    't'         '| tail '
    'tt'        '|& tail '
    'wc'        '| wc'
#    'wcb'       '| wc -c'
#    'wcc'       '| wc -m'
#    'wcw'       '| wc -w'
    'wcl'       '| wc -l'
    's'         '| sort'
    'su'        '| sort -u'
    'sl'        '| sort | less'
    'a'         '| awk '
#    'A1'        "| awk '{print \$1}'"
#    'A2'        "| awk '{print \$2}'"
#    'A3'        "| awk '{print \$3}'"
#    'A4'        "| awk '{print \$4}'"
#    'A5'        "| awk '{print \$5}'"
#    'A6'        "| awk '{print \$6}'"
#    'A7'        "| awk '{print \$7}'"
#    'A8'        "| awk '{print \$8}'"
#    'A9'        "| awk '{print \$9}'"
#    'CA'        "|& cat -A"
    'v'         '|& vim -'
    'x'         '| xargs'
    'xx'        '|& xargs'
    'hide'      "echo -en '\033]50;nil2\007'"
    'tiny'      'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-80-*-*-c-*-iso8859-15\007"'
    'small'     'echo -en "\033]50;6x10\007"'
    'medium'    'echo -en "\033]50;-misc-fixed-medium-r-normal--13-120-75-75-c-80-iso8859-15\007"'
    'default'   'echo -e "\033]50;-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-15\007"'
    'large'     'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-150-*-*-c-*-iso8859-15\007"'
    'huge'      'echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-210-*-*-c-*-iso8859-15\007"'
    'smartfont' 'echo -en "\033]50;-artwiz-smoothansi-*-*-*-*-*-*-*-*-*-*-*-*\007"'
    'semifont'  'echo -en "\033]50;-misc-fixed-medium-r-semicondensed-*-*-120-*-*-*-*-iso8859-15\007"'
    'da'        'du -sch '
    'j'         'jobs -l '
    'co'        "./configure && make && sudo make install"
    'ch'        "./configure --help"
    'rw-'       'chmod 600 '
    '600'       'chmod u+rw-x,g-rwx,o-rwx '
    'rwx'       'chmod u+rwx '
    '700'       'chmod u+rwx,g-rwx,o-rwx '
    'r--'       'chmod u+r-wx,g-rwx,o-rwx '
    '644'       'chmod u+rw-x,g+r-wx,o+r-wx\n # 4=r,2=w,1=x '
    '755'       'chmod u+rwx,g+r-w+x,o+r-w+x '
    'cx'        'chmod +x '
    'de'        'export DISPLAY=:0.0'
    'd'         'DISPLAY=:0.0'
)

globalias() {
    local MATCH
    LBUFFER=${LBUFFER%%(#m)[_a-zA-Z0-9]#}
    LBUFFER+=${abbreviations[$MATCH]:-$MATCH,,}
}

zle -N globalias
bindkey ",," globalias

# Source: https://github.com/junegunn/fzf/blob/master/shell/key-bindings.zsh
__fzf_use_tmux__() {
  [ -n "$TMUX_PANE" ] && [ "${FZF_TMUX:-0}" != 0 ] && [ ${LINES:-40} -gt 15 ]
}

__fzfcmd() {
  __fzf_use_tmux__ &&
    echo "fzf-tmux -d${FZF_TMUX_HEIGHT:-95%}" || echo "fzf"
}

# CTRL-R - Paste the selected command from history into the command line
# Changed to work with my personal history fetcher
fzf-history-widget() {
  local selected num
  setopt localoptions noglobsubst noposixbuiltins pipefail 2> /dev/null
  selected=( $(cat-history-notime |
    FZF_DEFAULT_OPTS="--height ${FZF_TMUX_HEIGHT:-95%} $FZF_DEFAULT_OPTS --tiebreak=index --bind=ctrl-r:toggle-sort $FZF_CTRL_R_OPTS --query=${(qqq)LBUFFER} +m" $(__fzfcmd)) )
  local ret=$?
  if [ -n "$selected" ]; then
	zle kill-buffer
	BUFFER="$selected"
  fi
  zle redisplay
  typeset -f zle-line-init >/dev/null && zle zle-line-init
  return $ret
}
zle     -N   fzf-history-widget
bindkey '^R' fzf-history-widget


# }}}
# Variables {{{
#export CDPATH=.:$HOME
export OOO_FORCE_DESKTOP=gnome
export EDITOR=vim
export VISUAL=$EDITOR
export PAGER=less
#if type vimpager &>/dev/null; then
	#export MANPAGER=vimpager
#fi
export MANWIDTH=80
export PERLDOC_PAGER=less
export PERLDOC="-MPod::Text::Color::Delight"
export LESSCHARSET="UTF-8"
export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
export LESS='-j10 -i -n -w -M -R -P%t?f%f \
:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'

# Less Colors for Man Pages
export LESS_TERMCAP_mb=$'\E[01;31m'       # begin blinking
export LESS_TERMCAP_md=$'\E[01;38;5;74m'  # begin bold
export LESS_TERMCAP_me=$'\E[0m'           # end mode
export LESS_TERMCAP_se=$'\E[0m'           # end standout-mode
export LESS_TERMCAP_so=$'\E[38;5;11m'    # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\E[0m'           # end underline
export LESS_TERMCAP_us=$'\E[04;38;5;146m' # begin underline

# }}}
# Terminal title {{{
# also found somewhere
prompt_eof_setup() {
  # preexec() is run after you press enter on your command but before the command is run.
  preexec() {
    # define screen/terminal title with the current command (http://aperiodic.net/phil/prompt/)
    case $TERM in
      rxvt-*)
        printf '\33]2;%s\007' $1
      ;;
      screen*)
        local CMD=${1[(wr)^(*=*|sudo|ssh|exec|-*)]}
        printf '\ek%s\e\\' $CMD;;
    esac
  }
}

prompt_eof_setup "$@"
# }}}
# Prompt {{{

# necessary if you want to use functions in the prompt
# without this they wouldn't be run again
#precmd () {
# this has to be on the edge or you have some spaces in the prompt
# if you have any workaround please tell
if [[ $UID != 0 ]]; then
  local username_color=$p_blue
else
  local username_color=$p_red
fi
local host_color=$p_GREEN
local path_color=$p_BLUE
PROMPT="${username_color}$USERNAME${p_nc}@${host_color}%m${p_nc} ${path_color}%~${p_nc} > "
#}

## Spelling prompt
SPROMPT='zsh: correct '%R' to '%r' ? ([Y]es/[N]o/[E]dit/[A]bort) '

# }}}
# Functions {{{ 

function cd () {
    if (( ${#argv} == 1 )) && [[ -f ${1} ]]; then
        [[ ! -e ${1:h} ]] && return 1
        print "Correcting ${1} to ${1:h}"
        builtin cd ${1:h}
    else
        builtin cd "$@"
    fi
}

sv() {
	vim "sudo:$1"
}

# add current time to a file
mbk() {
	mv -b "${1}" "$(echo $1 | sed -r "s/(.*)(\.|$)(.*)/\1_`date +%Y-%m-%d_%H%M%S`\2\3/")"
}

# easily make backups
bk() {
	rsync -phaxPHAX "${1}" "$(echo $1 | sed -r "s/(.*)(\.|$)(.*)/\1_`date +%Y-%m-%d_%H%M%S`\2\3/")"
}

# chpwd () => a function which is executed whenever the directory is changed
chpwd() {
  ls
}

# idea by Gigamo http://bbs.archlinux.org/viewtopic.php?pid=478094#p478094
ls () {
  /bin/ls -rhbtF --color=auto "$@" #&&
  #echo "${MAGENTA}Files: ${BLUE}$(/bin/ls -l $@ | grep -v "^[l|d|total]" | wc -l) ${GREEN}--- ${MAGENTA}Directories: ${BLUE}$(/bin/ls -l $@ | grep "^d" | wc -l)${NC}"
}

password() {
  if [[ -z $1 ]]; then
    count=8
  else
    count="$1"
  fi
  echo $(< /dev/urandom tr -dc A-Za-z0-9 | head -c$count)
}

# from the grml zshrc iirc
hglob() {
  echo -e "
      /      directories
      .      plain files
      @      symbolic links
      =      sockets
      p      named pipes (FIFOs)
      *      executable plain files (0100)
      %      device files (character or block special)
      %b     block special files
      %c     character special files
      r      owner-readable files (0400)
      w      owner-writable files (0200)
      x      owner-executable files (0100)
      A      group-readable files (0040)
      I      group-writable files (0020)
      E      group-executable files (0010)
      R      world-readable files (0004)
      W      world-writable files (0002)
      X      world-executable files (0001)
      s      setuid files (04000)
      S      setgid files (02000)
      t      files with the sticky bit (01000)
   print *(m-1)          # Dateien, die vor bis zu einem Tag modifiziert wurden.
   print *(a1)           # Dateien, auf die vor einem Tag zugegriffen wurde.
   print *(@)            # Nur Links
   print *(Lk+50)        # Dateien die ueber 50 Kilobytes grosz sind
   print *(Lk-50)        # Dateien die kleiner als 50 Kilobytes sind
   print **/*.c          # Alle *.c - Dateien unterhalb von \$PWD
   print **/*.c~file.c   # Alle *.c - Dateien, aber nicht 'file.c'
   print (foo|bar).*     # Alle Dateien mit 'foo' und / oder 'bar' am Anfang
   print *~*.*           # Nur Dateien ohne '.' in Namen
   chmod 644 *(.^x)      # make all non-executable files publically readable
   print -l *(.c|.h)     # Nur Dateien mit dem Suffix '.c' und / oder '.h'
   print **/*(g:users:)  # Alle Dateien/Verzeichnisse der Gruppe >users<
   echo /proc/*/cwd(:h:t:s/self//) # Analog zu >ps ax | awk '{print $1}'<"
}

# swaps 2 files
swap() {
  if [[ -z $1 ]] || [[ -z $2 ]] || [[ $1 = "-h" ]]; then
    echo -e "${blue}Usage:$NC swap <file> <file>";
    echo -e "Swaps files";
    return 1
  fi
  if [[ -f $1 ]] && [[ -f $2 ]]; then
    local TMPFILE=tmp.$$
    mv "$1" $TMPFILE
    mv "$2" "$1"
    mv $TMPFILE "$2"
  else
    echo -e "${RED}Error:$NC One or more files don't exist"
    return 1  
  fi
}

cget() {
	curl -fJOL --compressed "$@"
}

cat-history() {
	local histfiles=($(ls -t1 "$HISTORYDIRECTORY"/*))
	cat "${histfiles[@]}"
}

cat-history-notime() {
	cat-history "$@" | sed 's/^: [0-9]\+:0;//'
}

hgrep() {
	cat-history | mpgrep "$@" | less
}

cd-pkg() {
	local targets=(~/arch/{community,extra})
	local pkg=$1
	for target in "${targets[@]}"; do
		if [[ -f "$target/$pkg/trunk/PKGBUILD" ]]; then
			cd "$target/$pkg"
			svn up
			cd trunk
		fi
	done
}

# }}}
# History {{{
HISTORYDIRECTORY=~/.zsh/history
HISTFILE="$HISTORYDIRECTORY/histfile"
HISTSIZE=10000
SAVEHIST=10000000
# }}}
# Other ZSH options {{{
autoload -U colors
colors

autoload -U zmv

# .. -> cd ../
setopt autocd

# cd /etc/**/foo/blub searches ;)
setopt extendedglob

# push cds to directory stack
setopt auto_pushd

# don't push something twice
setopt pushd_ignore_dups

# don't kill jobs when exiting shell 
setopt no_hup
# and don't warn
setopt no_check_jobs

# show us when some command didn't exit with 0
setopt print_exit_value

# makepkg -g > PKGBUILD 
# zsh: file exists: PKGBUILD
#
# work saved ;)
setopt no_clobber

setopt inc_append_history
setopt no_bg_nice
setopt share_history
#setopt bang_hist
setopt extended_history
#setopt hist_reduce_blanks
setopt hist_ignore_space
setopt hist_find_no_dups
setopt hist_ignore_dups
setopt nohistverify
setopt prompt_subst
#setopt hist_fcntl_lock
setopt always_to_end

unsetopt auto_remove_slash

# show the output of time if commands takes longer than n secs (only user+system)
REPORTTIME=5

# allow comments in interactive shells
setopt interactivecomments

# ignore lines starting with a space
setopt hist_ignore_space

# disable XON/XOFF flow control (^s/^q)
stty -ixon

# }}}
# Aliases {{{
# better ask before we lose data
alias rm='rm -Iv'
alias cp='cp -iv'
alias mv='mv -iv'

# I don't like bytes
alias dum='du -kh --max-depth=2'
alias dus='du -skh'
alias du='du -kh'
alias df="df -Th"

# function to make ls look nice is below
alias ll='ls -l'
alias la='ls -a'
alias lla='ls -la'
alias lld='ls -ld'

# well I got used to that name ;)
alias aurball='mkaurball -f'

#alias sudo="sudo "    #Sudo wont recognize aliases without this
alias s='sudo '
alias mtr='mtr -t'
alias wcl='wc -l'
alias mdstat='cat /proc/mdstat'
alias keymap='setxkbmap de -variant nodeadkeys'
alias hexdump='hexdump -C'
alias grep='grep --color'
alias dmesg='dmesg -T'

alias vp='PAGER=vimpager'
if type nvim &>/dev/null && [[ -e "${XDG_CONFIG_HOME:-$HOME/.config}/nvim/init.vim" ]] ; then
	alias v='nvim'
elif type vim &>/dev/null; then
	alias v='vim'
fi
alias l='less'
alias rf='readlink -f'

alias sc='screen'
alias scw='screen -X eval "chdir $PWD"'

alias g='git'
alias tiga='tig --all'
alias xc="xclip"
alias xcp="xclip -o | fb"
alias xcpe="xclip -o | vipe | ifne fb"

alias nsl='nslookup'

alias rscp='rsync --partial --progress'
alias scp='scp -o ControlPath=none'

alias mkdir='nocorrect mkdir'
alias wget='nocorrect noglob wget'

alias p='pacman'
alias sd='systemctl --no-pager'
alias b='busybox'

alias su='su -'

# too long to remember
alias asciidoc_full='asciidoc -a icons -a toc -a linkcss -a quirks!'
alias nossh='ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
alias noscp='scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'
alias sshpw="ssh -S none -o PubkeyAuthentication=no"
alias nosshpw="ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -S none -o PubkeyAuthentication=no"
alias ssh-copy-id="ssh-copy-id -o ControlPath=none"
alias nosshfs='sshfs -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'

alias callgrind='valgrind --tool=callgrind'
alias vgfull='valgrind --leak-check=full --show-reachable=yes'

alias is="iostat -Nyxm 2"

alias md='mysqldump --quick --create-options --disable-keys --add-locks --add-drop-table --lock-tables --complete-insert --skip-extended-insert'

# other random aliases
alias ☠='pkill -9'
alias nocomment='egrep -v "^\s*(#|$)"'
alias wgetc="wget --content-disposition"

# global aliases work EVERYWHERE
# e.g. dmesg eg foo
# show last 50 lines of dmesg
alias -g eg='| egrep --color'

# }}}
# Completion stuff {{{
autoload -Uz compinit
compinit

unsetopt correct_all

# correct 7etc/foo to /etc/foo
# if anyone has a working solution for /etc7foo please contact me
function _7slash {
   if [[ $words[CURRENT] = 7(#b)(*)(#e) ]]
   then
     compadd -U -X 'Correct leading 7 to /' -f /$match[1]
   fi
}

zstyle :compinstall filename '$HOME/.zshrc'

# performance tweaks
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path $HOME/.zsh/cache
zstyle ':completion:*' use-perl on

# completion colours
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}

zstyle ':completion:*' completer _complete _match _approximate _7slash 
zstyle ':completion:*:match:*' original only

# allow more mistypes if longer command
#zstyle -e ':completion:*:approximate:*' \
#        max-errors 'reply=($((($#PREFIX+$#SUFFIX)/3))numeric)'

# ignore completion for commands we don't have
zstyle ':completion:*:functions' ignored-patterns '_*'

# get rid of .class and .o files for vim
zstyle ':completion:*:vim:*' ignored-patterns '*.(class|o)'

# show menu when tabbing
zstyle ':completion:*' menu yes select

# better completion for kill
zstyle ':completion:*:*:kill:*' command 'ps --forest -u$USER -o pid,%cpu,tty,cputime,cmd'

# Provide more processes in completion of programs like killall:
zstyle ':completion:*:processes-names' command 'ps c -u ${USER} -o command | uniq'
compdef pkill=killall

# bugged with zsh 4.3.10 for whatever reason
zstyle ':completion:*' file-sort time
#zstyle ':completion:*' file-sort name

# Ignore same file on rm
zstyle ':completion:*:(rm|kill|diff):*' ignore-line yes
zstyle ':completion:*:rm:*' file-patterns '*:all-files'

zstyle ':completion:*:wine:*' file-patterns '*.(exe|EXE):exe'

# don't complete usernames (the come from localhost!)
zstyle ':completion:*:(ssh|scp):*' users

# complete ssh hostnames
[[ -r ~/.ssh/known_hosts ]] && _ssh_hosts=(${${${${${${${(f)"$(<$HOME/.ssh/known_hosts)"}:#[\|]*}%%\ *}%%,*}%%:*}#\[}%\]}) || _ssh_hosts=()
[[ -r ~/.ssh/config ]] && _ssh_config_hosts=($(sed -rn 's/host\s+(.+)/\1/ip' "$HOME/.ssh/config" | grep -v "\*" )) || _ssh_config_hosts=()
hosts=(
        $HOST
        "$_ssh_hosts[@]"
        $_ssh_config_hosts[@]
        localhost
    )
zstyle ':completion:*:hosts' hosts $hosts

# automagic url quoter
autoload -U url-quote-magic
zle -N self-insert url-quote-magic

# e.g. ls foo//bar -> ls foo/bar
zstyle ':completion:*' squeeze-slashes true

# if in foo/bar don't show bar when cd ../<TAB>
zstyle ':completion:*:cd:*' ignore-parents parent pwd

# Prevent lost+found directory from being completed
zstyle ':completion:*:cd:*' ignored-patterns '(*/)#lost+found'

# ignore case when completing
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|[._-]=* r:|=*' 'l:|=* r:|=*'

# make some stuff look better
# from: http://ft.bewatermyfriend.org/comp/zsh/zshrc.d/compsys.html
zstyle ':completion:*:descriptions' format "- %{${fg[yellow]}%}%d%{${reset_color}%} -"
zstyle ':completion:*:messages'     format "- %{${fg[cyan]}%}%d%{${reset_color}%} -"
zstyle ':completion:*:corrections'  format "- %{${fg[yellow]}%}%d%{${reset_color}%} - (%{${fg[cyan]}%}errors %e%{${reset_color}%})"
zstyle ':completion:*:default'      \
	select-prompt \
	"%{${fg[yellow]}%}Match %{${fg_bold[cyan]}%}%m%{${fg_no_bold[yellow]}%}  Line %{${fg_bold[cyan]}%}%l%{${fg_no_bold[red]}%}  %p%{${reset_color}%}"
zstyle ':completion:*:default'      \
	list-prompt   \
	"%{${fg[yellow]}%}Line %{${fg_bold[cyan]}%}%l%{${fg_no_bold[yellow]}%}  Continue?%{${reset_color}%}"
zstyle ':completion:*:warnings'     \
	format        \
	"- %{${fg_no_bold[red]}%}no match%{${reset_color}%} - %{${fg_no_bold[yellow]}%}%d%{${reset_color}%}"
zstyle ':completion:*' group-name ''

# manual pages are sorted into sections
# from: http://ft.bewatermyfriend.org/comp/zsh/zshrc.d/compsys.html
zstyle ':completion:*:manuals'       separate-sections true
zstyle ':completion:*:manuals.(^1*)' insert-sections   true

### highlight the original input.
    zstyle ':completion:*:original' \
        list-colors "=*=$color[red];$color[bold]"

### highlight words like 'esac' or 'end'
    zstyle ':completion:*:reserved-words' \
        list-colors "=*=$color[red]"

### colorize hostname completion
    zstyle ':completion:*:*:*:*:hosts' \
        list-colors "=*=$color[cyan];$color[bg-black]"

### colorize username completion
    zstyle ':completion:*:*:*:*:users' \
        list-colors "=*=$color[red];$color[bg-black]"

### colorize processlist for 'kill'
    zstyle ':completion:*:*:kill:*:processes' \
        list-colors "=(#b) #([0-9]#) #([^ ]#)*=$color[none]=$color[yellow]=$color[green]"

# complete my little rc function (archlinux startscripts)
function _rc () { 
  case $CURRENT in
    2) compadd $(find /etc/rc.d/ -maxdepth 1 -type f -executable -printf '%f ');;
    3) compadd $(/etc/rc.d/$words[2] 2> /dev/null | grep -i usage | sed 's/.*{\(.*\)}/\1/; s/|/ /g');;
  esac
}
compdef _rc rc

# easier way to use sshfs ;)
function _ssh-mount () { 
  compadd $(cat ${HOME}/bin/ssh-mount.sh | egrep "Servers:.*" | sed "s#echo \-e \"\${green}Servers\:\$NC##g; s#\"\;##g; s#,##g") 
}
compdef _ssh-mount ssh-mount.sh

function _wake () {
  compadd $(wake)
}
compdef _wake wake

# }}}
# Greetings {{{
#sysinfo
# }}}
# {{{ Other stuff that doesn't fit anywhere else
umask 077
stty -ctlecho

# machine dependent stuff
source $HOME/.zshrc.local

if [[ -e $HOME/git/dotfiles/.zsh/zsh-syntax-highlighting-git/zsh-syntax-highlighting.zsh ]]; then
	source $HOME/git/dotfiles/.zsh/zsh-syntax-highlighting-git/zsh-syntax-highlighting.zsh
fi

#export SSH_AUTH_SOCK=$XDG_RUNTIME_DIR/gnupg/S.gpg-agent.ssh
export SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/keyring/ssh"

if [[ -e ~/perl5 ]]; then
	eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)
fi

#if type keychain >/dev/null; then
	#eval $(keychain --eval -q)
#fi

# }}}

# Show again
stty echo

# vim: set ft=zsh: