~bigbes/confluence-md-utilities

ref: 442bf5982d1e46a2737804b2f30a9b4895e9ac02 confluence-md-utilities/converter/xml2md.go -rw-r--r-- 37.1 KiB
442bf598 — Eugene Blikh fix: round-trip fidelity for tables, page links, and nested lists 2 months ago
                                                                                
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
package converter

import (
	"bytes"
	"fmt"
	htmlpkg "html"
	"strings"

	"golang.org/x/net/html"
)

// ConfluenceToMarkdown converts Confluence storage format XML to Markdown.
func ConfluenceToMarkdown(source string) (string, error) {
	// Preprocess: extract CDATA content and replace with escaped text,
	// because x/net/html doesn't handle CDATA sections.
	preprocessed := preprocessCDATA(source)

	// Wrap in a root element so the HTML parser handles it correctly.
	wrapped := "<div>" + preprocessed + "</div>"
	doc, err := html.Parse(strings.NewReader(wrapped))
	if err != nil {
		return "", fmt.Errorf("parsing confluence xml: %w", err)
	}

	var buf bytes.Buffer
	c := &xmlConverter{buf: &buf}

	// Navigate to the wrapper div: html > head > body > div
	body := findNode(doc, "body")
	if body == nil {
		return "", fmt.Errorf("unexpected parse structure")
	}
	wrapper := body.FirstChild
	if wrapper != nil {
		c.walkChildren(wrapper, 0)
	}

	result := buf.String()
	// Clean up excessive blank lines
	for strings.Contains(result, "\n\n\n") {
		result = strings.ReplaceAll(result, "\n\n\n", "\n\n")
	}
	return strings.TrimSpace(result) + "\n", nil
}

// preprocessCDATA replaces <![CDATA[...]]> with the content as a data attribute
// on the parent element, since x/net/html doesn't parse CDATA.
func preprocessCDATA(s string) string {
	var result strings.Builder
	for {
		idx := strings.Index(s, "<![CDATA[")
		if idx == -1 {
			result.WriteString(s)
			break
		}
		result.WriteString(s[:idx])
		s = s[idx+len("<![CDATA["):]
		endIdx := strings.Index(s, "]]>")
		if endIdx == -1 {
			result.WriteString(s)
			break
		}
		// Write CDATA content as a special element that we can detect
		content := s[:endIdx]
		result.WriteString("<cdatacontent>")
		result.WriteString(htmlpkg.EscapeString(content))
		result.WriteString("</cdatacontent>")
		s = s[endIdx+len("]]>"):]
	}
	return result.String()
}

type xmlConverter struct {
	buf         *bytes.Buffer
	listDepth   int
	inListItem  bool
	listIndents []int // per-level indent width contributed by each ancestor list
}

// pushList increments list depth and records the indent contribution for the
// new level (3 spaces for ordered, 2 for unordered/task). Items at deeper
// levels indent by the cumulative width of all ancestors.
func (c *xmlConverter) pushList(width int) {
	c.listDepth++
	c.listIndents = append(c.listIndents, width)
}

// popList undoes pushList.
func (c *xmlConverter) popList() {
	c.listDepth--
	if len(c.listIndents) > 0 {
		c.listIndents = c.listIndents[:len(c.listIndents)-1]
	}
}

// itemIndent returns the indent string for a list item at the current depth.
// It sums the contributions of all ancestor lists (everything except the
// innermost level, since that's the level whose marker we're about to emit).
func (c *xmlConverter) itemIndent() string {
	total := 0
	if len(c.listIndents) > 1 {
		for i := 0; i < len(c.listIndents)-1; i++ {
			total += c.listIndents[i]
		}
	}
	return strings.Repeat(" ", total)
}

// ensureSingleNewline writes a newline only if the buffer does not already end
// with one, preventing accidental blank lines that turn tight lists loose.
func (c *xmlConverter) ensureSingleNewline() {
	bs := c.buf.Bytes()
	if len(bs) == 0 || bs[len(bs)-1] != '\n' {
		c.buf.WriteByte('\n')
	}
}

func (c *xmlConverter) walkChildren(n *html.Node, depth int) {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		c.walk(child, depth)
	}
}

