Search code examples
pdfmarkdownpandoc

How to add a border to code blocks in pandoc?


I'm writing a Markdown file with code blocks in it, then building it to both DOCX and PDF with pandoc, specifically:

pandoc myfile.md --to=docx --defaults=defaults.yml -o myfile.docx
pandoc myfile.md --to=latex --defaults=defaults.yml -o myfile.pdf

The defaults.yml file just specifies LaTeX margins and to include a ToC.

The output looks very nice, but I'd like there to be borders around the code blocks, to make them visually separate from the surrounding text.

This TeX StackExchange question suggests changing the highlighting style to a dark theme, but my readers will definitely prefer a light one.

This SO question suggests switching to the listings package, but that produces much uglier code than pandoc's default. (That post is also 6 years old, and pandoc has changed a lot since then.)

Is there a way that doesn't have one of these downsides?


Solution

  • For LaTeX, you could use the highly customizable tcolorbox package to wrap the code block, inserting the necessary code via a Lua filter:

    function raw_tex (t)
      return pandoc.RawBlock('tex', t)
    end
    
    --- Wrap code blocks in tcolorbox environments
    function CodeBlock (cb)
      return {raw_tex'\\begin{tcolorbox}', cb, raw_tex '\\end{tcolorbox}'}
    end
    
    --- Ensure that the longfbox package is loaded.
    function Meta (m)
      m['header-includes'] = {raw_tex '\\usepackage{tcolorbox}'}
      return m
    end
    

    See the tcolorbox docs for more details.


    Docx is easier: modify the "Source Code" text style, then use the altered document as --reference-doc.