kuda.ai | code. guitar. life.

Open Your Code Projects in VSCode From Your Terminal -- Without Typing the Whole Path

created in December 2022, last update in January 2023

If you write code, chances are high that you use Visual Studio Code as your code editor. And if you do, you might use code . to open the current directory.

This models a typical workflow:

# change into the directory with your code:
cd ~/code/repos/core_services

# open the directory with visual studio code:
code .

# alternatively, open the repo directly without changing into it:
code ~/code/repos/core_services

In any case, you always have to either change the directory or type the directory.

There is a shortcut: zoxide, a better cd. Zoxide remembers the directories you visit, and enables you to go right into them, without browsing parent directories first.

# first things first: install zoxide
brew install zoxide

# and init zoxide
echo 'eval "$(zoxide init zsh)"' >> $HOME/.zshrc

# many people alias cd to zoxide, but I don't; instead:
echo 'alias z=zoxide' >> $HOME/.zshrc

# now activate the changes
source $HOME/.zshrc

Once you have done that, you can use a shortcut to roam around your filesystem:

alias z="zoxide"

# zoxide keeps a sqlite3 data base with known directories that were visited,
# so we need to visit a directory at least once:
z ~/code/repos/core_services

# instead of typing out the whole thing,
# you can abbreviate and use the last dir:
z core_services

# pro tip: you do not even have to spell the whole name:
z core # enough to get the right result; at this point, c would be enough, too

# now we can print that directory with "zoxide query <word>":
z query core
# prints the absolute path "/Users/david/code/repos/core_services"

# "zoxide query" will search the database for any directory 
# that matches the given <word>

Now we can use code with zoxide in a subshell:

code $(zoxide query core)

Of course, this is longer than the original way, so let's pack the logic into a function.

# note: cz stands for "code zoxide"
function cz {
  # $1 stands for first argument passed to cz
  path=$(zoxide query $1)
  code $path
}

# once you sourced that function, you can simply type:

cz core

# and this is going to open your repository in visual studio code :)