func (c *xmlConverter) walk(n *html.Node, depth int) {
	if n.Type == html.TextNode {
		text := n.Data
		// Skip whitespace-only text nodes inside lists
		if c.listDepth > 0 && strings.TrimSpace(text) == "" {
			return
		}
		// Collapse whitespace in text nodes (XML indentation artifacts)
		if strings.TrimSpace(text) != "" {
			// Replace sequences of whitespace (including newlines) with single space,
			// but preserve the trimmed content
			text = collapseWhitespace(text)
		}
		c.buf.WriteString(text)
		return
	}

	if n.Type != html.ElementNode {
		c.walkChildren(n, depth)
		return
	}

	tag := strings.ToLower(n.Data)

	switch {
	// Headings
	case tag == "h1":
		c.buf.WriteString("\n# ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")
	case tag == "h2":
		c.buf.WriteString("\n## ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")
	case tag == "h3":
		c.buf.WriteString("\n### ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")
	case tag == "h4":
		c.buf.WriteString("\n#### ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")
	case tag == "h5":
		c.buf.WriteString("\n##### ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")
	case tag == "h6":
		c.buf.WriteString("\n###### ")
		c.walkChildren(n, depth)
		c.buf.WriteString("\n\n")

	// Paragraphs
	case tag == "p":
		c.walkChildren(n, depth)
		if !c.inListItem {
			c.buf.WriteString("\n\n")
		}

	// Inline formatting
	case tag == "strong", tag == "b":
		c.buf.WriteString("**")
		c.walkChildren(n, depth)
		c.buf.WriteString("**")
	case tag == "em", tag == "i":
		c.buf.WriteString("*")
		c.walkChildren(n, depth)
		c.buf.WriteString("*")
	case tag == "del", tag == "s":
		c.buf.WriteString("~~")
		c.walkChildren(n, depth)
		c.buf.WriteString("~~")
	case tag == "code":
		if !isPrevSiblingCode(n) {
			c.buf.WriteString("`")
		}
		// Markdown code spans contain only literal text; drop inline-comment-marker
		// and other element wrappers and emit just the text content.
		c.buf.WriteString(collapseWhitespace(getTextContent(n)))
		if !isNextSiblingCode(n) {
			c.buf.WriteString("`")
		}

	// Links
	case tag == "a":
		href := getAttr(n, "href")
		c.buf.WriteString("[")
		c.walkChildren(n, depth)
		c.buf.WriteString("](")
		c.buf.WriteString(href)
		c.buf.WriteString(")")

	// Line break
	case tag == "br":
		c.buf.WriteString("  \n")

	// Horizontal rule
	case tag == "hr":
		c.buf.WriteString("\n---\n\n")

	// Lists
	case tag == "ul":
		c.pushList(2) // "- " marker → children indent 2 spaces
		if c.listDepth == 1 {
			c.buf.WriteString("\n")
		}
		c.walkChildren(n, depth)
		c.popList()
		if c.listDepth == 0 {
			c.buf.WriteString("\n")
		}
	case tag == "ol":
		c.pushList(3) // "1. " marker → children indent 3 spaces
		if c.listDepth == 1 {
			c.buf.WriteString("\n")
		}
		c.walkOL(n, depth)
		c.popList()
		if c.listDepth == 0 {
			c.buf.WriteString("\n")
		}
	case tag == "li":
		prev := c.inListItem
		c.inListItem = true
		// Check if this list item contains a task checkbox
		if hasTaskStatus(n) {
			// Task status handler will write the prefix, walkChildrenInline for text
			c.walkChildrenInline(n, depth)
			c.ensureSingleNewline()
		} else {
			c.buf.WriteString(c.itemIndent())
			c.buf.WriteString("- ")
			c.walkChildrenInline(n, depth)
			c.ensureSingleNewline()
		}
		c.inListItem = prev

	// Tables - convert to GFM table
	case tag == "table":
		c.renderTable(n, depth)

	// Confluence macros - handled via ac:* namespace (parsed as ac-*)
	// The HTML parser lowercases and handles colons differently.
	// We need to handle both ac:structured-macro and the parsed form.

	// Skip layout/structural elements, pass through children
	case tag == "div", tag == "span", tag == "tbody", tag == "thead",
		tag == "colgroup", tag == "col", tag == "content-wrapper":
		c.walkChildren(n, depth)

	// Handle Confluence-specific elements
	default:
		c.handleConfluenceElement(n, tag, depth)
	}
}

