last-working-dir.plugin.zsh 1.0 KB

12345678910111213141516171819202122232425262728
  1. # Flag indicating if we've previously jumped to last directory
  2. typeset -g ZSH_LAST_WORKING_DIRECTORY
  3. # Updates the last directory once directory is changed
  4. autoload -U add-zsh-hook
  5. add-zsh-hook chpwd chpwd_last_working_dir
  6. chpwd_last_working_dir() {
  7. # Don't run in subshells
  8. [[ "$ZSH_SUBSHELL" -eq 0 ]] || return 0
  9. # Add ".$SSH_USER" suffix to cache file if $SSH_USER is set and non-empty
  10. local cache_file="$ZSH_CACHE_DIR/last-working-dir${SSH_USER:+.$SSH_USER}"
  11. builtin pwd >| "$cache_file"
  12. }
  13. # Changes directory to the last working directory
  14. lwd() {
  15. # Add ".$SSH_USER" suffix to cache file if $SSH_USER is set and non-empty
  16. local cache_file="$ZSH_CACHE_DIR/last-working-dir${SSH_USER:+.$SSH_USER}"
  17. [[ -r "$cache_file" ]] && cd "$(cat "$cache_file")"
  18. }
  19. # Jump to last directory automatically unless:
  20. # - this isn't the first time the plugin is loaded
  21. # - it's not in $HOME directory
  22. [[ -n "$ZSH_LAST_WORKING_DIRECTORY" ]] && return
  23. [[ "$PWD" != "$HOME" ]] && return
  24. lwd 2>/dev/null && ZSH_LAST_WORKING_DIRECTORY=1 || true