z.sh 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. # Copyright (c) 2009 rupa deadwyler. Licensed under the WTFPL license, Version 2
  2. # maintains a jump-list of the directories you actually use
  3. #
  4. # INSTALL:
  5. # * put something like this in your .bashrc/.zshrc:
  6. # . /path/to/z.sh
  7. # * cd around for a while to build up the db
  8. # * PROFIT!!
  9. # * optionally:
  10. # set $_Z_CMD in .bashrc/.zshrc to change the command (default z).
  11. # set $_Z_DATA in .bashrc/.zshrc to change the datafile (default ~/.z).
  12. # set $_Z_MAX_SCORE lower to age entries out faster (default 9000).
  13. # set $_Z_NO_RESOLVE_SYMLINKS to prevent symlink resolution.
  14. # set $_Z_NO_PROMPT_COMMAND if you're handling PROMPT_COMMAND yourself.
  15. # set $_Z_EXCLUDE_DIRS to an array of directories to exclude.
  16. # set $_Z_OWNER to your username if you want use z while sudo with $HOME kept
  17. #
  18. # USE:
  19. # * z foo # cd to most frecent dir matching foo
  20. # * z foo bar # cd to most frecent dir matching foo and bar
  21. # * z -r foo # cd to highest ranked dir matching foo
  22. # * z -t foo # cd to most recently accessed dir matching foo
  23. # * z -l foo # list matches instead of cd
  24. # * z -e foo # echo the best match, don't cd
  25. # * z -c foo # restrict matches to subdirs of $PWD
  26. # * z -x # remove the current directory from the datafile
  27. # * z -h # show a brief help message
  28. [ -d "${_Z_DATA:-$HOME/.z}" ] && {
  29. echo "ERROR: z.sh's datafile (${_Z_DATA:-$HOME/.z}) is a directory."
  30. }
  31. _z() {
  32. local datafile="${_Z_DATA:-$HOME/.z}"
  33. # if symlink, dereference
  34. [ -h "$datafile" ] && datafile=$(readlink "$datafile")
  35. # bail if we don't own ~/.z and $_Z_OWNER not set
  36. [ -z "$_Z_OWNER" -a -f "$datafile" -a ! -O "$datafile" ] && return
  37. _z_dirs () {
  38. local line
  39. while read line; do
  40. # only count directories
  41. [ -d "${line%%\|*}" ] && echo "$line"
  42. done < "$datafile"
  43. return 0
  44. }
  45. # add entries
  46. if [ "$1" = "--add" ]; then
  47. shift
  48. # $HOME isn't worth matching
  49. [ "$*" = "$HOME" ] && return
  50. # don't track excluded directory trees
  51. local exclude
  52. for exclude in "${_Z_EXCLUDE_DIRS[@]}"; do
  53. case "$*" in "$exclude*") return;; esac
  54. done
  55. # maintain the data file
  56. local tempfile="$datafile.$RANDOM"
  57. local score=${_Z_MAX_SCORE:-9000}
  58. _z_dirs | awk -v path="$*" -v now="$(date +%s)" -v score=$score -F"|" '
  59. BEGIN {
  60. rank[path] = 1
  61. time[path] = now
  62. }
  63. $2 >= 1 {
  64. # drop ranks below 1
  65. if( $1 == path ) {
  66. rank[$1] = $2 + 1
  67. time[$1] = now
  68. } else {
  69. rank[$1] = $2
  70. time[$1] = $3
  71. }
  72. count += $2
  73. }
  74. END {
  75. if( count > score ) {
  76. # aging
  77. for( x in rank ) print x "|" 0.99*rank[x] "|" time[x]
  78. } else for( x in rank ) print x "|" rank[x] "|" time[x]
  79. }
  80. ' 2>/dev/null >| "$tempfile"
  81. # do our best to avoid clobbering the datafile in a race condition.
  82. if [ $? -ne 0 -a -f "$datafile" ]; then
  83. env rm -f "$tempfile"
  84. else
  85. [ "$_Z_OWNER" ] && chown $_Z_OWNER:"$(id -ng $_Z_OWNER)" "$tempfile"
  86. env mv -f "$tempfile" "$datafile" || env rm -f "$tempfile"
  87. fi
  88. # tab completion
  89. elif [ "$1" = "--complete" -a -s "$datafile" ]; then
  90. _z_dirs | awk -v q="$2" -F"|" '
  91. BEGIN {
  92. q = substr(q, 3)
  93. if( q == tolower(q) ) imatch = 1
  94. gsub(/ /, ".*", q)
  95. }
  96. {
  97. if( imatch ) {
  98. if( tolower($1) ~ q ) print $1
  99. } else if( $1 ~ q ) print $1
  100. }
  101. ' 2>/dev/null
  102. else
  103. # list/go
  104. local echo fnd last list opt typ
  105. while [ "$1" ]; do case "$1" in
  106. --) while [ "$1" ]; do shift; fnd="$fnd${fnd:+ }$1";done;;
  107. -*) opt=${1:1}; while [ "$opt" ]; do case ${opt:0:1} in
  108. c) fnd="^$PWD $fnd";;
  109. e) echo=1;;
  110. h) echo "${_Z_CMD:-z} [-cehlrtx] args" >&2; return;;
  111. l) list=1;;
  112. r) typ="rank";;
  113. t) typ="recent";;
  114. x) sed -i -e "\:^${PWD}|.*:d" "$datafile";;
  115. esac; opt=${opt:1}; done;;
  116. *) fnd="$fnd${fnd:+ }$1";;
  117. esac; last=$1; [ "$#" -gt 0 ] && shift; done
  118. [ "$fnd" -a "$fnd" != "^$PWD " ] || list=1
  119. # if we hit enter on a completion just go there
  120. case "$last" in
  121. # completions will always start with /
  122. /*) [ -z "$list" -a -d "$last" ] && builtin cd "$last" && return;;
  123. esac
  124. # no file yet
  125. [ -f "$datafile" ] || return
  126. local cd
  127. cd="$( < <( _z_dirs ) awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
  128. function frecent(rank, time) {
  129. # relate frequency and time
  130. dx = t - time
  131. return int(10000 * rank * (3.75/((0.0001 * dx + 1) + 0.25)))
  132. }
  133. function output(matches, best_match, common) {
  134. # list or return the desired directory
  135. if( list ) {
  136. if( common ) {
  137. printf "%-10s %s\n", "common:", common > "/dev/stderr"
  138. }
  139. cmd = "sort -n >&2"
  140. for( x in matches ) {
  141. if( matches[x] ) {
  142. printf "%-10s %s\n", matches[x], x | cmd
  143. }
  144. }
  145. } else {
  146. if( common && !typ ) best_match = common
  147. print best_match
  148. }
  149. }
  150. function common(matches) {
  151. # find the common root of a list of matches, if it exists
  152. for( x in matches ) {
  153. if( matches[x] && (!short || length(x) < length(short)) ) {
  154. short = x
  155. }
  156. }
  157. if( short == "/" ) return
  158. for( x in matches ) if( matches[x] && index(x, short) != 1 ) {
  159. return
  160. }
  161. return short
  162. }
  163. BEGIN {
  164. gsub(" ", ".*", q)
  165. hi_rank = ihi_rank = -9999999999
  166. }
  167. {
  168. if( typ == "rank" ) {
  169. rank = $2
  170. } else if( typ == "recent" ) {
  171. rank = $3 - t
  172. } else rank = frecent($2, $3)
  173. if( $1 ~ q ) {
  174. matches[$1] = rank
  175. } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
  176. if( matches[$1] && matches[$1] > hi_rank ) {
  177. best_match = $1
  178. hi_rank = matches[$1]
  179. } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
  180. ibest_match = $1
  181. ihi_rank = imatches[$1]
  182. }
  183. }
  184. END {
  185. # prefer case sensitive
  186. if( best_match ) {
  187. output(matches, best_match, common(matches))
  188. exit
  189. } else if( ibest_match ) {
  190. output(imatches, ibest_match, common(imatches))
  191. exit
  192. }
  193. exit(1)
  194. }
  195. ')"
  196. if [ "$?" -eq 0 ]; then
  197. if [ "$cd" ]; then
  198. if [ "$echo" ]; then echo "$cd"; else builtin cd "$cd"; fi
  199. fi
  200. else
  201. return $?
  202. fi
  203. fi
  204. }
  205. alias ${_Z_CMD:-z}='_z 2>&1'
  206. [ "$_Z_NO_RESOLVE_SYMLINKS" ] || _Z_RESOLVE_SYMLINKS="-P"
  207. if type compctl >/dev/null 2>&1; then
  208. # zsh
  209. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  210. # populate directory list, avoid clobbering any other precmds.
  211. if [ "$_Z_NO_RESOLVE_SYMLINKS" ]; then
  212. _z_precmd() {
  213. (_z --add "${PWD:a}" &)
  214. : $RANDOM
  215. }
  216. else
  217. _z_precmd() {
  218. (_z --add "${PWD:A}" &)
  219. : $RANDOM
  220. }
  221. fi
  222. [[ -n "${precmd_functions[(r)_z_precmd]}" ]] || {
  223. precmd_functions[$(($#precmd_functions+1))]=_z_precmd
  224. }
  225. }
  226. _z_zsh_tab_completion() {
  227. # tab completion
  228. local compl
  229. read -l compl
  230. reply=(${(f)"$(_z --complete "$compl")"})
  231. }
  232. compctl -U -K _z_zsh_tab_completion _z
  233. elif type complete >/dev/null 2>&1; then
  234. # bash
  235. # tab completion
  236. complete -o filenames -C '_z --complete "$COMP_LINE"' ${_Z_CMD:-z}
  237. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  238. # populate directory list. avoid clobbering other PROMPT_COMMANDs.
  239. grep "_z --add" <<< "$PROMPT_COMMAND" >/dev/null || {
  240. PROMPT_COMMAND="$PROMPT_COMMAND"$'\n''(_z --add "$(command pwd '$_Z_RESOLVE_SYMLINKS' 2>/dev/null)" 2>/dev/null &);'
  241. }
  242. }
  243. fi