Code highlighting with Markdown, Pygments and CodeHiliteExtension in Django. Regular code blocks work nice, but inline code like `print("hi")` doesn't

I have a problem with Markdown, Pygments and CodeHiliteExtension in Django. I have a blog post written in Markdown, then I have a save function like that:

    def save(self, *args, **kwargs):
        # Convert Markdown to HTML with syntax highlighting
        self.text_html = markdown.markdown(
            str(self.text_markdown),
            extensions=[
                "extra",
                "fenced_code",
                CodeHiliteExtension(linenums=False, css_class="codehilite", pygments_style="lightbulb"),
            ],
        )
        self.preview_html = markdown.markdown(
            str(self.preview_markdown),
            extensions=[
                "extra",
                "fenced_code",
                CodeHiliteExtension(linenums=False, css_class="codehilite", pygments_style="lightbulb"),
            ],
        )

        super().save(*args, **kwargs)

It works nicely - I mean it's highlighting a full Mardown code blocks with all syntax like that:

/```python

/print("hi")

/```

(without the forward slash, I used it as an escape character for the post formatting).

But the inline code like that - ``print("hi")` is not working.

I tried to use variations of pymdownx.inlinehilite in extensions but I wasn't able to make it work. After some googling I found this - https://facelessuser.github.io/pymdown-extensions/extensions/inlinehilite/ And right now I am able to get inline code to highlight properly by using regex and manually adding missing characters like - ":::language mycode" but it's of course far from the clean solution.

I was also looking into prism.js (which works well) but I wanted to avoid using additional JavaScript. But maybe it will be cleaner after all?

So I wanted to ask you about a nicer way to force Pygments to work with both regular code blocks and inline or some better alternatives?

Back to Top