-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsite_markdown.go
More file actions
1429 lines (1274 loc) · 36.7 KB
/
Copy pathsite_markdown.go
File metadata and controls
1429 lines (1274 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gomark
import (
"errors"
"fmt"
"html"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// routeFromFrontmatter returns an explicit route override from frontmatter
// (slug/permalink/route), normalized to a clean, fragment-free "/..." path, or
// "" if none is set or it cannot be made safe. Dot-segments are resolved so an
// override can never escape the site root (and, in the exporter, never escape
// the output directory).
func routeFromFrontmatter(meta map[string]string) string {
if meta == nil {
return ""
}
raw := strings.TrimSpace(firstNonEmpty(meta["slug"], meta["permalink"], meta["route"]))
if raw == "" {
return ""
}
route := normalizeLinkTarget(raw)
// Routes are paths, not anchors: drop any fragment.
if i := strings.IndexByte(route, '#'); i >= 0 {
route = route[:i]
}
if !strings.HasPrefix(route, "/") {
return ""
}
// path.Clean collapses "." and ".." (and ".." at root is dropped), so the
// result is always a rooted path that stays within the site.
cleaned := path.Clean(route)
if !strings.HasPrefix(cleaned, "/") {
return ""
}
return cleaned
}
var (
ErrInvalidMarkdownPath = errors.New("invalid markdown path")
ErrMarkdownNotFound = errors.New("markdown file not found")
)
var orderedListRe = regexp.MustCompile(`^(\d+)\.\s+(.+)$`)
var slugRe = regexp.MustCompile(`[^a-z0-9]+`)
// calloutRe matches a GitHub-style admonition marker (`[!NOTE]`, `[!TIP]`, …) as the
// first line of a blockquote, capturing the kind and any trailing inline text.
var calloutRe = regexp.MustCompile(`(?i)^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$`)
// tableSepCellRe matches a single GFM table delimiter cell (e.g. `---`, `:--`, `--:`,
// `:-:`), used to confirm that a `|`-bearing line is a real table header.
var tableSepCellRe = regexp.MustCompile(`^:?-+:?$`)
// listItem is one collected list entry. depth is the nesting level derived from leading
// indentation (two spaces per level); ordered distinguishes <ol> from <ul>. num is the
// source number of an ordered item (so an interrupted list resumes via <ol start>), and
// task is 0 for a plain item, 1 for an unchecked task ([ ]), or 2 for a checked one ([x]).
type listItem struct {
depth int
ordered bool
num int
task int
text string
}
// Heading is a single in-page heading collected during rendering, used to build
// the on-page table of contents.
type Heading struct {
Level int
Text string
ID string
}
type MarkdownRenderer interface {
Render(markdown string) (html string, headings []Heading)
}
type StdlibMarkdownRenderer struct {
RunnerEnabled bool
}
type MarkdownService struct {
renderer MarkdownRenderer
contentDir string
}
func NewMarkdownService(renderer MarkdownRenderer, contentDir string) MarkdownService {
if renderer == nil {
renderer = StdlibMarkdownRenderer{}
}
if strings.TrimSpace(contentDir) == "" {
contentDir = "content"
}
return MarkdownService{
renderer: renderer,
contentDir: filepath.Clean(contentDir),
}
}
// RenderedPage is the result of loading a markdown file: its resolved path, the
// rendered HTML body, and metadata pulled from optional YAML frontmatter.
type RenderedPage struct {
Path string
HTML string
Title string
Description string
Headings []Heading
HideTOC bool
HideNav bool
}
func (s MarkdownService) LoadAndRender(slug string) (RenderedPage, error) {
resolved, err := resolveContentPath(s.contentDir, slug)
if err != nil {
return RenderedPage{}, err
}
data, readErr := os.ReadFile(resolved)
if readErr != nil {
if errors.Is(readErr, os.ErrNotExist) {
return RenderedPage{}, ErrMarkdownNotFound
}
return RenderedPage{}, fmt.Errorf("read markdown %s: %w", resolved, readErr)
}
meta, body := parseFrontmatter(string(data))
title := meta["title"]
if heading, rest, ok := stripLeadingH1(body); ok {
body = rest
if title == "" {
title = heading
}
}
description := firstNonEmpty(meta["description"], meta["tagline"], meta["lede"])
html, headings := s.renderer.Render(body)
headings = limitTOCDepth(headings, tocDepth(meta))
return RenderedPage{
Path: resolved,
HTML: html,
Title: title,
Description: description,
Headings: headings,
HideTOC: tocHidden(meta),
HideNav: navHidden(meta),
}, nil
}
// frontmatterBool interprets a frontmatter value as a boolean, recognizing the
// usual truthy/falsy spellings ("true"/"false", "yes"/"no", "on"/"off",
// "show"/"hide", "1"/"0"). It returns ok=false if the key is absent or the
// value isn't recognized, so callers can fall back to other keys or defaults.
func frontmatterBool(meta map[string]string, key string) (value bool, ok bool) {
raw, present := meta[key]
if !present {
return false, false
}
switch strings.ToLower(strings.TrimSpace(raw)) {
case "false", "0", "no", "off", "hide", "none":
return false, true
case "true", "1", "yes", "on", "show":
return true, true
default:
return false, false
}
}
// tocHidden reports whether frontmatter disables the on-page table of contents,
// via either `toc: false` or `show_toc: false` (the latter takes precedence,
// letting a page override a folder/site default explicitly either way).
func tocHidden(meta map[string]string) bool {
if show, ok := frontmatterBool(meta, "show_toc"); ok {
return !show
}
if show, ok := frontmatterBool(meta, "toc"); ok {
return !show
}
return false
}
// navHidden reports whether frontmatter hides the sidebar navigation for this
// page via `show_nav: false` (also accepts 0/no/off/hide/none).
func navHidden(meta map[string]string) bool {
if show, ok := frontmatterBool(meta, "show_nav"); ok {
return !show
}
return false
}
// tocDepth returns the maximum heading level to include in the TOC from
// frontmatter `toc_depth` (2 or 3). It defaults to 3 (H2 + H3).
func tocDepth(meta map[string]string) int {
raw := strings.TrimSpace(firstNonEmpty(meta["toc_depth"], meta["tocdepth"]))
if raw == "" {
return 3
}
if n, err := strconv.Atoi(raw); err == nil && n >= 2 && n <= 3 {
return n
}
return 3
}
func limitTOCDepth(headings []Heading, maxLevel int) []Heading {
if maxLevel >= 3 {
return headings
}
out := make([]Heading, 0, len(headings))
for _, h := range headings {
if h.Level <= maxLevel {
out = append(out, h)
}
}
return out
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}
// parseFrontmatter splits an optional leading "---" YAML block from the body.
// It is intentionally minimal (flat key: value pairs) to stay dependency-free;
// values are trimmed of surrounding quotes and keys are lowercased.
func parseFrontmatter(raw string) (map[string]string, string) {
normalized := strings.ReplaceAll(raw, "\r\n", "\n")
lines := strings.Split(normalized, "\n")
if len(lines) == 0 || strings.TrimSpace(lines[0]) != "---" {
return nil, raw
}
closing := -1
for i := 1; i < len(lines); i++ {
if strings.TrimSpace(lines[i]) == "---" {
closing = i
break
}
}
if closing == -1 {
return nil, raw
}
meta := make(map[string]string)
for _, line := range lines[1:closing] {
key, value, found := strings.Cut(line, ":")
key = strings.ToLower(strings.TrimSpace(key))
if !found || key == "" {
continue
}
meta[key] = strings.Trim(strings.TrimSpace(value), `"'`)
}
body := strings.TrimLeft(strings.Join(lines[closing+1:], "\n"), "\n")
return meta, body
}
// stripLeadingH1 removes a leading "# Title" line so the body doesn't duplicate
// the page header rendered from frontmatter. It returns the heading text, the
// trimmed body, and whether a leading H1 was found.
func stripLeadingH1(body string) (string, string, bool) {
lines := strings.Split(body, "\n")
idx := 0
for idx < len(lines) && strings.TrimSpace(lines[idx]) == "" {
idx++
}
if idx >= len(lines) {
return "", body, false
}
heading := strings.TrimSpace(lines[idx])
if !strings.HasPrefix(heading, "# ") {
return "", body, false
}
remaining := append(lines[:idx:idx], lines[idx+1:]...)
rest := strings.TrimLeft(strings.Join(remaining, "\n"), "\n")
return strings.TrimSpace(heading[2:]), rest, true
}
func resolveContentPath(contentDir, slug string) (string, error) {
page := strings.TrimSpace(slug)
if page == "" {
page = "home"
}
cleanPage := filepath.Clean(page)
if filepath.IsAbs(cleanPage) {
return "", ErrInvalidMarkdownPath
}
if filepath.Ext(cleanPage) == "" {
cleanPage += ".md"
}
if filepath.Ext(cleanPage) != ".md" {
return "", ErrInvalidMarkdownPath
}
fullPath := filepath.Clean(filepath.Join(contentDir, cleanPage))
rel, err := filepath.Rel(contentDir, fullPath)
if err != nil {
return "", ErrInvalidMarkdownPath
}
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", ErrInvalidMarkdownPath
}
return fullPath, nil
}
func splitFenceInfo(info string) []string {
info = strings.TrimSpace(info)
if info == "" {
return nil
}
if prefix, rest, found := strings.Cut(info, ":"); found && !strings.ContainsAny(prefix, " \t\n\r") {
info = strings.TrimSpace(prefix + " " + rest)
}
var tokens []string
var current strings.Builder
var quote rune
justClosedQuote := false
flush := func() {
if current.Len() == 0 {
return
}
tokens = append(tokens, current.String())
current.Reset()
}
for _, r := range info {
switch {
case quote != 0:
if r == quote {
quote = 0
justClosedQuote = true
continue
}
current.WriteRune(r)
case r == '"' || r == '\'':
quote = r
case r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == ':':
flush()
justClosedQuote = false
default:
if justClosedQuote {
flush()
justClosedQuote = false
}
current.WriteRune(r)
}
}
flush()
return tokens
}
func (s StdlibMarkdownRenderer) Render(markdown string) (string, []Heading) {
lines := strings.Split(strings.ReplaceAll(markdown, "\r\n", "\n"), "\n")
var out strings.Builder
var headings []Heading
seen := map[string]int{}
makeID := func(text string) string {
base := slugify(text)
count := seen[base]
seen[base]++
if count == 0 {
return base
}
return fmt.Sprintf("%s-%d", base, count)
}
var paragraph []string
var quote []string
var listItems []listItem
var codeLines []string
inCode := false
codeLang := ""
codeTitle := ""
codeRun := false
codeEditable := false
codeGroup := ""
codeFenceChar := ""
codeFenceLen := 0
flushParagraph := func() {
if len(paragraph) == 0 {
return
}
out.WriteString("<p>")
out.WriteString(renderInline(strings.Join(paragraph, " ")))
out.WriteString("</p>\n")
paragraph = nil
}
flushQuote := func() {
if len(quote) == 0 {
return
}
if m := calloutRe.FindStringSubmatch(quote[0]); m != nil {
kind := strings.ToLower(m[1])
body := make([]string, 0, len(quote))
if rest := strings.TrimSpace(m[2]); rest != "" {
body = append(body, rest)
}
body = append(body, quote[1:]...)
out.WriteString(`<div class="callout callout-` + kind + `">`)
out.WriteString(`<p class="callout-title">` + calloutLabel(kind) + `</p>`)
if len(body) > 0 {
out.WriteString("<p>")
out.WriteString(renderInline(strings.Join(body, " ")))
out.WriteString("</p>")
}
out.WriteString("</div>\n")
quote = nil
return
}
out.WriteString("<blockquote><p>")
out.WriteString(renderInline(strings.Join(quote, " ")))
out.WriteString("</p></blockquote>\n")
quote = nil
}
flushList := func() {
if len(listItems) == 0 {
return
}
for i := 0; i < len(listItems); {
i = emitList(&out, listItems, i, listItems[0].depth)
}
listItems = nil
}
flushCode := func() {
if len(codeLines) == 0 && codeLang == "" {
return
}
title := codeTitle
if title == "" {
if codeLang != "" {
title = codeLang
} else {
title = "code"
}
}
classAttr := ""
if codeLang != "" {
classAttr = ` class="language-` + html.EscapeString(codeLang) + `"`
}
allowRun := s.RunnerEnabled && strings.EqualFold(codeLang, "go") && (codeRun || codeEditable)
editableAttr := "false"
if codeEditable {
editableAttr = "true"
}
out.WriteString("<div class=\"code-frame\"")
if codeEditable {
out.WriteString(" data-code-editable=\"true\"")
}
if allowRun {
out.WriteString(" data-runner-run=\"true\" data-runner-editable=\"")
out.WriteString(editableAttr)
out.WriteString("\"")
}
if codeGroup != "" {
// Adjacent code-frames sharing a group are merged into a tabbed
// multi-file example by the client; the title becomes the tab label.
out.WriteString(" data-tab-group=\"")
out.WriteString(html.EscapeString(codeGroup))
out.WriteString("\" data-tab-title=\"")
out.WriteString(html.EscapeString(title))
out.WriteString("\"")
}
out.WriteString(">")
out.WriteString("<div class=\"code-frame-header\">")
out.WriteString("<span class=\"code-frame-title\">")
out.WriteString(html.EscapeString(title))
out.WriteString("</span>")
out.WriteString("<div class=\"code-frame-actions\">")
if allowRun && codeEditable {
out.WriteString("<button type=\"button\" class=\"code-format\" data-format-code=\"\" aria-label=\"Format code block\" title=\"Format with gofmt\">Format</button>")
}
if allowRun {
out.WriteString("<button type=\"button\" class=\"code-run\" data-run-code=\"\" aria-label=\"Run code block\" title=\"Run in runner\">Run</button>")
}
out.WriteString("<button type=\"button\" class=\"code-copy\" data-copy-code=\"\" aria-label=\"Copy code block\" title=\"Copy code\">")
out.WriteString("<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg>")
out.WriteString("</button>")
out.WriteString("</div>")
out.WriteString("</div>")
out.WriteString("<pre><code")
out.WriteString(classAttr)
out.WriteString(">")
out.WriteString(html.EscapeString(strings.Join(codeLines, "\n")))
out.WriteString("</code></pre>")
out.WriteString("</div>\n")
codeLines = nil
codeLang = ""
codeTitle = ""
codeRun = false
codeEditable = false
codeGroup = ""
codeFenceChar = ""
codeFenceLen = 0
}
parseFence := func(line string) (string, int, string, bool) {
if line == "" {
return "", 0, "", false
}
var fenceChar byte
switch line[0] {
case '`', '~':
fenceChar = line[0]
default:
return "", 0, "", false
}
count := 0
for count < len(line) && line[count] == fenceChar {
count++
}
if count < 3 {
return "", 0, "", false
}
return string(fenceChar), count, strings.TrimSpace(line[count:]), true
}
parseFenceInfo := func(info string) (string, string, bool, bool, string) {
tokens := splitFenceInfo(info)
lang := ""
title := ""
run := false
editable := false
group := ""
for _, token := range tokens {
key, value, found := strings.Cut(token, "=")
if found {
switch strings.ToLower(strings.TrimSpace(key)) {
case "title", "name":
title = strings.TrimSpace(value)
case "run":
run = parseBoolMeta(value)
case "editable":
editable = parseBoolMeta(value)
case "group", "tab":
group = strings.TrimSpace(value)
}
continue
}
if lang == "" {
lang = token
}
}
if title == "" {
title = lang
}
return lang, title, run, editable, group
}
for i := 0; i < len(lines); i++ {
raw := lines[i]
line := strings.TrimRight(raw, "\r")
trimmed := strings.TrimSpace(line)
depth := (len(line) - len(strings.TrimLeft(line, " "))) / 2
if inCode {
if fenceChar, fenceLen, _, ok := parseFence(trimmed); ok && fenceChar == codeFenceChar && fenceLen >= codeFenceLen {
inCode = false
flushCode()
continue
}
codeLines = append(codeLines, line)
continue
}
if fenceChar, fenceLen, info, ok := parseFence(trimmed); ok {
flushParagraph()
flushQuote()
flushList()
inCode = true
codeFenceChar = fenceChar
codeFenceLen = fenceLen
codeLang, codeTitle, codeRun, codeEditable, codeGroup = parseFenceInfo(info)
codeLines = nil
continue
}
if trimmed == "" {
flushParagraph()
flushQuote()
flushList()
continue
}
if trimmed == "---" {
flushParagraph()
flushQuote()
flushList()
out.WriteString("<hr />\n")
continue
}
if strings.HasPrefix(trimmed, ">") {
flushParagraph()
flushList()
content := strings.TrimSpace(strings.TrimPrefix(trimmed, ">"))
quote = append(quote, content)
continue
}
// GFM table: a `|`-bearing line immediately followed by a delimiter row.
if strings.Contains(trimmed, "|") && i+1 < len(lines) {
nextTrim := strings.TrimSpace(strings.TrimRight(lines[i+1], "\r"))
if aligns, ok := parseTableSeparator(nextTrim); ok {
flushParagraph()
flushQuote()
flushList()
header := splitTableRow(trimmed)
out.WriteString("<table>\n<thead>\n<tr>")
for c, cell := range header {
al := ""
if c < len(aligns) {
al = aligns[c]
}
out.WriteString("<th")
if al != "" {
out.WriteString(` style="text-align:` + al + `"`)
}
out.WriteString(">")
out.WriteString(renderInline(cell))
out.WriteString("</th>")
}
out.WriteString("</tr>\n</thead>\n<tbody>\n")
j := i + 2
for j < len(lines) {
rowTrim := strings.TrimSpace(strings.TrimRight(lines[j], "\r"))
if rowTrim == "" || !strings.Contains(rowTrim, "|") {
break
}
cells := splitTableRow(rowTrim)
out.WriteString("<tr>")
for c := 0; c < len(header); c++ {
val := ""
if c < len(cells) {
val = cells[c]
}
al := ""
if c < len(aligns) {
al = aligns[c]
}
out.WriteString("<td")
if al != "" {
out.WriteString(` style="text-align:` + al + `"`)
}
out.WriteString(">")
out.WriteString(renderInline(val))
out.WriteString("</td>")
}
out.WriteString("</tr>\n")
j++
}
out.WriteString("</tbody>\n</table>\n")
i = j - 1
continue
}
}
if strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* ") {
flushParagraph()
flushQuote()
task, text := parseTaskListItem(strings.TrimSpace(trimmed[2:]))
listItems = append(listItems, listItem{depth: depth, ordered: false, task: task, text: text})
continue
}
if matches := orderedListRe.FindStringSubmatch(trimmed); len(matches) == 3 {
flushParagraph()
flushQuote()
num, _ := strconv.Atoi(matches[1])
listItems = append(listItems, listItem{depth: depth, ordered: true, num: num, text: strings.TrimSpace(matches[2])})
continue
}
headingLevel, headingText, ok := parseHeading(trimmed)
if ok {
flushParagraph()
flushQuote()
flushList()
id := makeID(headingText)
out.WriteString(fmt.Sprintf("<h%d id=\"%s\">%s<a class=\"heading-anchor\" href=\"#%s\" aria-label=\"Permalink to this section\">#</a></h%d>\n", headingLevel, id, renderInline(headingText), id, headingLevel))
if headingLevel == 2 || headingLevel == 3 {
headings = append(headings, Heading{Level: headingLevel, Text: headingPlain(headingText), ID: id})
}
continue
}
if len(quote) > 0 {
flushQuote()
}
if len(listItems) > 0 {
flushList()
}
paragraph = append(paragraph, trimmed)
}
if inCode {
flushCode()
}
flushParagraph()
flushQuote()
flushList()
return out.String(), headings
}
func parseBoolMeta(value string) bool {
v := strings.ToLower(strings.Trim(strings.TrimSpace(value), `"'`))
switch v {
case "1", "true", "yes", "on":
return true
default:
return false
}
}
// slugify turns heading text into a URL-fragment id: lowercase, runs of
// non-alphanumerics collapsed to single hyphens, trimmed.
func slugify(text string) string {
s := slugRe.ReplaceAllString(strings.ToLower(strings.TrimSpace(text)), "-")
s = strings.Trim(s, "-")
if s == "" {
return "section"
}
return s
}
// headingPlain strips inline markdown markers so a heading reads cleanly as a
// table-of-contents label.
func headingPlain(text string) string {
r := strings.NewReplacer("`", "", "**", "", "*", "", "_", "")
return strings.TrimSpace(r.Replace(text))
}
func parseHeading(line string) (int, string, bool) {
count := 0
for count < len(line) && line[count] == '#' {
count++
}
if count < 1 || count > 6 {
return 0, "", false
}
if len(line) <= count || line[count] != ' ' {
return 0, "", false
}
return count, strings.TrimSpace(line[count+1:]), true
}
func renderInline(input string) string {
remaining := input
var out strings.Builder
for {
start := strings.Index(remaining, "`")
if start == -1 {
out.WriteString(renderInlineText(remaining))
break
}
before := remaining[:start]
out.WriteString(renderInlineText(before))
rest := remaining[start+1:]
end := strings.Index(rest, "`")
if end == -1 {
out.WriteString(html.EscapeString("`" + rest))
break
}
codeText := rest[:end]
out.WriteString("<code>")
out.WriteString(html.EscapeString(codeText))
out.WriteString("</code>")
remaining = rest[end+1:]
}
return out.String()
}
func renderInlineText(input string) string {
var escapes []rune
remaining := protectBackslashEscapes(input, &escapes)
var out strings.Builder
var links []struct {
token string
html string
}
linkIndex := 0
for len(remaining) > 0 {
imgAt := strings.Index(remaining, "![")
wikiAt := strings.Index(remaining, "[[")
mdAt := strings.Index(remaining, "[")
urlAt := indexAutolink(remaining)
next := -1
for _, p := range []int{imgAt, wikiAt, mdAt, urlAt} {
if p >= 0 && (next == -1 || p < next) {
next = p
}
}
if next == -1 {
out.WriteString(remaining)
break
}
if next > 0 {
out.WriteString(remaining[:next])
remaining = remaining[next:]
continue
}
if strings.HasPrefix(remaining, "![") {
altEnd := strings.Index(remaining[2:], "]")
if altEnd == -1 || altEnd+3 >= len(remaining) || remaining[altEnd+3] != '(' {
// Not a complete image: emit the literal "!" and reprocess the "[".
out.WriteString(remaining[:1])
remaining = remaining[1:]
continue
}
altEnd += 2 // index of the closing "]" within remaining
hrefEnd := findMatchingParen(remaining, altEnd+1)
if hrefEnd == -1 {
out.WriteString(remaining[:1])
remaining = remaining[1:]
continue
}
altText := remaining[2:altEnd]
src := normalizeLinkTarget(strings.TrimSpace(remaining[altEnd+2 : hrefEnd]))
if src == "" {
out.WriteString(remaining[:hrefEnd+1])
} else {
token := fmt.Sprintf("@@LINK%d@@", linkIndex)
linkIndex++
links = append(links, struct {
token string
html string
}{
token: token,
html: `<img src="` + html.EscapeString(src) + `" alt="` + html.EscapeString(altText) + `" loading="lazy" />`,
})
out.WriteString(token)
}
remaining = remaining[hrefEnd+1:]
continue
}
if strings.HasPrefix(remaining, "[[") {
end := strings.Index(remaining[2:], "]]")
if end == -1 {
out.WriteString(html.EscapeString("[["))
remaining = remaining[2:]
continue
}
inner := strings.TrimSpace(remaining[2 : 2+end])
href, label := parseWikiLink(inner)
if href == "" {
out.WriteString(remaining[:end+4])
} else {
token := fmt.Sprintf("@@LINK%d@@", linkIndex)
linkIndex++
links = append(links, struct {
token string
html string
}{
token: token,
html: "<a href=\"" + html.EscapeString(href) + "\">" + renderInline(label) + "</a>",
})
out.WriteString(token)
}
remaining = remaining[end+4:]
continue
}
// Bare URL autolink (GFM): a http(s):// run not introduced by a "[" link.
if strings.HasPrefix(remaining, "http://") || strings.HasPrefix(remaining, "https://") {
end := autolinkEnd(remaining)
url := remaining[:end]
token := fmt.Sprintf("@@LINK%d@@", linkIndex)
linkIndex++
links = append(links, struct {
token string
html string
}{
token: token,
html: `<a href="` + html.EscapeString(url) + `">` + html.EscapeString(url) + `</a>`,
})
out.WriteString(token)
remaining = remaining[end:]
continue
}
labelEnd := strings.Index(remaining[1:], "]")
if labelEnd == -1 {
out.WriteString(html.EscapeString("["))
remaining = remaining[1:]
continue
}
labelEnd += 1
if labelEnd+1 >= len(remaining) || remaining[labelEnd+1] != '(' {
out.WriteString(remaining[:labelEnd+1])
remaining = remaining[labelEnd+1:]
continue
}
hrefEnd := findMatchingParen(remaining, labelEnd+1)
if hrefEnd == -1 {
out.WriteString(remaining[:labelEnd+2])
remaining = remaining[labelEnd+2:]
continue
}
label := remaining[1:labelEnd]
href := normalizeLinkTarget(strings.TrimSpace(remaining[labelEnd+2 : hrefEnd]))
if href == "" {
out.WriteString(remaining[:hrefEnd+1])
} else {
token := fmt.Sprintf("@@LINK%d@@", linkIndex)
linkIndex++
links = append(links, struct {
token string
html string
}{
token: token,
html: "<a href=\"" + html.EscapeString(href) + "\">" + renderInline(label) + "</a>",
})
out.WriteString(token)
}
remaining = remaining[hrefEnd+1:]
}
escaped := html.EscapeString(out.String())
formatted := applyInlineFormatting(escaped)
for _, link := range links {
formatted = strings.ReplaceAll(formatted, link.token, link.html)
}
return restoreBackslashEscapes(formatted, escapes)
}
// protectBackslashEscapes replaces each backslash-escaped ASCII-punctuation
// character ("\*", "\_", "\[" …) with an opaque placeholder, recording the literal
// rune in escapes. This runs before link and emphasis parsing so an escaped
// delimiter is treated as plain text; restoreBackslashEscapes swaps the
// placeholders back (HTML-escaped) once formatting is complete.
func protectBackslashEscapes(input string, escapes *[]rune) string {
if !strings.ContainsRune(input, '\\') {
return input
}
var b strings.Builder
for i := 0; i < len(input); i++ {
if input[i] == '\\' && i+1 < len(input) && isASCIIPunct(input[i+1]) {
fmt.Fprintf(&b, "@@ESC%d@@", len(*escapes))