]> gitweb.pimeys.fr Git - config-20-100.git/blob - .zsh/rc/extra/15_misc_functions
Ajout du zshrc, même s'il manque encore de commentaires etc.
[config-20-100.git] / .zsh / rc / extra / 15_misc_functions
1 #!/bin/zsh
2
3 # rename pictures based on information found in exif headers
4 #f5# Rename pictures based on information found in exif headers
5 exirename() {
6 emulate -L zsh
7 if [[ $# -lt 1 ]] ; then
8 echo 'Usage: jpgrename $FILES' >& 2
9 return 1
10 else
11 echo -n 'Checking for jhead with version newer than 1.9: '
12 jhead_version=`jhead -h | grep 'used by most Digital Cameras. v.*' | awk '{print $6}' | tr -d v`
13 if [[ $jhead_version > '1.9' ]]; then
14 echo 'success - now running jhead.'
15 jhead -n%Y-%m-%d_%Hh%M_%f $*
16 else
17 echo 'failed - exiting.'
18 fi
19 fi
20 }
21
22 # get_ic() - queries imap servers for capabilities; real simple. no imaps
23 ic_get() {
24 emulate -L zsh
25 local port
26 if [[ ! -z $1 ]] ; then
27 port=${2:-143}
28 print "querying imap server on $1:${port}...\n";
29 print "a1 capability\na2 logout\n" | nc $1 ${port}
30 else
31 print "usage:\n $0 <imap-server> [port]"
32 fi
33 }
34
35 # creates a Maildir/ with its {new,cur,tmp} subdirs
36 mkmaildir() {
37 emulate -L zsh
38 local root subdir
39 root=${MAILDIR_ROOT:-${HOME}/Mail}
40 if [[ -z ${1} ]] ; then print "Usage:\n $0 <dirname>" ; return 1 ; fi
41 subdir=${1}
42 mkdir -p ${root}/${subdir}/{cur,new,tmp}
43 }
44
45 #f5# Change the xterm title from within GNU-screen
46 xtrename() {
47 emulate -L zsh
48 if [[ $1 != "-f" ]] ; then
49 if [[ -z ${DISPLAY} ]] ; then
50 printf 'xtrename only makes sense in X11.\n'
51 return 1
52 fi
53 else
54 shift
55 fi
56 if [[ -z $1 ]] ; then
57 printf 'usage: xtrename [-f] "title for xterm"\n'
58 printf ' renames the title of xterm from _within_ screen.\n'
59 printf ' also works without screen.\n'
60 printf ' will not work if DISPLAY is unset, use -f to override.\n'
61 return 0
62 fi
63 print -n "\eP\e]0;${1}\C-G\e\\"
64 return 0
65 }
66
67 #f2# Find history events by search pattern and list them by date.
68 whatwhen() {
69 # {{{
70 emulate -L zsh
71 local usage help ident format_l format_s first_char remain first last
72 usage='USAGE: whatwhen [options] <searchstring> <search range>'
73 help='Use' \`'whatwhen -h'\'' for further explanations.'
74 ident=${(l,${#${:-Usage: }},, ,)}
75 format_l="${ident}%s\t\t\t%s\n"
76 format_s="${format_l//(\\t)##/\\t}"
77 # Make the first char of the word to search for case
78 # insensitive; e.g. [aA]
79 first_char=[${(L)1[1]}${(U)1[1]}]
80 remain=${1[2,-1]}
81 # Default search range is `-100'.
82 first=${2:-\-100}
83 # Optional, just used for `<first> <last>' given.
84 last=$3
85 case $1 in
86 ("")
87 printf '%s\n\n' 'ERROR: No search string specified. Aborting.'
88 printf '%s\n%s\n\n' ${usage} ${help} && return 1
89 ;;
90 (-h)
91 printf '%s\n\n' ${usage}
92 print 'OPTIONS:'
93 printf $format_l '-h' 'show help text'
94 print '\f'
95 print 'SEARCH RANGE:'
96 printf $format_l "'0'" 'the whole history,'
97 printf $format_l '-<n>' 'offset to the current history number; (default: -100)'
98 printf $format_s '<[-]first> [<last>]' 'just searching within a give range'
99 printf '\n%s\n' 'EXAMPLES:'
100 printf ${format_l/(\\t)/} 'whatwhen grml' '# Range is set to -100 by default.'
101 printf $format_l 'whatwhen zsh -250'
102 printf $format_l 'whatwhen foo 1 99'
103 ;;
104 (\?)
105 printf '%s\n%s\n\n' ${usage} ${help} && return 1
106 ;;
107 (*)
108 # -l list results on stout rather than invoking $EDITOR.
109 # -i Print dates as in YYYY-MM-DD.
110 # -m Search for a - quoted - pattern within the history.
111 fc -li -m "*${first_char}${remain}*" $first $last
112 ;;
113 esac
114 # }}}
115 }
116
117 # change fluxbox keys from 'Alt-#' to 'Alt-F#' and vice versa
118 fluxkey-change() {
119 emulate -L zsh
120 [[ -n "$FLUXKEYS" ]] || local FLUXKEYS="$HOME/.fluxbox/keys"
121 if ! [[ -r "$FLUXKEYS" ]] ; then
122 echo "Sorry, \$FLUXKEYS file $FLUXKEYS could not be read - nothing to be done."
123 return 1
124 else
125 if grep -q 'Mod1 F[0-9] :Workspace [0-9]' $FLUXKEYS ; then
126 echo -n 'Switching to Alt-# mode in ~/.fluxbox/keys: '
127 sed -i -e 's|^\(Mod[0-9]\+[: space :]\+\)F\([0-9]\+[: space :]\+:Workspace.*\)|\1\2|' $FLUXKEYS && echo done || echo failed
128 elif grep -q 'Mod1 [0-9] :Workspace [0-9]' $FLUXKEYS ; then
129 echo -n 'Switching to Alt-F# mode in ~/.fluxbox/keys: '
130 sed -i -e 's|^\(Mod[0-9]\+[: space :]\+\)\([0-9]\+[: space :]\+:Workspace.*\)|\1F\2|' $FLUXKEYS && echo done || echo failed
131 else
132 echo 'Sorry, do not know what to do.'
133 return 1
134 fi
135 fi
136 }
137
138 # retrieve weather information on the console
139 # Usage example: 'weather LOWG'
140 weather() {
141 emulate -L zsh
142 [ $1 = "-v" ] && local VERBOSE=1 && shift
143 [[ -n "$1" ]] || {
144 print 'Usage: weather [-v] <station_id>' >&2
145 print 'List of stations: http://en.wikipedia.org/wiki/List_of_airports_by_ICAO_code'>&2
146 print 'With -v, displays everything' >&2
147 return 1
148 }
149
150 local PLACE="${1:u}"
151 local FILE="$HOME/.weather/$PLACE"
152 local LOG="$HOME/.weather/log"
153
154 [[ -d $HOME/.weather ]] || {
155 print -n "Creating $HOME/.weather: "
156 mkdir $HOME/.weather
157 print 'done'
158 }
159
160 print "Retrieving information for ${PLACE}:"
161 print
162 wget -T 10 --no-verbose --output-file=$LOG --output-document=$FILE --timestamping http://weather.noaa.gov/pub/data/observations/metar/decoded/$PLACE.TXT
163
164 if [[ $? -eq 0 ]] ; then
165 if [[ -n "$VERBOSE" ]] ; then
166 cat $FILE
167 else
168 DATE=$(grep 'UTC' $FILE | sed 's#.* /##')
169 TEMPERATURE=$(awk '/Temperature/ { print $4" degree Celcius / " $2" degree Fahrenheit" }' $FILE| tr -d '(')
170 echo "date: $DATE"
171 echo "temp: $TEMPERATURE"
172 fi
173 else
174 print "There was an error retrieving the weather information for $PLACE" >&2
175 cat $LOG
176 return 1
177 fi
178 }
179
180 # d():Copyright 2005 Nikolai Weibull <nikolai@bitwi.se>
181 # note: option AUTO_PUSHD has to be set
182 #f5# Jump between directories
183 d() {
184 emulate -L zsh
185 autoload -U colors
186 local color=$fg_bold[blue]
187 integer i=0
188 dirs -p | while read dir; do
189 local num="${$(printf "%-4d " $i)/ /.}"
190 printf " %s $color%s$reset_color\n" $num $dir
191 (( i++ ))
192 done
193 integer dir=-1
194 read -r 'dir?Jump to directory: ' || return
195 (( dir == -1 )) && return
196 if (( dir < 0 || dir >= i )); then
197 echo d: no such directory stack entry: $dir
198 return 1
199 fi
200 cd ~$dir
201 }
202
203 #f5# Copied diff
204 cdiff() {
205 emulate -L zsh
206 diff -crd "$*" | egrep -v "^Only in |^Binary files "
207 }
208 #f5# Disassemble source files using gcc and as
209 disassemble(){
210 emulate -L zsh
211 gcc -pipe -S -o - -O -g $* | as -aldh -o /dev/null
212 }
213 #f5# Firefox remote control - open given URL
214 fir() {
215 if [ -e /etc/debian_version ]; then
216 firefox -a iceweasel -remote "openURL($1)" || firefox ${1}&
217 else
218 firefox -a firefox -remote "openURL($1)" || firefox ${1}&
219 fi
220 }
221 #f5# Unified diff to timestamped outputfile
222 mdiff() {
223 diff -udrP "$1" "$2" > diff.`date "+%Y-%m-%d"`."$1"
224 }
225 #f5# Show contents of gzipped tar file
226 shtar() {
227 emulate -L zsh
228 gunzip -c $1 | tar -tf - -- | $PAGER
229 }
230 #f5# Show contents of zip file
231 shzip() {
232 emulate -L zsh
233 unzip -l $1 | $PAGER
234 }
235 #f5# Unified diff
236 udiff() {
237 emulate -L zsh
238 diff -urd $* | egrep -v "^Only in |^Binary files "
239 }
240 #f5# (Mis)use \kbd{vim} as \kbd{less}
241 viless() {
242 emulate -L zsh
243 vim --cmd 'let no_plugin_maps = 1' -c "so \$VIMRUNTIME/macros/less.vim" "${@:--}"
244 }
245
246 # Function Usage: uopen $URL/$file
247 #f5# Download a file and display it locally
248 uopen() {
249 emulate -L zsh
250 if ! [[ -n "$1" ]] ; then
251 print "Usage: uopen \$URL/\$file">&2
252 return 1
253 else
254 FILE=$1
255 MIME=$(curl --head $FILE | grep Content-Type | cut -d ' ' -f 2 | cut -d\; -f 1)
256 MIME=${MIME%$'\r'}
257 curl $FILE | see ${MIME}:-
258 fi
259 }
260
261 #f5# Make screenshot
262 sshot() {
263 [[ ! -d ~/shots ]] && mkdir ~/shots
264 #cd ~/shots ; sleep 5 ; import -window root -depth 8 -quality 80 `date "+%Y-%m-%d--%H:%M:%S"`.png
265 cd ~/shots ; sleep 5; import -window root shot_`date --iso-8601=m`.jpg
266 }
267
268 # list images only
269 limg() {
270 local -a images
271 images=( *.{jpg,gif,png}(.N) )
272
273 if [[ $#images -eq 0 ]] ; then
274 print "No image files found"
275 else
276 ls "$images[@]"
277 fi
278 }
279
280 #f5# Create PDF file from source code
281 makereadable() {
282 emulate -L zsh
283 output=$1
284 shift
285 a2ps --medium A4dj -E -o $output $*
286 ps2pdf $output
287 }
288
289 # zsh with perl-regex - use it e.g. via:
290 # regcheck '\s\d\.\d{3}\.\d{3} Euro' ' 1.000.000 Euro'
291 #f5# Checks whether a regex matches or not.\\&\quad Example: \kbd{regcheck '.\{3\} EUR' '500 EUR'}
292 regcheck() {
293 emulate -L zsh
294 zmodload -i zsh/pcre
295 pcre_compile $1 && \
296 pcre_match $2 && echo "regex matches" || echo "regex does not match"
297 }
298
299 #f5# List files which have been changed within the last {\it n} days, {\it n} defaults to 1
300 changed() {
301 emulate -L zsh
302 print -l *(c-${1:1})
303 }
304
305 #f5# List files which have been modified within the last {\it n} days, {\it n} defaults to 1
306 new() {
307 emulate -L zsh
308 print -l *(m-${1:1})
309 }
310
311 # just press 'asdf' keys to toggle between dvorak and us keyboard layout
312 aoeu() {
313 echo -n 'Switching to us keyboard layout: '
314 [[ -z "$DISPLAY" ]] && $SUDO loadkeys us &>/dev/null || setxkbmap us &>/dev/null
315 echo 'Done'
316 }
317 asdf() {
318 echo -n 'Switching to dvorak keyboard layout: '
319 [[ -z "$DISPLAY" ]] && $SUDO loadkeys dvorak &>/dev/null || setxkbmap dvorak &>/dev/null
320 echo 'Done'
321 }
322 # just press 'asdf' key to toggle from neon layout to us keyboard layout
323 uiae() {
324 echo -n 'Switching to us keyboard layout: '
325 setxkbmap us && echo 'Done' || echo 'Failed'
326 }
327
328 # set up an ipv6 tunnel
329 ipv6-tunnel() {
330 emulate -L zsh
331 case $1 in
332 start)
333 if ifconfig sit1 2>/dev/null | grep -q 'inet6 addr: 2002:.*:1::1' ; then
334 print 'ipv6 tunnel already set up, nothing to be done.'
335 print 'execute: "ifconfig sit1 down ; ifconfig sit0 down" to remove ipv6-tunnel.' ; return 1
336 else
337 [[ -n "$PUBLIC_IP" ]] || \
338 local PUBLIC_IP=$(ifconfig $(route -n | awk '/^0\.0\.0\.0/{print $8; exit}') | \
339 awk '/inet addr:/ {print $2}' | tr -d 'addr:')
340
341 [[ -n "$PUBLIC_IP" ]] || { print 'No $PUBLIC_IP set and could not determine default one.' ; return 1 }
342 local IPV6ADDR=$(printf "2002:%02x%02x:%02x%02x:1::1" $(print ${PUBLIC_IP//./ }))
343 print -n "Setting up ipv6 tunnel $IPV6ADDR via ${PUBLIC_IP}: "
344 ifconfig sit0 tunnel ::192.88.99.1 up
345 ifconfig sit1 add "$IPV6ADDR" && print done || print failed
346 fi
347 ;;
348 status)
349 if ifconfig sit1 2>/dev/null | grep -q 'inet6 addr: 2002:.*:1::1' ; then
350 print 'ipv6 tunnel available' ; return 0
351 else
352 print 'ipv6 tunnel not available' ; return 1
353 fi
354 ;;
355 stop)
356 if ifconfig sit1 2>/dev/null | grep -q 'inet6 addr: 2002:.*:1::1' ; then
357 print -n 'Stopping ipv6 tunnel (sit0 + sit1): '
358 ifconfig sit1 down ; ifconfig sit0 down && print done || print failed
359 else
360 print 'No ipv6 tunnel found, nothing to be done.' ; return 1
361 fi
362 ;;
363 *)
364 print "Usage: ipv6-tunnel [start|stop|status]">&2 ; return 1
365 ;;
366 esac
367 }
368
369 # run dhclient for wireless device
370 iwclient() {
371 salias dhclient "$(wavemon -d | awk '/device/{print $2}')"
372 }
373
374 # spawn a minimally set up mksh - useful if you want to umount /usr/.
375 minimal-shell() {
376 emulate -L zsh
377 local shell="/bin/mksh"
378
379 if [[ ! -x ${shell} ]]; then
380 printf '`%s'\'' not available, giving up.\n' ${shell} >&2
381 return 1
382 fi
383
384 exec env -i ENV="/etc/minimal-shellrc" HOME="$HOME" TERM="$TERM" ${shell}
385 }
386
387 #f1# grep for patterns in grml's zsh setup
388 zg() {
389 #{{{
390 LANG=C perl -e '
391
392 sub usage {
393 print "usage: zg -[anr] <pattern>\n";
394 print " Search for patterns in grml'\''s zshrc.\n";
395 print " zg takes no or exactly one option plus a non empty pattern.\n\n";
396 print " options:\n";
397 print " -- no options (use if your pattern starts in with a dash.\n";
398 print " -a search for the pattern in all code regions\n";
399 print " -n search for the pattern in non-root code only\n";
400 print " -r search in code for everyone (also root) only\n\n";
401 print " The default is -a for non-root users and -r for root.\n\n";
402 print " If you installed the zshrc to a non-default locations (ie *NOT*\n";
403 print " in /etc/zsh/zshrc) do: export GRML_ZSHRC=\$HOME/.zshrc\n";
404 print " ...in case you copied the file to that location.\n\n";
405 exit 1;
406 }
407
408 if ($ENV{GRML_ZSHRC} ne "") {
409 $RC = $ENV{GRML_ZSHRC};
410 } else {
411 $RC = "/etc/zsh/zshrc";
412 }
413
414 usage if ($#ARGV < 0 || $#ARGV > 1);
415 if ($> == 0) { $mode = "allonly"; }
416 else { $mode = "all"; }
417
418 $opt = $ARGV[0];
419 if ($opt eq "--") { shift; }
420 elsif ($opt eq "-a") { $mode = "all"; shift; }
421 elsif ($opt eq "-n") { $mode = "nonroot"; shift; }
422 elsif ($opt eq "-r" ) { $mode = "allonly"; shift; }
423 elsif ($opt =~ m/^-/ || $#ARGV > 0) { usage(); }
424
425 $pattern = $ARGV[0];
426 usage() if ($pattern eq "");
427
428 open FH, "<$RC" or die "zg: Could not open $RC: $!\n";
429 while ($line = <FH>) {
430 chomp $line;
431 if ($line =~ m/^#:grep:marker:for:mika:/) { $markerfound = 1; next; }
432 next if ($mode eq "nonroot" && markerfound == 0);
433 break if ($mode eq "allonly" && markerfound == 1);
434 print $line, "\n" if ($line =~ /$pattern/);
435 }
436 close FH;
437 exit 0;
438
439 ' -- "$@"
440 #}}}
441 return $?
442 }
443
444 # {{{ wonderful idea of using "e" glob qualifier by Peter Stephenson
445 # You use it as follows:
446 # $ NTREF=/reference/file
447 # $ ls -l *(e:nt:)
448 # This lists all the files in the current directory newer than the reference file.
449 # You can also specify the reference file inline; note quotes:
450 # $ ls -l *(e:'nt ~/.zshenv':)
451 nt() {
452 if [[ -n $1 ]] ; then
453 local NTREF=${~1}
454 fi
455 [[ $REPLY -nt $NTREF ]]
456 }
457 # }}}
458
459 # shell functions {{{
460
461 #f1# Provide csh compatibility
462 setenv() { typeset -x "${1}${1:+=}${(@)argv[2,$#]}" } # csh compatibility
463
464 #f1# Reload an autoloadable function
465 freload() { while (( $# )); do; unfunction $1; autoload -U $1; shift; done }
466 compdef _functions freload
467
468 #f1# List symlinks in detail (more detailed version of 'readlink -f' and 'whence -s')
469 sll() {
470 [[ -z "$1" ]] && printf 'Usage: %s <file(s)>\n' "$0" && return 1
471 for file in "$@" ; do
472 while [[ -h "$file" ]] ; do
473 ls -l $file
474 file=$(readlink "$file")
475 done
476 done
477 }
478
479 # fast manual access
480 if check_com qma ; then
481 #f1# View the zsh manual
482 manzsh() { qma zshall "$1" }
483 compdef _man qma
484 else
485 manzsh() { /usr/bin/man zshall | vim -c "se ft=man| se hlsearch" +/"$1" - ; }
486 fi
487
488 # zsh profiling
489 profile() {
490 ZSH_PROFILE_RC=1 $SHELL "$@"
491 }
492
493 #f1# Edit an alias via zle
494 edalias() {
495 [[ -z "$1" ]] && { echo "Usage: edalias <alias_to_edit>" ; return 1 } || vared aliases'[$1]' ;
496 }
497 compdef _aliases edalias
498
499 #f1# Edit a function via zle
500 edfunc() {
501 [[ -z "$1" ]] && { echo "Usage: edfun <function_to_edit>" ; return 1 } || zed -f "$1" ;
502 }
503 compdef _functions edfunc
504
505 #f1# Provides useful information on globbing
506 H-Glob() {
507 echo -e "
508 / directories
509 . plain files
510 @ symbolic links
511 = sockets
512 p named pipes (FIFOs)
513 * executable plain files (0100)
514 % device files (character or block special)
515 %b block special files
516 %c character special files
517 r owner-readable files (0400)
518 w owner-writable files (0200)
519 x owner-executable files (0100)
520 A group-readable files (0040)
521 I group-writable files (0020)
522 E group-executable files (0010)
523 R world-readable files (0004)
524 W world-writable files (0002)
525 X world-executable files (0001)
526 s setuid files (04000)
527 S setgid files (02000)
528 t files with the sticky bit (01000)
529
530 print *(m-1) # Files modified up to a day ago
531 print *(a1) # Files accessed a day ago
532 print *(@) # Just symlinks
533 print *(Lk+50) # Files bigger than 50 kilobytes
534 print *(Lk-50) # Files smaller than 50 kilobytes
535 print **/*.c # All *.c files recursively starting in \$PWD
536 print **/*.c~file.c # Same as above, but excluding 'file.c'
537 print (foo|bar).* # Files starting with 'foo' or 'bar'
538 print *~*.* # All Files that do not contain a dot
539 chmod 644 *(.^x) # make all plain non-executable files publically readable
540 print -l *(.c|.h) # Lists *.c and *.h
541 print **/*(g:users:) # Recursively match all files that are owned by group 'users'
542 echo /proc/*/cwd(:h:t:s/self//) # Analogous to >ps ax | awk '{print $1}'<"
543 }
544 alias help-zshglob=H-Glob #dépendant du truc au dessus
545
546 function swapfiles(){
547 TMPF="/tmp/tmp.$$"
548 mv -f $1 $TMPF
549 mv -f $2 $1
550 mv -f $TMPF $2
551 }