]> gitweb.pimeys.fr Git - config-20-100.git/blob - .zsh/rc/extra/05_useful_functions
Ajout du zshrc, même s'il manque encore de commentaires etc.
[config-20-100.git] / .zsh / rc / extra / 05_useful_functions
1 #!/bin/zsh
2
3 #f5# Backup \kbd{file {\rm to} file\_timestamp}
4 bk() {
5 emulate -L zsh
6 cp -b $1 $1_`date --iso-8601=m`
7 }
8
9 #f5# cd to directoy and list files
10 cl() {
11 emulate -L zsh
12 cd $1 && ls -al
13 }
14
15 #f5# Create Directoy and \kbd{cd} to it
16 mcd() {
17 mkdir -p "$@" && cd "$@"
18 }
19
20 #f5# Memory overview
21 memusage() {
22 ps aux | awk '{if (NR > 1) print $5; if (NR > 2) print "+"} END { print "p" }' | dc
23 }
24
25 # Function Usage: doc packagename
26 #f5# \kbd{cd} to /usr/share/doc/\textit{package}
27 doc() {
28 emulate -L zsh
29 cd /usr/share/doc/$1 && ls
30 }
31 _doc() { _files -W /usr/share/doc -/ }
32 check_com compdef && compdef _doc doc
33
34 #f5# Grep in history
35 greph() {
36 emulate -L zsh
37 history 0 | grep $1
38 }
39
40 #f5# Watch manpages in a stretched style
41 man2() { PAGER='dash -c "sed G | /usr/bin/less"' command man "$@" ; }
42
43 #f5# Clean up directory - remove well known tempfiles
44 purge() {
45 FILES=(*~(N) .*~(N) \#*\#(N) *.o(N) a.out(N) *.core(N) *.cmo(N) *.cmi(N) .*.swp(N) .*.COMPILED)
46 NBFILES=${#FILES}
47 if [[ $NBFILES > 0 ]] ; then
48 print $FILES
49 local ans
50 echo -n "Remove these files? [y/n] "
51 read -q ans
52 if [[ $ans == "y" ]] ; then
53 rm ${FILES}
54 echo ">> $PWD purged, $NBFILES files removed"
55 else
56 echo "Ok. .. then not.."
57 fi
58 fi
59 }
60
61 #f5# List all occurrences of programm in current PATH
62 plap() {
63 emulate -L zsh
64 if [[ $# = 0 ]] ; then
65 echo "Usage: $0 program"
66 echo "Example: $0 zsh"
67 echo "Lists all occurrences of program in the current PATH."
68 else
69 ls -l ${^path}/*$1*(*N)
70 fi
71 }
72
73 # Usage: simple-extract <file>
74 #f5# Smart archive extractor
75 simple-extract () {
76 emulate -L zsh
77 if [[ -f $1 ]] ; then
78 case $1 in
79 *.tar.bz2) bzip2 -v -d $1 ;;
80 *.tar.gz) tar -xvzf $1 ;;
81 *.rar) unrar $1 ;;
82 *.deb) ar -x $1 ;;
83 *.bz2) bzip2 -d $1 ;;
84 *.lzh) lha x $1 ;;
85 *.gz) gunzip -d $1 ;;
86 *.tar) tar -xvf $1 ;;
87 *.tgz) gunzip -d $1 ;;
88 *.tbz2) tar -jxvf $1 ;;
89 *.zip) unzip $1 ;;
90 *.Z) uncompress $1 ;;
91 *) echo "'$1' Error. Please go away" ;;
92 esac
93 else
94 echo "'$1' is not a valid file"
95 fi
96 }
97
98 # Usage: smartcompress <file> (<type>)
99 #f5# Smart archive creator
100 smartcompress() {
101 emulate -L zsh
102 if [[ -n $2 ]] ; then
103 case $2 in
104 tgz | tar.gz) tar -zcvf$1.$2 $1 ;;
105 tbz2 | tar.bz2) tar -jcvf$1.$2 $1 ;;
106 tar.Z) tar -Zcvf$1.$2 $1 ;;
107 tar) tar -cvf$1.$2 $1 ;;
108 gz | gzip) gzip $1 ;;
109 bz2 | bzip2) bzip2 $1 ;;
110 *)
111 echo "Error: $2 is not a valid compression type"
112 ;;
113 esac
114 else
115 smartcompress $1 tar.gz
116 fi
117 }
118
119 # Usage: show-archive <archive>
120 #f5# List an archive's content
121 show-archive() {
122 emulate -L zsh
123 if [[ -f $1 ]] ; then
124 case $1 in
125 *.tar.gz) gunzip -c $1 | tar -tf - -- ;;
126 *.tar) tar -tf $1 ;;
127 *.tgz) tar -ztf $1 ;;
128 *.zip) unzip -l $1 ;;
129 *.bz2) bzless $1 ;;
130 *.deb) dpkg-deb --fsys-tarfile $1 | tar -tf - -- ;;
131 *) echo "'$1' Error. Please go away" ;;
132 esac
133 else
134 echo "'$1' is not a valid archive"
135 fi
136 }
137
138 # It's shameless stolen from <http://www.vim.org/tips/tip.php?tip_id=167>
139 #f5# Use \kbd{vim} as your manpage reader
140 vman() {
141 emulate -L zsh
142 man $* | col -b | view -c 'set ft=man nomod nolist' -
143 }
144
145 # TODO: So, this is the third incarnation of this function!?
146 #f5# Reload given functions
147 refunc() {
148 for func in $argv ; do
149 unfunction $func
150 autoload $func
151 done
152 }
153
154 # a small check to see which DIR is located on which server/partition.
155 # stolen and modified from Sven's zshrc.forall
156 #f5# Report diskusage of a directory
157 dirspace() {
158 emulate -L zsh
159 if [[ -n "$1" ]] ; then
160 for dir in "$@" ; do
161 if [[ -d "$dir" ]] ; then
162 ( cd $dir; echo "-<$dir>"; du -shx .; echo);
163 else
164 echo "warning: $dir does not exist" >&2
165 fi
166 done
167 else
168 for dir in $path; do
169 if [[ -d "$dir" ]] ; then
170 ( cd $dir; echo "-<$dir>"; du -shx .; echo);
171 else
172 echo "warning: $dir does not exist" >&2
173 fi
174 done
175 fi
176 }
177
178 #f5# Show some status info
179 status() {
180 print
181 print "Date..: "$(date "+%Y-%m-%d %H:%M:%S")
182 print "Shell.: Zsh $ZSH_VERSION (PID = $$, $SHLVL nests)"
183 print "Term..: $TTY ($TERM), ${BAUD:+$BAUD bauds, }$COLUMNS x $LINES chars"
184 print "Login.: $LOGNAME (UID = $EUID) on $HOST"
185 print "Groups: $(groups)"
186 print "System: $(cat /etc/[A-Za-z]*[_-][rv]e[lr]*)"
187 print "Uptime:$(uptime)"
188 print
189 }
190
191 #f5# RFC 2396 URL encoding in Z-Shell
192 urlencode() {
193 emulate -L zsh
194 setopt extendedglob
195 input=( ${(s::)1} )
196 print ${(j::)input/(#b)([^A-Za-z0-9_.!~*\'\(\)-])/%${(l:2::0:)$(([##16]#match))}}
197 }
198
199 #f5# Indent source code
200 smart-indent() {
201 indent -npro -kr -i8 -ts8 -sob -l80 -ss -ncs "$@"
202 }
203
204 # hl() highlighted less
205 # http://ft.bewatermyfriend.org/comp/data/zsh/zfunct.html
206 if check_com -c highlight ; then
207 function hl() {
208 emulate -L zsh
209 local theme lang
210 theme=${HL_THEME:-""}
211 case ${1} in
212 (-l|--list)
213 ( printf 'available languages (syntax parameter):\n\n' ;
214 highlight --list-langs ; ) | less -SMr
215 ;;
216 (-t|--themes)
217 ( printf 'available themes (style parameter):\n\n' ;
218 highlight --list-themes ; ) | less -SMr
219 ;;
220 (-h|--help)
221 printf 'usage: hl <syntax[:theme]> <file>\n'
222 printf ' available options: --list (-l), --themes (-t), --help (-h)\n\n'
223 printf ' Example: hl c main.c\n'
224 ;;
225 (*)
226 if [[ -z ${2} ]] || (( ${#argv} > 2 )) ; then
227 printf 'usage: hl <syntax[:theme]> <file>\n'
228 printf ' available options: --list (-l), --themes (-t), --help (-h)\n'
229 (( ${#argv} > 2 )) && printf ' Too many arguments.\n'
230 return 1
231 fi
232 lang=${1%:*}
233 [[ ${1} == *:* ]] && [[ -n ${1#*:} ]] && theme=${1#*:}
234 if [[ -n ${theme} ]] ; then
235 highlight --xterm256 --syntax ${lang} --style ${theme} ${2} | less -SMr
236 else
237 highlight --ansi --syntax ${lang} ${2} | less -SMr
238 fi
239 ;;
240 esac
241 return 0
242 }
243 # ... and a proper completion for hl()
244 # needs 'highlight' as well, so it fits fine in here.
245 function _hl_genarg() {
246 local expl
247 if [[ -prefix 1 *: ]] ; then
248 local themes
249 themes=(${${${(f)"$(LC_ALL=C highlight --list-themes)"}/ #/}:#*(Installed|Use name)*})
250 compset -P 1 '*:'
251 _wanted -C list themes expl theme compadd ${themes}
252 else
253 local langs
254 langs=(${${${(f)"$(LC_ALL=C highlight --list-langs)"}/ #/}:#*(Installed|Use name)*})
255 _wanted -C list languages expl languages compadd -S ':' -q ${langs}
256 fi
257 }
258 function _hl_complete() {
259 _arguments -s '1: :_hl_genarg' '2:files:_path_files'
260 }
261 compdef _hl_complete hl
262 fi
263
264 # Create small urls via http://tinyurl.com using wget(1).
265 function tinyurl() {
266 emulate -L zsh
267 [[ -z $1 ]] && { print "USAGE: tinyurl <URL>" ; return 1 }
268
269 local PN url tiny grabber search result preview
270 PN=$0
271 url=$1
272 # Check existence of given URL with the help of ping(1).
273 # N.B. ping(1) only works without an eventual given protocol.
274 ping -c 1 ${${url#(ftp|http)://}%%/*} >& /dev/null || \
275 read -q "?Given host ${${url#http://*/}%/*} is not reachable by pinging. Proceed anyway? [y|n] "
276
277 if (( $? == 0 )) ; then
278 # Prepend 'http://' to given URL where necessary for later output.
279 [[ ${url} != http(s|)://* ]] && url='http://'${url}
280 tiny='http://tinyurl.com/create.php?url='
281 if check_com -c wget ; then
282 grabber='wget -O- -o/dev/null'
283 else
284 print "wget is not available, but mandatory for ${PN}. Aborting."
285 fi
286 # Looking for i.e.`copy('http://tinyurl.com/7efkze')' in TinyURL's HTML code.
287 search='copy\(?http://tinyurl.com/[[:alnum:]]##*'
288 result=${(M)${${${(f)"$(${=grabber} ${tiny}${url})"}[(fr)${search}*]}//[()\';]/}%%http:*}
289 # TinyURL provides the rather new feature preview for more confidence. <http://tinyurl.com/preview.php>
290 preview='http://preview.'${result#http://}
291
292 printf '%s\n\n' "${PN} - Shrinking long URLs via webservice TinyURL <http://tinyurl.com>."
293 printf '%s\t%s\n\n' 'Given URL:' ${url}
294 printf '%s\t%s\n\t\t%s\n' 'TinyURL:' ${result} ${preview}
295 else
296 return 1
297 fi
298 }
299
300 #f2# Print a specific line of file(s).
301 linenr () {
302 # {{{
303 emulate -L zsh
304 if [ $# -lt 2 ] ; then
305 print "Usage: linenr <number>[,<number>] <file>" ; return 1
306 elif [ $# -eq 2 ] ; then
307 local number=$1
308 local file=$2
309 command ed -s $file <<< "${number}n"
310 else
311 local number=$1
312 shift
313 for file in "$@" ; do
314 if [ ! -d $file ] ; then
315 echo "${file}:"
316 command ed -s $file <<< "${number}n" 2> /dev/null
317 else
318 continue
319 fi
320 done | less
321 fi
322 # }}}
323 }
324
325 # use it e.g. via 'Restart apache2'
326 #m# f6 Start() \kbd{/etc/init.d/\em{process}}\quad\kbd{start}
327 #m# f6 Restart() \kbd{/etc/init.d/\em{process}}\quad\kbd{restart}
328 #m# f6 Stop() \kbd{/etc/init.d/\em{process}}\quad\kbd{stop}
329 #m# f6 Reload() \kbd{/etc/init.d/\em{process}}\quad\kbd{reload}
330 #m# f6 Force-Reload() \kbd{/etc/init.d/\em{process}}\quad\kbd{force-reload}
331 if [[ -d /etc/init.d || -d /etc/service ]] ; then
332 __start_stop() {
333 local action_="${1:l}" # e.g Start/Stop/Restart
334 local service_="$2"
335 local param_="$3"
336
337 local service_target_="$(readlink /etc/init.d/$service_)"
338 if [[ $service_target_ == "/usr/bin/sv" ]]; then
339 # runit
340 case "${action_}" in
341 start) if [[ ! -e /etc/service/$service_ ]]; then
342 $SUDO ln -s "/etc/sv/$service_" "/etc/service/"
343 else
344 $SUDO "/etc/init.d/$service_" "${action_}" "$param_"
345 fi ;;
346 # there is no reload in runits sysv emulation
347 reload) $SUDO "/etc/init.d/$service_" "force-reload" "$param_" ;;
348 *) $SUDO "/etc/init.d/$service_" "${action_}" "$param_" ;;
349 esac
350 else
351 # sysvinit
352 $SUDO "/etc/init.d/$service_" "${action_}" "$param_"
353 fi
354 }
355
356 for i in Start Restart Stop Force-Reload Reload ; do
357 eval "$i() { __start_stop $i \"\$1\" \"\$2\" ; }"
358 done
359 fi
360
361 # grep for running process, like: 'any vim'
362 any() {
363 emulate -L zsh
364 if [[ -z "$1" ]] ; then
365 echo "any - grep for process(es) by keyword" >&2
366 echo "Usage: any <keyword>" >&2 ; return 1
367 else
368 local STRING=$1
369 local LENGTH=$(expr length $STRING)
370 local FIRSCHAR=$(echo $(expr substr $STRING 1 1))
371 local REST=$(echo $(expr substr $STRING 2 $LENGTH))
372 ps xauwww| grep "[$FIRSCHAR]$REST"
373 fi
374 }
375
376 # After resuming from suspend, system is paging heavily, leading to very bad interactivity.
377 # taken from $LINUX-KERNELSOURCE/Documentation/power/swsusp.txt
378 [[ -r /proc/1/maps ]] && \
379 deswap() {
380 print 'Reading /proc/[0-9]*/maps and sending output to /dev/null, this might take a while.'
381 cat $(sed -ne 's:.* /:/:p' /proc/[0-9]*/maps | sort -u | grep -v '^/dev/') > /dev/null
382 print 'Finished, running "swapoff -a; swapon -a" may also be useful.'
383 }
384
385 # print hex value of a number
386 hex() {
387 emulate -L zsh
388 [[ -n "$1" ]] && printf "%x\n" $1 || { print 'Usage: hex <number-to-convert>' ; return 1 }
389 }
390
391 # calculate (or eval at all ;-)) with perl => p[erl-]eval
392 # hint: also take a look at zcalc -> 'autoload zcalc' -> 'man zshmodules | less -p MATHFUNC'
393 peval() {
394 [[ -n "$1" ]] && CALC="$*" || print "Usage: calc [expression]"
395 perl -e "print eval($CALC),\"\n\";"
396 }
397 functions peval &>/dev/null && alias calc=peval
398
399 # brltty seems to have problems with utf8 environment and/or font Uni3-Terminus16 under
400 # certain circumstances, so work around it, no matter which environment we have
401 brltty() {
402 if [[ -z "$DISPLAY" ]] ; then
403 consolechars -f /usr/share/consolefonts/default8x16.psf.gz
404 command brltty "$@"
405 else
406 command brltty "$@"
407 fi
408 }
409
410 # switches two files
411 permute() {
412 F1=${1##*/}
413 cp $1 /tmp/$F1 && cp $2 $1 && mv /tmp/$F1 $2
414 }