diff --git a/block.go b/block.go index 2636c52..cb3de22 100644 --- a/block.go +++ b/block.go @@ -101,7 +101,7 @@ func (p *parser) block(out *bytes.Buffer, data []byte) { // } // ``` if p.flags&EXTENSION_FENCED_CODE != 0 { - if i := p.fencedCode(out, data); i > 0 { + if i := p.fencedCode(out, data, true); i > 0 { data = data[i:] continue } @@ -599,7 +599,7 @@ func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (s return } -func (p *parser) fencedCode(out *bytes.Buffer, data []byte) int { +func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int { var lang *string beg, marker := p.isFencedCode(data, &lang, "") if beg == 0 || beg >= len(data) { @@ -631,7 +631,9 @@ func (p *parser) fencedCode(out *bytes.Buffer, data []byte) int { } // verbatim copy to the working buffer - work.Write(data[beg:end]) + if doRender { + work.Write(data[beg:end]) + } beg = end } @@ -640,7 +642,9 @@ func (p *parser) fencedCode(out *bytes.Buffer, data []byte) int { syntax = *lang } - p.r.BlockCode(out, work.Bytes(), syntax) + if doRender { + p.r.BlockCode(out, work.Bytes(), syntax) + } return beg } diff --git a/markdown.go b/markdown.go index 1b170e4..174bef8 100644 --- a/markdown.go +++ b/markdown.go @@ -305,6 +305,7 @@ func Markdown(input []byte, renderer Renderer, extensions int) []byte { // - expand tabs // - normalize newlines // - copy everything else +// - add missing newlines before fenced code blocks func firstPass(p *parser, input []byte) []byte { var out bytes.Buffer tabSize := TAB_SIZE_DEFAULT @@ -312,6 +313,8 @@ func firstPass(p *parser, input []byte) []byte { tabSize = TAB_SIZE_EIGHT } beg, end := 0, 0 + lastLineWasBlank := false + lastFencedCodeBlockEnd := 0 for beg < len(input) { // iterate over lines if end = isReference(p, input[beg:], tabSize); end > 0 { beg += end @@ -321,6 +324,16 @@ func firstPass(p *parser, input []byte) []byte { end++ } + // when last line was none blank and a fenced code block comes after + if !lastLineWasBlank && beg >= lastFencedCodeBlockEnd { + i := p.fencedCode(&out, append(input[beg:], '\n'), false) + if i > 0 { + out.WriteByte('\n') // need to inject additional linebreak + lastFencedCodeBlockEnd = beg + i + } + } + lastLineWasBlank = end == beg + // add the line body if present if end > beg { expandTabs(&out, input[beg:end], tabSize)