DEV Community

zhihu wu
zhihu wu

Posted on

Four Spaces Is a Syntax Element: When Markdown Turns Your Text Into Code

I pasted a failing command into a README last week and the page rendered it inside a grey code box. I pasted the same two lines into a GitHub issue and they came out as ordinary prose. Nothing about the text changed. What changed was one empty line.

That is the whole trick. In Markdown, four spaces at the start of a line is not "indentation" — it is the code-block syntax. Whether those four spaces act as an indent or as code depends entirely on what comes before them.

Same text, two outputs:

Here is what happened:
    npm install failed
Enter fullscreen mode Exit fullscreen mode

That renders as a single paragraph; the spaces survive as spaces inside one <p>. Now insert one blank line:

Here is what happened:

    npm install failed
Enter fullscreen mode Exit fullscreen mode

and you get <p> followed by <pre><code>. I ran both through marked, the GFM parser GitHub, Dev.to and most static site generators use. Same library, same text, one blank line apart.

A few rules follow from that, and I measured each of them:

  • Three spaces is still a paragraph, four is code, and a tab counts as code. Three leading spaces after a blank line gave me a <p> with the three spaces preserved.
  • Inside a list the threshold moves right. A code block has to be indented four spaces past the item's text column, not past the page margin. Under - Step one: four spaces produced a plain paragraph inside the list item; eight produced a <pre> inside it. Under 1. item the text column is one character deeper, so the minimum is seven.
  • Continuation is lazy. A line with no > marker following > quoted line still belongs to the blockquote. A line indented by a single space after - item one still belongs to the list item. Removing the marker does not necessarily get you out of the container, and neither does removing the indentation.

The practical failure modes are both boring and both silent. Prose pasted from a log excerpt, a YAML fragment, or a chat transcript arrives indented and turns into a code block. A code sample indented three spaces looks correctly indented in your editor and renders as a wall of text. Neither one produces an error message; you only see it after publishing.

The fix is to delete the leading whitespace, or fence the block explicitly with three backticks. A fence carries no blank-line dependency, so it stays a code block no matter where you paste it. And check the rendered result, not the source, because this is exactly the case where the source looks right and the HTML is wrong.

I keep a local GFM preview open while editing READMEs: codetoolbox.pro/tools/markdown-preview.html renders with marked in the browser, so pasting the file shows the paragraph-versus-code flip immediately and nothing is uploaded anywhere.

Top comments (0)