zshrc: Fixing a bug in urlencode()
[grml-etc-core.git] / etc / skel / .zshrc
1 # Filename:      .zshrc
2 # Purpose:       config file for zsh
3 # Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
4 # Bug-Reports:   see http://grml.org/bugs/
5 # License:       This file is licensed under the GPL v2.
6 ################################################################################
7
8 # source ~/.zshrc.global {{{
9
10 # see /etc/zsh/zshrc for some general settings
11 # If you don't have write permissions to /etc/zsh/zshrc on your own
12 # copy the file to your $HOME as /.zshrc.global and we source it:
13
14 # Note, that xsource() is defined in the global file, so here,
15 # we will have to do the sourcing manually for once:
16
17 [[ -z "$ZSHRC_GLOBAL_HAS_BEEN_READ" ]]  \
18 && [[ -r "${HOME}/.zshrc.global" ]]     \
19 && source "${HOME}/.zshrc.global"
20 # }}}
21
22 # check whether global file has been read {{{
23 if [[ -z "$ZSHRC_GLOBAL_HAS_BEEN_READ" ]] ; then
24     print 'Warning: global zsh config has not been read.' >&2
25     print '         prepare for possible errors!'         >&2
26     print '' >&2
27     print 'See our refcard for info on how to get the complete configuration:' >&2
28     print '    <http://grml.org/zsh/grml-zsh-refcard.pdf>' >&2
29 fi
30 # }}}
31
32 # autoloading stuff {{{
33 # associate types and extensions (be aware with perl scripts and anwanted behaviour!)
34 #  check_com zsh-mime-setup || { autoload zsh-mime-setup && zsh-mime-setup }
35 #  alias -s pl='perl -S'
36 # }}}
37
38 # completion system {{{
39 # just make sure it is loaded in this file too
40 # TODO: is this *really* needed? compsys should be run in the global zshrc already.
41 check_com compinit || { autoload -U compinit && compinit }
42 # }}}
43
44 # make sure isgrmlsmall is defined {{{
45 check_com isgrmlsmall || function isgrmlsmall () { return 1 }
46 # }}}
47
48 # variables {{{
49
50 # do you want grmlsmall-specific adjustments?
51 GRMLSMALL_SPECIFIC=1
52
53 # set terminal property (used e.g. by msgid-chooser)
54 export COLORTERM="yes"
55
56 # set default browser
57 if [[ -z "$BROWSER" ]] ; then
58     if [[ -n "$DISPLAY" ]] ; then
59         #v# If X11 is running
60         check_com -c firefox && export BROWSER=firefox
61     else
62         #v# If no X11 is running
63         check_com -c w3m && export BROWSER=w3m
64     fi
65 fi
66
67 #m# v QTDIR \kbd{/usr/share/qt[34]}\quad [for non-root only]
68 [[ -d /usr/share/qt3 ]] && export QTDIR=/usr/share/qt3
69 [[ -d /usr/share/qt4 ]] && export QTDIR=/usr/share/qt4
70
71 # support running 'jikes *.java && jamvm HelloWorld' OOTB:
72 #v# [for non-root only]
73 [[ -f /usr/share/classpath/glibj.zip ]] && export JIKESPATH=/usr/share/classpath/glibj.zip
74 # }}}
75
76 # set options {{{
77
78 # Allow comments even in interactive shells i. e.
79 # $ uname # This command prints system informations
80 # zsh: bad pattern: #
81 # $ setopt interactivecomments
82 # $ uname # This command prints system informations
83 # Linux
84 #  setopt interactivecomments
85
86 # ctrl-s will no longer freeze the terminal.
87 #  stty erase "^?"
88
89 # }}}
90
91 # {{{ global aliases
92 # These do not have to be at the beginning of the command line.
93 # Avoid typing cd ../../ for going two dirs down and so on
94 # Usage, e.g.: "$ cd ...' or just '$ ...' with 'setopt auto_cd'
95 # Notice: deactivated by 061112 by default, we use another approach
96 # known as "power completion / abbreviation expansion"
97 #  alias -g '...'='../..'
98 #  alias -g '....'='../../..'
99 #  alias -g BG='& exit'
100 #  alias -g C='|wc -l'
101 #  alias -g G='|grep'
102 #  alias -g H='|head'
103 #  alias -g Hl=' --help |& less -r'
104 #  alias -g K='|keep'
105 #  alias -g L='|less'
106 #  alias -g LL='|& less -r'
107 #  alias -g M='|most'
108 #  alias -g N='&>/dev/null'
109 #  alias -g R='| tr A-z N-za-m'
110 #  alias -g SL='| sort | less'
111 #  alias -g S='| sort'
112 #  alias -g T='|tail'
113 #  alias -g V='| vim -'
114 # }}}
115
116 # aliases {{{
117
118 # Xterm resizing-fu.
119 # Based on http://svn.kitenet.net/trunk/home-full/.zshrc?rev=11710&view=log (by Joey Hess)
120 alias hide='echo -en "\033]50;nil2\007"'
121 alias tiny='echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-80-*-*-c-*-iso8859-15\007"'
122 alias small='echo -en "\033]50;6x10\007"'
123 alias medium='echo -en "\033]50;-misc-fixed-medium-r-normal--13-120-75-75-c-80-iso8859-15\007"'
124 alias default='echo -e "\033]50;-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-15\007"'
125 alias large='echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-150-*-*-c-*-iso8859-15\007"'
126 alias huge='echo -en "\033]50;-misc-fixed-medium-r-normal-*-*-210-*-*-c-*-iso8859-15\007"'
127 alias smartfont='echo -en "\033]50;-artwiz-smoothansi-*-*-*-*-*-*-*-*-*-*-*-*\007"'
128 alias semifont='echo -en "\033]50;-misc-fixed-medium-r-semicondensed-*-*-120-*-*-*-*-iso8859-15\007"'
129 #  if [[ "$TERM" == "xterm" ]] && [[ "$LINES" -ge 50 ]] && [[ "$COLUMNS" -ge 100 ]] && [[ -z "$SSH_CONNECTION" ]] ; then
130 #          large
131 #  fi
132
133 # general
134 #a2# Execute \kbd{du -sch}
135 alias da='du -sch'
136 #a2# Execute \kbd{jobs -l}
137 alias j='jobs -l'
138 #  alias u='translate -i'          # translate
139
140 # compile stuff
141 #a2# Execute \kbd{./configure}
142 alias CO="./configure"
143 #a2# Execute \kbd{./configure --help}
144 alias CH="./configure --help"
145
146 # http://conkeror.mozdev.org/
147 #a2# Run a keyboard driven firefox
148 alias conkeror='firefox -chrome chrome://conkeror/content'
149
150 # arch/tla stuff
151 if check_com -c tla ; then
152     #a2# Execute \kbd{tla what-changed --diffs | less}
153     alias tdi='tla what-changed --diffs | less'
154     #a2# Execute \kbd{tla-buildpackage}
155     alias tbp='tla-buildpackage'
156     #a2# Execute \kbd{tla archive-mirror}
157     alias tmi='tla archive-mirror'
158     #a2# Execute \kbd{tla commit}
159     alias tco='tla commit'
160     #a2# Execute \kbd{tla star-merge}
161     alias tme='tla star-merge'
162 fi
163
164 # listing stuff
165 #a2# Execute \kbd{ls -lSrah}
166 alias dir="ls -lSrah"
167 #a2# Only show dot-directories
168 alias lad='ls -d .*(/)'                # only show dot-directories
169 #a2# Only show dot-files
170 alias lsa='ls -a .*(.)'                # only show dot-files
171 #a2# Only files with setgid/setuid/sticky flag
172 alias lss='ls -l *(s,S,t)'             # only files with setgid/setuid/sticky flag
173 #a2# Only show 1st ten symlinks
174 alias lsl='ls -l *(@[1,10])'           # only symlinks
175 #a2# Display only executables
176 alias lsx='ls -l *(*[1,10])'           # only executables
177 #a2# Display world-{readable,writable,executable} files
178 alias lsw='ls -ld *(R,W,X.^ND/)'       # world-{readable,writable,executable} files
179 #a2# Display the ten biggest files
180 alias lsbig="ls -flh *(.OL[1,10])"     # display the biggest files
181 #a2# Only show directories
182 alias lsd='ls -d *(/)'                 # only show directories
183 #a2# Only show empty directories
184 alias lse='ls -d *(/^F)'               # only show empty directories
185 #a2# Display the ten newest files
186 alias lsnew="ls -rl *(D.om[1,10])"     # display the newest files
187 #a2# Display the ten oldest files
188 alias lsold="ls -rtlh *(D.om[1,10])"   # display the oldest files
189 #a2# Display the ten smallest files
190 alias lssmall="ls -Srl *(.oL[1,10])"   # display the smallest files
191
192 # chmod
193 #a2# Execute \kbd{chmod 600}
194 alias rw-='chmod 600'
195 #a2# Execute \kbd{chmod 700}
196 alias rwx='chmod 700'
197 #m# a2 r-{}- Execute \kbd{chmod 644}
198 alias r--='chmod 644'
199 #a2# Execute \kbd{chmod 755}
200 alias r-x='chmod 755'
201
202 # some useful aliases
203 #a2# Execute \kbd{mkdir -o}
204 alias md='mkdir -p'
205
206 check_com -c ipython && alias ips='ipython -p sh'
207
208 # console stuff
209 #a2# Execute \kbd{mplayer -vo fbdev}
210 alias cmplayer='mplayer -vo fbdev'
211 #a2# Execute \kbd{mplayer -vo fbdev -fs -zoom}
212 alias fbmplayer='mplayer -vo fbdev -fs -zoom'
213 #a2# Execute \kbd{links2 -driver fb}
214 alias fblinks='links2 -driver fb'
215
216 # ignore ~/.ssh/known_hosts entries
217 #  alias insecssh='ssh -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "PreferredAuthentications=keyboard-interactive"'
218 #a2# ssh with StrictHostKeyChecking=no \\&\quad and UserKnownHostsFile unset
219 alias insecssh='ssh -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null"'
220 alias insecscp='scp -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null"'
221
222 # simple webserver
223 check_com -c python && alias http="python -m SimpleHTTPServer"
224
225 # Use 'g' instead of 'git':
226 check_com g || alias g='git'
227
228 # use colors when browsing man pages, but only if not using LESS_TERMCAP_* from /etc/zsh/zshenv:
229 if [[ -z "$LESS_TERMCAP_md" ]] ; then
230     [[ -d ~/.terminfo/ ]] && alias man='TERMINFO=~/.terminfo/ LESS=C TERM=mostlike PAGER=less man'
231 fi
232
233 # check whether Debian's package management (dpkg) is running
234 if check_com salias ; then
235     #a2# Check whether a dpkg instance is currently running
236     salias check_dpkg_running="dpkg_running"
237 fi
238
239 # work around non utf8 capable software in utf environment via $LANG and luit
240 if check_com isutfenv && check_com luit ; then
241     if check_com -c mrxvt ; then
242         isutfenv && [[ -n "$LANG" ]] && \
243             alias mrxvt="LANG=${LANG/(#b)(*)[.@]*/$match[1].iso885915} luit mrxvt"
244     fi
245
246     if check_com -c aterm ; then
247         isutfenv && [[ -n "$LANG" ]] && \
248             alias aterm="LANG=${LANG/(#b)(*)[.@]*/$match[1].iso885915} luit aterm"
249     fi
250
251     if check_com -c centericq ; then
252         isutfenv && [[ -n "$LANG" ]] && \
253             alias centericq="LANG=${LANG/(#b)(*)[.@]*/$match[1].iso885915} luit centericq"
254     fi
255 fi
256 # }}}
257
258 # useful functions {{{
259
260 # searching
261 #f4# Search for newspostings from authors
262 agoogle() { ${=BROWSER} "http://groups.google.com/groups?as_uauthors=$*" ; }
263 #f4# Search Debian Bug Tracking System
264 debbug()  {
265     setopt localoptions extendedglob
266     if [[ $# -eq 1 ]]; then
267         case "$1" in
268             ([0-9]##)
269             ${=BROWSER} "http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=$1"
270             ;;
271             (*@*)
272             ${=BROWSER} "http://bugs.debian.org/cgi-bin/pkgreport.cgi?submitter=$1"
273             ;;
274             (*)
275             ${=BROWSER} "http://bugs.debian.org/$*"
276             ;;
277         esac
278     else
279         print "$0 needs one argument"
280         return 1
281     fi
282 }
283 #f4# Search Debian Bug Tracking System in mbox format
284 debbugm() { bts show --mbox $1 } # provide bugnummer as "$1"
285 #f4# Search DMOZ
286 dmoz()    { ${=BROWSER} http://search.dmoz.org/cgi-bin/search\?search=${1// /_} }
287 #f4# Search German   Wiktionary
288 dwicti()  { ${=BROWSER} http://de.wiktionary.org/wiki/${(C)1// /_} }
289 #f4# Search English  Wiktionary
290 ewicti()  { ${=BROWSER} http://en.wiktionary.org/wiki/${(C)1// /_} }
291 #f4# Search Google Groups
292 ggogle()  { ${=BROWSER} "http://groups.google.com/groups?q=$*" }
293 #f4# Search Google
294 google()  { ${=BROWSER} "http://www.google.com/search?&num=100&q=$*" }
295 #f4# Search Google Groups for MsgID
296 mggogle() { ${=BROWSER} "http://groups.google.com/groups?selm=$*" }
297 #f4# Search Netcraft
298 netcraft(){ ${=BROWSER} "http://toolbar.netcraft.com/site_report?url=$1" }
299 #f4# Use German Wikipedia's full text search
300 swiki()   { ${=BROWSER} http://de.wikipedia.org/wiki/Spezial:Search/${(C)1} }
301 #f4# search \kbd{dict.leo.org}
302 oleo()    { ${=BROWSER} "http://dict.leo.org/?search=$*" }
303 #f4# Search German   Wikipedia
304 wikide()  { ${=BROWSER} http://de.wikipedia.org/wiki/"${(C)*}" }
305 #f4# Search English  Wikipedia
306 wikien()  { ${=BROWSER} http://en.wikipedia.org/wiki/"${(C)*}" }
307 #f4# Search official debs
308 wodeb()   { ${=BROWSER} "http://packages.debian.org/search?keywords=$1&searchon=contents&suite=${2:=unstable}&section=all" }
309
310 #m# f4 gex() Exact search via Google
311 check_com google && gex () { google "\"[ $1]\" $*" } # exact search at google
312
313 # misc
314 #f5# Backup \kbd{file {\rm to} file\_timestamp}
315 bk()      { cp -b ${1} ${1}_`date --iso-8601=m` }
316 #f5# Copied diff
317 cdiff()   { diff -crd "$*" | egrep -v "^Only in |^Binary files " }
318 #f5# cd to directoy and list files
319 cl()      { cd $1 && ls -a }        # cd && ls
320 #f5# Cvs add
321 cvsa()    { cvs add $* && cvs com -m 'initial checkin' $* }
322 #f5# Cvs diff
323 cvsd()    { cvs diff -N $* |& $PAGER }
324 #f5# Cvs log
325 cvsl()    { cvs log $* |& $PAGER }
326 #f5# Cvs update
327 cvsq()    { cvs -nq update }
328 #f5# Rcs2log
329 cvsr()    { rcs2log $* | $PAGER }
330 #f5# Cvs status
331 cvss()    { cvs status -v $* }
332 #f5# Disassemble source files using gcc and as
333 disassemble(){ gcc -pipe -S -o - -O -g $* | as -aldh -o /dev/null }
334 #f5# Firefox remote control - open given URL
335 fir()     { firefox -a firefox -remote "openURL($1)" }
336 #f5# Create Directoy and \kbd{cd} to it
337 mcd()     { mkdir -p "$@"; cd "$@" } # mkdir && cd
338 #f5# Unified diff to timestamped outputfile
339 mdiff()   { diff -udrP "$1" "$2" > diff.`date "+%Y-%m-%d"`."$1" }
340 #f5# Memory overview
341 memusage(){ ps aux | awk '{if (NR > 1) print $5; if (NR > 2) print "+"} END { print "p" }' | dc }
342 #f5# Show contents of tar file
343 shtar()   { gunzip -c $1 | tar -tf - -- | $PAGER }
344 #f5# Show contents of tgz file
345 shtgz()   { tar -ztf $1 | $PAGER }
346 #f5# Show contents of zip file
347 shzip()   { unzip -l $1 | $PAGER }
348 #f5# Greps signature from file
349 sig()     { agrep -d '^-- $' "$*" ~/.Signature }
350 #f5# Unified diff
351 udiff()   { diff -urd $* | egrep -v "^Only in |^Binary files " }
352 #f5# (Mis)use \kbd{vim} as \kbd{less}
353 viless()  { vim --cmd 'let no_plugin_maps = 1' -c "so \$VIMRUNTIME/macros/less.vim" "${@:--}" }
354
355 # download video from youtube
356 ytdl() {
357     if ! [[ -n "$2" ]] ; then
358         print "Usage: ydtl http://youtube.com/watch?v=.... outputfile.flv">&2
359         return 1
360     else
361         wget -O${2} "http://youtube.com/get_video?"${${${"$(wget -o/dev/null -O- "${1}" | grep -e watch_fullscreen)"}##*watch_fullscreen\?}%%\&fs=*}
362     fi
363 }
364
365 # Function Usage: uopen $URL/$file
366 #f5# Download a file and display it locally
367 uopen() {
368     if ! [[ -n "$1" ]] ; then
369         print "Usage: uopen \$URL/\$file">&2
370         return 1
371     else
372         FILE=$1
373         MIME=$(curl --head $FILE | grep Content-Type | cut -d ' ' -f 2 | cut -d\; -f 1)
374         MIME=${MIME%$'\r'}
375         curl $FILE | see ${MIME}:-
376     fi
377 }
378
379 # Function Usage: doc packagename
380 #f5# \kbd{cd} to /usr/share/doc/\textit{package}
381 doc() { cd /usr/share/doc/$1 && ls }
382 _doc() { _files -W /usr/share/doc -/ }
383 check_com compdef && compdef _doc doc
384
385 #f5# Make screenshot
386 sshot() {
387     [[ ! -d ~/shots  ]] && mkdir ~/shots
388     #cd ~/shots ; sleep 5 ; import -window root -depth 8 -quality 80 `date "+%Y-%m-%d--%H:%M:%S"`.png
389     cd ~/shots ; sleep 5; import -window root shot_`date --iso-8601=m`.jpg
390 }
391
392 # list images only
393 limg() {
394     local -a images
395     images=( *.{jpg,gif,png}(.N) )
396
397     if [[ $#images -eq 0 ]] ; then
398         print "No image files found"
399     else
400         ls "$@" "$images[@]"
401     fi
402 }
403
404 #f5# Create PDF file from source code
405 makereadable() {
406     output=$1
407     shift
408     a2ps --medium A4dj -E -o $output $*
409     ps2pdf $output
410 }
411
412 # zsh with perl-regex - use it e.g. via:
413 # regcheck '\s\d\.\d{3}\.\d{3} Euro' ' 1.000.000 Euro'
414 #f5# Checks whether a regex matches or not.\\&\quad Example: \kbd{regcheck '.\{3\} EUR' '500 EUR'}
415 regcheck() {
416     zmodload -i zsh/pcre
417     pcre_compile $1 && \
418     pcre_match $2 && echo "regex matches" || echo "regex does not match"
419 }
420
421 #f5# List files which have been modified within the last {\it n} days
422 new() { print -l *(m-$1) }
423
424 #f5# Grep in history
425 greph() { history 0 | grep $1 }
426 # use colors when GNU grep with color-support
427 #a2# Execute \kbd{grep -{}-color=auto}
428 (grep --help 2>/dev/null |grep -- --color) >/dev/null && alias grep='grep --color=auto'
429 #a2# Execute \kbd{grep -i -{}-color=auto}
430 alias GREP='grep -i --color=auto'
431
432 # one blank line between each line
433 if [[ -r ~/.terminfo/m/mostlike ]] ; then
434 #   alias man2='MANPAGER="sed -e G |less" TERMINFO=~/.terminfo TERM=mostlike /usr/bin/man'
435     #f5# Watch manpages in a stretched style
436     man2() { PAGER='dash -c "sed G | /usr/bin/less"' TERM=mostlike /usr/bin/man "$@" ; }
437 fi
438
439 # d():Copyright 2005 Nikolai Weibull <nikolai@bitwi.se>
440 # notice: option AUTO_PUSHD has to be set
441 #f5# Jump between directories
442 d() {
443     emulate -L zsh
444     autoload -U colors
445     local color=$fg_bold[blue]
446     integer i=0
447     dirs -p | while read dir; do
448         local num="${$(printf "%-4d " $i)/ /.}"
449         printf " %s  $color%s$reset_color\n" $num $dir
450         (( i++ ))
451     done
452     integer dir=-1
453     read -r 'dir?Jump to directory: ' || return
454     (( dir == -1 )) && return
455     if (( dir < 0 || dir >= i )); then
456         echo d: no such directory stack entry: $dir
457         return 1
458     fi
459     cd ~$dir
460 }
461
462 # usage example: 'lcheck strcpy'
463 #f5# Find out which libs define a symbol
464 lcheck() {
465     if [[ -n "$1" ]] ; then
466         nm -go /usr/lib/lib*.a 2>/dev/null | grep ":[[:xdigit:]]\{8\} . .*$1"
467     else
468         echo "Usage: lcheck <function>" >&2
469     fi
470 }
471
472 #f5# Clean up directory - remove well known tempfiles
473 purge() {
474     FILES=(*~(N) .*~(N) \#*\#(N) *.o(N) a.out(N) *.core(N) *.cmo(N) *.cmi(N) .*.swp(N))
475     NBFILES=${#FILES}
476     if [[ $NBFILES > 0 ]] ; then
477         print $FILES
478         local ans
479         echo -n "Remove these files? [y/n] "
480         read -q ans
481         if [[ $ans == "y" ]] ; then
482             rm ${FILES}
483             echo ">> $PWD purged, $NBFILES files removed"
484         else
485             echo "Ok. .. than not.."
486         fi
487     fi
488 }
489
490 # Translate DE<=>EN
491 # 'translate' looks up fot a word in a file with language-to-language
492 # translations (field separator should be " : "). A typical wordlist looks
493 # like at follows:
494 #  | english-word : german-transmission
495 # It's also only possible to translate english to german but not reciprocal.
496 # Use the following oneliner to turn back the sort order:
497 #  $ awk -F ':' '{ print $2" : "$1" "$3 }' \
498 #    /usr/local/lib/words/en-de.ISO-8859-1.vok > ~/.translate/de-en.ISO-8859-1.vok
499 #f5# Translates a word
500 trans() {
501     case "$1" in
502         -[dD]*)
503             translate -l de-en $2
504             ;;
505         -[eE]*)
506             translate -l en-de $2
507             ;;
508         *)
509             echo "Usage: $0 { -D | -E }"
510             echo "         -D == German to English"
511             echo "         -E == English to German"
512     esac
513 }
514
515 # Some quick Perl-hacks aka /useful/ oneliner
516 #  bew() { perl -le 'print unpack "B*","'$1'"' }
517 #  web() { perl -le 'print pack "B*","'$1'"' }
518 #  hew() { perl -le 'print unpack "H*","'$1'"' }
519 #  weh() { perl -le 'print pack "H*","'$1'"' }
520 #  pversion()    { perl -M$1 -le "print $1->VERSION" } # i. e."pversion LWP -> 5.79"
521 #  getlinks ()   { perl -ne 'while ( m/"((www|ftp|http):\/\/.*?)"/gc ) { print $1, "\n"; }' $* }
522 #  gethrefs ()   { perl -ne 'while ( m/href="([^"]*)"/gc ) { print $1, "\n"; }' $* }
523 #  getanames ()  { perl -ne 'while ( m/a name="([^"]*)"/gc ) { print $1, "\n"; }' $* }
524 #  getforms ()   { perl -ne 'while ( m:(\</?(input|form|select|option).*?\>):gic ) { print $1, "\n"; }' $* }
525 #  getstrings () { perl -ne 'while ( m/"(.*?)"/gc ) { print $1, "\n"; }' $*}
526 #  getanchors () { perl -ne 'while ( m/«([^«»\n]+)»/gc ) { print $1, "\n"; }' $* }
527 #  showINC ()    { perl -e 'for (@INC) { printf "%d %s\n", $i++, $_ }' }
528 #  vimpm ()      { vim `perldoc -l $1 | sed -e 's/pod$/pm/'` }
529 #  vimhelp ()    { vim -c "help $1" -c on -c "au! VimEnter *" }
530
531 #f5# List all occurrences of programm in current PATH
532 plap() {
533     if [[ $# = 0 ]] ; then
534         echo "Usage:    $0 program"
535         echo "Example:  $0 zsh"
536         echo "Lists all occurrences of program in the current PATH."
537     else
538         ls -l ${^path}/*$1*(*N)
539     fi
540 }
541
542 # Found in the mailinglistarchive from Zsh (IIRC ~1996)
543 #f5# Select items for specific command(s) from history
544 selhist() {
545     emulate -L zsh
546     local TAB=$'\t';
547     (( $# < 1 )) && {
548         echo "Usage: $0 command"
549         return 1
550     };
551     cmd=(${(f)"$(grep -w $1 $HISTFILE | sort | uniq | pr -tn)"})
552     print -l $cmd | less -F
553     echo -n "enter number of desired command [1 - $(( ${#cmd[@]} - 1 ))]: "
554     local answer
555     read answer
556     print -z "${cmd[$answer]#*$TAB}"
557 }
558
559 # Use vim to convert plaintext to HTML
560 #f5# Transform files to html with highlighting
561 2html() { vim -u NONE -n -c ':syntax on' -c ':so $VIMRUNTIME/syntax/2html.vim' -c ':wqa' $1 &>/dev/null }
562
563 # Usage: simple-extract <file>
564 #f5# Smart archive extractor
565 simple-extract () {
566     if [[ -f $1 ]] ; then
567         case $1 in
568             *.tar.bz2)  bzip2 -v -d $1      ;;
569             *.tar.gz)   tar -xvzf $1        ;;
570             *.rar)      unrar $1            ;;
571             *.deb)      ar -x $1            ;;
572             *.bz2)      bzip2 -d $1         ;;
573             *.lzh)      lha x $1            ;;
574             *.gz)       gunzip -d $1        ;;
575             *.tar)      tar -xvf $1         ;;
576             *.tgz)      gunzip -d $1        ;;
577             *.tbz2)     tar -jxvf $1        ;;
578             *.zip)      unzip $1            ;;
579             *.Z)        uncompress $1       ;;
580             *)          echo "'$1' Error. Please go away" ;;
581         esac
582     else
583         echo "'$1' is not a valid file"
584     fi
585 }
586
587 # Usage: smartcompress <file> (<type>)
588 #f5# Smart archive creator
589 smartcompress() {
590     if [[ -n $2 ]] ; then
591         case $2 in
592             tgz | tar.gz)   tar -zcvf$1.$2 $1 ;;
593             tbz2 | tar.bz2) tar -jcvf$1.$2 $1 ;;
594             tar.Z)          tar -Zcvf$1.$2 $1 ;;
595             tar)            tar -cvf$1.$2  $1 ;;
596             gz | gzip)      gzip           $1 ;;
597             bz2 | bzip2)    bzip2          $1 ;;
598             *)
599                 echo "Error: $2 is not a valid compression type"
600                 ;;
601         esac
602     else
603         smartcompress $1 tar.gz
604     fi
605 }
606
607 # Usage: show-archive <archive>
608 #f5# List an archive's content
609 show-archive() {
610     if [[ -f $1 ]] ; then
611         case $1 in
612             *.tar.gz)      gunzip -c $1 | tar -tf - -- ;;
613             *.tar)         tar -tf $1 ;;
614             *.tgz)         tar -ztf $1 ;;
615             *.zip)         unzip -l $1 ;;
616             *.bz2)         bzless $1 ;;
617             *.deb)         dpkg-deb --fsys-tarfile $1 | tar -tf - -- ;;
618             *)             echo "'$1' Error. Please go away" ;;
619         esac
620     else
621         echo "'$1' is not a valid archive"
622     fi
623 }
624
625 # It's shameless stolen from <http://www.vim.org/tips/tip.php?tip_id=167>
626 #f5# Use \kbd{vim} as your manpage reader
627 vman() { man $* | col -b | view -c 'set ft=man nomod nolist' - }
628
629 # function readme() { $PAGER -- (#ia3)readme* }
630 #f5# View all README-like files in current directory in pager
631 readme() {
632     local files
633     files=(./(#i)*(read*me|lue*m(in|)ut)*(ND))
634     if (($#files)) ; then
635         $PAGER $files
636     else
637         print 'No README files.'
638     fi
639 }
640
641 # function ansi-colors()
642 #f5# Display ANSI colors
643 ansi-colors() {
644     typeset esc="\033[" line1 line2
645     echo " _ _ _40 _ _ _41_ _ _ _42 _ _ 43_ _ _ 44_ _ _45 _ _ _ 46_ _ _ 47_ _ _ 49_ _"
646     for fore in 30 31 32 33 34 35 36 37; do
647         line1="$fore "
648         line2="   "
649         for back in 40 41 42 43 44 45 46 47 49; do
650             line1="${line1}${esc}${back};${fore}m Normal ${esc}0m"
651             line2="${line2}${esc}${back};${fore};1m Bold   ${esc}0m"
652         done
653         echo -e "$line1\n$line2"
654     done
655 }
656
657 # suidfind() { ls -latg $path | grep '^...s' }
658 #f5# Find all files in \$PATH with setuid bit set
659 suidfind() { ls -latg $path/*(sN) }
660
661 # See above but this is /better/ ... anywise ..
662 findsuid() {
663     print 'Output will be written to ~/suid_* ...'
664     $SUDO find / -type f \( -perm -4000 -o -perm -2000 \) -ls > ~/suid_suidfiles.`date "+%Y-%m-%d"`.out 2>&1
665     $SUDO find / -type d \( -perm -4000 -o -perm -2000 \) -ls > ~/suid_suiddirs.`date "+%Y-%m-%d"`.out 2>&1
666     $SUDO find / -type f \( -perm -2 -o -perm -20 \) -ls > ~/suid_writefiles.`date "+%Y-%m-%d"`.out 2>&1
667     $SUDO find / -type d \( -perm -2 -o -perm -20 \) -ls > ~/suid_writedirs.`date "+%Y-%m-%d"`.out 2>&1
668     print 'Finished'
669 }
670
671 #f5# Reload given functions
672 refunc() {
673     for func in $argv ; do
674         unfunction $func
675         autoload $func
676     done
677 }
678
679 # a small check to see which DIR is located on which server/partition.
680 # stolen and modified from Sven's zshrc.forall
681 #f5# Report diskusage of a directory
682 dirspace() {
683     if [[ -n "$1" ]] ; then
684         for dir in $* ; do
685             if [[ -d "$dir" ]] ; then
686                 ( cd $dir; echo "-<$dir>"; du -shx .; echo);
687             else
688                 echo "warning: $dir does not exist" >&2
689             fi
690         done
691     else
692         for dir in $path; do
693             if [[ -d "$dir" ]] ; then
694                 ( cd $dir; echo "-<$dir>"; du -shx .; echo);
695             else
696                 echo "warning: $dir does not exist" >&2
697             fi
698         done
699     fi
700 }
701
702 # % slow_print `cat /etc/passwd`
703 #f5# Slowly print out parameters
704 slow_print() {
705     for argument in "${@}" ; do
706         for ((i = 1; i <= ${#1} ;i++)) ; do
707             print -n "${argument[i]}"
708             sleep 0.08
709         done
710         print -n " "
711     done
712     print ""
713 }
714
715 #f5# Show some status info
716 status() {
717     print ""
718     print "Date..: "$(date "+%Y-%m-%d %H:%M:%S")""
719     print "Shell.: Zsh $ZSH_VERSION (PID = $$, $SHLVL nests)"
720     print "Term..: $TTY ($TERM), $BAUD bauds, $COLUMNS x $LINES cars"
721     print "Login.: $LOGNAME (UID = $EUID) on $HOST"
722     print "System: $(cat /etc/[A-Za-z]*[_-][rv]e[lr]*)"
723     print "Uptime:$(uptime)"
724     print ""
725 }
726
727 # Rip an audio CD
728 #f5# Rip an audio CD
729 audiorip() {
730     mkdir -p ~/ripps
731     cd ~/ripps
732     cdrdao read-cd --device $DEVICE --driver generic-mmc audiocd.toc
733     cdrdao read-cddb --device $DEVICE --driver generic-mmc audiocd.toc
734     echo " * Would you like to burn the cd now? (yes/no)"
735     read input
736     if [[ "$input" = "yes" ]] ; then
737         echo " ! Burning Audio CD"
738         audioburn
739         echo " * done."
740     else
741         echo " ! Invalid response."
742     fi
743 }
744
745 # and burn it
746 #f5# Burn an audio CD (in combination with audiorip)
747 audioburn() {
748     cd ~/ripps
749     cdrdao write --device $DEVICE --driver generic-mmc audiocd.toc
750     echo " * Should I remove the temporary files? (yes/no)"
751     read input
752     if [[ "$input" = "yes" ]] ; then
753         echo " ! Removing Temporary Files."
754         cd ~
755         rm -rf ~/ripps
756         echo " * done."
757     else
758         echo " ! Invalid response."
759     fi
760 }
761
762 #f5# Make an audio CD from all mp3 files
763 mkaudiocd() {
764     # TODO: do the renaming more zshish, possibly with zmv()
765     cd ~/ripps
766     for i in *.[Mm][Pp]3; do mv "$i" `echo $i | tr '[A-Z]' '[a-z]'`; done
767     for i in *.mp3; do mv "$i" `echo $i | tr ' ' '_'`; done
768     for i in *.mp3; do mpg123 -w `basename $i .mp3`.wav $i; done
769     normalize -m *.wav
770     for i in *.wav; do sox $i.wav -r 44100 $i.wav resample; done
771 }
772
773 #f5# Create an ISO image. You are prompted for\\&\quad volume name, filename and directory
774 mkiso() {
775     echo " * Volume name "
776     read volume
777     echo " * ISO Name (ie. tmp.iso)"
778     read iso
779     echo " * Directory or File"
780     read files
781     mkisofs -o ~/$iso -A $volume -allow-multidot -J -R -iso-level 3 -V $volume -R $files
782 }
783
784 #f5# Simple thumbnails generator
785 genthumbs() {
786     rm -rf thumb-* index.html
787     echo "
788 <html>
789   <head>
790     <title>Images</title>
791   </head>
792   <body>" > index.html
793     for f in *.(gif|jpeg|jpg|png) ; do
794         convert -size 100x200 "$f" -resize 100x200 thumb-"$f"
795         echo "    <a href=\"$f\"><img src=\"thumb-$f\"></a>" >> index.html
796     done
797     echo "
798   </body>
799 </html>" >> index.html
800 }
801
802 #f5# Set all ulimit parameters to \kbd{unlimited}
803 allulimit() {
804     ulimit -c unlimited
805     ulimit -d unlimited
806     ulimit -f unlimited
807     ulimit -l unlimited
808     ulimit -n unlimited
809     ulimit -s unlimited
810     ulimit -t unlimited
811 }
812
813 # ogg2mp3 with bitrate of 192
814 ogg2mp3_192() {
815     oggdec -o - ${1} | lame -b 192 - ${1:r}.mp3
816 }
817
818 #f5# RFC 2396 URL encoding in Z-Shell
819 urlencode() {
820     setopt localoptions extendedglob
821     input=( ${(s::)1} )
822     print ${(j::)input/(#b)([^A-Za-z0-9_.!~*\'\(\)-])/%${(l:2::0:)$(([##16]#match))}}
823 }
824
825 #f5# Install x-lite (VoIP software)
826 getxlite() {
827     setopt local_options
828     setopt errreturn
829     [[ -d ~/tmp ]] || mkdir ~/tmp
830     cd ~/tmp
831
832     echo "Downloading http://www.counterpath.com/download/X-Lite_Install.tar.gz and storing it in ~/tmp:"
833     if wget http://www.counterpath.com/download/X-Lite_Install.tar.gz ; then
834         unp X-Lite_Install.tar.gz && echo done || echo failed
835     else
836         echo "Error while downloading." ; return 1
837     fi
838
839     if [[ -x xten-xlite/xtensoftphone ]] ; then
840         echo "Execute xten-xlite/xtensoftphone to start xlite."
841     fi
842 }
843
844 #f5# Install skype
845 getskype() {
846     setopt local_options
847     setopt errreturn
848     echo "Downloading debian package of skype."
849     echo "Notice: If you want to use a more recent skype version run 'getskypebeta'."
850     wget http://www.skype.com/go/getskype-linux-deb
851     $SUDO dpkg -i skype*.deb && echo "skype installed."
852 }
853
854 #f5# Install beta-version of skype
855 getskypebeta() {
856     setopt local_options
857     setopt errreturn
858     echo "Downloading debian package of skype (beta version)."
859     wget http://www.skype.com/go/getskype-linux-beta-deb
860     $SUDO dpkg -i skype-beta*.deb && echo "skype installed."
861 }
862
863 #f5# Install gizmo (VoIP software)
864 getgizmo() {
865     setopt local_options
866     setopt errreturn
867     echo "libgtk2.0-0, gconf2, libstdc++6, libasound2 and zlib1g have to be available. Installing."
868     $SUDO apt-get update
869     $SUDO apt-get install libgtk2.0-0 gconf2 libstdc++6 libasound2 zlib1g
870     wget "$(lynx --dump http://gizmo5.com/pc/download/linux/ | awk '/libstdc\+\+6.*\.deb/ {print $2}')"
871     $SUDO dpkg -i gizmo-project*.deb && echo "gizmo installed."
872 }
873
874 #f5# Get and run AIR (Automated Image and Restore)
875 getair() {
876     setopt local_options
877     setopt errreturn
878     [[ -w . ]] || { echo 'Error: you do not have write permissions in this directory. Exiting.' ; return 1 }
879     local VER='1.2.8'
880     wget http://puzzle.dl.sourceforge.net/sourceforge/air-imager/air-$VER.tar.gz
881     tar zxf air-$VER.tar.gz
882     cd air-$VER
883     INTERACTIVE=no $SUDO ./install-air-1.2.8
884     [[ -x /usr/local/bin/air ]] && [[ -n "$DISPLAY" ]] && $SUDO air
885 }
886
887 #f5# Get specific git commitdiff
888 git-get-diff() {
889     if [[ -z $GITTREE ]] ; then
890         GITTREE='linux/kernel/git/torvalds/linux-2.6.git'
891     fi
892     if ! [[ -z $1 ]] ; then
893         ${=BROWSER} "http://kernel.org/git/?p=$GITTREE;a=commitdiff;h=$1"
894     else
895         echo "Usage: git-get-diff <commit>"
896     fi
897 }
898
899 #f5# Get specific git commit
900 git-get-commit() {
901     if [[ -z $GITTREE ]] ; then
902         GITTREE='linux/kernel/git/torvalds/linux-2.6.git'
903     fi
904     if ! [[ -z $1 ]] ; then
905         ${=BROWSER} "http://kernel.org/git/?p=$GITTREE;a=commit;h=$1"
906     else
907         echo "Usage: git-get-commit <commit>"
908     fi
909 }
910
911 #f5# Get specific git diff
912 git-get-plaindiff () {
913     if [[ -z $GITTREE ]] ; then
914        GITTREE='linux/kernel/git/torvalds/linux-2.6.git'
915     fi
916     if [[ -z $1 ]] ; then
917        echo 'Usage: git-get-plaindiff '
918     else
919        echo -n "Downloading $1.diff ... "
920        # avoid "generating ..." stuff from kernel.org server:
921        wget --quiet "http://kernel.org/git/?p=$GITTREE;a=commitdiff_plain;h=$1" -O /dev/null
922        wget --quiet "http://kernel.org/git/?p=$GITTREE;a=commitdiff_plain;h=$1" -O $1.diff \
923             && echo done || echo failed
924     fi
925 }
926
927
928 # http://strcat.de/blog/index.php?/archives/335-Software-sauber-deinstallieren...html
929 #f5# Log 'make install' output
930 mmake() {
931     [[ ! -d ~/.errorlogs ]] && mkdir ~/.errorlogs
932     make -n install > ~/.errorlogs/${PWD##*/}-makelog
933 }
934
935 #f5# Indent source code
936 smart-indent() {
937     indent -npro -kr -i8 -ts8 -sob -l80 -ss -ncs $*
938 }
939
940 # highlight important stuff in diff output, usage example: hg diff | hidiff
941 #m# a2 hidiff \kbd{histring} oneliner for diffs
942 check_com -c histring && \
943     alias hidiff="histring -fE '^Comparing files .*|^diff .*' | histring -c yellow -fE '^\-.*' | histring -c green -fE '^\+.*'"
944
945 # rename pictures based on information found in exif headers
946 #f5# Rename pictures based on information found in exif headers
947 exirename() {
948     if [[ $# -lt 1 ]] ; then
949         echo 'Usage: jpgrename $FILES' >& 2
950         return 1
951     else
952         echo -n 'Checking for jhead with version newer than 1.9: '
953         jhead_version=`jhead -h | grep 'used by most Digital Cameras.  v.*' | awk '{print $6}' | tr -d v`
954         if [[ $jhead_version > '1.9' ]]; then
955             echo 'success - now running jhead.'
956             jhead -n%Y-%m-%d_%Hh%M_%f $*
957         else
958             echo 'failed - exiting.'
959         fi
960     fi
961 }
962
963 # open file in vim and jump to line
964 # http://www.downgra.de/archives/2007/05/08/T19_21_11/
965 j2v() {
966     local -a params
967     params=(${*//(#m):[0-9]*:/\\n+${MATCH//:/}}) # replace ':23:' to '\n+23'
968     params=(${(s|\n|)${(j|\n|)params}}) # join array using '\n', then split on all '\n'
969     vim ${params}
970 }
971
972 # get_ic() - queries imap servers for capabilities; real simple. no imaps
973 ic_get() {
974     local port
975     if [[ ! -z $1 ]] ; then
976         port=${2:-143}
977         print "querying imap server on $1:${port}...\n";
978         print "a1 capability\na2 logout\n" | nc $1 ${port}
979     else
980         print "usage:\n  $0 <imap-server> [port]"
981     fi
982 }
983
984 # creates a Maildir/ with its {new,cur,tmp} subdirs
985 mkmaildir() {
986     local root subdir
987     root=${MAILDIR_ROOT:-${HOME}/Mail}
988     if [[ -z ${1} ]] ; then print "Usage:\n $0 <dirname>" ; return 1 ; fi
989     subdir=${1}
990     mkdir -p ${root}/${subdir}/{cur,new,tmp}
991 }
992
993 # xtrename() rename xterm from within GNU-screen
994 xtrename() {
995     if [[ -z ${DISPLAY} ]] ; then
996         printf 'xtrename only makes sense in X11.\n'
997         return 1
998     fi
999     if [[ -z ${1} ]] ; then
1000         printf 'usage: xtrename() "title for xterm"\n'
1001         printf '  renames the title of xterm from _within_ screen.\n'
1002         printf '  Also works without screen.\n'
1003         return 0
1004     fi
1005     print -n "\eP\e]0;${1}\C-G\e\\"
1006     return 0
1007 }
1008
1009 # hl() highlighted less
1010 # http://ft.bewatermyfriend.org/comp/data/zsh/zfunct.html
1011 if check_com -c highlight ; then
1012     function hl() {
1013         local theme lang
1014         theme=${HL_THEME:-""}
1015         case ${1} in
1016             (-l|--list)
1017                 ( printf 'available languages (syntax parameter):\n\n' ;
1018                     highlight --list-langs ; ) | less -SMr
1019                 ;;
1020             (-t|--themes)
1021                 ( printf 'available themes (style parameter):\n\n' ;
1022                     highlight --list-themes ; ) | less -SMr
1023                 ;;
1024             (-h|--help)
1025                 printf 'usage: hl <syntax[:theme]> <file>\n'
1026                 printf '    available options: --list (-l), --themes (-t), --help (-h)\n\n'
1027                 printf '  Example: hl c main.c\n'
1028                 ;;
1029             (*)
1030                 if [[ -z ${2} ]] || (( ${#argv} > 2 )) ; then
1031                     printf 'usage: hl <syntax[:theme]> <file>\n'
1032                     printf '    available options: --list (-l), --themes (-t), --help (-h)\n'
1033                     (( ${#argv} > 2 )) && printf '  Too many arguments.\n'
1034                     return 1
1035                 fi
1036                 lang=${1%:*}
1037                 [[ ${1} == *:* ]] && [[ -n ${1#*:} ]] && theme=${1#*:}
1038                 if [[ -n ${theme} ]] ; then
1039                     highlight --xterm256 --syntax ${lang} --style ${theme} ${2} | less -SMr
1040                 else
1041                     highlight --ansi --syntax ${lang} ${2} | less -SMr
1042                 fi
1043                 ;;
1044         esac
1045         return 0
1046     }
1047     # ... and a proper completion for hl()
1048     # needs 'highlight' as well, so it fits fine in here.
1049     function _hl_genarg()  {
1050         local expl
1051         if [[ -prefix 1 *: ]] ; then
1052             local themes
1053             themes=(${${${(f)"$(LC_ALL=C highlight --list-themes)"}/ #/}:#*(Installed|Use name)*})
1054             compset -P 1 '*:'
1055             _wanted -C list themes expl theme compadd ${themes}
1056         else
1057             local langs
1058             langs=(${${${(f)"$(LC_ALL=C highlight --list-langs)"}/ #/}:#*(Installed|Use name)*})
1059             _wanted -C list languages expl languages compadd -S ':' -q ${langs}
1060         fi
1061     }
1062     function _hl_complete() {
1063         _arguments -s '1: :_hl_genarg' '2:files:_path_files'
1064     }
1065     compdef _hl_complete hl
1066 fi
1067
1068 # create small urls via tinyurl.com using wget, grep and sed
1069 zurl() {
1070     [[ -z ${1} ]] && print "please give an url to shrink." && return 1
1071     local url=${1}
1072     local tiny="http://tinyurl.com/create.php?url="
1073     #print "${tiny}${url}" ; return
1074     wget  -O-             \
1075           -o/dev/null     \
1076           "${tiny}${url}" \
1077         | grep -Eio 'value="(http://tinyurl.com/.*)"' \
1078         | sed 's/value=//;s/"//g'
1079 }
1080
1081 #f2# Print a specific line of file(s).
1082 linenr () {
1083 # {{{
1084     if [ $# -lt 2 ] ; then
1085        print "Usage: linenr <number>[,<number>] <file>" ; return 1
1086     elif [ $# -eq 2 ] ; then
1087          local number=$1
1088          local file=$2
1089          command ed -s $file <<< "${number}n"
1090     else
1091          local number=$1
1092          shift
1093          for file in "$@" ; do
1094              if [ ! -d $file ] ; then
1095                 echo "${file}:"
1096                 command ed -s $file <<< "${number}n" 2> /dev/null
1097              else
1098                 continue
1099              fi
1100          done | less
1101     fi
1102 # }}}
1103 }
1104
1105 #f2# Find history events by search pattern and list them by date.
1106 whatwhen()  {
1107 # {{{
1108     local usage help ident format_l format_s first_char remain first last
1109     usage='USAGE: whatwhen [options] <searchstring> <search range>'
1110     help='Use' \`'whatwhen -h'\'' for further explanations.'
1111     ident=${(l,${#${:-Usage: }},, ,)}
1112     format_l="${ident}%s\t\t\t%s\n"
1113     format_s="${format_l//(\\t)##/\\t}"
1114     # Make the first char of the word to search for case
1115     # insensitive; e.g. [aA]
1116     first_char=[${(L)1[1]}${(U)1[1]}]
1117     remain=${1[2,-1]}
1118     # Default search range is `-100'.
1119     first=${2:-\-100}
1120     # Optional, just used for `<first> <last>' given.
1121     last=$3
1122     case $1 in
1123         ("")
1124             printf '%s\n\n' 'ERROR: No search string specified. Aborting.'
1125             printf '%s\n%s\n\n' ${usage} ${help} && return 1
1126         ;;
1127         (-h)
1128             printf '%s\n\n' ${usage}
1129             print 'OPTIONS:'
1130             printf $format_l '-h' 'show help text'
1131             print '\f'
1132             print 'SEARCH RANGE:'
1133             printf $format_l "'0'" 'the whole history,'
1134             printf $format_l '-<n>' 'offset to the current history number; (default: -100)'
1135             printf $format_s '<[-]first> [<last>]' 'just searching within a give range'
1136             printf '\n%s\n' 'EXAMPLES:'
1137             printf ${format_l/(\\t)/} 'whatwhen grml' '# Range is set to -100 by default.'
1138             printf $format_l 'whatwhen zsh -250'
1139             printf $format_l 'whatwhen foo 1 99'
1140         ;;
1141         (\?)
1142             printf '%s\n%s\n\n' ${usage} ${help} && return 1
1143         ;;
1144         (*)
1145             # -l list results on stout rather than invoking $EDITOR.
1146             # -i Print dates as in YYYY-MM-DD.
1147             # -m Search for a - quoted - pattern within the history.
1148             fc -li -m "*${first_char}${remain}*" $first $last
1149         ;;
1150     esac
1151 # }}}
1152 }
1153
1154 # change fluxbox keys from 'Alt-#' to 'Alt-F#' and vice versa
1155 fluxkey-change() {
1156     [[ -n "$FLUXKEYS" ]] || local FLUXKEYS="$HOME/.fluxbox/keys"
1157     if ! [[ -r "$FLUXKEYS" ]] ; then
1158         echo "Sorry, \$FLUXKEYS file $FLUXKEYS could not be read - nothing to be done."
1159         return 1
1160     else
1161         if grep -q 'Mod1 F[0-9] :Workspace [0-9]' $FLUXKEYS ; then
1162             echo -n 'Switching to Alt-# mode in ~/.fluxbox/keys: '
1163             sed -i -e 's|^\(Mod[0-9]\+[: space :]\+\)F\([0-9]\+[: space :]\+:Workspace.*\)|\1\2|' $FLUXKEYS && echo done || echo failed
1164         elif grep -q 'Mod1 [0-9] :Workspace [0-9]' $FLUXKEYS ; then
1165             echo -n 'Switching to Alt-F# mode in ~/.fluxbox/keys: '
1166             sed -i -e 's|^\(Mod[0-9]\+[: space :]\+\)\([0-9]\+[: space :]\+:Workspace.*\)|\1F\2|' $FLUXKEYS && echo done || echo failed
1167         else
1168             echo 'Sorry, do not know what to do.'
1169             return 1
1170         fi
1171     fi
1172 }
1173
1174 # retrieve weather information on the console
1175 # Usage example: 'weather LOWG'
1176 weather() {
1177     [[ -n "$1" ]] || {
1178         print 'Usage: weather <station_id>' >&2
1179         print 'List of stations: http://en.wikipedia.org/wiki/List_of_airports_by_ICAO_code'>&2
1180         return 1
1181     }
1182
1183     local PLACE="${1:u}"
1184     local FILE="$HOME/.weather/$PLACE"
1185     local LOG="$HOME/.weather/log"
1186
1187     [[ -d $HOME/.weather ]] || {
1188         print -n "Creating $HOME/.weather: "
1189         mkdir $HOME/.weather
1190         print 'done'
1191     }
1192
1193     print "Retrieving information for ${PLACE}:"
1194     print
1195     wget -T 10 --no-verbose --output-file=$LOG --output-document=$FILE --timestamping http://weather.noaa.gov/pub/data/observations/metar/decoded/$PLACE.TXT
1196
1197     if [[ $? -eq 0 ]] ; then
1198         if [[ -n "$VERBOSE" ]] ; then
1199             cat $FILE
1200         else
1201             DATE=$(grep 'UTC' $FILE | sed 's#.* /##')
1202             TEMPERATURE=$(awk '/Temperature/ { print $4" degree Celcius / " $2" degree Fahrenheit" }' $FILE| tr -d '(')
1203             echo "date: $DATE"
1204             echo "temp:  $TEMPERATURE"
1205         fi
1206     else
1207         print "There was an error retrieving the weather information for $PLACE" >&2
1208         cat $LOG
1209         return 1
1210     fi
1211 }
1212 # }}}
1213
1214 # mercurial related stuff {{{
1215 if check_com -c hg ; then
1216     # gnu like diff for mercurial
1217     # http://www.selenic.com/mercurial/wiki/index.cgi/TipsAndTricks
1218     #f5# GNU like diff for mercurial
1219     hgdi() {
1220         for i in $(hg status -marn "$@") ; diff -ubwd <(hg cat "$i") "$i"
1221     }
1222
1223     # build debian package
1224     #a2# Alias for \kbd{hg-buildpackage}
1225     alias hbp='hg-buildpackage'
1226
1227     # execute commands on the versioned patch-queue from the current repos
1228     alias mq='hg -R $(readlink -f $(hg root)/.hg/patches)'
1229
1230     # diffstat for specific version of a mercurial repository
1231     #   hgstat      => display diffstat between last revision and tip
1232     #   hgstat 1234 => display diffstat between revision 1234 and tip
1233     #f5# Diffstat for specific version of a mercurial repos
1234     hgstat() {
1235         [[ -n "$1" ]] && hg diff -r $1 -r tip | diffstat || hg export tip | diffstat
1236     }
1237
1238     #f5# Get current mercurial tip via hg itself
1239     gethgclone() {
1240         setopt local_options
1241         setopt errreturn
1242         if [[ -f mercurial-tree/.hg ]] ; then
1243             cd mercurial-tree
1244             echo "Running hg pull for retreiving latest version..."
1245             hg pull
1246             echo "Finished update. Building mercurial"
1247             make local
1248             echo "Setting \$PATH to $PWD:\$PATH..."
1249             export PATH="$PWD:$PATH"
1250         else
1251             echo "Downloading mercurial via hg"
1252             hg clone http://selenic.com/repo/hg mercurial-tree
1253             cd mercurial-tree
1254             echo "Building mercurial"
1255             make local
1256             echo "Setting \$PATH to $PWD:\$PATH..."
1257             export PATH="$PWD:$PATH"
1258             echo "make sure you set it permanent via ~/.zshrc if you plan to use it permanently."
1259             # echo "Setting \$PYTHONPATH to PYTHONPATH=\${HOME}/lib/python,"
1260             # export PYTHONPATH=${HOME}/lib/python
1261         fi
1262     }
1263
1264 fi # end of check whether we have the 'hg'-executable
1265
1266 # get current mercurial snapshot
1267 #f5# Get current mercurial snapshot
1268 gethgsnap() {
1269     setopt local_options
1270     setopt errreturn
1271     if [[ -f mercurial-snapshot.tar.gz ]] ; then
1272          echo "mercurial-snapshot.tar.gz exists already, skipping download."
1273     else
1274         echo "Downloading mercurial snapshot"
1275         wget http://www.selenic.com/mercurial/mercurial-snapshot.tar.gz
1276     fi
1277     echo "Unpacking mercurial-snapshot.tar.gz"
1278     tar zxf mercurial-snapshot.tar.gz
1279     cd mercurial-snapshot/
1280     echo "Installing required build-dependencies"
1281     $SUDO apt-get update
1282     $SUDO apt-get install python2.4-dev
1283     echo "Building mercurial"
1284     make local
1285     echo "Setting \$PATH to $PWD:\$PATH..."
1286     export PATH="$PWD:$PATH"
1287     echo "make sure you set it permanent via ~/.zshrc if you plan to use it permanently."
1288 }
1289 # }}}
1290
1291 # some useful commands often hard to remember - let's grep for them {{{
1292
1293 # Work around ion/xterm resize bug.
1294 #if [[ "$SHLVL" -eq 1 ]]; then
1295 #       if check_com -c resize ; then
1296 #               eval `resize </dev/null`
1297 #       fi
1298 #fi
1299
1300 # enable jackd:
1301 #  /usr/bin/jackd -dalsa -dhw:0 -r48000 -p1024 -n2
1302 # now play audio file:
1303 #  alsaplayer -o jack foobar.mp3
1304
1305 # send files via netcat
1306 # on sending side:
1307 #  send() {j=$*; tar cpz ${j/%${!#}/}|nc -w 1 ${!#} 51330;}
1308 #  send dir* $HOST
1309 #  alias receive='nc -vlp 51330 | tar xzvp'
1310
1311 # debian stuff:
1312 # dh_make -e foo@localhost -f $1
1313 # dpkg-buildpackage -rfakeroot
1314 # lintian *.deb
1315 # dpkg-scanpackages ./ /dev/null | gzip > Packages.gz
1316 # dpkg-scansources . | gzip > Sources.gz
1317 # grep-dctrl --field Maintainer $* /var/lib/apt/lists/*
1318
1319 # other stuff:
1320 # convert -geometry 200x200 -interlace LINE -verbose
1321 # ldapsearch -x -b "OU=Bedienstete,O=tug" -h ldap.tugraz.at sn=$1
1322 # ps -ao user,pcpu,start,command
1323 # gpg --keyserver blackhole.pca.dfn.de --recv-keys
1324 # xterm -bg black -fg yellow -fn -misc-fixed-medium-r-normal--14-140-75-75-c-90-iso8859-15 -ah
1325 # nc -vz $1 1-1024   # portscan via netcat
1326 # wget --mirror --no-parent --convert-links
1327 # pal -d `date +%d`
1328 # autoload -U tetris; zle -N tetris; bindkey '...' ; echo "press ... for playing tennis"
1329 #
1330 # modify console cursor
1331 # see http://www.tldp.org/HOWTO/Framebuffer-HOWTO-5.html
1332 # print $'\e[?96;0;64c'
1333 # }}}
1334
1335 # finally source a local zshrc and grmlsmall-specific configuration {{{
1336
1337 # The following file is used to remove zsh-config-items that do not work
1338 # in grml-small by default.
1339 # If you do not want these adjustments (for whatever reason),
1340 # there are three ways to accomplish that:
1341 #  a) at the beginning of this file (variables section), set
1342 #     $GRMLSMALL_SPECIFIC to 0 or comment out the variable definition.
1343 #  b) remove/rename .zshrc.grmlsmall
1344 #  c) comment out the following line
1345 (( GRMLSMALL_SPECIFIC > 0 )) && isgrmlsmall && source ~/.zshrc.grmlsmall
1346
1347 # this allows us to stay in sync with /etc/skel/.zshrc
1348 # through 'ln -s /etc/skel/.zshrc ~/.zshrc' and put own
1349 # modifications in ~/.zshrc.local
1350 xsource "${HOME}/.zshrc.local"
1351
1352 # }}}
1353
1354 ### doc strings for external functions from files
1355 #m# f5 grml-wallpaper() Sets a wallpaper (try completion for possible values)
1356 ## END OF FILE #################################################################
1357 # vim:foldmethod=marker autoindent expandtab shiftwidth=4