Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display highlighted code blocks in Markdown code block in GitHub Flavored Markdown

I want to have a markdown block using ```md and inside of that Markdown block I want to have a JavaScript block using ```js.

I tried having:

```md
```js
function myFunction () {
   return 42;
}
```
```

This is how is rendered:

Basically, it's almost as expected, but the last ``` is missing (and a new code block was created instead).

I expected to see it like this:

I edited it in the browser developer tools.

So, basically, how to show JavaScript (or any other language) code blocks in Markdown code blocks in GitHub Flavored Markdown?


I did try to escape the ``` snippets using \`\`\` or \```, but they get rendered as well. I also tried to use more backticks for the Markdown code block, but that didn't work:

Currently I did this:

<pre>
```js
function myFunction () {
   return 42;
}
```
</pre>

But the code is not highlighted, obviously.

like image 402
Ionică Bizău Avatar asked Dec 25 '22 12:12

Ionică Bizău


1 Answers

What you are asking for is not possible. Markdown simply identifies a code block as one and then ignores the content. In other words, if you nest a second codeblock within the first one, Markdown simply sees that as part of the first codeblock and will not parse it as a codeblock itself. In fact, it can't because it is in a code block. How else would an author demonstrate how to nest code blocks?

Regarding highlighting, the JavaScript block nested in the Markdown codeblock should not be highlighted as JavaScript. In its current form it is sipmly a codeblock in a Markdown document. Therefore, any highlighting would be to indicate that it is a codeblock in a Markdown document. Weather the code contained therein is JavaScript, Python, Haskell, C, Perl, or anything else is irrelevant.

Finally, to nest one code block in another (using fenced code blocks) you need to use a different number of backticks for each level of nesting. Like this:

````md
```js
function myFunction () {
   return 42;
}
```
````

Which will correctly render as:

```js
function myFunction () {
   return 42;
}
```

Note that that is what a codeblock looks like in a Markdown document. So yes, that is the correct rendering. If you just want a JavaScript codebloc, then skip the nesting:

```js
function myFunction () {
   return 42;
}
```

Which will give you:

function myFunction () {
   return 42;
}
like image 85
Waylan Avatar answered May 06 '23 06:05

Waylan