Step 1 of 5 · Reading · ~3 min
Read
Block Elements
Paragraphs & Line Breaks
A paragraph is Markdown's default: any run of non-blank lines that no other block rule claimed. That makes the paragraph handler the last branch in your block dispatcher, and it makes the blank line the single most important character sequence in the format.
What ends a paragraph?
A blank line, and essentially nothing else. Two or three or ten blank lines do the same job as one — they are a separator, not a count.
Two details in eight lines of code carry most of the weight. if para: is what
stops a run of blank lines from emitting empty <p></p> shells. And the flush
after the loop is what saves the last paragraph of a document that does not end
with a blank line — the single most common way this function is written wrong.
The accumulator is a two-state machine
Every block type you add later plugs into this same skeleton: enter on a recognising line, accumulate, leave on a terminator, flush at EOF.
What does a newline inside a paragraph mean?
It is a soft line break. CommonMark is deliberate here: a conforming parser may render a soft break either as a line ending or as a single space, because browsers collapse both to the same thing. The reference implementation keeps the newline; this course joins with a space so expected output stays on one line. Both are legal — but know which one your tests picked.
A hard line break is different: it is a real <br />, and you ask for it
with two or more trailing spaces, or with a backslash immediately before the
newline.
| Source line ending | Result |
|---|---|
✓ roses are red·· (two spaces) | roses are red<br /> |
✓ roses are red\ (backslash) | roses are red<br /> |
✗ roses are red (nothing) | soft break — no <br /> |
| ✗ two spaces on the last line | stripped, no <br /> |
That last row is the trap. Trailing whitespace at the end of a block is removed before inline parsing runs, so a paragraph cannot end in a dangling break.
Two invisible spaces changing the output is the reason the backslash form exists, and the reason many style guides ban the space form outright.
Your exercise
Group stdin into paragraphs and wrap each one in <p>.
The mistake the grader catches is emitting an empty paragraph for blank
runs. One visible test feeds a document whose middle is three consecutive
blank lines; another begins with blank lines before any text, and another ends
with two. If your flush is unconditional you produce <p></p> for each blank
stretch and those three tests fail together — the count of <p> tags will be
wrong even though every word is in the right place.
Guard the flush with a "do I have any lines?" check, strip each line before joining, and the leading, trailing and repeated blank-line cases all pass with the same code path.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…