Render code blocks using a different font in Markdown

I’m trying to style CodeMirror into a rich text editor in Markdown mode. I’d like to style code blocks using a monospace font but the rest of the text should be rendered using a sans-serif font. This causes problems rendering whitespace characters since they aren’t wrapped in spans: there seems to be no CSS selector I can use to style only code blocks using a specific font.

Any help with this would be much appreciated.

Any input on this @marijn? I tried adding CSS classes to the HTML output after CodeMirror renders, but I’m guessing that the character positions are cached, because the cursor would render in a completely different position than what it looked like I was editing. I would happily hack the source to get this working, but can’t quite figure out which functions I should be calling after adding my CSS classes to update the calculated character positions.

Yes, you can’t mess with the HTML after it is rendered, but you might be able to kludge something together with a "renderLine" handler.

Excellent, will try, thank you!

You mean the indentation whitespace, right?
I’m seing a <span class=cm-comment> from first non-blank char to end of line (including internal and trailing spaces).
I added a class to the leading whitespace by trivial modification of trailingspace addon:

But that applies to ALL leading whitespace, not only on code block lines.
I wanted that, to help indenting lists: https://www.mathdown.net/?doc=help
But if you want it for blocks only, I don’t see anything better than renderLine looking for lines that contain only one cm-comment span…

How about modifying markdown mode itself (and gfm I think) to return a style like line-codeblock comment in code blocks? The line-... style would then be lifted by CM to the whole line, making styling easy.
Bonus: it should also allow styling code block background. (Ideally I’d like indented blocks to get grey background not on whole width but from the 4-space boundary to infinity; not sure it’s possible with CM.)
I’ll try to send a PR but not sure when I’ll get around to it.

Thanks @cben! I did manage to implement this feature by parsing the source myself (``` at the start of line), but obviously would prefer a built-in solution. I initially did look into modifying gfm mode but couldn’t quite figure out how everything works.

A renderLine event gets passed the CodeMirror and line objects as well as the element. How can you tell that the current line is inside of a code block given that information?

Could you share your code? I tried a few methods and observed values through debugging but it’s clear that I’m not familiar with CodeMirror. It would help a lot.