Update.
[scripts.git] / bashrc
1 # -*-Shell-script-*-
2
3 # PS4='+ $(date "+%s.%N")\011 '
4 # set -x
5
6 #########################################################################
7 # This program is free software: you can redistribute it and/or modify  #
8 # it under the terms of the version 3 of the GNU General Public License #
9 # as published by the Free Software Foundation.                         #
10 #                                                                       #
11 # This program is distributed in the hope that it will be useful, but   #
12 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
14 # General Public License for more details.                              #
15 #                                                                       #
16 # You should have received a copy of the GNU General Public License     #
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
18 #                                                                       #
19 # Written by and Copyright (C) Francois Fleuret                         #
20 # Contact <francois@fleuret.org> for comments & bug reports             #
21 #########################################################################
22
23 # The site-specific and confidential settings are in another file
24
25 PRIVATE_BASHRC="${HOME}/private/bashrc.perso"
26
27 # If the MANPATH is not set, set it
28
29 [[ "${MANPATH}" ]] || MANPATH=$(manpath)
30
31 # If the private bashrc exists, execute it
32
33 [[ -f "${PRIVATE_BASHRC}" ]] && source "${PRIVATE_BASHRC}"
34
35 # !!! THIS HAS TO BE HERE EVEN IN THE NON-INTERACTIVE PART OR YOU WILL
36 # LOSE YOU PREVIOUS HISTORY !!!
37
38 export HISTFILESIZE=20000
39 export HISTSIZE=${HISTFILESIZE}
40
41 export HISTIGNORE="${HISTIGNORE}:&:[ ]*"
42
43 # I want to save the command time, but I do not want to see it in
44 # history
45
46 export HISTTIMEFORMAT=""
47
48 shopt -s histappend
49
50 # I realized that most of my settings are meaningful only in
51 # interactive mode. This should maybe be done more properly through
52 # using different .bash_profile and .bash_login
53
54 [ ${TERM} == "dumb" ] || [[ ! -t 0 ]] && return
55
56 # Remove the annoying beeps in console
57
58 # setterm -blength 0
59
60 # || setterm --blength 0 # Seriously?
61
62 ######################################################################
63 ## The interactive part
64
65 export VT_RESET=$'\e[0m'
66 export VT_BOLD=$'\e[1m'
67 export VT_UNDERLINE=$'\e[4m'
68 export VT_BLINK=$'\e[5m'
69
70 export VT_SET_TITLE=$'\e]0;'
71 export VT_END_TITLE=$'\007'
72
73 export VT_BLACK_FG=$'\e[30m'
74 export VT_RED_FG=$'\e[31m'
75 export VT_GREEN_FG=$'\e[32m'
76 export VT_YELLOW_FG=$'\e[33m'
77 export VT_BLUE_FG=$'\e[34m'
78 export VT_MAGENTA_FG=$'\e[35m'
79 export VT_CYAN_FG=$'\e[36m'
80 export VT_WHITE_FG=$'\e[37m'
81
82 export VT_BLACK_BG=$'\e[40m'
83 export VT_RED_BG=$'\e[41m'
84 export VT_GREEN_BG=$'\e[42m'
85 export VT_YELLOW_BG=$'\e[43m'
86 export VT_BLUE_BG=$'\e[44m'
87 export VT_MAGENTA_BG=$'\e[45m'
88 export VT_CYAN_BG=$'\e[46m'
89 export VT_WHITE_BG=$'\e[47m'
90
91 # Colorize man pages!
92
93 export LESS_TERMCAP_us=${VT_GREEN_FG}
94 export LESS_TERMCAP_ue=${VT_RESET}
95 export LESS_TERMCAP_md=${VT_BLUE_FG}${VT_BOLD}
96 export LESS_TERMCAP_me=${VT_RESET}
97
98 # I do not like to clutter my home with history files
99
100 export LESSHISTFILE=/dev/null
101
102 # export LESS_TERMCAP_md=$'\e[1;34;40m'
103
104 # This prevents ^S from freezing the shell
105
106 # stty -ixon
107
108 ulimit -c unlimited
109
110 alias ..='cd ..'
111 alias -- -='cd -'
112 alias rm='rm -v -i'
113 alias mv='mv -v -i'
114 alias chmod='chmod -c'
115 alias cp='cp -v -i'
116 alias rd=rmdir
117 alias md='mkdir -pv'
118 alias ps='ps uxaf'
119 alias df='df -hT'
120 # alias df='df -hT --sync'
121 alias grep='grep -i -E --color=auto'
122 alias find='ionice -c3 find'
123 alias pd=pushd
124 alias val='valgrind --leak-check=full --show-reachable=yes --db-attach=yes '
125
126 alias s='screen -d -R default -U && clear'
127 alias p='feh --force-aliasing -d --full-screen --auto-zoom'
128 alias gp=gnuplot
129
130 function nh () {
131     export HISTFILE=/dev/null
132     unalias cd
133 }
134
135 function select-tz () {
136     # Select a value for TZ
137     TMP=$(mktemp /tmp/select-tz.XXXXXX)
138     selector -o "${TMP}" <(grep -v ^# /usr/share/zoneinfo/zone.tab  | awk '{print $3}' | sort -u)
139     cat "${TMP}"
140     \rm -f "${TMP}"
141 }
142
143 function ding () {
144     if [[ $1 ]] && which winshepherd.sh
145     then
146         play -q ~/local/sounds/deskbell.wav &
147         unset E_APP_WINDOW
148         winshepherd.sh message green "$1"
149     else
150         play -q ~/local/sounds/deskbell.wav
151     fi
152 }
153
154 alias impressive="impressive -s -D 1000 -t Crossfade -T 100"
155
156 if [[ -e "${HOME}/.dircolors" ]]
157 then
158     eval $(dircolors "${HOME}/.dircolors")
159     alias ls='ls -p --group-directories-first --color'
160     alias lt='ls -p --color -gohtr --time-style="+%Y %b %d %H:%M"'
161     alias ll='ls -p --color -goh --time-style="+%Y %b %d %H:%M"'
162     alias lll='ls -p --color -lth'
163     alias l='ls -p --color -I "*~" -I "*.o"'
164     alias less='less -R'
165 else
166     alias ls='ls -p --group-directories-first'
167     alias lt='ls -p -gohtr --time-style="+%Y %b %d %H:%M"'
168     alias ll='ls -p -goh --time-style="+%Y %b %d %H:%M"'
169     alias lll='ls -p -lth'
170     alias l='ls -p -I "*~" -I "*.o"'
171 fi
172
173 export EDITOR=emacsclient
174 export GIT_EDITOR=${EDITOR}
175
176 ######################################################################
177 # Ignored extensions when completing
178
179 # export FIGNORE="CVS"
180
181 function latexdiff () {
182     wdiff -n \
183         -w $'\033[30;41m' -x $'\033[0m' \
184         -y $'\033[30;42m' -z $'\033[0m' \
185         "$@"
186 }
187
188 # Looks for the most recent .log and pdflatex + bibtex the
189 # corresponding tex file
190
191 function rl () {
192     # RECENT_LOG=$(ls -t $(find -maxdepth 1 -name "*.log" -type f) | head -1)
193
194     RECENT_LOG=$(ls -t *.log | head -1)
195
196     if [[ ${RECENT_LOG} ]]
197     then
198         FILEBASE="${RECENT_LOG/.log/}"
199
200         if [[ -f "${FILEBASE}.tex" ]]
201         then
202
203             pdflatex --shell-escape "${FILEBASE}"
204             bibtex "${FILEBASE}"
205             pdflatex --shell-escape "${FILEBASE}"
206             pdflatex --shell-escape "${FILEBASE}"
207
208             if [[ "$1" ]]
209             then
210                 if [[ "$1" == "-v" ]] || [[ "$1" == "--view" ]]
211                 then
212                     # xpdf "${FILEBASE}.pdf"
213                     zathura "${FILEBASE}.pdf"
214                 elif [[ "$1" == "-p" ]] || [[ "$1" == "--print" ]]
215                 then
216                     lpr "${FILEBASE}.pdf"
217                 else
218                     echo "Usage: rl [-v|--view] [-p|--print]" >&2
219                     echo "Unknown option $1" >&2
220                     return 1
221                 fi
222             fi
223
224         else
225
226             echo "Can not find a tex file corresponding to the most recent log (${RECENT_LOG/.log/})." >&2
227             return 1
228
229         fi
230
231     else
232         echo "Can not find a recent log." >&2
233         return 1
234     fi
235 }
236
237
238 ######################################################################
239 # Functions
240
241 # http://www.reddit.com/r/linux/comments/2cgu5k/a_handy_little_script_for_interacting_with_your/
242 function clip () {
243     if [[ -t 0 ]] && [[ -z "$1" ]]
244     then
245         # output contents of clipboard
246         xclip -out -selection clipboard || exit 1
247     elif [[ "$1" ]]
248     then
249         # copy file contents to clipboard
250         xclip -in -selection clipboard < "$1" || exit 1
251     else
252         # copy stdin to clipboard
253         xclip -in -selection clipboard <&0 || exit 1
254     fi
255 }
256
257 # Find a file whose name contains a substring
258
259 function fn () {
260     name=$1
261     shift
262     find "$@" -name "*${name}*";
263 }
264
265 function bak () {
266     while [[ "$1" ]]
267     do
268         cp "$1" "$1".bak
269         shift
270     done
271 }
272
273 function scan () {
274     n=1
275
276     while [[ -f "${HOME}/scan-${n}.jpg" ]]
277     do
278         n=$((n+1))
279     done
280
281     while [[ "$1" ]]
282     do
283         if [[ "$1" == "color" ]]
284         then
285             OPTS+=" --mode Color"
286         elif [[ "$1" == "gray" ]]
287         then
288             OPTS+=" --mode Gray"
289         elif [[ "$1" == "a4crop" ]]
290         then
291             OPTS+=" -l 5 -t 0 -x 200 -y 300"
292         elif [[ "$1" == "help" ]] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]
293         then
294             echo "$0 [color|gray] [a4crop]" && return 0
295         else
296             echo "Unknown argument \`$1'"
297         fi
298         shift
299     done
300
301     echo "**"
302     echo "** Scanning to ${HOME}/scan-${n}.jpg"
303     echo "**"
304
305     SCANNER=$(scanimage -L | grep "Canon LiDE 60" | sed -e "s/^.*\`\(.*\)'.*$/\1/")
306
307     scanimage -d ${SCANNER} \
308               --format=pnm \
309               --mode=color \
310               --depth=8 \
311               -v \
312               --resolution=300 \
313               ${OPTS} | \
314         convert -rotate 180 - "${HOME}/scan-${n}.jpg"
315
316     echo "** Done".
317 }
318
319 # A password generator
320
321 function genpw () {
322     PW=$(tr -dc A-Za-z0-9 < /dev/urandom | head -c16)
323     if [[ ! "$1" == "-s" ]]
324     then
325        echo "$(date) ${PW}" >> ${HOME}/private/genpw.log
326     fi
327     echo ${PW}
328     # tr -dc [:graph:] < /dev/urandom | head -c16
329     echo
330 }
331
332 function ua () {
333
334     [[ "$1" ]] || ( echo "Universal unarchive: ua <file> [<file> ...]" >&2 && return 1)
335
336     while [[ "$1" ]]
337     do
338
339         case "$1" in
340             *.tgz|*.tar.gz|*.tbz|*.tar.bz2)
341                 tar xvf "$1"
342                 ;;
343
344             *.rar)
345                 unrar -kb x "$1"
346                 ;;
347
348             *.zip)
349                 unzip "$1"
350                 ;;
351
352             *)
353                 echo "Unknown file extension $1"
354                 ;;
355         esac
356
357         shift
358
359     done
360 }
361
362 # Create a dir and cd there
363
364 function mcd () {
365     mkdir -vp "$1"
366     cd "$1"
367 }
368
369 # Capture the screen in a dated png
370
371 function cap () {
372     if [[ $2 ]]
373     then
374         name=$2
375     else
376         name="capture-$(date +%s).png"
377     fi
378
379     if [[ "$1" ]]
380     then
381         echo "Waiting $1 s and saving to ${name}."
382         sleep "$1"
383     else
384         echo "Saving to ${name}."
385     fi
386
387     echo "Please click on the window to capture."
388     xwd  | convert xwd:- ${name}
389     \ls -l ${name}
390 }
391
392 # Create and CD in a /tmp/tmp.XXXXXX directory. With the '-'
393 # arguments, do not create one and CD in the most recent instead
394
395 function cdt () {
396     if [[ "$1" ]]
397     then
398         if [[ "$1" == "-" ]]
399         then
400             cd $(\ls -td /tmp/tmp.?????? | head -1)
401         else
402             echo "USAGE: cdt [-]" >&2
403             return 1
404         fi
405     else
406         dir=$(mktemp -d /tmp/tmp.XXXXXX)
407         link=/tmp/tmp
408         if [[ -h ${link} ]]
409         then
410             \rm ${link}
411         fi
412         if [[ ! -a ${link} ]]
413         then
414             ln -s ${dir} ${link}
415         fi
416         cd ${dir}
417     fi
418 }
419
420 alias t='cd /tmp'
421 alias a='cd /tmp/at'
422
423 function trash () {
424     TRASH=$(date +/tmp/trash-${USER}-%Y-%b-%d-%Hh)
425     LINK=/tmp/trash
426
427     mkdir -p ${TRASH}
428
429     [[ -h ${LINK} ]] && \rm ${LINK}
430
431     [[ ! -f ${LINK} ]] && ln -s ${TRASH} ${LINK}
432
433     mv "$@" ${TRASH}
434     echo "Trashed $@"
435 }
436
437 function trashlatex () {
438     TRASH=$(date +/tmp/trash-latex-${USER}-%Y-%b-%d-%Hh)
439     LINK=/tmp/trash
440
441     mkdir -p ${TRASH}
442
443     [[ -h ${LINK} ]] && \rm ${LINK}
444
445     [[ ! -f ${LINK} ]] && ln -s ${TRASH} ${LINK}
446
447     mv -v \
448        *.log *.pdf *.aux *.nav *.pdfpc *.snm *.toc *.out \
449        *.bbl *.blg \
450        *.*.table *.*.gnuplot \
451        ${TRASH}
452 }
453
454 ######################################################################
455 ## A version of pho which stores the image numbers in environment
456 ## variables
457
458 function pho () {
459     TEMP=$(mktemp /tmp/pho.XXXXXXX)
460     $(which pho) "$@" | tee ${TEMP}
461     PHO_NOTE_1=$(grep ^"Note 1: " ${TEMP} | sed -e "s/^[^:]*: //")
462     PHO_NOTE_2=$(grep ^"Note 2: " ${TEMP} | sed -e "s/^[^:]*: //")
463     PHO_NOTE_3=$(grep ^"Note 3: " ${TEMP} | sed -e "s/^[^:]*: //")
464     PHO_NOTE_R90=$(grep ^"Rotate 90 \(CW\): " ${TEMP} | sed -e "s/^[^:]*: //")
465     PHO_NOTE_R180=$(grep ^"Rotate 180: " ${TEMP} | sed -e "s/^[^:]*: //")
466     PHO_NOTE_R270=$(grep ^"Rotate -90 \(CCW\): " ${TEMP} | sed -e "s/^[^:]*: //")
467     [[ "${PHO_NOTE_1}" ]] || unset PHO_NOTE_1
468     [[ "${PHO_NOTE_2}" ]] || unset PHO_NOTE_2
469     [[ "${PHO_NOTE_3}" ]] || unset PHO_NOTE_3
470     [[ "${PHO_NOTE_R90}" ]] || unset PHO_NOTE_R90
471     [[ "${PHO_NOTE_R180}" ]] || unset PHO_NOTE_R180
472     [[ "${PHO_NOTE_R270}" ]] || unset PHO_NOTE_R270
473     \rm ${TEMP}
474 }
475
476 ######################################################################
477 ## A version of date that shows the time at home if TZ is set
478
479 function dt () {
480     echo "Local - $(date)"
481     unset TZ
482     echo "Home  - $(date)"
483 }
484
485 ######################################################################
486 ## ifup / ifdown with sudo
487
488 [ ${NETUP_HISTORY} ] || NETUP_HISTORY="${HOME}/.netup_history"
489
490 function netup () {
491     local upped_wifi
492
493     [[ "${WIFI_INTERFACE}" ]] || WIFI_INTERFACE=wlan0
494
495     if [[ "$1" == "--scan" ]]
496     then
497         if ifconfig -s | grep -v -q ${WIFI_INTERFACE}
498         then
499             sudo ifconfig ${WIFI_INTERFACE} up
500             upped_wifi=1
501         fi
502
503         sudo iwlist ${WIFI_INTERFACE} scan | \grep -E 'ESS|Quali|Encry' | sed -e 's/^[ \t]*//'
504
505         if [[ ${upped_wifi} ]]
506         then
507             sudo ifconfig ${WIFI_INTERFACE} down
508             unset upped_wifi
509         fi
510
511         return 0
512     fi
513
514     if \ifconfig -s | grep -q -v ^'(Iface|lo) '
515     then
516         echo "There is/are already interface(s) up." >&2
517         return 1
518     fi
519
520     if \ps h -C dhclient | grep -q .
521     then
522         echo "There is already a dhcp client running." >&2
523         return 1
524     fi
525
526     if \ps h -C wpa_supplicant | grep -q .
527     then
528         echo "There is already a wpa_supplicant running." >&2
529         return 1
530     fi
531
532     if [[ ! "$@" ]] && [[ -s ${NETUP_HISTORY} ]]
533     then
534         echo "netup <interface>" >&2
535         return 1
536         # # If we have no argument and there is a .netup_history, use it
537         # ARGS=$(cat ${NETUP_HISTORY})
538     else
539         # Otherwise uses the given arguments, and store them
540         ARGS="$@"
541         echo ${ARGS} > ${NETUP_HISTORY}
542     fi
543
544     if [[ "${PRIVATE_INTERFACE_DEFINITION}" ]]
545     then
546         ARGS="-i ${PRIVATE_INTERFACE_DEFINITION} ${ARGS}"
547     fi
548
549     echo "Executing ${VT_GREEN_FG}[sudo ifup ${ARGS}]${VT_RESET}"
550     sudo ifup ${ARGS}
551
552     # Ugly hack to remove the dsl modem dns server when we add
553     # explicitely a dns in the /etc/network/interfaces
554
555     REMOVE_LOCAL_DNS=/usr/local/bin/remove-local-dns.sh
556     # REMOVE_LOCAL_DNS=${HOME}/sources/scripts/remove-local-dns.sh
557
558     if [[ -x ${REMOVE_LOCAL_DNS} ]]
559     then
560         echo "Executing ${VT_GREEN_FG}[sudo ${REMOVE_LOCAL_DNS} 192.168]${VT_RESET}"
561         sudo ${REMOVE_LOCAL_DNS} 192.168
562     fi
563 }
564
565 function netdown () {
566     if [[ ! "$@" ]] && [[ -s ${NETUP_HISTORY} ]]
567     then
568         # If there are no arguments and there is a .netup_history, get the
569         # interface from it
570         ARGS=$(tail -1 ${NETUP_HISTORY} | sed -e "s/=.*$//")
571     else
572         # Otherwise, use the standard ifdown
573         ARGS="$@"
574     fi
575
576     [[ "${PRIVATE_INTERFACE_DEFINITION}" ]] && ARGS="-i ${PRIVATE_INTERFACE_DEFINITION} ${ARGS}"
577
578     echo "Executing sudo ${VT_GREEN_FG}[ifdown ${ARGS}]${VT_RESET}"
579     sudo ifdown ${ARGS}
580
581     # if [[ $(\ps -C dhclient | tail -n +2) ]]
582     # then
583     # echo "There is still a dhcp client running." >&2
584     # return 1
585     # fi
586
587     # if [[ $(\ps -C wpa_supplicant | tail -n +2) ]]
588     # then
589     # echo "There is still a wpa_supplicant running." >&2
590     # return 1
591     # fi
592 }
593
594 function checkgw () {
595     GW=$(route -n | grep ^0.0.0.0 | awk '{print $2}')
596     if [[ "${GW}" ]]
597     then
598         ping ${GW}
599     else
600         echo "Can not find a getaway." >&2
601         return 1
602     fi
603 }
604
605 ######################################################################
606 # Show the most recent files, no scroll
607
608 function lr () {
609     TERM_SIZE=($(stty size))
610     INVIS="${VT_GREEN_FG}${VT_RESET}"
611     \ls -goth --time-style="+${VT_GREEN_FG}%Y %b %d %H:%M${VT_RESET}" "$@" | \
612         head -$((TERM_SIZE[0]-2)) | cut -b1-$((TERM_SIZE[1]+${#INVIS}))
613 }
614
615 ######################################################################
616
617 reduce-pdf () {
618
619     # /screen selects low-resolution output
620     # /ebook selects medium-resolution output
621     # /printer selects "Print Optimized" setting.
622     # /prepress selects "Prepress Optimized" setting.
623
624     quality="printer"
625
626     while [[ "$1" ]]
627     do
628         if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]
629         then
630             echo "$0 [<file.pdf>|--quality <screen|ebook|printer|prepress>] ..."
631             return 0
632
633         elif [[ "$1" == "--quality" ]]
634         then
635             shift
636             quality="$1"
637
638         elif [[ -f "$1" ]]
639         then
640             result="$(basename "$1" .pdf)-${quality}.pdf"
641             echo -n "Generating ${result} with quality ${quality} ... "
642             gs -sDEVICE=pdfwrite \
643                -dCompatibilityLevel=1.4 \
644                -dPDFSETTINGS=/${quality} \
645                -dColorConversionStrategy=/LeaveColorUnchanged \
646                -dNOPAUSE -dQUIET -dBATCH \
647                -sOutputFile="${result}" "$1"
648             echo "done."
649             ls -hl "$1" "${result}"
650
651         else
652             echo "Cannot fine $1"
653
654         fi
655         shift
656     done
657 }
658
659 ######################################################################
660 # You can change the xterm background color on the fly!
661
662 function setxtermbg () {
663     echo -n $'\e]11;'$1$'\007'
664 }
665
666 ######################################################################
667 # Shuffle the lines from the stdin
668
669 function shuffle () {
670     SEED=$1
671     [[ $SEED ]] || SEED=0
672     awk 'BEGIN{srand('${SEED}')} { print rand()" "$0 }' | sort -g | sed -e "s/^[0-9\.e\-]* //"
673 }
674
675 ######################################################################
676 # Stores the last entered command into a file
677
678 KEPT_COMMANDS=${HOME}/.kept_bash_commands
679
680 function keep () {
681     if [[ ${KEPT_COMMANDS} ]]
682     then
683         TOKEEP=$(mktemp /tmp/keep.XXXXXX)
684         if [[ "$@" ]]
685         then
686             echo "$@" > ${TOKEEP}
687         else
688             selector -b -i -d -l ${HISTSIZE} -o "${TOKEEP}" <(history)
689         fi
690
691         if [[ -s "${TOKEEP}" ]]
692         then
693             echo $(date)": "$(cat ${TOKEEP}) >> ${KEPT_COMMANDS}
694             cat "${TOKEEP}"
695         else
696             echo "No command stored!"
697         fi
698
699         \rm ${TOKEEP}
700     else
701         echo "You have to set \$KEPT_COMMANDS"
702     fi
703 }
704
705 ######################################################################
706 # I sometime burn CDs and DVDs
707
708 function burn () {
709     [[ "${DEV_BURNER}" ]] || DEV_BURNER="/dev/sr0"
710     if [[ ! "$1" ]]
711     then
712         echo "burn <iso name | dirname>" >&2
713     elif [[ -f "$1" ]]
714     then
715         if [[ $(file "$1" | \grep -E 'ISO 9660|UDF filesystem data') ]]
716         then
717             wodim -eject -v dev=${DEV_BURNER} "$1"
718         else
719             echo "Do not know what to do with $1" >&2
720         fi
721     elif [[ -d "$1" ]]
722     then
723         [[ "${TMP_ROOT}" ]] || TMP_ROOT=/tmp/
724         echo "Using ${TMP_ROOT} as temporary directory."
725         TMP=$(mktemp ${TMP_ROOT}/cdimage.XXXXXX) && \
726             genisoimage -input-charset iso8859-1 -r -o ${TMP} "$1" && \
727             wodim -eject -v dev=${DEV_BURNER} ${TMP}
728         rm -f ${TMP}
729     else
730         echo "Can not find $1" >&2
731     fi
732 }
733
734 ######################################################################
735 # And watch DVDs too!
736
737 function dvd () {
738
739     echo
740     echo " ! @   Seek to the beginning of the previous/next chapter"
741     echo " j     Cycle through the available subtitles"
742     echo " o     Show/hide the timing"
743     echo " x z   Subtitle delay"
744     echo " / *   Volume"
745     echo
746
747     if [[ "$1" ]]
748     then
749         dvd_device="$1"
750         shift
751     else
752         dvd_device="/dev/dvd"
753     fi
754
755     title="1"
756
757     if [[ "$1" ]]
758     then
759         title=$1
760         shift
761     fi
762
763     # -vc ffmpeg12 -vf yadif
764
765     mplayer > /dev/null \
766         -stop-xscreensaver \
767         -quiet \
768         -alang en -slang en \
769         -softvol -softvol-max 1000 \
770         -dvd-device ${dvd_device} ${MPLAYER_OPTIONS} dvd://${title}
771 }
772
773 function ripdvd () {
774     if [[ -e "/dev/dvd" ]]
775     then
776         DVD_DEVICE="/dev/dvd"
777     elif [[ -e "/dev/dvd3" ]]
778     then
779         DVD_DEVICE="/dev/dvd3"
780     else
781         echo "Can not find the dvd device." >&2
782         return 1
783     fi
784
785     echo "Attemptin to rip from ${DVD_DEVICE}."
786
787     mkdir -p ${HOME}/dvds
788
789     cd ${HOME}/dvds
790     time dvdbackup -i ${DVD_DEVICE} -v -M "$@" && eject
791 }
792
793 alias ripcd=abcde
794
795 ######################################################################
796 # Create small images from images
797
798 function mksmall () {
799
800     if [[ "$1" == "--params" ]]
801     then
802         shift
803         PARAMS="$1"
804         shift
805     fi
806
807     [[ "${PARAMS}" ]] || PARAMS="-geometry 1280x1024"
808
809     # Auto-orient does not seem to work at all, hence the ugly hack
810     # with exif below
811
812     # PARAMS="-auto-orient -geometry 800x600"
813
814     echo "Using ${PARAMS}"
815
816     DEST_DIR=$1
817
818     [[ ${DEST_DIR} ]] || DEST_DIR=./small
819
820     mkdir -p ${DEST_DIR}
821
822     if [[ ! -d ${DEST_DIR} ]]
823     then
824         echo "Can not create ${DEST_DIR}" >&2
825         return
826     fi
827
828     NB_TOTAL=$(find -maxdepth 1 -type f | wc -l)
829     NB=0
830
831     for i in $(find -maxdepth 1 -type f)
832     do
833         if [[ $(file $i | grep image) ]]
834         then
835             if [[ -e ${DEST_DIR}/$i ]]
836             then
837                 echo "The file ${DEST_DIR}/$i already exists."
838             else
839                 if [[ $(file ${i/%.*/}.* | grep -E movie) ]] 
840                 then
841                     CAPTION_PARAMS="-font FreeSans-Bold -pointsize 32 -fill green -annotate +10+32 Video"
842                 else
843                     CAPTION_PARAMS=""
844                 fi
845
846                 convert ${rotation_cmd} $i ${PARAMS} ${CAPTION_PARAMS} ${DEST_DIR}/$i
847             fi
848
849             \ls -lt ${DEST_DIR}/$i
850         fi
851
852         NB=$((NB+1))
853
854         echo "$((NB*100/NB_TOTAL))% (${NB}/${NB_TOTAL})"
855     done
856 }
857
858 ######################################################################
859 # Move a file to the ~/sources/config directory and replace it where
860 # it was by a symbolic link
861
862 function mvtoconfig () {
863     CONFIGDIR=${HOME}/sources/config
864     if [[ -d ${CONFIGDIR} ]]
865     then
866         NEWNAME=${CONFIGDIR}/$(basename "$1" | sed -e "s/^\.//")
867         mv "$1" $NEWNAME
868         ln -s $NEWNAME $1
869     else
870         echo "Can not find ${CONFIGDIR}"
871     fi
872 }
873
874 ######################################################################
875 # The complex prompt policy
876
877 export PS1
878
879 if [[ "${CONSOLE}" == "yes" ]]
880 then
881
882     PS1=""
883
884 else
885
886     # If the login is a standard one (as specified in
887     # IGNORED_PROMPT_LOGIN, which is set in the private bash file), do not
888     # show it. I have IGNORED_PROMPT_LOGIN="^fleuret$".
889
890     if [[ ! ${IGNORED_PROMPT_LOGIN} ]] || [[ ! ${USER} =~ ${IGNORED_PROMPT_LOGIN} ]]
891     then
892         IDENT="${USER}"
893     fi
894
895     # If the display is not the main one, make the assumption that the
896     # shell is not running on the localhost, and show the hostname
897
898     [[ "${DISPLAY}" != ":0.0" ]] && IDENT="${IDENT}@\h"
899
900     # If there is the login or the hostname, add a ":" to the prompt
901
902     [[ "${IDENT}" ]] && IDENT="${IDENT}:"
903
904     if [[ ${USER} == "root" ]]
905     then
906         # If we are root, show that in red
907         PS1="\[${VT_RED_BG}${VT_WHITE_FG}\]${IDENT}\w\[${VT_RESET}\] "
908     else
909         if [[ $(\grep QEMU /proc/cpuinfo) ]]
910         then
911             # If we are in a qemu virtual machine, in yellow
912             PS1="\[${VT_YELLOW_BG}${VT_BLACK_FG}\]${IDENT}\w\[${VT_RESET}\] "
913         else
914             # Otherwise in white
915             PS1="\[${VT_WHITE_BG}${VT_BLACK_FG}\]${IDENT}\w\[${VT_RESET}\] "
916         fi
917     fi
918
919 fi
920
921 PS1="${PSCUE}${PS1}"
922
923 ######################################################################
924 # This implements a local history. If we are in a directory containing
925 # a writable local history file, we add the last line of the global
926 # history to it.
927
928 LOCAL_HISTORY_FILE=".local_bash_history"
929
930 function keep_local_history () {
931     if [[ -w "${LOCAL_HISTORY_FILE}" ]]
932     then
933         history 1 | sed -e 's/^ *[0-9]* *//' >> ${LOCAL_HISTORY_FILE}
934         TMP=$(mktemp /tmp/lh.XXXXXX)
935         \chmod 600 ${TMP}
936         uniq < ${LOCAL_HISTORY_FILE} | tail -${HISTSIZE} > ${TMP}
937         # mv would replace a symbolic link, while cp keeps it
938         \cp ${TMP} ${LOCAL_HISTORY_FILE}
939         \rm ${TMP}
940         LOCAL_HISTORY_HINT="* "
941     else
942         LOCAL_HISTORY_HINT=""
943     fi
944 }
945
946 PS1="\[${VT_WHITE_BG}\]\${LOCAL_HISTORY_HINT}\[${VT_RESET}\]${PS1}"
947
948 ######################################################################
949 # Show the history path if it is unusual
950
951 function histfile_cue () {
952     if [[ ! "${HISTFILE}" == "${HOME}/.bash_history" ]]
953     then
954         HISTORY_CUE="[${HISTFILE}]"
955     else
956         HISTORY_CUE=""
957     fi
958 }
959
960 PS1="\[${VT_YELLOW_BG}\]\${HISTORY_CUE}\[${VT_RESET}\]${PS1}"
961
962 ######################################################################
963 # The dus command is available on my web site
964 #
965 # git clone http://fleuret.org/git/dus/
966
967 alias dus='dus -f -i'
968
969 ######################################################################
970 # The finddup command is available on my web site
971 #
972 # git clone http://fleuret.org/git/finddup/
973
974 alias finddup='finddup -p'
975
976 ######################################################################
977 # The selector command is available on my web site
978 #
979 # git clone http://fleuret.org/git/selector/
980
981 export SELECTOR_CD_HISTORY_SIZE=10000
982
983 source bash-selector.sh --hist --cd
984
985 ######################################################################
986 # And we avoid to put in the history the use of the selector, which we
987 # do too often
988
989 HISTIGNORE="${HISTIGNORE}:selector-history"
990
991 ######################################################################
992
993 function selector-printer () {
994     TMP=$(mktemp /tmp/selector-printer.XXXXXX)
995     selector -o ${TMP} <(lpstat -a | awk '{print $1}')
996     export PRINTER=$(cat ${TMP})
997     echo "PRINTER=${PRINTER}"
998     rm -f ${TMP}
999     lpq
1000 }
1001
1002 ######################################################################
1003 # A ls with memory to notice what files have been added/removed from
1004 # the current directory
1005
1006 function lsn () {
1007     [[ "${LSN_STATE_FILE}" ]] || LSN_STATE_FILE=".lsn-state"
1008
1009     if  [[ $1 == "--mem" ]] || [[ "$1" == "-m" ]]
1010     then
1011
1012         \ls -pa | sort > "${LSN_STATE_FILE}"
1013         echo "State updated." >&2
1014
1015     elif [[ $1 == "+" ]]
1016     then
1017
1018         shift
1019
1020         TMP=$(mktemp /tmp/lsn.XXXXXX)
1021         \ls -d "$@" > ${TMP}
1022         cat "${LSN_STATE_FILE}" >> ${TMP}
1023         sort ${TMP} | uniq -u > "${LSN_STATE_FILE}"
1024         \rm ${TMP}
1025
1026     elif [[ "$1" ]]
1027     then
1028         cat >&2 <<EOF
1029 lsn [--help|-h] [--mem|-m] [+ <file> ...]
1030
1031 Where
1032
1033   --help|-h
1034      prints this help
1035
1036   --mem|-m
1037      stores the current state of the directory
1038
1039   + <file> [<file> ...]
1040      switches the presence/absence of the indicated files in the
1041      stored state
1042
1043 EOF
1044         if [[ ! "$1" == "-h" ]] && [[ ! "$1" == "--help" ]]
1045         then
1046             echo >&2 "Unknown option \`\`$1''."
1047             return 1
1048         fi
1049
1050     else
1051
1052         if [[ -f "${LSN_STATE_FILE}" ]]
1053         then
1054             TMP=$(mktemp /tmp/lsn.XXXXXX)
1055             \ls -pa | sort > ${TMP}
1056             if diff > /dev/null ${TMP} "${LSN_STATE_FILE}"
1057             then
1058                 echo "${VT_GREEN_FG}${VT_BOLD}No change (since $(date +"%b %d, %Y" -r "${LSN_STATE_FILE}"))${VT_RESET}"
1059             else
1060                 \comm -1 -3 "${LSN_STATE_FILE}" ${TMP}
1061                 \comm -2 -3 "${LSN_STATE_FILE}" ${TMP} | while read line
1062                                                          do
1063                     echo "${VT_RED_FG}${VT_BOLD}${line}${VT_RESET} (missing)"
1064                 done
1065             fi
1066             \rm ${TMP}
1067         else
1068             echo "${VT_RED_FG}${VT_BOLD}No lsn state here.${VT_RESET}" >&2
1069             return 1
1070         fi
1071
1072     fi
1073 }
1074
1075 ######################################################################
1076
1077 function prompt_command () {
1078     [[ "${CORE_CHECK_PWD}" == ${PWD} ]] || find . -maxdepth 1 -name "core__*" | awk '{print "'${VT_RED_FG}'"$0"'${VT_RESET}'"}'
1079     CORE_CHECK_PWD=${PWD}
1080
1081     # if [[ $(umask) != 0022 ]]
1082     # then
1083         # echo "Umask changed to $(umask)"
1084     # fi
1085     # save the history after every command to avoid loosing some when
1086     # multiple shells are open
1087     history -a
1088     # load the saved history
1089     # history -n
1090     # and the local histories system defined above
1091     keep_local_history
1092     # and the history cue
1093     histfile_cue
1094 }
1095
1096 PROMPT_COMMAND="prompt_command"
1097
1098 ######################################################################
1099
1100 # Displaying the timezone if it is set
1101
1102 [[ ${TZ} ]] && echo "${VT_BLUE_FG}Time zone is ${TZ}.${VT_RESET}"
1103
1104 ######################################################################
1105
1106 source /usr/share/bash-completion/bash_completion
1107
1108 ######################################################################
1109
1110 # added by Miniconda3 installer
1111 export PATH="/home/fleuret/conda/bin:$PATH"