Code Splitting in ZSH

Josh Burns,zsh

If you're like me and cosntantly hack away at your configuration files you most likely end up with .*rc files 100s of lines long (this may or may not be a personal annecdote). With this blog post I aim to demonstrate how i've managed to solve this issue and my approach to keeping my .zshrc file consice and still managable to hack away at.

All of my configs for things like zsh, emacs, etc. All seem to end up with one thing in common some form of an ad-hoc module system that requires/loads/includes (pick a verb) other self-contained pieces of code into runtime.

For those who have used things like oh-my-zsh in the past will be familliar with this style of optional plugin functionality, By way of OMZ's plugin system. Which by the way is the direct inspiration for the way I do things and in-directly, this blog post.

So what is a plugin? For us in this context? Simply a snippet of code that will be loaded in-line with the rest of our zsh config. Think of a plugin as simply taking a section of your .zshrc and then putting it in another file.

Before we can start loading plugins, we need a plugin to load. For the purpose of illustration our plugin will be a simple alias definition for Launching Emacs.app from a terminal without it hanging in the foreground. Whilst this is not important to the main point, It is helpful to see what code is being loaded.

# $HOME/.zsh-plugins/emacs-osx.plugin.zsh
 
alias emacs="open -a Emacs $@"

Lets Write a Loader

The quickest way to load your plugins is via for loop. We will simply tell Zshell to look in a particular directory. And pass each file it finds with the naming scheme of .plugin.zsh to the source command. We can express this in a simple one-liner like this

# Load Plugins
for file in $HOME/.zsh-plugins/**/*.plugin.zsh; source $file

Thats all we need for a fully functional plugin system in our shell configuration, with no external or third party tooling (or even an internet connection) required. From here all you have to do is create a new script in the $HOME/.zsh-plugins directory with a .plugin.zsh extension. When it loads, your shell will detect the new file and load it in as if it were written directly inside of your .zshrc file itself.

fin

© Josh Burns.RSS