Repository navigation
Expand file tree
/
Copy pathh2m.go
More file actions
2428 lines (2232 loc) · 84.1 KB
/
Copy pathh2m.go
File metadata and controls
2428 lines (2232 loc) · 84.1 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
// Lute - 一款结构化的 Markdown 引擎,支持 Go 和 JavaScript
// Copyright (c) 2019-present, b3log.org
//
// Lute is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
// http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
package lute
import (
"bytes"
"fmt"
"path"
"slices"
strconv "strconv"
"strings"
"unicode"
"github.com/88250/lute/ast"
"github.com/88250/lute/editor"
"github.com/88250/lute/html"
"github.com/88250/lute/html/atom"
"github.com/88250/lute/lex"
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
"github.com/88250/lute/util"
)
// HTML2Markdown 将 HTML 转换为 Markdown。
func (lute *Lute) HTML2Markdown(htmlStr string) (markdown string, err error) {
//fmt.Println(htmlStr)
// 将字符串解析为 DOM 树
tree := lute.HTML2Tree(htmlStr)
// 将 AST 进行 Markdown 格式化渲染
var formatted []byte
renderer := render.NewFormatRenderer(tree, lute.RenderOptions, lute.ParseOptions)
for nodeType, rendererFunc := range lute.HTML2MdRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
formatted = renderer.Render()
markdown = util.BytesToStr(formatted)
return
}
// HTML2Tree 将 HTML 转换为 AST。
func (lute *Lute) HTML2Tree(dom string) (ret *parse.Tree) {
htmlRoot := util.ParseHTML(dom)
return lute.HTMLNode2Tree(htmlRoot)
}
func (lute *Lute) HTMLNode2Tree(n *html.Node) (ret *parse.Tree) {
if nil == n {
return nil
}
// 调整 DOM 结构
if lute.ParseOptions.ProtyleWYSIWYG && !lute.ParseOptions.DisableTableCellRich {
preserveHTMLTableCellStructure(n)
}
lute.fixTableStructure(n)
lute.adjustVditorDOM(n)
// 将 HTML 树转换为 Markdown AST
ret = &parse.Tree{Name: "", Root: &ast.Node{Type: ast.NodeDocument}, Context: &parse.Context{ParseOption: lute.ParseOptions}}
ret.Context.Tip = ret.Root
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.genASTByDOM(c, ret)
}
// 调整树结构
var previousLis, unlinks []*ast.Node
ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if entering {
if ast.NodeList == n.Type {
// ul.ul => ul.li.ul
if nil != n.Parent && ast.NodeList == n.Parent.Type {
previousLi := n.Previous
if nil != previousLi {
previousLis = append(previousLis, previousLi)
unlinks = append(unlinks, n)
}
}
}
}
return ast.WalkContinue
})
for i, unlink := range unlinks {
unlink.Unlink()
previousLis[i].AppendChild(unlink)
}
styled := false
ast.Walk(ret.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
if entering && (node.Type == ast.NodeTextMark || node.Type == ast.NodeCodeSpan) && node.IALAttr("style") != "" {
styled = true
}
return ast.WalkContinue
})
if styled {
parse.NestedInlines2FlattedSpansHybrid(ret, false)
ast.Walk(ret.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
if entering && node.Type == ast.NodeTextMark {
parse.ApplyHTMLTextStyle(node, node.IALAttr("style"))
}
return ast.WalkContinue
})
}
return ret
}
// escapeHTMLTextMarkers 将 HTML 文本中的标记符保存为转义节点,避免格式扁平化时将转义符混入正文。
func escapeHTMLTextMarkers(node *ast.Node) {
start := 0
for i, token := range node.Tokens {
if !lex.IsProtyleInlineMarker(token) {
continue
}
if start < i {
node.InsertBefore(&ast.Node{Type: node.Type, Tokens: node.Tokens[start:i]})
}
backslash := &ast.Node{Type: ast.NodeBackslash}
backslash.AppendChild(&ast.Node{Type: ast.NodeBackslashContent, Tokens: node.Tokens[i : i+1]})
node.InsertBefore(backslash)
start = i + 1
}
if start == 0 {
return
}
if start < len(node.Tokens) {
node.Tokens = node.Tokens[start:]
} else {
node.Unlink()
}
}
// fixTableStructure 直接修改传入的 *html.Node 树,完美兼容 th、td 以及 colspan、rowspan 合并单元格。
// 外部 HTML(如从浏览器、Excel、Word 复制)的合并单元格遵循 HTML 标准:被合并覆盖的位置没有对应的
// td/th 节点。而思源内部规范需要这些位置存在 class="fn__none" 的占位单元格(见 parse/table.go、
// spin_block_test.go 用例 112-116)。本函数按表格做二维网格计算,在跨行/跨列覆盖的位置补齐占位 td,
// 同时保留原“补齐残缺行列数”的行为。
func (lute *Lute) fixTableStructure(root *html.Node) {
if root == nil {
return
}
// 1. 递归查找 root 节点下的所有 table 节点,按表格分组处理以避免多表格相互污染列数
var tableNodes []*html.Node
var findTables func(*html.Node)
findTables = func(n *html.Node) {
if n.Type == html.ElementNode && n.DataAtom == atom.Table {
tableNodes = append(tableNodes, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
findTables(c)
}
}
findTables(root)
for _, table := range tableNodes {
lute.fixOneTableStructure(table)
}
}
// fixOneTableStructure 处理单个 table:计算 maxCols 并补齐 fn__none 占位单元格。
func (lute *Lute) fixOneTableStructure(table *html.Node) {
// 收集该 table 下的所有 tr(跨 thead/tbody/tfoot)
var trNodes []*html.Node
var findTRs func(*html.Node)
findTRs = func(n *html.Node) {
if n.Type == html.ElementNode && n.DataAtom == atom.Tr {
trNodes = append(trNodes, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
findTRs(c)
}
}
findTRs(table)
if 0 == len(trNodes) {
return
}
// 辅助函数:读取单元格的 colspan(默认 1,非法值视为 1)
readColspan := func(cell *html.Node) int {
if cs := util.DomAttrValue(cell, "colspan"); "" != cs {
if val, err := strconv.Atoi(cs); err == nil && val > 0 {
return val
}
}
return 1
}
// 辅助函数:读取单元格的 rowspan(默认 1,非法值视为 1)
readRowspan := func(cell *html.Node) int {
if rs := util.DomAttrValue(cell, "rowspan"); "" != rs {
if val, err := strconv.Atoi(rs); err == nil && val > 0 {
return val
}
}
return 1
}
// 2. 遍历所有 tr,先用 colspan 权重算出真实最大总列数(保留原逻辑)
maxCols := 0
for _, tr := range trNodes {
rowCols := 0
for c := tr.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && (c.DataAtom == atom.Td || c.DataAtom == atom.Th) {
if "fn__none" == util.DomAttrValue(c, "class") {
// 已有的占位单元格不计入逻辑列(它们是被覆盖的位置)
continue
}
rowCols += readColspan(c)
}
}
if rowCols > maxCols {
maxCols = rowCols
}
}
if 0 == maxCols {
return
}
// 3. 二维网格:occupied[row][col] 标记被跨行/跨列单元格覆盖的位置
// 用模拟 HTML 表格布局的方式补齐占位单元格
// 第 3 步统一处理所有行(含表头):colspan 单元格后补 fn__none 占位、被 rowspan 覆盖处补占位、行末补齐,
// 使每行物理 td 数恰好等于 maxCols,从而 GFM 往返时各行 | 数一致,避免右侧列错位。
rowCount := len(trNodes)
occupied := make([][]bool, rowCount)
for i := range occupied {
occupied[i] = make([]bool, maxCols)
}
isCell := func(c *html.Node) bool {
return c.Type == html.ElementNode && (c.DataAtom == atom.Td || c.DataAtom == atom.Th)
}
isPlaceholder := func(c *html.Node) bool {
return isCell(c) && "fn__none" == util.DomAttrValue(c, "class")
}
for ri, tr := range trNodes {
colIdx := 0
// 预先收集本行的真实单元格(跳过已有的占位 td,它们属于被覆盖位置)
var realCells []*html.Node
for c := tr.FirstChild; c != nil; c = c.NextSibling {
if isCell(c) && !isPlaceholder(c) {
realCells = append(realCells, c)
}
}
for _, cell := range realCells {
// 跳过被占用列(被上方 rowspan 覆盖的位置):在 cell 之前插入 fn__none 占位 td
for colIdx < maxCols && occupied[ri][colIdx] {
insertPlaceholderBefore(cell)
colIdx++
}
if colIdx >= maxCols {
// 超出表格宽度的单元格,忽略(理论上不应发生,maxCols 已按 colspan 算过)
break
}
colspan := readColspan(cell)
// 读取 rowspan 并截断到表格剩余行数,避免越界
rowspan := readRowspan(cell)
if remaining := rowCount - ri; rowspan > remaining {
rowspan = remaining
}
// 标记二维占用(包含起始格自身)
for dr := 0; dr < rowspan && ri+dr < rowCount; dr++ {
for dc := 0; dc < colspan && colIdx+dc < maxCols; dc++ {
occupied[ri+dr][colIdx+dc] = true
}
}
// 单元格跨多列时,在其后补 (colspan-1) 个 fn__none 占位 td,使本行物理 td 数与逻辑列数一致。
// 否则 GFM 表格按 | 数对齐时该行会少列,导致 markdown 往返后右侧内容串列。
//(与思源内部规范一致:colspan 单元格后跟 fn__none 占位,见 spin_block_test 用例 112/113)
for dc := 1; dc < colspan && colIdx+dc <= maxCols; dc++ {
appendPlaceholderAfter(cell)
}
colIdx += colspan
}
// 行末:补齐到 maxCols
for colIdx < maxCols {
if occupied[ri][colIdx] {
// 被 rowspan 覆盖的位置:插 fn__none 占位 td
appendPlaceholder(tr, true)
} else {
// 行本身列数不足(残缺表格):补普通空 td,不加 fn__none
appendPlaceholder(tr, false)
}
colIdx++
}
}
// 4. 处理 thead:如果表格没有 <thead>,且首行含 rowspan>1 的单元格,
// 则用 <thead> 包裹首行 rowspan 覆盖的所有行,避免 rowspan 跨越 thead/tbody 边界导致渲染错乱
//(siyuan 内部规范要求 rowspan 覆盖的行与起始格在同一 section)
if 1 > len(util.DomChildrenByType(table, atom.Thead)) && 0 < len(trNodes) {
firstTR := trNodes[0]
theadRows := 1
for c := firstTR.FirstChild; nil != c; c = c.NextSibling {
if html.ElementNode != c.Type || (atom.Th != c.DataAtom && atom.Td != c.DataAtom) {
continue
}
if rs := util.DomAttrValue(c, "rowspan"); "" != rs {
if val, err := strconv.Atoi(rs); err == nil && val > theadRows {
theadRows = val
}
}
}
if theadRows > 1 && theadRows <= len(trNodes) {
// 用 <thead> 包裹前 theadRows 个 tr
thead := &html.Node{Type: html.ElementNode, DataAtom: atom.Thead, Data: atom.Thead.String()}
// 在第一个 tr 之前插入 thead(无论它在 tbody 里还是 table 直接子节点)
firstTR.InsertBefore(thead)
for i := 0; i < theadRows; i++ {
tr := trNodes[i]
tr.Parent.RemoveChild(tr)
thead.AppendChild(tr)
}
}
}
}
// insertPlaceholderBefore 在 ref 之前插入一个 class="fn__none" 的空 td。
func insertPlaceholderBefore(ref *html.Node) {
td := newPlaceholderTD()
ref.InsertBefore(td)
}
// appendPlaceholder 将一个空 td 追加到 tr 末尾。fnNone 为 true 时标记为 class="fn__none"(合并覆盖占位)。
func appendPlaceholder(tr *html.Node, fnNone bool) {
tr.AppendChild(newTD(fnNone))
}
// appendPlaceholderAfter 在 ref 之后插入一个 class="fn__none" 的空 td,用作 colspan 单元格横向覆盖的占位。
func appendPlaceholderAfter(ref *html.Node) {
td := newPlaceholderTD()
ref.InsertAfter(td)
}
// newPlaceholderTD 构造一个 <td class="fn__none"></td> 节点(合并单元格覆盖占位)。
func newPlaceholderTD() *html.Node {
return newTD(true)
}
// newTD 构造一个空 <td> 节点。fnNone 为 true 时添加 class="fn__none"。
func newTD(fnNone bool) *html.Node {
td := &html.Node{
Type: html.ElementNode,
DataAtom: atom.Td,
Data: atom.Td.String(),
}
if fnNone {
td.Attr = []*html.Attribute{{Key: "class", Val: "fn__none"}}
}
return td
}
// extractTableCaption 将外部 HTML 表格标题规范化为思源表格 caption IAL,并从表格 DOM 中移除原节点。
func extractTableCaption(table *html.Node) string {
for caption := table.FirstChild; nil != caption; caption = caption.NextSibling {
if atom.Caption != caption.DataAtom {
continue
}
title := strings.TrimSpace(util.DomText(caption))
style := util.DomAttrValue(caption, "style")
caption.Unlink()
if "" == title {
return ""
}
captionHTML := `<caption contenteditable="false"`
if tableCaptionAtBottom(style) {
captionHTML += ` style="caption-side: bottom;"`
}
captionHTML += ">" + html.EscapeHTMLStr(title) + "</caption>"
return html.EscapeHTMLStr(captionHTML)
}
return ""
}
// tableCaptionAtBottom 判断外部表格标题是否明确设置在表格下方。
func tableCaptionAtBottom(style string) bool {
for _, declaration := range strings.Split(style, ";") {
parts := strings.SplitN(declaration, ":", 2)
if 2 != len(parts) || !strings.EqualFold(strings.TrimSpace(parts[0]), "caption-side") {
continue
}
value := strings.TrimSpace(strings.TrimSuffix(strings.ToLower(strings.TrimSpace(parts[1])), "!important"))
return "bottom" == value
}
return false
}
// setTableCellSpanIAL 保留表格合并结构和与表头不同的水平对齐样式,忽略外部网页的其它样式。
// class 仅保留由 fixTableStructure 插入的 fn__none 占位标记。
func setTableCellSpanIAL(node *ast.Node, n *html.Node) {
if nil == node || nil == n {
return
}
if atom.Th != n.DataAtom && atom.Td != n.DataAtom {
return
}
colspan := util.DomAttrValue(n, "colspan")
if "" != colspan {
node.SetIALAttr("colspan", colspan)
}
rowspan := util.DomAttrValue(n, "rowspan")
if "" != rowspan {
node.SetIALAttr("rowspan", rowspan)
}
class := util.DomAttrValue(n, "class")
if "fn__none" == class {
// 仅保留思源合并单元格占位标记,丢弃外部网页的样式 class
node.SetIALAttr("class", class)
}
if node.TableCellAlign != tableHeadCellAlign(node) {
align := "start"
switch node.TableCellAlign {
case 1:
align = "left"
case 2:
align = "center"
case 3:
align = "right"
}
node.SetIALAttr("style", "text-align: "+align+";")
}
if "" == colspan && "" == rowspan && "" == node.IALAttr("class") && "" == node.IALAttr("style") {
return
}
ialTokens := parse.IAL2Tokens(node.KramdownIAL)
ial := &ast.Node{Type: ast.NodeKramdownSpanIAL, Tokens: ialTokens}
node.PrependChild(ial)
}
// tableHeadCellAlign 返回同一视觉列的表头对齐方式,供逐格样式往返使用。
func tableHeadCellAlign(node *ast.Node) int {
if nil == node.Parent {
return 0
}
column := 0
for previous := node.Previous; nil != previous; previous = previous.Previous {
if ast.NodeTableCell == previous.Type {
column++
}
}
table := node.Parent.Parent
if nil != table && ast.NodeTableHead == table.Type {
table = table.Parent
}
if nil == table || nil == table.FirstChild || ast.NodeTableHead != table.FirstChild.Type || nil == table.FirstChild.FirstChild {
return 0
}
for cell := table.FirstChild.FirstChild.FirstChild; nil != cell; cell = cell.Next {
if ast.NodeTableCell != cell.Type {
continue
}
if 0 == column {
return cell.TableCellAlign
}
column--
}
return 0
}
// trimTableCellTextTokens 清理表格单元格文本边界,并保留相邻行级节点之间的一个空格。
func trimTableCellTextTokens(n *html.Node, tokens []byte) []byte {
trimmed := bytes.TrimSpace(tokens)
if nil == n.Parent || (atom.Td != n.Parent.DataAtom && atom.Th != n.Parent.DataAtom) {
return trimmed
}
if 0 == len(trimmed) {
if nil != n.PrevSibling && nil != n.NextSibling &&
(strings.ContainsRune(n.Data, ' ') || strings.ContainsRune(n.Data, '\u00a0')) {
return []byte(" ")
}
return nil
}
runes := []rune(n.Data)
if nil != n.PrevSibling && atom.Br != n.PrevSibling.DataAtom && 0 < len(runes) &&
(' ' == runes[0] || '\u00a0' == runes[0]) {
trimmed = append([]byte(" "), trimmed...)
}
if nil != n.NextSibling && atom.Br != n.NextSibling.DataAtom && 0 < len(runes) &&
(' ' == runes[len(runes)-1] || '\u00a0' == runes[len(runes)-1]) {
trimmed = append(trimmed, ' ')
}
return trimmed
}
// genASTByDOM 根据指定的 DOM 节点 n 进行深度优先遍历并逐步生成 Markdown 语法树 tree。
func (lute *Lute) genASTByDOM(n *html.Node, tree *parse.Tree) {
normalizeCodeBlockBanner(n)
if lute.genASTByTabsDOM(n, tree) {
return
}
if html.CommentNode == n.Type || atom.Meta == n.DataAtom {
return
}
if "svg" == n.Namespace {
return
}
dataRender := util.DomAttrValue(n, "data-render")
if "1" == dataRender {
return
}
class := util.DomAttrValue(n, "class")
if strings.HasPrefix(class, "line-number") &&
!strings.HasPrefix(class, "line-numbers" /* 简书代码块 https://github.com/siyuan-note/siyuan/issues/4361 */) {
return
}
if strings.Contains(class, "mw-editsection") {
// 忽略 Wikipedia [编辑] Do not clip the `Edit` element next to Wikipedia headings https://github.com/siyuan-note/siyuan/issues/11600
return
}
if strings.Contains(class, "citation-comment") {
// 忽略 Wikipedia 引用中的注释 https://github.com/siyuan-note/siyuan/issues/11640
return
}
if lute.genASTByCalloutDOM(n, tree) {
return
}
if 0 == n.DataAtom && html.ElementNode == n.Type { // 自定义标签
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.genASTByDOM(c, tree)
}
return
}
node := &ast.Node{Type: ast.NodeText, Tokens: util.StrToBytes(n.Data)}
textStyle := ""
if lute.ParseOptions.ProtyleWYSIWYG {
textStyle = parse.HTMLNodeTextStyle(n).CSS()
defer func() {
if node.Parent == nil || textStyle == "" {
return
}
if node.Type == ast.NodeCodeSpan {
node.SetIALAttr("style", textStyle)
node.InsertAfter(&ast.Node{Type: ast.NodeKramdownSpanIAL, Tokens: parse.IAL2Tokens(node.KramdownIAL)})
} else {
parse.ApplyHTMLTextStyle(node, textStyle)
if node.Type == ast.NodeTextMark {
parse.ApplyHTMLTextSemantics(node, n)
}
}
}()
}
withIAL := false
withDOMIAL := false
if atom.Table == n.DataAtom {
if caption := extractTableCaption(n); "" != caption {
node.SetIALAttr("caption", caption)
withIAL = true
}
}
if 0 < len(lute.ParseOptions.HTML2MarkdownAttrs) {
for _, attr := range n.Attr {
if util.ContainsStr(attr.Key, lute.ParseOptions.HTML2MarkdownAttrs) {
node.SetIALAttr(attr.Key, attr.Val)
withIAL = true
withDOMIAL = true
}
if strings.HasPrefix(attr.Key, "custom-") && util.ContainsStr("custom-*", lute.ParseOptions.HTML2MarkdownAttrs) {
node.SetIALAttr(attr.Key, attr.Val)
withIAL = true
withDOMIAL = true
}
}
}
if withIAL {
ialTokens := parse.IAL2Tokens(node.KramdownIAL)
if withDOMIAL {
ialTokens = lute.setBlockIAL2(n, node)
}
ial := &ast.Node{Type: ast.NodeKramdownBlockIAL, Tokens: ialTokens}
defer tree.Context.TipAppendChild(ial)
}
switch n.DataAtom {
case 0:
class := util.DomAttrValue(n.PrevSibling, "class")
if "fn__space5" == class {
// 链滴剪藏图片时多了长宽显示 https://github.com/siyuan-note/siyuan/issues/10987
return
}
if nil != n.Parent && atom.A == n.Parent.DataAtom {
node.Type = ast.NodeLinkText
}
// 将 \n空格空格* 转换为\n
for strings.Contains(string(node.Tokens), "\n ") {
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("\n "), []byte("\n "))
}
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("\n "), []byte("\n"))
node.Tokens = bytes.Trim(node.Tokens, "\t\n")
if lute.parentIs(n, atom.Table) {
if "\n" == n.Data {
if nil == tree.Context.Tip.FirstChild || nil == n.NextSibling {
break
}
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeBr})
break
} else {
if "" == strings.TrimSpace(n.Data) {
node.Tokens = []byte(" ")
tree.Context.Tip.AppendChild(node)
break
}
}
node.Tokens = trimTableCellTextTokens(n, node.Tokens)
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("\n"), []byte(" "))
}
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte{194, 160}, []byte{' '}) // 将 转换为空格
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("\n"), []byte{' '}) // 将 \n 转换为空格 https://github.com/siyuan-note/siyuan/issues/6052
if ast.NodeStrong == tree.Context.Tip.Type ||
ast.NodeEmphasis == tree.Context.Tip.Type ||
ast.NodeStrikethrough == tree.Context.Tip.Type ||
ast.NodeMark == tree.Context.Tip.Type ||
ast.NodeSup == tree.Context.Tip.Type ||
ast.NodeSub == tree.Context.Tip.Type {
if bytes.HasPrefix(node.Tokens, []byte(" ")) || 1 > len(bytes.TrimSpace(node.Tokens)) {
if nil != tree.Context.Tip.LastChild && tree.Context.Tip.LastChild.IsMarker() {
node.Tokens = append([]byte(editor.Zwsp), node.Tokens...)
}
}
if bytes.HasSuffix(node.Tokens, []byte(" ")) && nil == n.NextSibling {
node.Tokens = append(node.Tokens, []byte(editor.Zwsp)...)
}
}
if ast.NodeParagraph == tree.Context.Tip.Type && bytes.HasPrefix(node.Tokens, []byte("$$")) && bytes.HasSuffix(node.Tokens, []byte("$$")) && 2 == bytes.Count(node.Tokens, []byte("$$")) {
// 将其转换为公式块 https://github.com/siyuan-note/siyuan/issues/14360
tex := bytes.TrimSpace(node.Tokens[2 : len(node.Tokens)-2])
appendMathBlock(tree, util.BytesToStr(tex))
return
}
escapeMarkers := false
if textStyle != "" || (nil != n.Parent && atom.Span == n.Parent.DataAtom && 0 == len(n.Parent.Attr)) {
// 按原文解析,不处理转义
} else {
if lute.ParseOptions.ProtyleWYSIWYG {
if ast.NodeLink != tree.Context.Tip.Type { // a 标签锚文本中的标记符不进行转义 https://github.com/siyuan-note/siyuan/issues/14733
escapeMarkers = true
}
} else {
node.Tokens = lex.EscapeCommonMarkers(node.Tokens)
if lute.parentIs(n, atom.Table) {
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("\\|"), []byte("|"))
node.Tokens = bytes.ReplaceAll(node.Tokens, []byte("|"), []byte("\\|"))
}
}
}
if 1 > len(node.Tokens) {
return
}
if ast.NodeListItem == tree.Context.Tip.Type || (nil != tree.Context.Tip.Parent && ast.NodeListItem == tree.Context.Tip.Parent.Type) ||
(nil != tree.Context.Tip.Parent && nil != tree.Context.Tip.Parent.Parent && ast.NodeListItem == tree.Context.Tip.Parent.Parent.Type) {
// 去掉文本中开头的列表项标记符 https://github.com/siyuan-note/siyuan/issues/14329
if idx := bytes.Index(node.Tokens, []byte(". ")); 0 < idx {
num := node.Tokens[:idx]
isLi := true
for _, b := range num {
if !lex.IsDigit(b) {
isLi = false
break
}
}
if isLi {
node.Tokens = node.Tokens[idx+2:]
}
}
if (nil != tree.Context.Tip.ListData && 0 == tree.Context.Tip.ListData.Typ) || (nil != tree.Context.Tip.Parent.ListData && 0 == tree.Context.Tip.Parent.ListData.Typ) ||
(nil != tree.Context.Tip.Parent && nil != tree.Context.Tip.Parent.Parent.ListData && 0 == tree.Context.Tip.Parent.Parent.ListData.Typ) {
if idx := bytes.Index(node.Tokens, []byte("•")); 0 == idx {
node.Tokens = bytes.TrimSpace(bytes.TrimPrefix(node.Tokens, []byte("•")))
}
if idx := bytes.Index(node.Tokens, []byte("●")); 0 == idx {
node.Tokens = bytes.TrimSpace(bytes.TrimPrefix(node.Tokens, []byte("●")))
}
}
}
if ast.NodeListItem == tree.Context.Tip.Type {
p := &ast.Node{Type: ast.NodeParagraph}
p.AppendChild(node)
tree.Context.Tip.AppendChild(p)
tree.Context.Tip = p
} else {
if nil != n.Parent && atom.Dt == n.Parent.DataAtom {
strong := &ast.Node{Type: ast.NodeStrong}
strong.AppendChild(&ast.Node{Type: ast.NodeStrongA6kOpenMarker, Tokens: util.StrToBytes("**")})
strong.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: util.StrToBytes(util.DomText(n))})
strong.AppendChild(&ast.Node{Type: ast.NodeStrongA6kCloseMarker, Tokens: util.StrToBytes("**")})
tree.Context.Tip.AppendChild(strong)
return
}
tree.Context.Tip.AppendChild(node)
}
if escapeMarkers {
escapeHTMLTextMarkers(node)
}
case atom.P, atom.Div, atom.Section, atom.Dt, atom.Dd:
if ast.NodeLink == tree.Context.Tip.Type {
break
}
if lute.parentIs(n, atom.Table) {
if nil != n.PrevSibling && strings.Contains(n.PrevSibling.Data, "\n") {
break
}
if nil != n.NextSibling && strings.Contains(n.NextSibling.Data, "\n") {
break
}
if nil == tree.Context.Tip.FirstChild {
break
}
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeBr})
break
}
if ast.NodeHeading == tree.Context.Tip.Type {
// h 下存在 div/p/section 则忽略分块
break
}
class := util.DomAttrValue(n, "class")
if atom.Div == n.DataAtom || atom.Section == n.DataAtom {
if class == "language-math" && util.DomAttrValue(n, "data-math") == "" && n.FirstChild != nil && n.FirstChild.Type == html.TextNode && n.FirstChild.NextSibling == nil {
appendMathBlock(tree, util.DomText(n))
return
}
// 解析 GitHub 语法高亮代码块
language := ""
if strings.Contains(class, "-source-") {
language = class[strings.LastIndex(class, "-source-")+len("-source-"):]
} else if strings.Contains(class, "-text-html-basic") {
language = "html"
} else if strings.Contains(class, "language-") && !strings.Contains(class, "-math") {
language = class[strings.LastIndex(class, "language-")+len("language-"):]
if !render.NoHighlight(language) {
language = ""
}
}
if "" != language {
node.Type = ast.NodeCodeBlock
node.IsFencedCodeBlock = true
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceOpenMarker, Tokens: util.StrToBytes("```"), CodeBlockFenceLen: 3})
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceInfoMarker})
buf := &bytes.Buffer{}
node.LastChild.CodeBlockInfo = []byte(language)
buf.WriteString(util.DomText(n))
tokens := buf.Bytes()
tokens = bytes.ReplaceAll(tokens, []byte("\u00A0"), []byte(" "))
tokens = bytes.TrimSuffix(tokens, []byte("\n"+editor.Zwsp))
content := &ast.Node{Type: ast.NodeCodeBlockCode, Tokens: tokens}
node.AppendChild(content)
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceCloseMarker, Tokens: util.StrToBytes("```"), CodeBlockFenceLen: 3})
tree.Context.Tip.AppendChild(node)
return
}
// The browser extension supports CSDN formula https://github.com/siyuan-note/siyuan/issues/5624
if strings.Contains(class, "MathJax") && nil != n.NextSibling && atom.Script == n.NextSibling.DataAtom && strings.Contains(util.DomAttrValue(n.NextSibling, "type"), "math/tex") {
tex := util.DomText(n.NextSibling)
appendMathBlock(tree, tex)
n.NextSibling.Unlink()
return
}
// The browser extension supports Wikipedia formula clipping https://github.com/siyuan-note/siyuan/issues/11583
if tex := strings.TrimSpace(util.DomAttrValue(n, "data-tex")); "" != tex {
appendMathBlock(tree, tex)
return
}
}
if strings.Contains(strings.ToLower(class), "mathjax") {
return
}
if "" == strings.TrimSpace(util.DomText(n)) {
for { // 这里用 for 是为了简化实现
if util.DomExistChildByType(n, atom.Img, atom.Picture, atom.Annotation, atom.Iframe, atom.Video, atom.Audio, atom.Source, atom.Canvas, atom.Svg, atom.Math) {
break
}
if tex := util.GetFormula(n); "" != tex {
// https://github.com/siyuan-note/siyuan/issues/15457
appendMathBlock(tree, tex)
return
}
// span 可能是 TextMark 元素,也可能是公式,其他情况则忽略
spans := util.DomChildrenByType(n, atom.Span)
if 0 < len(spans) {
span := spans[0]
if "" != util.DomAttrValue(span, "data-type") || "" != util.DomAttrValue(span, "data-tex") {
break
}
}
return
}
}
node.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6:
if ast.NodeLink == tree.Context.Tip.Type {
break
}
node.Type = ast.NodeHeading
node.HeadingLevel = int(node.Tokens[1] - byte('0'))
node.AppendChild(&ast.Node{Type: ast.NodeHeadingC8hMarker, Tokens: util.StrToBytes(strings.Repeat("#", node.HeadingLevel))})
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Hr:
node.Type = ast.NodeThematicBreak
tree.Context.Tip.AppendChild(node)
case atom.Blockquote:
node.Type = ast.NodeBlockquote
node.AppendChild(&ast.Node{Type: ast.NodeBlockquoteMarker, Tokens: util.StrToBytes(">")})
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Ol, atom.Ul:
node.Type = ast.NodeList
node.ListData = &ast.ListData{}
if atom.Ol == n.DataAtom {
node.ListData.Typ = 1
}
node.ListData.Tight = true
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Li:
node.Type = ast.NodeListItem
marker := util.DomAttrValue(n, "data-marker")
var bullet byte
if "" == marker {
if nil != n.Parent && atom.Ol == n.Parent.DataAtom {
start := util.DomAttrValue(n.Parent, "start")
if "" == start {
marker = "1."
} else {
marker = start + "."
}
if nil != tree.Context.Tip.LastChild && ast.NodeListItem == tree.Context.Tip.LastChild.Type && nil != tree.Context.Tip.LastChild.ListData {
lastNum := tree.Context.Tip.LastChild.ListData.Marker[:len(tree.Context.Tip.LastChild.ListData.Marker)-1]
lastNumInt := 0
for _, b := range lastNum {
lastNumInt = lastNumInt*10 + int(b-'0')
}
lastNumInt++
marker = fmt.Sprintf("%d.", lastNumInt)
}
} else {
marker = "*"
bullet = marker[0]
}
} else {
if nil != n.Parent && "1." != marker && atom.Ol == n.Parent.DataAtom && nil != n.Parent.Parent && (atom.Ol == n.Parent.Parent.DataAtom || atom.Ul == n.Parent.Parent.DataAtom) {
// 子有序列表必须从 1 开始
marker = "1."
}
}
typ := 0
if nil != tree.Context.Tip.ListData {
typ = tree.Context.Tip.ListData.Typ
}
if 1 == typ && !strings.HasSuffix(marker, ".") {
marker += "."
}
node.ListData = &ast.ListData{Typ: typ, Marker: []byte(marker), BulletChar: bullet}
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Pre:
normalizeCodeMirrorPre(n)
firstc := n.FirstChild
if nil == firstc {
return
}
codes := util.DomChildrenByType(n, atom.Code)
if 0 < len(codes) {
// 删除第一个 code 之前的标签
unlinks := []*html.Node{}
for prev := codes[0].PrevSibling; nil != prev; prev = prev.PrevSibling {
unlinks = append(unlinks, prev)
}
for _, unlink := range unlinks {
unlink.Unlink()
}
firstc = n.FirstChild
if nil == firstc {
return
}
}
class := util.DomAttrValue(firstc, "class")
if strings.Contains(class, "iconfont") {
// 处理 pre.i,ol 的情况,i 标签为“复制代码”或“隐藏代码”,ol 标签为“行号”
// https://github.com/siyuan-note/siyuan/issues/15314
firstc = firstc.NextSibling
n.FirstChild.Unlink()
}
if atom.Em == firstc.DataAtom && nil != firstc.NextSibling && atom.Em == firstc.NextSibling.DataAtom {
// pre.em,em,code 的情况,这两个 em 是“复制代码”和“隐藏代码” https://github.com/siyuan-note/siyuan/issues/13026
if 0 < len(codes) {
firstc = codes[0]
if nil != firstc {
unlinks := []*html.Node{}
for prev := firstc.PrevSibling; nil != prev; prev = prev.PrevSibling {
unlinks = append(unlinks, prev)
}
for _, unlink := range unlinks {
unlink.Unlink()
}
}
}
}
if atom.Div == firstc.DataAtom {
if nil == firstc.NextSibling {
if 1 == len(codes) {
code := codes[0]
// pre 下只有一个 div,且 div 下只有一个 code,那么将 pre.div 替换为 pre.code https://github.com/siyuan-note/siyuan/issues/11131
code.Unlink()
n.AppendChild(code)
firstc.Unlink()
firstc = n.FirstChild
}
} else {
// pre 下全是 div,每个 div 为一行代码 https://github.com/siyuan-note/siyuan/issues/14195
// 将其转换为 pre.code, code, ... code,每个 div 为一行代码,然后交由后续处理
var unlinks, codes []*html.Node
for div := firstc; nil != div; div = div.NextSibling {
code := &html.Node{Data: "code", DataAtom: atom.Code, Type: html.ElementNode}
for child := div.FirstChild; nil != child; child = div.FirstChild {
child.Unlink()
code.AppendChild(child)
}
codes = append(codes, code)
unlinks = append(unlinks, div)
}
for _, unlink := range unlinks {
unlink.Unlink()
}
for _, code := range codes {
n.AppendChild(code)
}
firstc = n.FirstChild
}
}
// 改进两种 pre.ol.li 的代码块解析 https://github.com/siyuan-note/siyuan/issues/11296
// 第一种:将 pre.ol.li.p.span, span, ... span 转换为 pre.ol.li.p.code, code, ... code,然后交由第二种处理
span2Code := false
if atom.Ol == firstc.DataAtom && nil == firstc.NextSibling && nil != firstc.FirstChild && atom.Li == firstc.FirstChild.DataAtom &&
nil != firstc.FirstChild.FirstChild && atom.P == firstc.FirstChild.FirstChild.DataAtom &&
nil != firstc.FirstChild.FirstChild.FirstChild && (atom.Span == firstc.FirstChild.FirstChild.FirstChild.DataAtom || html.TextNode == firstc.FirstChild.FirstChild.FirstChild.Type) {