Some of these trees can get quite deep, and sometimes, when I’m working in one of the directories deep in the tree, I need to access a file somewhere else in the tree. Now, you can do that via ../../../path/to/file, or ~/src/project/path/to/file, but neither are very efficient. I wanted a way to efficiently refer to the root of the current project.

Finding the root is easy. In my case, $(pwd) | cut -d / -f 1-5 gives me what I need. Now I use some Zsh trickery to efficiently use that in commands. I want ‘~~‘ to expand to this directory. Enter the following code in my .zshrc:

Every time you press ‘~’, the widget ‘my-expand-tilde’ is run. If this is the second ‘~’ in a row, it will strip of the previous ‘~’ and add the root of the current project to the command I am typing. So effectively, whenever I type ‘~~’, it is immediately substituted by the directory that I need.

Ideas for this code where borrowed from ZSH-LOVERS(1), look in that page for a widget named ‘rationalise-dot‘.