z.sh 8.6 KB

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