Wrapping Code Blocks in Print

When I write, I usually export my Markdown to HTML before I create a .docx or .pdf. Most of what I write gets posted so, for me, exporting to HTML first only makes sense. If I need to create anything else, I can use Pandoc to convert from the HTML.

One of the cool things about Markdown is the ability to create code blocks. Code blocks are usually fixed-width text so that a reader can tell that they are looking at information that stands out from the rest of the text.

Once the Markdown is exported to HTML, the code block is displayed with no changes in formatting. If a line of code goes beyond the width of the browser’s view, a slider, at the bottom of the code block, appears, so that the reader can scroll left or right, to view the code.

This doesn’t really work in print, however. Text can go beyond the view of a web page because the scroll bar appears. Not so in print. Any text in the code block, beyond the right margin of the page, is cut off. This cutting off of excess text also occurs in e-books.

To get around this, we just adjust our CSS. Some Markdown editors allow us to export Markdown to HTML without styling and with styling. Choose styling if your editor gives that option.

Once the HTML is created, look for a line in your CSS that looks like this:

white-space: pre;

You’ll find it in a declaration similar to this:

pre>code {
  margin: 0;
  padding: 30;
  white-space: pre;
  border: none;
}

Change white-space: pre; to:

white-space: pre-wrap;

This change will allow your code block text to wrap when you print. An unintended side-effect is that you may lose the scroll bar, at the bottom of the code block, when displaying as a web page - but your code will wrap. From here, you can use Pandoc for create other documents from the HTML without your code getting cut off at the margin; it will wrap like the other parts of your document.

This change is also effective when using the HTML in .epub or other e-book formats.