dirs.txt 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #
  2. # DIRECTORY MANIPULATION FUNCTIONS PUSHD, POPD AND DIRS
  3. #
  4. # Uses global parameters _push_max _push_top _push_stack
  5. integer _push_max=100 _push_top=100
  6. # Display directory stack -- $HOME displayed as ~
  7. function dirs
  8. {
  9. typeset dir="${PWD#$HOME/}"
  10. case $dir in
  11. $HOME)
  12. dir=\~
  13. ;;
  14. /*) ;;
  15. *) dir=\~/$dir
  16. esac
  17. print -r - "$dir ${_push_stack[@]}"
  18. }
  19. # Change directory and put directory on front of stack
  20. function pushd
  21. {
  22. typeset dir= type=0
  23. integer i
  24. case $1 in
  25. "") # pushd
  26. if ((_push_top >= _push_max))
  27. then print pushd: No other directory.
  28. return 1
  29. fi
  30. type=1 dir=${_push_stack[_push_top]}
  31. ;;
  32. +[1-9]|+[1-9][0-9]) # pushd +n
  33. integer i=_push_top$1-1
  34. if ((i >= _push_max))
  35. then print pushd: Directory stack not that deep.
  36. return 1
  37. fi
  38. type=2 dir=${_push_stack[i]}
  39. ;;
  40. *) if ((_push_top <= 0))
  41. then print pushd: Directory stack overflow.
  42. return 1
  43. fi
  44. esac
  45. case $dir in
  46. \~*) dir=$HOME${dir#\~}
  47. esac
  48. cd "${dir:-$1}" > /dev/null || return 1
  49. dir=${OLDPWD#$HOME/}
  50. case $dir in
  51. $HOME)
  52. dir=\~
  53. ;;
  54. /*) ;;
  55. *) dir=\~/$dir
  56. esac
  57. case $type in
  58. 0) # pushd name
  59. _push_stack[_push_top=_push_top-1]=$dir
  60. ;;
  61. 1) # pushd
  62. _push_stack[_push_top]=$dir
  63. ;;
  64. 2) # push +n
  65. type=${1#+} i=_push_top-1
  66. set -- "${_push_stack[@]}" "$dir" "${_push_stack[@]}"
  67. shift $type
  68. for dir
  69. do (((i=i+1) < _push_max)) || break
  70. _push_stack[i]=$dir
  71. done
  72. esac
  73. dirs
  74. }
  75. # Pops the top directory
  76. function popd
  77. {
  78. typeset dir
  79. if ((_push_top >= _push_max))
  80. then print popd: Nothing to pop.
  81. return 1
  82. fi
  83. case $1 in
  84. "")
  85. dir=${_push_stack[_push_top]}
  86. case $dir in
  87. \~*) dir=$HOME${dir#\~}
  88. esac
  89. cd "$dir" || return 1
  90. ;;
  91. +[1-9]|+[1-9][0-9])
  92. typeset savedir
  93. integer i=_push_top$1-1
  94. if ((i >= _push_max))
  95. then print pushd: Directory stack not that deep.
  96. return 1
  97. fi
  98. while ((i > _push_top))
  99. do _push_stack[i]=${_push_stack[i-1]}
  100. i=i-1
  101. done
  102. ;;
  103. *) print pushd: Bad directory.
  104. return 1
  105. esac
  106. unset '_push_stack[_push_top]'
  107. _push_top=_push_top+1
  108. dirs
  109. }