Never again: broken code snippets in your blog posts
You probably know the feeling when you discover that your code snippets you embed into your blog are not doing what they should do or, even worse, not even compiling. I mean, you did your best, carefully checking everything in the IDE and copying it over. Perhaps it happens here or in a later stage where you change some little detail in the assumption that you are smart enough to make no errors.
Can it be more reliable, especially when I want to make changes to the code later? I figured that there are two approaches:
- extract and run your code snippets from the posts
- extract your snippets from (tested) code files and embed them into your posts
Option 2 intrigued me more, so I asked google to solve this for me. I actually found some solutions, but I was not really satisfied.
I came across
- snippet-extractor: Extracts labeled snippets of code to files.
- GitHub - ARMmbed/snippet: A Python3 tool to extract code snippets from source files
- Maven – Guide to the Snippet Macro
Still, the feeling that I missed a really good tool remains. If you know one, drop me a note on twitter.
I looked at the code, the syntax and community and decided: I want to write my own. For fun. And full control. And I can play around with poetry.
And here it is:
With this package you can extract snippets from any source code project you have. Which means you can still run the originating code or build unit tests for it.
In short, you can mark a snippet as follows:
# :snippet def-sanitize-for-filename
def sanitize_for_file_name(v):
return re.sub(VALID_NAME_RE, "-", v)
# :endsnippet
snex will extract the snippet to file called snippets/src-def-sanitize-for-filename.md
.
This snippet you can include in your posts or documentation. The output directory,
comment prefix, etc. need to be defined in a config file beforehand:
default:
output_path: "snippets"
src:
comment_prefix: "# "
lang: python
root: src
glob: "**/*.py"
More documentation you can find in the README of the git repo.
I usually add the snippet files to my github repo where I also keep my blog posts.
Including snippets
Unfortunately, Markdown does not have native include support, but you can find potential solutions en masse. I have selected some here.
m4
You can emulate mustache syntax with
M4. Suppose you have a file
called input.md
:
changequote(`{{', `}}')dnl
# post about the world
lorem ipsum ...
include({{src-def-sanitize-for-filename.md}})
... more text ...
you can compile the markdown with m4 -I./snippets/ input.md > result.md
.
markdown include
{!snippets/src-def-sanitize-for-filename.md!}
pymdown snippet extension
--8<-- "snippets/src-def-sanitize-for-filename.md"
Jekkyll Liquid
{% include snippets/src-def-sanitize-for-filename.md %}