func (c *xmlConverter) handleConfluenceElement(n *html.Node, tag string, depth int) {
	switch {
	// Layout elements — preserve as HTML comments for round-trip
	case strings.Contains(tag, "ac:layout-section") || strings.Contains(tag, "layout-section"):
		sectionType := getAttr(n, "ac:type")
		if sectionType == "" {
			sectionType = getAttr(n, "type")
		}
		fmt.Fprintf(c.buf, "<!-- ac:layout-section type=%q -->\n", sectionType)
		c.walkChildren(n, depth)
		c.buf.WriteString("<!-- /ac:layout-section -->\n")

	case strings.Contains(tag, "ac:layout-cell") || strings.Contains(tag, "layout-cell"):
		c.buf.WriteString("<!-- ac:layout-cell -->\n")
		c.walkChildren(n, depth)
		c.buf.WriteString("<!-- /ac:layout-cell -->\n")

	case tag == "ac:layout" || strings.Contains(tag, "layout") && !strings.Contains(tag, "layout-"):
		c.buf.WriteString("<!-- ac:layout -->\n")
		c.walkChildren(n, depth)
		c.buf.WriteString("<!-- /ac:layout -->\n")
	// Confluence structured macros (code blocks, panels, etc.)
	case strings.Contains(tag, "structured-macro") || strings.Contains(tag, "ac:structured-macro"):
		macroName := getAttr(n, "ac:name")
		if macroName == "" {
			macroName = getAttr(n, "name")
		}
		macroID := getAttr(n, "ac:macro-id")
		if macroID == "" {
			macroID = getAttr(n, "macro-id")
		}
		switch macroName {
		case "code":
			c.renderCodeMacro(n, macroID)
		case "info", "note", "warning":
			c.renderPanelAsBlockquote(n, depth, macroName, macroID)
		case "toc":
			// Preserve TOC macro as HTML comment. If the parent is a <p>,
			// emit a "-in-p" variant so the round-trip restores the <p> wrapper.
			marker := "ac:toc"
			if isParentTag(n, "p") {
				marker = "ac:toc-in-p"
			}
			if macroID != "" {
				fmt.Fprintf(c.buf, "<!-- %s macro-id=%q -->\n", marker, macroID)
			} else {
				fmt.Fprintf(c.buf, "<!-- %s -->\n", marker)
			}
		default:
			c.walkChildren(n, depth)
		}

	// Confluence images
	case strings.Contains(tag, "image") || strings.Contains(tag, "ac:image"):
		alt := getAttr(n, "ac:alt")
		if alt == "" {
			alt = getAttr(n, "alt")
		}
		imgRef := c.findImageRef(n)
		if imgRef.isAttachment {
			// Preserve attachment reference as round-trippable HTML
			fmt.Fprintf(c.buf, `<span data-attachment="%s"`, imgRef.filename)
			if alt != "" {
				fmt.Fprintf(c.buf, ` data-alt="%s"`, alt)
			}
			c.buf.WriteString("/>")
		} else {
			c.buf.WriteString("![")
			c.buf.WriteString(alt)
			c.buf.WriteString("](")
			c.buf.WriteString(imgRef.url)
			c.buf.WriteString(")")
		}

	// Confluence links (user mentions, page links)
	case strings.Contains(tag, "ac:link"):
		if pageNode := findPageChild(n); pageNode != nil {
			c.writePageLinkSpan(pageNode, n)
		} else {
			c.walkChildren(n, depth)
		}

	// Confluence emoticons
	case strings.Contains(tag, "emoticon") || strings.Contains(tag, "ac:emoticon"):
		name := getAttr(n, "ac:name")
		if name == "" {
			name = getAttr(n, "name")
		}
		switch name {
		case "plus":
			c.buf.WriteString("(+)")
		case "minus":
			c.buf.WriteString("(-)")
		case "question":
			c.buf.WriteString("(?)")
		case "tick":
			c.buf.WriteString("(v)")
		case "cross":
			c.buf.WriteString("(x)")
		}

	// Confluence task lists
	case strings.Contains(tag, "task-list"):
		c.pushList(2)
		c.walkChildren(n, depth)
		c.popList()
	case strings.Contains(tag, "task-body"):
		c.walkChildren(n, depth)
		c.ensureSingleNewline()
	case strings.Contains(tag, "task-status"):
		status := strings.TrimSpace(getTextContent(n))
		indent := c.itemIndent()
		if status == "complete" {
			c.buf.WriteString(indent + "- [x] ")
		} else {
			c.buf.WriteString(indent + "- [ ] ")
		}
	case strings.Contains(tag, "task-id"):
		// Skip task IDs
	case strings.Contains(tag, "task") && !strings.Contains(tag, "task-"):
		c.walkChildren(n, depth)

	// Confluence inline comment markers — preserve as span with data attribute
	case strings.Contains(tag, "inline-comment-marker"):
		ref := getAttr(n, "ac:ref")
		if ref == "" {
			ref = getAttr(n, "ref")
		}
		if ref != "" {
			fmt.Fprintf(c.buf, `<span data-inline-comment="%s">`, ref)
			c.walkChildren(n, depth)
			c.buf.WriteString("</span>")
		} else {
			c.walkChildren(n, depth)
		}

	// User references — preserve as round-trippable HTML span
	case strings.Contains(tag, "ri:user"):
		userKey := getAttr(n, "ri:userkey")
		if userKey == "" {
			userKey = getAttr(n, "userkey")
		}
		if userKey != "" {
			fmt.Fprintf(c.buf, `<span data-user-key="%s"/>`, userKey)
		}

	// Time elements
	case tag == "time":
		datetime := getAttr(n, "datetime")
		if datetime != "" {
			c.buf.WriteString(datetime)
		}

	// Fallback: just walk children
	default:
		c.walkChildren(n, depth)
	}
}

func (c *xmlConverter) renderCodeMacro(n *html.Node, macroID string) {
	language := ""
	code := ""

	// Walk children to find parameters and body
	var walkMacro func(*html.Node)
	walkMacro = func(node *html.Node) {
		if node.Type == html.ElementNode {
			tag := strings.ToLower(node.Data)
			if strings.Contains(tag, "parameter") || strings.Contains(tag, "ac:parameter") {
				name := getAttr(node, "ac:name")
				if name == "" {
					name = getAttr(node, "name")
				}
				if name == "language" {
					language = getTextContent(node)
				}
			}
			if strings.Contains(tag, "plain-text-body") || strings.Contains(tag, "ac:plain-text-body") {
				code = getCDATAContent(node)
			}
		}
		for child := node.FirstChild; child != nil; child = child.NextSibling {
			walkMacro(child)
		}
	}
	walkMacro(n)

	// Extract original attribute order for round-trip fidelity
	attrOrder := extractAttrOrder(n)

	if macroID != "" {
		if attrOrder != "" {
			fmt.Fprintf(c.buf, "\n<!-- ac:code macro-id=%q attr-order=%q -->\n", macroID, attrOrder)
		} else {
			fmt.Fprintf(c.buf, "\n<!-- ac:code macro-id=%q -->\n", macroID)
		}
	} else {
		c.buf.WriteString("\n")
	}
	c.buf.WriteString("```")
	c.buf.WriteString(language)
	c.buf.WriteString("\n")
	c.buf.WriteString(code)
	if !strings.HasSuffix(code, "\n") {
		c.buf.WriteString("\n")
	}
	c.buf.WriteString("```\n\n")
}

