Directory Temporal Locality in Zsh

I tend to work with many terminal windows or tabs whenever I'm doing something productive. cd-ing over to the directory where I'm currently working always bothered me. However, I wasn't satisfied with others' solutions, so I rolled my own that exploits temporal locality. In this post, I'll explain why I chose it, what it is, and how it works.

Why

Others have addressed this problem in a few different ways. The two most popular classes that come to mind are some combination of:

  • Fuzzy directory switching

Using some sort of fuzzy search heuristic and an intelligent sorting of possible hits (maybe by frequency of visits) expand something like cd d/w/k/gme to cd docs/working/koalas/game

  • Marking a location and jumping to the mark

If one runs some command mm game in a directory docs/working/koalas/game, he or she can later jump to that directory with mj game.

Both involve executing an extra command manually. I want to execute, on average, less than one command whenever I open a new terminal to jump to where I want to work.

According to temporal locality (usually used in the context of caching), one is more likely to use some specific resource if he or she has used it very recently. I felt that this idea can apply in my situation as well.

My solution works by automatically jumping to the most recent directory that I have visited whenever I open a new terminal (i.e. with zero extra commands). Typically, when I open a new terminal, I am expanding my workspace for the same project -- in the same directory. Thus, with my solution, I do average less than one command to switch to my current working directory. Even when I actually want to be in my home directory, the old default starting location, a simple cd with no arguments will take me there.

What

Automatically jump the most recently cd-ed folder on a new terminal instance.

Stick this in your ~/.zshrc:

autoload -U add-zsh-hook

record_pwd() { pwd > /tmp/.cwd }

#register hooks
add-zsh-hook chpwd record_pwd

#cd to the most recent place saved
touch /tmp/.cwd
cd `cat /tmp/.cwd`

How

Zsh allows you to register callbacks that are called when certain events happen. In this case, we are inserting a callback into the chpwd hook -- which is called immediately after changing directories -- and we just save our new working directory, pwd, into a file. Finally, we change to the directory where we were last before returning control to the user (i.e. the ~/.zshrc finishes executing).

Thoughts

I've been using this temporal locality hack for at least a year now, and I can't live without it. I've saved a lot of time by not having to change directories more than one time per task even if that task involves opening N terminal instances.