z.sh 8.7 KB

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