Recommended way to print whole editor’s formatted content

I’m wondering what would be the best way to print the entire (formatted) content of the editor when hitting Cmd+P in the browser.

My first approach was to register an event listener with window.beforeprint which passes the contents of state.doc.toString() to an external highlighter library (e.g., marked) and updates the normally hidden DOM element for print content with its resulting HTML.

However, this does not produce a correct print preview. Since events are asynchronous, the print preview shows an empty document. I cannot force the print dialog to wait until my DOM is up-to-date.

So the second thing I tried, was to update den print DOM on every doc change. But this is very costly in terms of CPU, since this happens on every key press. Especially with large documents. So I tried to get rid of the external syntax highlighter and just use CM’s markup by writing editor.contentDOM.innerHTML into my desired printable DOM element. However, this only prints what’s currently inside CM’s buffer and not the whole document.

I’m really out of ideas right now. Maybe anyone had a similar challenge?

I’m really quite sure beforeprint runs before the document is queried for printing (a test seems to confirm this in both Firefox and Chrome), so I suppose you should look at that again.

After some additional troubleshooting, I can confirm, that window.beforeprint actually allows DOM manipulations to happen before the print view is generated. The problem in my case was the framework: Vue.js. The Vue component didn’t update in time. If I manipulate the DOM directly inside the event handler, it works. Thanks for your feedback!

This brings me to another question: Is it possible to get the whole syntax highlighted HTML from CodeMirros’s view? Basically editor.contentDOM.innerHTML but for the whole document, not just the current buffer? This would save me another syntax highlighter just for the print view.

See highlightTree, which you should be able to use to syntax-highlight the editor’s tree pretty easily.

Cool, thanks. But this doesn’t include my view updates via MatchDecorator, right?

No, that’s just syntax highlighting.