z.sh 9.1 KB

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