z.sh 8.7 KB

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