64cda91182f8a93b48318758809c8c633aeb829a
[selector.git] / bash-selector.sh
1 #!/bin/bash
2
3 #########################################################################
4 # This program is free software: you can redistribute it and/or modify  #
5 # it under the terms of the version 3 of the GNU General Public License #
6 # as published by the Free Software Foundation.                         #
7 #                                                                       #
8 # This program is distributed in the hope that it will be useful, but   #
9 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
11 # General Public License for more details.                              #
12 #                                                                       #
13 # You should have received a copy of the GNU General Public License     #
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
15 #                                                                       #
16 # Written by and Copyright (C) Francois Fleuret                         #
17 # Contact <francois.fleuret@idiap.ch> for comments & bug reports        #
18 #########################################################################
19
20 # Selector based history
21
22 function selector-history () {
23     selector --bash -u -c 7,4,0,3 -q <(history)
24 }
25
26 # Maintains a list of visited directories and provide a selector-based
27 # command to go back to any of them.
28
29 export SELECTOR_CD_HISTORY
30
31 [[ "${SELECTOR_CD_HISTORY}" ]] || SELECTOR_CD_HISTORY=${HOME}/.selector-cd-history
32
33 function selector-cd () {
34     if [[ -z "$1" ]]; then
35         cd
36     else
37         cd "$@"
38     fi
39     TMP=$(mktemp /tmp/selector-cd.XXXXXX)
40     tail -1000 < ${SELECTOR_CD_HISTORY} > ${TMP}
41     echo $PWD | sed -e "s!${HOME}!~!" >> ${TMP}
42     cat ${TMP} > ${SELECTOR_CD_HISTORY}
43     rm -f ${TMP}
44 }
45
46 function selector-cd-search () {
47     PATH_TEMP=$(mktemp /tmp/selector-cd-path.XXXXXX)
48     selector -u -t "cd" -l 10000 -d -i -c 7,2,0,3 -o ${PATH_TEMP} -q ${SELECTOR_CD_HISTORY}
49     NEW_PATH="$(cat ${PATH_TEMP} | sed -e 's!~!'${HOME}'!')"
50     if [[ -s "${NEW_PATH}" ]]; then
51         selector-cd "$(cat ${PATH_TEMP} | sed -e 's!~!'${HOME}'!')"
52     fi
53     \rm ${PATH_TEMP}
54 }
55
56 alias cd=selector-cd
57
58 # M-r puts the selected history line in place of the current one
59
60 bind '"\C-[r":"\C-a\C-kselector-history\C-m"'
61
62 # M-t appends the selected history line and the end of the current one
63 # bind '"\C-[t":"\C-a\C-kselector-history\C-m\C-a\C-y\C-e"'
64
65 # M-c provides a dynamic list of directories to cd into
66
67 bind '"\C-[c":"\C-a\C-kselector-cd-search\C-m"'