dircycle.plugin.zsh
2597 bytes
1# enables cycling through the directory stack using
2# Ctrl+Shift+Left/Right
3#
4# left/right direction follows the order in which directories
5# were visited, like left/right arrows do in a browser
6
7# NO_PUSHD_MINUS syntax:
8# pushd +N: start counting from left of `dirs' output
9# pushd -N: start counting from right of `dirs' output
10
11# Either switch to a directory from dirstack, using +N or -N syntax
12# or switch to a directory by path, using `switch-to-dir -- <path>`
13switch-to-dir () {
14 # If $1 is --, then treat $2 as a directory path
15 if [[ $1 == -- ]]; then
16 # We use `-q` because we don't want chpwd to run, we'll do it manually
17 [[ -d "$2" ]] && builtin pushd -q "$2" &>/dev/null
18 return $?
19 fi
20
21 setopt localoptions nopushdminus
22 [[ ${#dirstack} -eq 0 ]] && return 1
23
24 while ! builtin pushd -q $1 &>/dev/null; do
25 # We found a missing directory: pop it out of the dir stack
26 builtin popd -q $1
27
28 # Stop trying if there are no more directories in the dir stack
29 [[ ${#dirstack} -eq 0 ]] && return 1
30 done
31}
32
33insert-cycledleft () {
34 switch-to-dir +1 || return $?
35
36 local fn
37 for fn in chpwd $chpwd_functions precmd $precmd_functions; do
38 (( $+functions[$fn] )) && $fn
39 done
40 zle reset-prompt
41}
42zle -N insert-cycledleft
43
44insert-cycledright () {
45 switch-to-dir -0 || return $?
46
47 local fn
48 for fn in chpwd $chpwd_functions precmd $precmd_functions; do
49 (( $+functions[$fn] )) && $fn
50 done
51 zle reset-prompt
52}
53zle -N insert-cycledright
54
55insert-cycledup () {
56 switch-to-dir -- .. || return $?
57
58 local fn
59 for fn in chpwd $chpwd_functions precmd $precmd_functions; do
60 (( $+functions[$fn] )) && $fn
61 done
62 zle reset-prompt
63}
64zle -N insert-cycledup
65
66insert-cycleddown () {
67 switch-to-dir -- "$(find . -mindepth 1 -maxdepth 1 -type d | sort -n | head -n 1)" || return $?
68
69 local fn
70 for fn in chpwd $chpwd_functions precmd $precmd_functions; do
71 (( $+functions[$fn] )) && $fn
72 done
73 zle reset-prompt
74}
75zle -N insert-cycleddown
76
77# These sequences work for xterm, Apple Terminal.app, and probably others.
78# Not for rxvt-unicode, but it doesn't seem differentiate Ctrl-Shift-Arrow
79# from plain Shift-Arrow, at least by default.
80#
81# iTerm2 does not have these key combinations defined by default; you will need
82# to add them under "Keys" in your profile if you want to use this. You can do
83# this conveniently by loading the "xterm with Numeric Keypad" preset.
84bindkey "\e[1;6D" insert-cycledleft # Ctrl+Shift+Left
85bindkey "\e[1;6C" insert-cycledright # Ctrl+Shift+Right
86bindkey "\e[1;6A" insert-cycledup # Ctrl+Shift+Up
87bindkey "\e[1;6B" insert-cycleddown # Ctrl+Shift+Down