ines/course-starter-python

Syntax highlighting in code blocks in slides

rly opened this issue ยท 4 comments

rly commented

Suggestion: Would it be possible to add syntax highlighting in code blocks in the slides? Syntax highlighting exists for exercises, but for slides with a lot of code, it would help the reader to have syntax colored the same way. Currently, code in the slides is colored uniformly as var(--syntax-text) in slides.module.sass.

Thank you! This is an awesome starter package.

ines commented

Thanks! And yes, the problem at the moment is that the code blocks in the slides aren't actually parsed by any the syntax highlighter. The slides stuff was a bit annoying to set up, so I didn't end up adding the highlighting.

I just tested it and you should be able to add the following at the end of componentDidMount in components/slides.js:

const langs = ['python']  // whichever languages you need
Promise.all(langs.map(lang => import(`prismjs/components/prism-${lang}`))).then(() =>
    Prism.highlightAll()
)

And import Prism at the top:

import Prism from 'prismjs'

This will only add the underlying markup and classes โ€“ you'll still have to add the Prism theme and/or CSS styling of the classes, e.g. in index.sass where the other syntax highlighting is defined.

It'd be nice to make this an out-of-the-box feature as well! But I still need to come up with a good way to not require a list of languages upfront or make them easily configurable.

rly commented

Awesome, that worked!

It would also be nice for the exercises and slides to use the same syntax labeler/highlighter (currently CodeMirror and Prism) since there are slight discrepancies between how they label code. But this is a great solution for the time being. Thank you.

ines commented

Yeah, the thing is that CodeMirror kinda implements its own highlightighting, as far as I know. We need to use that for the interactive editors, while the static code blocks should stay static. Prism integrates well with Markdown, so I've been using that for the static code blocks in the exercises and now also in the slides. (Reveal.js integrates more deeply with Highlight.js, but there's absolutely no way I'm going to use three different syntax highlighters in the same project ๐Ÿ˜…)

Btw, if you end up finding a solution for syncing Prism and CodeMirror better, let me know. I'm using the two together quite a lot and I've also noticed the difference in highlighting.

rly commented

Interestingly, after the slides are closed and reopened, Prism cannot find any elements to highlight. Must have something to do with how React loads cached data. I don't know. So I crudely changed your workaround to:

const langs = ['python']
Promise.all(langs.map(lang => import(`prismjs/components/prism-${lang}`))).then(() =>
     setTimeout(() => { Prism.highlightAll() }, 1000)
)

and now it works great. Just updating for others to see.