func (c *xmlConverter) renderPanelAsBlockquote(n *html.Node, depth int, panelName string, macroID string) {
	// Collect panel parameters and body. Parameters are preserved via an HTML
	// comment marker so md2xml's blockquote renderer can restore them.
	var params []string
	var hasInnerP bool

	var findBody func(*html.Node)
	var bodyBuf bytes.Buffer
	origBuf := c.buf
	c.buf = &bodyBuf

	findBody = func(node *html.Node) {
		if node.Type == html.ElementNode {
			tag := strings.ToLower(node.Data)
			switch {
			case strings.Contains(tag, "ac:parameter") || strings.Contains(tag, "parameter"):
				name := getAttr(node, "ac:name")
				if name == "" {
					name = getAttr(node, "name")
				}
				val := getTextContent(node)
				if name != "" {
					params = append(params, fmt.Sprintf("%s=%q", name, val))
				}
				return
			case strings.Contains(tag, "rich-text-body"):
				// Track whether body has an explicit <p> wrapper, so we can
				// reproduce it on round-trip.
				for ch := node.FirstChild; ch != nil; ch = ch.NextSibling {
					if ch.Type == html.ElementNode && strings.ToLower(ch.Data) == "p" {
						hasInnerP = true
						break
					}
				}
				c.walkChildren(node, depth)
				return
			}
		}
		for child := node.FirstChild; child != nil; child = child.NextSibling {
			findBody(child)
		}
	}
	findBody(n)

	c.buf = origBuf

	// Emit metadata marker so md2xml can restore name, macro-id, and parameters.
	var marker strings.Builder
	fmt.Fprintf(&marker, "<!-- ac:%s", panelName)
	if macroID != "" {
		fmt.Fprintf(&marker, " macro-id=%q", macroID)
	}
	for _, p := range params {
		marker.WriteString(" param-")
		marker.WriteString(p)
	}
	if !hasInnerP {
		marker.WriteString(" body-bare")
	}
	marker.WriteString(" -->\n")
	c.buf.WriteString(marker.String())

	text := strings.TrimSpace(bodyBuf.String())
	lines := strings.Split(text, "\n")
	for _, line := range lines {
		c.buf.WriteString("> ")
		c.buf.WriteString(line)
		c.buf.WriteString("\n")
	}
	c.buf.WriteString("\n")
}

func (c *xmlConverter) renderTable(n *html.Node, depth int) {
	// If the table contains structures that don't survive a GFM round-trip
	// (block content in cells, row-header th cells, bullet lists in cells,
	// structured macros in cells), serialize the entire table as raw XML
	// inside a markdown HTML block. md2xml passes HTML blocks through
	// verbatim, which preserves the structure exactly.
	if tableNeedsRawSerialize(n) {
		c.buf.WriteString("\n")
		serializeNodeXML(c.buf, n)
		c.buf.WriteString("\n\n")
		return
	}

	rows := collectTableRows(n)
	if len(rows) == 0 {
		return
	}

	// Determine column count
	cols := 0
	for _, row := range rows {
		if len(row.cells) > cols {
			cols = len(row.cells)
		}
	}
	if cols == 0 {
		return
	}

	// Preserve table attributes and colgroup as HTML comment
	tableAttrs := extractTableAttrs(n)
	if tableAttrs != "" {
		fmt.Fprintf(c.buf, "\n<!-- table-attrs: %s -->\n", tableAttrs)
	} else {
		c.buf.WriteString("\n")
	}

	// If first row is a header
	isFirstRowHeader := len(rows) > 0 && rows[0].isHeader
	startIdx := 0

	if isFirstRowHeader {
		c.writeTableRow(rows[0].cells, cols)
		c.writeTableSep(cols)
		startIdx = 1
	} else {
		// Write empty header and separator
		empty := make([]string, cols)
		c.writeTableRow(empty, cols)
		c.writeTableSep(cols)
	}

	for i := startIdx; i < len(rows); i++ {
		c.writeTableRow(rows[i].cells, cols)
	}
	c.buf.WriteString("\n")
}

