last-working-dir.plugin.zsh 804 B

1234567891011121314151617181920212223242526
  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. if [ "$ZSH_SUBSHELL" = 0 ]; then
  8. local cache_file="$ZSH_CACHE_DIR/last-working-dir"
  9. pwd >| "$cache_file"
  10. fi
  11. }
  12. # Changes directory to the last working directory
  13. lwd() {
  14. local cache_file="$ZSH_CACHE_DIR/last-working-dir"
  15. [[ -r "$cache_file" ]] && cd "$(cat "$cache_file")"
  16. }
  17. # Jump to last directory automatically unless:
  18. # - this isn't the first time the plugin is loaded
  19. # - it's not in $HOME directory
  20. [[ -n "$ZSH_LAST_WORKING_DIRECTORY" ]] && return
  21. [[ "$PWD" != "$HOME" ]] && return
  22. lwd 2>/dev/null && ZSH_LAST_WORKING_DIRECTORY=1 || true