last-working-dir.plugin.zsh 859 B

1234567891011121314151617181920212223242526
  1. #!/usr/bin/env zsh
  2. # Keeps track of the last used working directory and automatically jumps
  3. # into it for new shells.
  4. # Flag indicating if we've previously jumped to last directory.
  5. typeset -g ZSH_LAST_WORKING_DIRECTORY
  6. mkdir -p $ZSH_CACHE_DIR
  7. cache_file="$ZSH_CACHE_DIR/last-working-dir"
  8. # Updates the last directory once directory is changed.
  9. chpwd_functions+=(chpwd_last_working_dir)
  10. function chpwd_last_working_dir() {
  11. # Use >| in case noclobber is set to avoid "file exists" error
  12. pwd >| "$cache_file"
  13. }
  14. # Changes directory to the last working directory.
  15. function lwd() {
  16. [[ ! -r "$cache_file" ]] || cd "`cat "$cache_file"`"
  17. }
  18. # Automatically jump to last working directory unless this isn't the first time
  19. # this plugin has been loaded.
  20. if [[ -z "$ZSH_LAST_WORKING_DIRECTORY" ]]; then
  21. lwd 2>/dev/null && ZSH_LAST_WORKING_DIRECTORY=1 || true
  22. fi