// tableNeedsRawSerialize reports whether the table contains structures that
// can't survive round-trip through GFM markdown table syntax. Triggers for
// raw-serialize: row-header th cells (after row 0), or block content
// (lists, structured macros, task-lists, content-wrappers) inside cells.
func tableNeedsRawSerialize(table *html.Node) bool {
	rowIdx := -1
	var complex bool
	var walk func(*html.Node)
	walk = func(n *html.Node) {
		if complex || n.Type != html.ElementNode {
			if !complex {
				for c := n.FirstChild; c != nil; c = c.NextSibling {
					walk(c)
				}
			}
			return
		}
		tag := strings.ToLower(n.Data)
		switch tag {
		case "tr":
			rowIdx++
		case "th":
			if rowIdx > 0 {
				complex = true
				return
			}
		case "td":
			if cellHasComplexContent(n) {
				complex = true
				return
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			walk(c)
		}
	}
	walk(table)
	return complex
}

// cellHasComplexContent reports whether the cell contains block-level structures
// that can't be represented as inline markdown in a GFM table cell.
func cellHasComplexContent(cell *html.Node) bool {
	var found bool
	var walk func(*html.Node)
	walk = func(n *html.Node) {
		if found || n.Type != html.ElementNode {
			if !found {
				for c := n.FirstChild; c != nil; c = c.NextSibling {
					walk(c)
				}
			}
			return
		}
		tag := strings.ToLower(n.Data)
		switch {
		case tag == "ul" || tag == "ol":
			found = true
			return
		case strings.Contains(tag, "structured-macro"):
			found = true
			return
		case strings.Contains(tag, "task-list"):
			found = true
			return
		case strings.Contains(tag, "ac:link"):
			// ac:link with ri:page (page link) needs full XML; ri:user is fine inline.
			for c := n.FirstChild; c != nil; c = c.NextSibling {
				if c.Type == html.ElementNode {
					ct := strings.ToLower(c.Data)
					if strings.Contains(ct, "ri:page") || strings.Contains(ct, "page") {
						if !strings.Contains(ct, "ri:user") {
							found = true
							return
						}
					}
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			walk(c)
		}
	}
	walk(cell)
	return found
}

func (c *xmlConverter) writeTableRow(cells []string, cols int) {
	c.buf.WriteString("|")
	for i := range cols {
		cell := ""
		if i < len(cells) {
			cell = cells[i]
		}
		c.buf.WriteString(" ")
		c.buf.WriteString(escapeTablePipes(cell))
		c.buf.WriteString(" |")
	}
	c.buf.WriteString("\n")
}

// escapeTablePipes escapes literal `|` characters in GFM table cell content.
// Per the GFM spec, `\|` is recognized as an escaped pipe at table-parse time
// and reduced to `|` before inline parsing — so escaped pipes survive even
// inside `code spans`. Pre-existing `\|` sequences are left alone to avoid
// double-escaping.
func escapeTablePipes(s string) string {
	var b strings.Builder
	b.Grow(len(s))
	for i := 0; i < len(s); i++ {
		ch := s[i]
		if ch == '\\' && i+1 < len(s) && s[i+1] == '|' {
			b.WriteByte('\\')
			b.WriteByte('|')
			i++
			continue
		}
		if ch == '|' {
			b.WriteByte('\\')
			b.WriteByte('|')
			continue
		}
		b.WriteByte(ch)
	}
	return b.String()
}

func (c *xmlConverter) writeTableSep(cols int) {
	c.buf.WriteString("|")
	for range cols {
		c.buf.WriteString("---|")
	}
	c.buf.WriteString("\n")
}

func (c *xmlConverter) walkOL(n *html.Node, depth int) {
	idx := 1
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type != html.ElementNode {
			continue
		}
		tag := strings.ToLower(child.Data)
		if tag == "li" {
			c.buf.WriteString(c.itemIndent())
			fmt.Fprintf(c.buf, "%d. ", idx)
			c.walkChildrenInline(child, depth)
			c.ensureSingleNewline()
			idx++
		}
	}
}

func (c *xmlConverter) walkChildrenInline(n *html.Node, depth int) {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type == html.TextNode {
			// Collapse whitespace but preserve a single space between inline elements
			text := collapseWhitespace(child.Data)
			// Only trim leading space if this is the very first child
			if child == n.FirstChild {
				text = strings.TrimLeft(text, " ")
			}
			// Only trim trailing space if this is the very last child
			if child.NextSibling == nil {
				text = strings.TrimRight(text, " ")
			}
			if text != "" {
				c.buf.WriteString(text)
			}
			continue
		}
		if child.Type == html.ElementNode {
			tag := strings.ToLower(child.Data)
			switch {
			case tag == "p":
				c.walkChildrenInline(child, depth)
			case tag == "ul", tag == "ol":
				c.buf.WriteString("\n")
				c.walk(child, depth)
			default:
				c.walk(child, depth)
			}
		}
	}
}

// extractTableAttrs extracts class, style, and colgroup info as a JSON-like string for preservation.
func extractTableAttrs(table *html.Node) string {
	var parts []string

	// Table class and style
	cls := getAttr(table, "class")
	style := getAttr(table, "style")
	if cls != "" {
		parts = append(parts, fmt.Sprintf("class=%q", cls))
	}
	if style != "" {
		parts = append(parts, fmt.Sprintf("style=%q", style))
	}

	// Colgroup
	var colWidths []string
	for child := table.FirstChild; child != nil; child = child.NextSibling {
		if child.Type == html.ElementNode && strings.ToLower(child.Data) == "colgroup" {
			for col := child.FirstChild; col != nil; col = col.NextSibling {
				if col.Type == html.ElementNode && strings.ToLower(col.Data) == "col" {
					colStyle := getAttr(col, "style")
					if colStyle != "" {
						colWidths = append(colWidths, colStyle)
					}
				}
			}
		}
	}
	if len(colWidths) > 0 {
		parts = append(parts, fmt.Sprintf("cols=[%s]", strings.Join(colWidths, "|")))
	}

	return strings.Join(parts, " ")
}

type tableRow struct {
	isHeader bool
	cells    []string
}

func collectTableRows(table *html.Node) []tableRow {
	var rows []tableRow
	var walk func(*html.Node, bool)
	walk = func(n *html.Node, inHeader bool) {
		if n.Type == html.ElementNode {
			tag := strings.ToLower(n.Data)
			switch tag {
			case "thead":
				for child := n.FirstChild; child != nil; child = child.NextSibling {
					walk(child, true)
				}
				return
			case "tbody":
				for child := n.FirstChild; child != nil; child = child.NextSibling {
					walk(child, false)
				}
				return
			case "tr":
				row := tableRow{isHeader: inHeader}
				for child := n.FirstChild; child != nil; child = child.NextSibling {
					if child.Type == html.ElementNode {
						cellTag := strings.ToLower(child.Data)
						if cellTag == "th" {
							row.isHeader = true
							row.cells = append(row.cells, strings.TrimSpace(renderCellMarkdown(child)))
						} else if cellTag == "td" {
							row.cells = append(row.cells, strings.TrimSpace(renderCellMarkdown(child)))
						}
					}
				}
				rows = append(rows, row)
				return
			}
		}
		for child := n.FirstChild; child != nil; child = child.NextSibling {
			walk(child, inHeader)
		}
	}
	walk(table, false)
	return rows
}

// renderCellMarkdown renders cell content to inline markdown, preserving
// formatting like bold, italic, code, links, br, and user references.
func renderCellMarkdown(cell *html.Node) string {
	var buf bytes.Buffer
	renderCellNode(&buf, cell)
	return buf.String()
}

func renderCellNode(buf *bytes.Buffer, n *html.Node) {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		switch child.Type {
		case html.TextNode:
			text := collapseWhitespace(child.Data)
			buf.WriteString(text)
		case html.ElementNode:
			tag := strings.ToLower(child.Data)
			switch {
			case tag == "strong" || tag == "b":
				buf.WriteString("**")
				renderCellNode(buf, child)
				buf.WriteString("**")
			case tag == "em" || tag == "i":
				buf.WriteString("*")
				renderCellNode(buf, child)
				buf.WriteString("*")
			case tag == "del" || tag == "s":
				buf.WriteString("~~")
				renderCellNode(buf, child)
				buf.WriteString("~~")
			case tag == "code":
				buf.WriteString("`")
				buf.WriteString(collapseWhitespace(getTextContent(child)))
				buf.WriteString("`")
			case tag == "a":
				href := getAttr(child, "href")
				buf.WriteString("[")
				renderCellNode(buf, child)
				buf.WriteString("](")
				buf.WriteString(href)
				buf.WriteString(")")
			case tag == "br":
				buf.WriteString("<br/>")
			case tag == "p":
				// Unwrap <p> inside cells
				renderCellNode(buf, child)
			case tag == "div":
				renderCellNode(buf, child)
			case strings.Contains(tag, "user"):
				userKey := getAttr(child, "ri:userkey")
				if userKey == "" {
					userKey = getAttr(child, "userkey")
				}
				if userKey != "" {
					fmt.Fprintf(buf, `<span data-user-key="%s"/>`, userKey)
				}
			case strings.Contains(tag, "ac:link"):
				renderCellNode(buf, child)
			case strings.Contains(tag, "image"):
				// Handle images in cells
				alt := getAttr(child, "ac:alt")
				if alt == "" {
					alt = getAttr(child, "alt")
				}
				var imgBuf bytes.Buffer
				c := &xmlConverter{buf: &imgBuf}
				ref := c.findImageRef(child)
				if ref.isAttachment {
					fmt.Fprintf(buf, `<span data-attachment="%s"`, ref.filename)
					if alt != "" {
						fmt.Fprintf(buf, ` data-alt="%s"`, alt)
					}
					buf.WriteString("/>")
				} else if ref.url != "" {
					buf.WriteString("![")
					buf.WriteString(alt)
					buf.WriteString("](")
					buf.WriteString(ref.url)
					buf.WriteString(")")
				}
			case strings.Contains(tag, "task-list"):
				renderCellTaskList(buf, child)
			case strings.Contains(tag, "emoticon"):
				name := getAttr(child, "ac:name")
				if name == "" {
					name = getAttr(child, "name")
				}
				switch name {
				case "plus":
					buf.WriteString("(+)")
				case "minus":
					buf.WriteString("(-)")
				case "question":
					buf.WriteString("(?)")
				case "tick":
					buf.WriteString("(v)")
				case "cross":
					buf.WriteString("(x)")
				}
			case strings.Contains(tag, "inline-comment-marker"):
				ref := getAttr(child, "ac:ref")
				if ref == "" {
					ref = getAttr(child, "ref")
				}
				if ref != "" {
					fmt.Fprintf(buf, `<span data-inline-comment="%s">`, ref)
					renderCellNode(buf, child)
					buf.WriteString("</span>")
				} else {
					renderCellNode(buf, child)
				}
			default:
				renderCellNode(buf, child)
			}
		}
	}
}

