Doxygen-style code snippet functionality

I’m writing tutorials for a library in Hugo and find that I am frequently copy/pasting snippets of functional example code into my tutorials. Has anyone thought or otherwise developed a method to include code snippets directly from source files? For example, Doxygen the \snippet command to do something similar to this.

You can use readFile and write your own shortcode:

Indeed. The problem isn’t reading the files, it is extracting snippets from the code. I suppose I could use readFile combined with some regular expression magic to make it happen within a shortcode; however, that’s less than ideal.

For the moment, I’m parsing the files ahead of time with SED and generating snippet files that are included with readFile. I’m hoping the Hugo gurus here might have a different idea than what I’ve described above.

This is how I did it.


  • from / to corresponding to the line numbers
  • filepath

then in the actual shortcode:

  • readFile filepath
  • split the file at line breaks
  • range through the lines printing out only the lines between from / to

It did a bunch of other things, but that’s the main bit.

Here’s what I ended up doing:

  1. I wrote a Python script that recursively reads a source tree and searches for Doxygen-style \snippet tags in the source code. It extracts the snippets to the data/snippets directory. If an error is found while parsing the snippet, the script errors out. The snippets are named using a Filename.Extention_SnippetName.txt convention.
  2. I wrote a shortcode that takes Filename SnippetName as arguments. The shortcode uses readFile to search for the corresponding snippet. It errors out if the snippet doesn’t exist.
  3. I wrote an external build script that calls the Python file followed by Hugo.

Although this is far from ideal, it is reasonably extensible if future versions of Hugo would permit more flexible files parsing techniques.