|
5 | 5 | package markdown |
6 | 6 |
|
7 | 7 | import ( |
| 8 | + "bytes" |
8 | 9 | "errors" |
9 | 10 | "html/template" |
10 | 11 | "io" |
@@ -182,6 +183,7 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error |
182 | 183 | bufWithMetadataLength := len(buf) |
183 | 184 |
|
184 | 185 | rc := &RenderConfig{Meta: markup.RenderMetaAsDetails} |
| 186 | + // Extract metadata if present. If not present, ExtractMetadataBytes returns original contents and an error. |
185 | 187 | buf, _ = ExtractMetadataBytes(buf, rc) |
186 | 188 | /* |
187 | 189 | // Only attempt to extract YAML front matter when the first line is a YAML separator |
@@ -225,6 +227,42 @@ func render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error |
225 | 227 | metaLength := max(bufWithMetadataLength-len(buf), 0) |
226 | 228 | rc.metaLength = metaLength |
227 | 229 |
|
| 230 | + // Workaround: goldmark may parse following lists as plain text if the original |
| 231 | + // input started with a hyphen-only line (e.g. "-" or "-------") but there |
| 232 | + // was no valid YAML front-matter. In that case, prefix the buffer with a |
| 233 | + // zero-width space so the parser doesn't treat the hyphen line specially. |
| 234 | + if rc.metaLength == 0 && len(buf) > 0 { |
| 235 | + // inspect the first line of the ORIGINAL contents (we have buf already set to body |
| 236 | + // so use the original length to find the original first line from input - but we no |
| 237 | + // longer have the original bytes. Instead, re-check the beginning of the current |
| 238 | + // buf: if it starts with a hyphen-only line, apply fix. This is safe because |
| 239 | + // ExtractMetadataBytes returned original contents if there was no metadata. |
| 240 | + idx := bytes.IndexByte(buf, '\n') |
| 241 | + firstLine := buf |
| 242 | + if idx >= 0 { |
| 243 | + firstLine = buf[:idx] |
| 244 | + } |
| 245 | + // check if firstLine contains only spaces and hyphens |
| 246 | + onlyHyphen := true |
| 247 | + foundHyphen := false |
| 248 | + for i := 0; i < len(firstLine); i++ { |
| 249 | + b := firstLine[i] |
| 250 | + if b == '-' { |
| 251 | + foundHyphen = true |
| 252 | + continue |
| 253 | + } |
| 254 | + if b == ' ' || b == '\t' || b == '\r' { |
| 255 | + continue |
| 256 | + } |
| 257 | + onlyHyphen = false |
| 258 | + break |
| 259 | + } |
| 260 | + if onlyHyphen && foundHyphen { |
| 261 | + // prefix zero-width space |
| 262 | + buf = append([]byte("\n"), buf...) |
| 263 | + } |
| 264 | + } |
| 265 | + |
228 | 266 | pc.Set(renderConfigKey, rc) |
229 | 267 |
|
230 | 268 | if err := converter.Convert(buf, lw, parser.WithContext(pc)); err != nil { |
|
0 commit comments