// renderCellTaskList renders a task list inside a table cell as inline markdown.
func renderCellTaskList(buf *bytes.Buffer, n *html.Node) {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type != html.ElementNode {
			continue
		}
		tag := strings.ToLower(child.Data)
		if !strings.Contains(tag, "task") || strings.Contains(tag, "task-list") {
			continue
		}
		// This is an ac:task element
		status := ""
		var bodyContent string
		for tc := child.FirstChild; tc != nil; tc = tc.NextSibling {
			if tc.Type != html.ElementNode {
				continue
			}
			tcTag := strings.ToLower(tc.Data)
			if strings.Contains(tcTag, "task-status") {
				status = strings.TrimSpace(getTextContent(tc))
			} else if strings.Contains(tcTag, "task-body") {
				bodyContent = strings.TrimSpace(renderCellMarkdown(tc))
			}
		}
		check := "[ ]"
		if status == "complete" {
			check = "[x]"
		}
		fmt.Fprintf(buf, "- %s %s<br/>", check, bodyContent)
	}
}

type imageRef struct {
	url          string
	filename     string
	isAttachment bool
}

func (c *xmlConverter) findImageRef(n *html.Node) imageRef {
	var ref imageRef
	var walk func(*html.Node)
	walk = func(node *html.Node) {
		if node.Type == html.ElementNode {
			tag := strings.ToLower(node.Data)
			// <ri:url ri:value="..."/>
			if strings.Contains(tag, "url") {
				v := getAttr(node, "ri:value")
				if v == "" {
					v = getAttr(node, "value")
				}
				if v != "" {
					ref.url = v
					return
				}
			}
			// <ri:attachment ri:filename="..."/>
			if strings.Contains(tag, "attachment") {
				f := getAttr(node, "ri:filename")
				if f == "" {
					f = getAttr(node, "filename")
				}
				if f != "" {
					ref.filename = f
					ref.isAttachment = true
					return
				}
			}
		}
		for child := node.FirstChild; child != nil; child = child.NextSibling {
			walk(child)
		}
	}
	walk(n)
	return ref
}

