Search code examples
pandocepubkindle

Kindle displays source code with blank lines after each line


I have the following text in Markdown:

```
# Testing
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. 

```java
for (int i = 0; i < 10; i++) {
    System.out.println("hello world");
}
```

Then I convert this file to an epub using Pandoc. When I inspect this file in a desktop reader like Calibre it looks well:

ebook in calibre

However, Kindle displays the source code with an empty line after each line of source code. enter image description here

How can I style this so it does not display these empty lines on Kindle?


Solution

  • I found a solution to this problem after inspecting the epub's XHTML that Pandoc generates. Simplified, Pandoc creates the following structure from a source code block:

    <div class="sourceCode">
      <pre class="sourceCode">
        <code class="sourceCode">
          <span>for (int i = 0; i < 10; i++) {</span>
          <span>    System.out.println("hello world");</span>
          <span>}</span>
        </code>
      </pre>
    </div>
    

    For the <span> elements that are used for each line of code, the following styling statement causes the issue mentioned above:

    pre > code.sourceCode > span { display: inline-block; line-height: 1.25; }
    

    Tthe problem can be solved by overwriting this styling in a book's custom CSS via:

    pre > code.sourceCode > span { display: inline; }