jk's blog

Including GitHub Source Code into Markdown with a Preprocessor

I’m doing some writing in Pandoc, and the Markdown implementation doesn’t have an “include” feature to pull in source code. After looking around, there are some tools that implement #include or !include, but there weren’t quite what I wanted, so I wrote this in awk.

#! /usr/bin/awk -f

  if ( $1 == "#sourcecode" ) {
        print filename ":n"
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
        system(sprintf("cat %s", filename));
        print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
  } else {
        print $0

To use it:

This is some markdown text.

#sourcecode path/to/listing.py

In your dev environment, you can clone a Git repo with all your sources.

Obviously, this script could be rewritten to make nicer paths, allow titles, and so forth, but this works for now.