last-working-dir.plugin.zsh 1.1 KB

12345678910111213141516171819202122232425262728293031
  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' 'echo' '-E' "$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 "$(<"$cache_file")"
  18. }
  19. # Jump to last directory automatically unless:
  20. #
  21. # - This isn't the first time the plugin is loaded
  22. # - We're not in the $HOME directory (e.g. if terminal opened a different folder)
  23. [[ -z "$ZSH_LAST_WORKING_DIRECTORY" ]] || return
  24. [[ "$PWD" == "$HOME" ]] || return
  25. if lwd 2>/dev/null; then
  26. ZSH_LAST_WORKING_DIRECTORY=1
  27. fi