func (c *xmlConverter) hasUserChild(n *html.Node) bool {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type == html.ElementNode {
			tag := strings.ToLower(child.Data)
			if strings.Contains(tag, "user") {
				return true
			}
		}
	}
	return false
}

// findPageChild returns the <ri:page> descendant of an <ac:link>, if any.
// ac:link wraps either an <ri:user>, <ri:page>, or other ri:* reference;
// page links need a special preservation path because they have no plain
// markdown equivalent.
func findPageChild(n *html.Node) *html.Node {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type == html.ElementNode {
			tag := strings.ToLower(child.Data)
			if strings.Contains(tag, "ri:page") {
				return child
			}
		}
	}
	return nil
}

// writePageLinkSpan emits a <span data-page-link …> placeholder that survives
// markdown round-trip. md2xml's convertRawSpan reverses this back into a full
// <ac:link><ri:page …/></ac:link>.
func (c *xmlConverter) writePageLinkSpan(page, link *html.Node) {
	space := getAttr(page, "ri:space-key")
	if space == "" {
		space = getAttr(page, "space-key")
	}
	title := getAttr(page, "ri:content-title")
	if title == "" {
		title = getAttr(page, "content-title")
	}
	anchor := getAttr(link, "ac:anchor")
	if anchor == "" {
		anchor = getAttr(link, "anchor")
	}

	c.buf.WriteString(`<span data-page-link="1"`)
	if space != "" {
		fmt.Fprintf(c.buf, ` data-space-key=%q`, space)
	}
	if title != "" {
		fmt.Fprintf(c.buf, ` data-content-title=%q`, title)
	}
	if anchor != "" {
		fmt.Fprintf(c.buf, ` data-anchor=%q`, anchor)
	}
	// Body of the ac:link, if any (plain-text-link-body or text node).
	body := pageLinkBody(link)
	if body != "" {
		c.buf.WriteString(">")
		c.buf.WriteString(body)
		c.buf.WriteString("</span>")
	} else {
		c.buf.WriteString("/>")
	}
}

// pageLinkBody returns the plain-text body of an <ac:link>, dropping the
// <ri:page> reference itself. Confluence allows <ac:plain-text-link-body> or
// raw text as the visible label of a page link.
func pageLinkBody(link *html.Node) string {
	var b strings.Builder
	for child := link.FirstChild; child != nil; child = child.NextSibling {
		switch child.Type {
		case html.TextNode:
			b.WriteString(child.Data)
		case html.ElementNode:
			tag := strings.ToLower(child.Data)
			if strings.Contains(tag, "ri:page") || strings.Contains(tag, "ri:user") {
				continue
			}
			b.WriteString(getTextContent(child))
		}
	}
	return strings.TrimSpace(b.String())
}

// Helper functions

func findNode(n *html.Node, tag string) *html.Node {
	if n.Type == html.ElementNode && n.Data == tag {
		return n
	}
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if found := findNode(child, tag); found != nil {
			return found
		}
	}
	return nil
}

func getAttr(n *html.Node, key string) string {
	for _, attr := range n.Attr {
		attrKey := attr.Key
		if attr.Namespace != "" {
			attrKey = attr.Namespace + ":" + attr.Key
		}
		if attrKey == key {
			return attr.Val
		}
	}
	return ""
}

// collapseWhitespace replaces runs of whitespace with a single space,
// preserving leading/trailing single space if original had whitespace there.
func collapseWhitespace(s string) string {
	var buf strings.Builder
	inWS := false
	for _, r := range s {
		if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
			if !inWS {
				buf.WriteByte(' ')
				inWS = true
			}
		} else {
			buf.WriteRune(r)
			inWS = false
		}
	}
	return buf.String()
}

// hasTaskStatus checks if a node contains a task-status element.
func hasTaskStatus(n *html.Node) bool {
	for child := n.FirstChild; child != nil; child = child.NextSibling {
		if child.Type == html.ElementNode {
			tag := strings.ToLower(child.Data)
			if strings.Contains(tag, "task-status") {
				return true
			}
		}
	}
	return false
}

// getCDATAContent retrieves content from preprocessed CDATA sections.
// It looks for <cdatacontent> elements and unescapes their text.
func getCDATAContent(n *html.Node) string {
	var buf bytes.Buffer
	var walk func(*html.Node)
	walk = func(node *html.Node) {
		if node.Type == html.ElementNode && node.Data == "cdatacontent" {
			text := getTextContent(node)
			buf.WriteString(htmlpkg.UnescapeString(text))
			return
		}
		if node.Type == html.TextNode {
			buf.WriteString(node.Data)
		}
		for child := node.FirstChild; child != nil; child = child.NextSibling {
			walk(child)
		}
	}
	walk(n)
	return buf.String()
}

