Codebraid – live code in Pandoc Markdown

Always interesting to see how this person tackled the idea of inlined executable journals


Markdown source test.md:

```{.python .cb.run}
print('Hello from Python!')
print('$2^8 = {}$'.format(2**8))
```

Run codebraid (to save the output, add something like -o test_out.md, and
add --overwrite if it already exists):

codebraid pandoc --from markdown --to markdown test.md

Output:

Hello from Python! $2^8 = 256$
1 Like

This is actually something you can do quite easily in pandoc without any external tools, using the built-in lua filters.

Create run.lua:

--- run.lua
function CodeBlock(el)
  if el.classes:includes("run") then
    local prog = el.classes[1]
    local result = pandoc.pipe(prog, {}, el.text)
    return pandoc.RawBlock(FORMAT, result)
  end
end

function Code(el)
  if el.classes:includes("run") then
    local prog = el.classes[1]
    local result = pandoc.pipe(prog, {}, el.text):gsub('\n$','')
    return pandoc.RawInline(FORMAT, result)
  end
end

Now run

% cat > test.md
```{.python .run}
print("Hello from Python!")
print('$2^8 = {}$'.format(2**8))
```

Here's the date: `date`{.sh .run}.
^D
% pandoc --lua-filter run.lua -t markdown test.md 
Hello from Python!
$2^8 = 256$

Here's the date: Thu Feb 28 09:52:21 PST 2019.

Note that the lua interpreter is built into pandoc, so you don’t need to install anything other than pandoc to use this.

3 Likes