Actually, you can even include code blocks inside lists without <pre>
, as long as you indent them by an extra four spaces (or one tab) for each level of nesting.
It looks best if you also consistently indent your nested lists by four spaces; while the Markdown parser is generally forgiving and allows you to use any number of spaces to indent lists, code blocks are a special case and require more rigor.
Example:
* This is a list item.
This is another paragraph inside the same list item.
This is a code block inside the list item.
* This is a nested list item.
This is a code block inside the nested list item.
* This is another list item.
Produces:
This is a list item.
This is another paragraph inside the same list item.
This is a code block inside the list item.
This is another list item.
A problem does occur if you want a code block to immediately follow a list item, but not be nested inside it. One solution is to reset the nesting level e.g. by placing a dummy HTML comment (<!-- comment -->
) before the code block. (On sites that have syntax highlighting enabled, like SO, you can also use the comment to specify the correct language for the highlighter.)
For example:
* This is a list item.
This is some normal text inside the list item.
<!-- this is an invisible comment -->
This is a code block outside the list.
Produces:
This is a code block outside the list.
Of course, all this also works with numbered lists (1.
, 2.
, etc.) and block quotes (>
) just like it works with bulleted lists (*
/ +
/ -
).
One thing you cannot do, however, is briefly "pop out" of a list back to a lower indentation level, and then later return to the higher indentation without a new bullet point / item number. That is to say, this will not work, and cannot be made to work:
* This is a list item.
This is some normal, non-indented text.
This is supposed to be a continuation of the previous list item
(but will actually be parsed as a code block).
Alas, there's really nothing you can do about that, except to rethink the structure of your post. Markdown simply does not support this.
(In fact, it's kind of tricky to achieve this even in raw HTML, although there are a couple of more or less klugy solutions, like setting a negative CSS margin on the "outdented" block, or making the continuation a separate list item with an invisible bullet. None of those work on SE, though.)