// extractAttrOrder returns a comma-separated list of short attribute names
// (e.g. "name,schema-version,macro-id") preserving the original order from the HTML node.
// The "ac:" prefix is stripped for brevity.
func extractAttrOrder(n *html.Node) string {
	var names []string
	for _, attr := range n.Attr {
		key := attr.Key
		if attr.Namespace != "" {
			key = attr.Namespace + ":" + attr.Key
		}
		short := strings.TrimPrefix(key, "ac:")
		names = append(names, short)
	}
	return strings.Join(names, ",")
}

// isNextSiblingCode checks if the next sibling is a <code> element directly
// adjacent in the source. Any intervening text node (even whitespace) breaks
// adjacency, so `<code>a</code> <code>b</code>` does not merge.
func isNextSiblingCode(n *html.Node) bool {
	s := n.NextSibling
	if s == nil {
		return false
	}
	return s.Type == html.ElementNode && strings.ToLower(s.Data) == "code"
}

// isPrevSiblingCode checks if the previous sibling is a <code> element directly
// adjacent in the source. Any intervening text node (even whitespace) breaks
// adjacency.
func isPrevSiblingCode(n *html.Node) bool {
	s := n.PrevSibling
	if s == nil {
		return false
	}
	return s.Type == html.ElementNode && strings.ToLower(s.Data) == "code"
}

// isParentTag reports whether n's parent is an element with the given tag name.
func isParentTag(n *html.Node, tag string) bool {
	p := n.Parent
	if p == nil || p.Type != html.ElementNode {
		return false
	}
	return strings.EqualFold(p.Data, tag)
}

func getTextContent(n *html.Node) string {
	var buf bytes.Buffer
	var walk func(*html.Node)
	walk = func(node *html.Node) {
		if node.Type == html.TextNode {
			buf.WriteString(node.Data)
		}
		for child := node.FirstChild; child != nil; child = child.NextSibling {
			walk(child)
		}
	}
	walk(n)
	return buf.String()
}

// xmlVoidTags lists Confluence/HTML elements that are always self-closing.
var xmlVoidTags = map[string]bool{
	"br":             true,
	"hr":             true,
	"col":            true,
	"img":            true,
	"ri:user":        true,
	"ri:url":         true,
	"ri:attachment":  true,
	"ri:page":        true,
	"ri:space":       true,
	"ri:blog-post":   true,
	"ri:shortcut":    true,
	"time":           true,
}

// serializeNodeXML writes an html.Node back to Confluence-style XML.
// Used for round-tripping table fragments that can't be represented in
// GFM markdown — they survive as raw HTML blocks in the markdown output.
func serializeNodeXML(buf *bytes.Buffer, n *html.Node) {
	switch n.Type {
	case html.TextNode:
		buf.WriteString(htmlpkg.EscapeString(n.Data))
	case html.ElementNode:
		// Restore CDATA from preprocessing.
		if n.Data == "cdatacontent" {
			buf.WriteString("<![CDATA[")
			buf.WriteString(htmlpkg.UnescapeString(getTextContent(n)))
			buf.WriteString("]]>")
			return
		}
		buf.WriteString("<")
		buf.WriteString(n.Data)
		for _, attr := range n.Attr {
			buf.WriteString(" ")
			if attr.Namespace != "" {
				buf.WriteString(attr.Namespace)
				buf.WriteString(":")
			}
			buf.WriteString(attr.Key)
			buf.WriteString(`="`)
			buf.WriteString(htmlpkg.EscapeString(attr.Val))
			buf.WriteString(`"`)
		}
		// Confluence storage format treats certain elements as always self-closing
		// (br, hr, col, ri:user, ri:attachment, time, ...). The HTML parser doesn't
		// know about the Confluence-specific ones and may attach trailing text or
		// elements as children. We emit "/>" anyway, then re-emit those misplaced
		// children as siblings so they survive the round-trip.
		if xmlVoidTags[n.Data] {
			buf.WriteString(" />")
			for c := n.FirstChild; c != nil; c = c.NextSibling {
				serializeNodeXML(buf, c)
			}
			return
		}
		hasChild := n.FirstChild != nil
		if !hasChild {
			// Empty non-void element: emit open+close to preserve semantics
			// (e.g. <td></td>).
			buf.WriteString("></")
			buf.WriteString(n.Data)
			buf.WriteString(">")
			return
		}
		buf.WriteString(">")
		// Inside <code> spans, drop inline-comment-marker wrappers since they
		// can't be preserved through markdown code spans (also normalized away
		// in normalizeForVerify).
		inCode := strings.ToLower(n.Data) == "code"
		for child := n.FirstChild; child != nil; child = child.NextSibling {
			if inCode && child.Type == html.ElementNode &&
				strings.Contains(strings.ToLower(child.Data), "inline-comment-marker") {
				// Inline children of the marker, skip the marker wrapper itself.
				for gc := child.FirstChild; gc != nil; gc = gc.NextSibling {
					serializeNodeXML(buf, gc)
				}
				continue
			}
			serializeNodeXML(buf, child)
		}
		buf.WriteString("</")
		buf.WriteString(n.Data)
		buf.WriteString(">")
	}
}