kernpunkt Digital GmbH · Follow
8 min read · Apr 18, 2023
--
Hello, fellow devs!
Today, we’re talking about Code Snippets. When I use that term, I’m talking about a short segment of code, typically about 3 to 10 lines, that serves to solve a singular, very specific problem. I put an unconscionable amount of effort into organizing my code snippets, because I find myself going back to the same ones over and over again, and making them easy to find and quick to jot down made me a better, more reliable, and more efficient programmer. If you ever found yourself thinking “Aw crud, how do I do XYZ again?”, you’re reading the right post. I will show you how to make a lightweight, stunningly fast, reliable, and future-proof repository of code snippets, using the free tool Obsidian.
At its core, Obsidian is a note-taking app that works with plain text files. But two features make it stand out to me: using Markdown as a lightweight markup language, and the ability to interlink notes using a Wiki-style syntax (wrapping it in two brackets, [[like this!]]
).
Markdown was created in 2004 by John Gruber with the goal of creating a syntax that is easy to read and write. It can also easily be converted into HTML, and is incredibly easy to use! For example, if you wrap text in a *single pair of asterisks*
, it becomes italic! **Two asterisks**
make a text bold! And links look like this: [kernpunkt](https://kernpunkt.de)
. Once you get used to using Markdown to insert headings or links while writing, it gives you the power to create publishing-ready documents¹ without having to fiddle with settings or remembering the keyboard hotkey for making a text bold.
Obsidian enhances Markdown with the ability to link notes to other notes, creating a wiki-style web of notes that resemble the net of neurons in your brain. But we’re getting ahead of ourselves; let’s get our hands dirty.
Head on over to obsidian.md, download and install the software. Upon opening Obsidian for the first time, it will ask you where you want to create your Vault. A vault is nothing more than a folder on your computer that is used to store all the notes. Give your vault a fitting name, choose a location and click Create
.
After creating your vault, click on Create a new file
or use Cmd/Ctrl+N to create your first note. Feel free to use your own example for a useful code snippet, but I will name my new file "Bulk Renaming File Extensions in Bash". Here's my content:
Technology::[[Bash]]```bash
for f in \*.txt; do
mv -- "$f" "${f%.txt}.md"
done
```
The triple back-ticks are used in Markdown to designate a code block, and when you move your cursor out of the back-ticks in Obsidian, you will see that the app formats it with a monospace font. Even cooler, by providing bash
as the language of the code block, Obsidian adds syntax highlighting automatically. Neat.
If you click on the word Bash
after the word Technology
, you will notice that Obsidian automatically creates a new note file called "Bash". Congratulations! You just linked your first two files together! Press Ctrl/Cmd+G to open up Graph View and see your vault in all its interconnected glory:
Let’s create a new folder by clicking on the new folder icon in Obsidian’s file navigator, and name it Technologies. Open the Bash
note and summon Obsidian's command palette by hitting Cmd/Ctrl+P. The command palette gives you access to all of Obsidian's functionality, and you can select the command just by typing and thus filtering down the list until you find the command you need. Select Move current file to another folder
and move the Bash
note in the new Technologies
folder. Way more tidy.
Another big selling point for Obsidian is that everyone can supply community plugins to enhance the editor’s functionality by coding in Typescript². One of the most popular plugins is Dataview. This plugin can be used to create dynamic, data-driven views of your notes, displaying multiple data points from your notes as lists or tables, and basically making a database out of your note files.
To install Dataview, click the settings icon in the lower left corner of Obsidian (looks like a cogwheel). Select the tab called Community Plugins. Installing third-party plugins is turned off by default as a security precaution. But since Dataview is a tried and tested pillar of the Obsidian community, I feel safe recommending that you click on Turn on community plugins.
A click on Browse takes you to the list of plugins. You can use the Search Bar to filter the view down to the Dataview plugin. Select the plugin and click Install. After the installation, click Enable.
Cool, so now we got Dataview installed. What do we do with it? Computer magic! Open up the Bash note we created earlier and insert the following:
```dataview
LIST FROM [[Bash]]
```
The dataview
code block tells Obsidian to interpret the contents as a Dataview query. In this case, it means: Get me a list of Notes that link to the Bash note. Of course, only our bulk renaming note shows up so far, but every future note you link to your Bash note will automatically start showing up here. You have created what the Obsidian folks (and other note-taking communities) call a MOC, a map of content, a note with the purpose of linking to other notes.
Let’s create some more Bash notes:
# New note: find and delete files
Technology::[[Bash]]
#find
```bash
find . -name '*.js*' -delete
```
# New note: find and grep to find text in all files
Technology::[[Bash]]
#find #grep
```bash
find . -name '*bills*' -exec grep -iH "searchforthis" {} \;
```
And change the query of the Bash note a little bit so it reads:
```dataview
TABLE
join(file.tags, " ") as Tags
FROM ""
WHERE contains(Technology,[[Bash]])
```
As you can see, Dataview now renders a table with all our Bash notes! It even displays the tags of the files, given us another axis to organize our notes by.
The query searches for note that have the Technology
field set to the bash note. You might have noted the double colons (::) we used in our notes: This is one way of telling Dataview that this is a Dataview field. Similar to a traditional database, you can use these fields to store all kinds of information about your notes and later query them with the plugin. Other ways of providing Dataview fields can be seen in Dataview's documentation page.
Using a Dataview field to link our snippet to technologies gives us the possibility of also linking it to multiple technologies. Here’s an example of a note that is both linked to the [[PHP]]
and the [[PhpUnit]]
technologies and will show up in both MOC notes:
Technology::[[PHP]]
Technology::[[PhpUnit]]```php
public function testNothingInParticular() { $this->expectNotToPerformAssertions(); }
```
Glad you asked! How about a note that gives us a list of all technologies that have code snippets associated? Create a new note in the Technology folder called + Technologies. The plus sign at the beginning will make sure it will always be displayed first in the file navigator. Here’s the content:
```dataview
TABLE
length(file.inlinks) as Snippets
FROM "Technologies" AND !"Technologies/+ Technologies"
SORT length(file.inlinks) DESC
```
If you’re not afraid to get your hands a little dirty and you know your way around JavaScript, you can get even more fancy by using a dataviewjs
code block. To do so, access Obsidian's settings menu again, click the Dataview tab and enable the checkbox for Enable JavaScript queries. This allows you to modify your + Technologies note like this:
```dataviewjs
const pages = dv.pages('"Technologies" AND !"Technologies/+ Technologies"');
dv.table(["Technology", "Snippet Count", "Random Snippet"], pages.map((page) => {
return[
dv.fileLink(page.file.name),
page.file.inlinks.length,
page.file.inlinks[page.file.inlinks.length * Math.random() | 0]
];
}));
```
As you can see, the table now also displays a random snippet that belongs to the technology.
In my humble opinion, Obsidian is the perfect tool for storing and — more importantly — finding and retrieving code snippets. Yes, a simple Google search can easily find everything I have stored in my snippet repository. But when I retrieve a file from my vault, I don’t have to accept any cookies, close any newsletter popups or read through the dev’s life story before I get to the juicy code. Heck, I don’t even have to have an internet connection.
Because Obsidian uses plain text files under the hood, it leverages all advantages that text files bring:
- Portability: Text files can be easily transferred between different systems. Every OS can read and write plain text.
- Accessibility: If Obsidian ceases development tomorrow, I can still access my files with any text editor of my choosing.
- Version control: Afraid of losing your snippets? Stick ’em in a Git repository! Easy as that.
- Searchability: In addition to Obsidian’s awesome tools for finding files (just press Cmd/Ctrl+O and start typing), I can even use Unix tools like
find
andgrep
to find my snippets if I have to.
The functionality that Obsidian offers on top of plain text and Markdown allows me to generate dynamic views into my notes, showing me exactly which snippet I’m looking for at any given moment.
Plus — and I cannot overstate this enough — it’s just plain fun to work with. I highly recommend you check out the software and start building your own little collection of useful code snippets. Once you got a couple of files added to your vault, I would not be surprised if you found yourself using it multiple times a day.
If you’re interested in building your own vault, you can find a Git repository with some samples (including the ones we wrote together during this article) here: https://github.com/joerncodes/code-snippets.
And if you already have a cool repository of code snippets that you just can’t wait to put to work, kernpunkt would love to welcome you on board as soon as possible. We’re always on the lookout for talented developers, so feel free to reach out on our website kernpunkt.de/jobs.
Jörn is a 38-year-old web developer from Bonn, Germany, who works in the Funkeys++ team at kernpunkt Digital GmbH. Originally a die-hard “Backend Nerd™,” he recently began transitioning into a full-stack position. No matter the job title, he will never lose his 🖤 of databases and APIs. When he’s not spending time with his wife and son, he moonlights as a fantasy and horror illustrator and collects an upsetting amount of pocket knives.