Eleventy Markdown code block line highlighting made simple
Numbered Code Block Lines in Eleventy with Shiki Twoslash
Last Updated
Markdown Code Block Styling, Part 1
This article is part of a series on styling markdown code blocks.
This first installment covers numbering lines. The second will cover highlighting lines. The third will cover added lines, deleted lines, and focused lines, in combination with numbered and/or highlighted lines.
The second, Highlight Code Block Lines In Eleventy with Shiki Twoslash, covers line highlighting.
The third will cover styling added lines, deleted lines, and focused lines, in combination with numbered and/or highlighted lines.
There’s no way to number lines in the code block HTML generated by Eleventy’s default Markdown library, markdown-it, which turns Markdown like this
into HTML like this
The Prism-based first party syntax highlighting plugin, eleventy-plugin-syntaxhighlight, doesn’t pick up on Prism’s line number support. You can try to hack it by misusing Prism’s line highlighting, setting eleventy-plugin-syntaxhighlight
’s undocumented alwaysWrapLineHighlights
option to true
, but ⚠️ there are multiple reports of that being glitchy — 11ty/eleventy-plugin-syntaxhighlight#10.
A solution
remark-shiki-twoslash, on the other hand, wraps each code block line in a div. For Eleventy v2 there’s the remark-shiki-twoslash
plugin eleventy-plugin-shiki-twoslash
. For Eleventy v3 you can use remark-shiki-twoslash
with a small wrapper in your .eleventy.js
file; see shikijs/twoslash#193 for details.
Shiki Twoslash, not to be confused with Shiki Twoslash
As of this writing, there are two Shiki Twoslashes, one under the shikijs org and one under the twoslashes org. remark-shiki-twoslash
uses shikijs/twoslash.
Not just for Eleventy
There are remark-shiki-twoslash
plugins for Markdown-It, Docusaurus, Eleventy, Gatsby, Hexo, and VuePress. Learn more at https://github.com/shikijs/twoslash.
This Markdown
becomes markup similar to this
A CSS counter can be used to style those .line
s. Something like
Opting out of line numbers
With remark-shiki-twoslash
, classes can be added to code blocks by including class attribute markup on the Markdown code block’s opening fence if a language is also specified on the opening fence.
This
renders as
Use that to support opting out of line numbers:
Mentions around the web
Reposts
Articles You Might Enjoy
-
Highlight Code Block Lines In Eleventy with Shiki Twoslash
-
-