last-working-dir.plugin.zsh 779 B

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