xref: /titanic_41/usr/src/lib/libshell/common/fun/dirs (revision 40db2e2b777b79f3dd0d6d9629593a07f86b9c0a)
1#
2# DIRECTORY MANIPULATION FUNCTIONS, REPLACES CD
3#
4# Uses global parameters _push_max _push_top _push_stack
5integer _push_max=${CDSTACK-32} _push_top=${CDSTACK-32}
6unalias cd
7alias cd=_cd
8# Display directory stack -- $HOME displayed as ~
9function dirs
10{
11    typeset dir="${PWD#$HOME/}"
12    case $dir in
13    $HOME)
14        dir=\~
15        ;;
16    /*) ;;
17    *)  dir=\~/$dir
18    esac
19    PS3=
20    select i in "$dir" "${_push_stack[@]}"
21    do	:
22    done < /dev/null
23}
24
25# Change directory and put directory on front of stack
26function _cd
27{
28    typeset dir=
29    integer n=0 type=4
30    case $1 in
31    -|-1|2) # \cd -
32        n=_push_top type=1
33        ;;
34    -[1-9]*([0-9])) # \cd -n
35        n=_push_top+${1#-}-1 type=2
36        ;;
37    1)  # keep present directory
38        print -r - "$PWD"
39	return
40        ;;
41    [1-9]*([0-9])) # \cd n
42        n=_push_top+${1}-2 type=2
43        ;;
44    *)  if    ((_push_top <= 0))
45        then  type=3 n=_push_max
46        fi
47    esac
48    if    ((type<3))
49    then  if    ((n >= _push_max+1))
50          then  print -u2 cd: Directory stack not that deep.
51                return 1
52          else  dir=${_push_stack[n]}
53          fi
54    fi
55    case $dir in
56    \~*)   dir=$HOME${dir#\~}
57    esac
58    \cd "${dir:-$@}" >| /dev/null || return 1
59    dir=${OLDPWD#$HOME/}
60    case $TERM in
61    630)
62	    print "\033[?${#PWD};2v$PWD\c"
63	    ;;
64    esac
65    case $dir in
66    $HOME)
67        dir=\~
68        ;;
69    /*) ;;
70    *)  dir=\~/$dir
71    esac
72    case $type in
73    1)  # swap first two elements
74        _push_stack[_push_top]=$dir
75        ;;
76    2|3)  # put $dir on top and shift down by one until top
77        integer i=_push_top
78        for dir in "$dir" "${_push_stack[@]}"
79        do  ((i > n)) && break
80            _push_stack[i]=$dir
81            i=i+1
82        done
83        ;;
84    4)  # push name
85        _push_stack[_push_top=_push_top-1]=$dir
86        ;;
87    esac
88    print -r - "$PWD"
89}
90
91# Menu driven change directory command
92function mcd
93{
94    typeset dir="${PWD#$HOME/}"
95    case $dir in
96    $HOME)
97        dir=\~
98        ;;
99    /*) ;;
100    *)  dir=\~/$dir
101    esac
102    PS3='Select by number or enter a name: '
103    select dir in "$dir" "${_push_stack[@]}"
104    do  if    _cd $REPLY
105        then  return
106        fi
107    done
108}
109