z.sh 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. e) local echo=echo;;
  99. h) echo "${_Z_CMD:-z} [-cehlrtx] args" >&2; return;;
  100. l) local list=1;;
  101. r) local typ="rank";;
  102. t) local typ="recent";;
  103. x) sed -i -e "\:^${PWD}|.*:d" "$datafile";;
  104. esac; opt=${opt:1}; done;;
  105. *) local fnd="$fnd${fnd:+ }$1";;
  106. esac; local last=$1; [ "$#" -gt 0 ] && shift; done
  107. [ "$fnd" -a "$fnd" != "^$PWD " ] || local list=1
  108. # if we hit enter on a completion just go there
  109. case "$last" in
  110. # completions will always start with /
  111. /*) [ -z "$list" -a -d "$last" ] && cd "$last" && return;;
  112. esac
  113. # no file yet
  114. [ -f "$datafile" ] || return
  115. local cd
  116. cd="$(while read line; do
  117. [ -d "${line%%\|*}" ] && echo $line
  118. done < "$datafile" | awk -v t="$(date +%s)" -v list="$list" -v typ="$typ" -v q="$fnd" -F"|" '
  119. function frecent(rank, time) {
  120. # relate frequency and time
  121. dx = t - time
  122. if( dx < 3600 ) return rank * 4
  123. if( dx < 86400 ) return rank * 2
  124. if( dx < 604800 ) return rank / 2
  125. return rank / 4
  126. }
  127. function output(files, out, common) {
  128. # list or return the desired directory
  129. if( list ) {
  130. cmd = "sort -n >&2"
  131. for( x in files ) {
  132. if( files[x] ) printf "%-10s %s\n", files[x], x | cmd
  133. }
  134. if( common ) {
  135. printf "%-10s %s\n", "common:", common > "/dev/stderr"
  136. }
  137. } else {
  138. if( common ) out = common
  139. print out
  140. }
  141. }
  142. function common(matches) {
  143. # find the common root of a list of matches, if it exists
  144. for( x in matches ) {
  145. if( matches[x] && (!short || length(x) < length(short)) ) {
  146. short = x
  147. }
  148. }
  149. if( short == "/" ) return
  150. # use a copy to escape special characters, as we want to return
  151. # the original. yeah, this escaping is awful.
  152. clean_short = short
  153. gsub(/\[\(\)\[\]\|\]/, "\\\\&", clean_short)
  154. for( x in matches ) if( matches[x] && x !~ clean_short ) return
  155. return short
  156. }
  157. BEGIN {
  158. gsub(" ", ".*", q)
  159. hi_rank = ihi_rank = -9999999999
  160. }
  161. {
  162. if( typ == "rank" ) {
  163. rank = $2
  164. } else if( typ == "recent" ) {
  165. rank = $3 - t
  166. } else rank = frecent($2, $3)
  167. if( $1 ~ q ) {
  168. matches[$1] = rank
  169. } else if( tolower($1) ~ tolower(q) ) imatches[$1] = rank
  170. if( matches[$1] && matches[$1] > hi_rank ) {
  171. best_match = $1
  172. hi_rank = matches[$1]
  173. } else if( imatches[$1] && imatches[$1] > ihi_rank ) {
  174. ibest_match = $1
  175. ihi_rank = imatches[$1]
  176. }
  177. }
  178. END {
  179. # prefer case sensitive
  180. if( best_match ) {
  181. output(matches, best_match, common(matches))
  182. } else if( ibest_match ) {
  183. output(imatches, ibest_match, common(imatches))
  184. }
  185. }
  186. ')"
  187. [ $? -gt 0 ] && return
  188. [ "$cd" ] || return
  189. ${echo:-cd} "$cd"
  190. fi
  191. }
  192. alias ${_Z_CMD:-z}='_z 2>&1'
  193. [ "$_Z_NO_RESOLVE_SYMLINKS" ] || _Z_RESOLVE_SYMLINKS="-P"
  194. if type compctl >/dev/null 2>&1; then
  195. # zsh
  196. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  197. # populate directory list, avoid clobbering any other precmds.
  198. if [ "$_Z_NO_RESOLVE_SYMLINKS" ]; then
  199. _z_precmd() {
  200. _z --add "${PWD:a}"
  201. }
  202. else
  203. _z_precmd() {
  204. _z --add "${PWD:A}"
  205. }
  206. fi
  207. [[ -n "${precmd_functions[(r)_z_precmd]}" ]] || {
  208. precmd_functions[$(($#precmd_functions+1))]=_z_precmd
  209. }
  210. }
  211. _z_zsh_tab_completion() {
  212. # tab completion
  213. local compl
  214. read -l compl
  215. reply=(${(f)"$(_z --complete "$compl")"})
  216. }
  217. compctl -U -K _z_zsh_tab_completion _z
  218. elif type complete >/dev/null 2>&1; then
  219. # bash
  220. # tab completion
  221. complete -o filenames -C '_z --complete "$COMP_LINE"' ${_Z_CMD:-z}
  222. [ "$_Z_NO_PROMPT_COMMAND" ] || {
  223. # populate directory list. avoid clobbering other PROMPT_COMMANDs.
  224. grep "_z --add" <<< "$PROMPT_COMMAND" >/dev/null || {
  225. PROMPT_COMMAND="$PROMPT_COMMAND"$'\n''_z --add "$(command pwd '$_Z_RESOLVE_SYMLINKS' 2>/dev/null)" 2>/dev/null;'
  226. }
  227. }
  228. fi