last-working-dir.plugin.zsh
1116 bytes
1# Flag indicating if we've previously jumped to last directory
2typeset -g ZSH_LAST_WORKING_DIRECTORY
3
4# Updates the last directory once directory is changed
5autoload -U add-zsh-hook
6add-zsh-hook chpwd chpwd_last_working_dir
7chpwd_last_working_dir() {
8 # Don't run in subshells
9 [[ "$ZSH_SUBSHELL" -eq 0 ]] || return 0
10 # Add ".$SSH_USER" suffix to cache file if $SSH_USER is set and non-empty
11 local cache_file="$ZSH_CACHE_DIR/last-working-dir${SSH_USER:+.$SSH_USER}"
12 'builtin' 'echo' '-E' "$PWD" >| "$cache_file"
13}
14
15# Changes directory to the last working directory
16lwd() {
17 # Add ".$SSH_USER" suffix to cache file if $SSH_USER is set and non-empty
18 local cache_file="$ZSH_CACHE_DIR/last-working-dir${SSH_USER:+.$SSH_USER}"
19 [[ -r "$cache_file" ]] && cd "$(<"$cache_file")"
20}
21
22# Jump to last directory automatically unless:
23#
24# - This isn't the first time the plugin is loaded
25# - We're not in the $HOME directory (e.g. if terminal opened a different folder)
26[[ -z "$ZSH_LAST_WORKING_DIRECTORY" ]] || return 0
27[[ "$PWD" == "$HOME" ]] || return 0
28
29if lwd 2>/dev/null; then
30 ZSH_LAST_WORKING_DIRECTORY=1
31fi