lindelof
lindelof

Reputation: 35240

Is there a way in pandoc to include a filename on top of code blocks?

I'm working on a document in markdown (using pandoc for generating the final document) and would like to have code blocks showing excerpts from files. I would like to have the name of the file on top of the code block, something like this:

enter image description here

I have searched through pandoc's documentation but couldn't find anything.

Upvotes: 4

Views: 4253

Answers (2)

tarleb
tarleb

Reputation: 22609

One method would be to use attributes and custom CSS, like so:

<style>
div.sourceCode::before {
    content: attr(data-filename);
    display: block;
    background-color: #cfeadd;
    font-family: monospace;
}
</style>

``` {.python filename="ch1/test_one.py"}
def test_passing():
    assert (1, 2, 3) == (1, 2, 3)
```

This allows to specify the filename as a code block attribute, and uses CSS to render the attribute as a header.

rendered HTML


An alternative approach is via a pandoc filter; I usually suggest using Lua filters. This would also allow to include the file directly, so one could just write

``` {.python filename="ch1/test_one.py"}
```

and a filter would handle the content inclusion. It should be only a few lines of Lua.

Upvotes: 3

eskwayrd
eskwayrd

Reputation: 4521

Markdown generally does not have a facility to "include" files or excerpts of files, although there may be a Markdown variant that could support that capability. So, excerpts would normally be achieved through copy+paste.

You would also have to include the filename yourself. Markdown/Pandoc is not aware of the filenames for code snippets.

Separately, Markdown generally does not have a facility to apply custom styles. You would have to embed HTML to achieve that, and embedded HTML might prove problematic for output formats other than HTML.

Have you considered using Asciidoctor markup instead of Markdown? It's a markup format that is similar to, but more capable than Markdown. Asciidoctor permits file includes, file excerpts, and author-specified roles (which result in CSS classes). You could create your own include extension that embedded the name of an included file in the output (or copy+paste).

Upvotes: 0

Related Questions