forked from 88250/lute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvditor_ir_block.go
1564 lines (1476 loc) · 50.4 KB
/
vditor_ir_block.go
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"
"github.com/88250/lute/lex"
"strconv"
"strings"
"github.com/88250/lute/ast"
"github.com/88250/lute/html"
"github.com/88250/lute/html/atom"
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
"github.com/88250/lute/util"
)
// SpinVditorIRBlockDOM 自旋 Vditor Instant-Rendering Block DOM,用于即时渲染块模式下的编辑。
func (lute *Lute) SpinVditorIRBlockDOM(ivHTML string) (ovHTML string) {
// 替换插入符
ivHTML = strings.ReplaceAll(ivHTML, "<wbr>", util.Caret)
markdown := lute.vditorIRBlockDOM2Md(ivHTML)
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
ovHTML = lute.Tree2VditorIRBlockDOM(tree, lute.RenderOptions)
// 替换插入符
ovHTML = strings.ReplaceAll(ovHTML, util.Caret, "<wbr>")
return
}
// HTML2VditorIRBlockDOM 将 HTML 转换为 Vditor Instant-Rendering Block DOM,用于即时渲染块模式下粘贴。
func (lute *Lute) HTML2VditorIRBlockDOM(sHTML string) (vHTML string) {
//fmt.Println(sHTML)
markdown, err := lute.HTML2Markdown(sHTML)
if nil != err {
vHTML = err.Error()
return
}
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewVditorIRBlockRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.HTML2VditorIRBlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = string(output)
return
}
// VditorIRBlockDOM2HTML 将 Vditor Instant-Rendering Block DOM 转换为 HTML,用于 Vditor.getHTML() 接口。
func (lute *Lute) VditorIRBlockDOM2HTML(vhtml string) (sHTML string) {
markdown := lute.vditorIRBlockDOM2Md(vhtml)
sHTML = lute.Md2HTML(markdown)
return
}
// Md2VditorIRBlockDOM 将 markdown 转换为 Vditor Instant-Rendering Block DOM,用于从源码模式切换至即时渲染块模式。
func (lute *Lute) Md2VditorIRBlockDOM(markdown string) (vHTML string) {
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewVditorIRBlockRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.Md2VditorIRBlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = string(output)
return
}
// VditorIRBlockDOM2Md 将 Vditor Instant-Rendering DOM 转换为 markdown,用于从即时渲染块模式切换至源码模式。
func (lute *Lute) VditorIRBlockDOM2Md(htmlStr string) (markdown string) {
htmlStr = strings.ReplaceAll(htmlStr, parse.Zwsp, "")
markdown = lute.vditorIRBlockDOM2Md(htmlStr)
markdown = strings.ReplaceAll(markdown, parse.Zwsp, "")
return
}
// VditorIRBlockDOM2StdMd 将 Vditor Instant-Rendering DOM 转换为标准 markdown,用于复制剪切。
func (lute *Lute) VditorIRBlockDOM2StdMd(htmlStr string) (markdown string) {
htmlStr = strings.ReplaceAll(htmlStr, parse.Zwsp, "")
// DOM 转 AST
tree, err := lute.VditorIRBlockDOM2Tree(htmlStr)
if nil != err {
return err.Error()
}
// 将 kramdown IAL 节点内容置空
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if ast.NodeKramdownBlockIAL == n.Type || ast.NodeKramdownSpanIAL == n.Type {
n.Tokens = nil
}
return ast.WalkContinue
})
// 将 AST 进行 Markdown 格式化渲染
options := render.NewOptions()
options.AutoSpace = false
options.FixTermTypo = false
options.KramdownBlockIAL = true
options.KramdownSpanIAL = true
renderer := render.NewFormatRenderer(tree, options)
formatted := renderer.Render()
markdown = string(formatted)
markdown = strings.ReplaceAll(markdown, parse.Zwsp, "")
return
}
func (lute *Lute) VditorIRBlockDOM2Text(htmlStr string) (text string) {
tree, err := lute.VditorIRBlockDOM2Tree(htmlStr)
if nil != err {
return ""
}
return tree.Root.Text()
}
func (lute *Lute) VditorIRBlockDOM2TextLen(htmlStr string) int {
tree, err := lute.VditorIRBlockDOM2Tree(htmlStr)
if nil != err {
return 0
}
return tree.Root.TextLen()
}
func (lute *Lute) Tree2VditorIRBlockDOM(tree *parse.Tree, options *render.Options) (vHTML string) {
renderer := render.NewVditorIRBlockRenderer(tree, options)
output := renderer.Render()
vHTML = string(output)
return
}
func RenderNodeVditorIRBlockDOM(node *ast.Node, parseOptions *parse.Options, renderOptions *render.Options) string {
root := &ast.Node{Type: ast.NodeDocument}
tree := &parse.Tree{Root: root, Context: &parse.Context{ParseOption: parseOptions}}
renderer := render.NewVditorIRBlockRenderer(tree, renderOptions)
renderer.Writer = &bytes.Buffer{}
ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
rendererFunc := renderer.RendererFuncs[n.Type]
return rendererFunc(n, entering)
})
return renderer.Writer.String()
}
func (lute *Lute) VditorIRBlockDOM2Tree(htmlStr string) (ret *parse.Tree, err error) {
// 删掉插入符
htmlStr = strings.ReplaceAll(htmlStr, "<wbr>", "")
// 替换结尾空白,否则 HTML 解析会产生冗余节点导致生成空的代码块
htmlStr = strings.ReplaceAll(htmlStr, "\t\n", "\n")
htmlStr = strings.ReplaceAll(htmlStr, " \n", " \n")
// 将字符串解析为 DOM 树
htmlRoot := lute.parseHTML(htmlStr)
if nil == htmlRoot {
return
}
// 调整 DOM 结构
lute.adjustVditorDOM(htmlRoot)
// 将 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 := htmlRoot.FirstChild; nil != c; c = c.NextSibling {
lute.genASTByVditorIRBlockDOM(c, ret)
}
// 调整树结构
ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if entering {
switch n.Type {
case ast.NodeInlineHTML, ast.NodeCodeSpan, ast.NodeInlineMath, ast.NodeHTMLBlock, ast.NodeCodeBlockCode, ast.NodeMathBlockContent:
n.Tokens = html.UnescapeHTML(n.Tokens)
if nil != n.Next && ast.NodeCodeSpan == n.Next.Type && n.CodeMarkerLen == n.Next.CodeMarkerLen && nil != n.FirstChild && nil != n.FirstChild.Next {
// 合并代码节点 https://github.com/Vanessa219/vditor/issues/167
n.FirstChild.Next.Tokens = append(n.FirstChild.Next.Tokens, n.Next.FirstChild.Next.Tokens...)
n.Next.Unlink()
}
}
}
return ast.WalkContinue
})
return
}
func (lute *Lute) vditorIRBlockDOM2Md(htmlStr string) (markdown string) {
tree, err := lute.VditorIRBlockDOM2Tree(htmlStr)
if nil != err {
return err.Error()
}
// 将 AST 进行 Markdown 格式化渲染
options := render.NewOptions()
options.AutoSpace = false
options.FixTermTypo = false
options.KramdownBlockIAL = true
options.KramdownSpanIAL = true
renderer := render.NewFormatRenderer(tree, options)
formatted := renderer.Render()
markdown = string(formatted)
return
}
func (lute *Lute) VditorIRBlockDOMListCommand(listHTML, command string, param1, param2 string) (vHTML string) {
//fmt.Println(listHTML, command, "id1:"+param1, "id2:"+param2)
listHTML = strings.ReplaceAll(listHTML, "<wbr>", util.Caret)
md := lute.vditorIRBlockDOM2Md(listHTML)
//fmt.Println(md)
lines := strings.Split(md, "\n")
buf := &bytes.Buffer{}
for i := 0; i < len(lines); i++ {
line := lines[i]
var writeLine string
if ("tab1" == command) && strings.Contains(line, param1) { // 缩进到上下子列表
// 忽略上方子列表 IAL
continue
}
if "tab2" == command && strings.Contains(line, param1) {
continue
}
if strings.Contains(line, util.Caret) {
isOrder := lex.IsDigit(strings.TrimSpace(line)[0])
switch command {
case "tab2": // 带子项缩进
buf.WriteString("\n")
indent := countIndent(line)
if isOrder {
l := strings.TrimSpace(line)[1:]
writeLine = " " + indent + "1" + l + "\n"
buf.WriteString(writeLine)
} else {
writeLine = " " + line + "\n"
buf.WriteString(writeLine)
}
j := i + 1
for ; j < len(lines); j++ {
ial := lines[j]
if strings.Contains(ial, param2) {
buf.WriteString(ial + "\n")
break
}
if isOrder {
buf.WriteString(" " + lines[j] + "\n")
} else {
buf.WriteString(" " + lines[j] + "\n")
}
}
i = j
continue
case "tab0": // 不带子项缩进
buf.WriteString("\n")
indent := countIndent(line)
if isOrder {
if spaces := IndentOrder(line); 0 < spaces {
indent += strings.Repeat(" ", spaces)
}
}
ialIdx := i + 1
for ; ialIdx < len(lines); ialIdx++ {
ial := lines[ialIdx]
if isOrder {
if strings.HasPrefix(ial, " "+indent+"{:") {
break
}
} else {
if strings.HasPrefix(ial, " "+indent+"{:") {
break
}
}
}
if isOrder {
l := trimOrder(line)
writeLine = " " + indent + "1" + l + "\n"
lines[ialIdx] = " " + lines[ialIdx]
} else {
writeLine = " " + line + "\n"
lines[ialIdx] = " " + lines[ialIdx]
}
buf.WriteString(writeLine)
continue
case "stab": // 反向缩进
if isOrder {
writeLine = line[3:] + "\n"
} else {
writeLine = line[2:] + "\n"
}
if strings.HasPrefix(writeLine, ".") {
writeLine = "*" + writeLine[1:]
}
buf.WriteString(writeLine)
}
} else {
writeLine = line + "\n"
buf.WriteString(writeLine)
}
}
md = buf.String()
//fmt.Println(md)
vHTML = lute.Md2VditorIRBlockDOM(md)
vHTML = strings.ReplaceAll(vHTML, util.Caret, "<wbr>")
return
}
func trimOrder(orderListItemLine string) string {
l := strings.TrimSpace(orderListItemLine)
if idx := strings.Index(l, ". "); 0 > idx {
return l
} else {
return l[idx:]
}
}
func IndentOrder(orderListItemLine string) int {
l := strings.TrimSpace(orderListItemLine)
return strings.Index(l, ".")
}
func countIndent(line string) (ret string) {
for _, b := range line {
if ' ' == b {
ret += " "
} else {
break
}
}
return
}
// genASTByVditorIRBlockDOM 根据指定的 Vditor IR DOM 节点 n 进行深度优先遍历并逐步生成 Markdown 语法树 tree。
func (lute *Lute) genASTByVditorIRBlockDOM(n *html.Node, tree *parse.Tree) {
dataRender := lute.domAttrValue(n, "data-render")
if "1" == dataRender || "2" == dataRender { // 1:浮动工具栏,2:preview 代码块、数学公式块或者不解析的节点
return
}
dataType := lute.domAttrValue(n, "data-type")
if "ref-text-tpl-render-result" == dataType { // 剔除渲染好的锚文本
return
}
class := lute.domAttrValue(n, "class")
content := strings.ReplaceAll(n.Data, parse.Zwsp, "")
nodeID := lute.domAttrValue(n, "data-node-id")
node := &ast.Node{ID: nodeID, Type: ast.NodeText, Tokens: []byte(content)}
if "" == nodeID {
if "p" == dataType || "ul" == dataType || "ol" == dataType || "blockquote" == dataType ||
"math-block" == dataType || "code-block" == dataType || "table" == dataType || "h" == dataType ||
"link-ref-defs-block" == dataType || "footnotes-block" == dataType || "super-block" == dataType ||
"git-conflict" == dataType {
nodeID = ast.NewNodeID()
node.ID = nodeID
}
}
if "" != node.ID && !lute.parentIs(n, atom.Table) {
node.KramdownIAL = [][]string{{"id", node.ID}}
ialTokens := lute.setIAL(n, node)
ial := &ast.Node{Type: ast.NodeKramdownBlockIAL, Tokens: ialTokens}
defer tree.Context.TipAppendChild(ial)
}
if atom.Div == n.DataAtom {
if "link-ref-defs-block" == dataType {
text := lute.domText(n)
if !strings.HasPrefix(text, "[") {
subTree := parse.Parse("", []byte(text), lute.ParseOptions)
if nil != subTree.Root.FirstChild {
tree.Context.Tip.AppendChild(subTree.Root.FirstChild)
}
return
}
defBlock := &ast.Node{Type: ast.NodeLinkRefDefBlock}
tree.Context.Tip.AppendChild(defBlock)
for def := n.FirstChild; nil != def; def = def.NextSibling {
text = lute.domText(def)
subTree := parse.Parse("", []byte(text), lute.ParseOptions)
child := subTree.Root.FirstChild.FirstChild
if ast.NodeLinkRefDef == child.Type {
defBlock.AppendChild(subTree.Root.FirstChild.FirstChild)
} else {
tree.Context.Tip.AppendChild(subTree.Root.FirstChild)
}
}
return
} else if "footnotes-def" == dataType {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if nil == c.FirstChild {
continue
}
if c == n.FirstChild && !strings.HasPrefix(c.FirstChild.Data, "[^") {
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(lute.domText(c))})
continue
}
if strings.HasPrefix(c.FirstChild.Data, "[^") && strings.Contains(c.FirstChild.Data, "]: ") {
label := c.FirstChild.Data[1:strings.Index(c.FirstChild.Data, "]: ")]
tree.Context.Tip.Tokens = []byte(label)
c.FirstChild.Data = c.FirstChild.Data[strings.Index(c.FirstChild.Data, "]: ")+3:]
}
lute.genASTByVditorIRBlockDOM(c, tree)
}
return
} else if "footnotes-block" == dataType {
footnotesBlock := &ast.Node{Type: ast.NodeFootnotesDefBlock}
tree.Context.Tip.AppendChild(footnotesBlock)
for def := n.FirstChild; nil != def; def = def.NextSibling {
defNode := &ast.Node{Type: ast.NodeFootnotesDef}
originalHTML := &bytes.Buffer{}
if err := html.Render(originalHTML, def); nil == err {
subTree, _ := lute.VditorIRBlockDOM2Tree(originalHTML.String())
if nil != subTree.Root.Tokens {
var children []*ast.Node
for c := subTree.Root.FirstChild; nil != c; c = c.Next {
children = append(children, c)
}
for _, c := range children {
defNode.AppendChild(c)
}
defNode.Tokens = subTree.Root.Tokens
footnotesBlock.AppendChild(defNode)
} else {
footnotesBlock.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(subTree.Root.Text())})
}
}
}
return
} else if "toc-block" == dataType {
node := &ast.Node{Type: ast.NodeToC}
tree.Context.Tip.AppendChild(node)
return
} else if "block-query-embed" == dataType {
text := lute.domText(n)
t := parse.Parse("", []byte(text), lute.ParseOptions)
t.Root.LastChild.Unlink() // 移除 doc IAL
if blockQueryEmbed := t.Root.FirstChild; nil != blockQueryEmbed && ast.NodeBlockQueryEmbed == blockQueryEmbed.Type {
ial, id := node.KramdownIAL, node.ID
node = blockQueryEmbed
node.KramdownIAL, node.ID = ial, id
next := blockQueryEmbed.Next
tree.Context.Tip.AppendChild(node)
appendNextToTip(next, tree)
return
}
node := &ast.Node{Type: ast.NodeText, Tokens: []byte(text)}
tree.Context.Tip.AppendChild(node)
return
}
}
switch n.DataAtom {
case 0:
if "" == content {
return
}
if html.ElementNode == n.Type {
break
}
checkIndentCodeBlock := strings.ReplaceAll(content, util.Caret, "")
checkIndentCodeBlock = strings.ReplaceAll(checkIndentCodeBlock, "\t", " ")
if (!lute.isInline(n.PrevSibling)) && strings.HasPrefix(checkIndentCodeBlock, " ") {
node.Type = ast.NodeCodeBlock
node.IsFencedCodeBlock = true
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceOpenMarker, Tokens: []byte("```"), CodeBlockFenceLen: 3})
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceInfoMarker})
startCaret := strings.HasPrefix(content, util.Caret)
if startCaret {
content = strings.ReplaceAll(content, util.Caret, "")
}
content = strings.TrimSpace(content)
if startCaret {
content = util.Caret + content
}
content := &ast.Node{Type: ast.NodeCodeBlockCode, Tokens: []byte(content)}
node.AppendChild(content)
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceCloseMarker, Tokens: []byte("```"), CodeBlockFenceLen: 3})
tree.Context.Tip.AppendChild(node)
return
}
if nil != n.Parent && atom.A == n.Parent.DataAtom {
node.Type = ast.NodeLinkText
}
if ast.NodeCodeBlock == tree.Context.Tip.Type {
// 开始代码块标记符后退格的情况
tree.Context.Tip.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(content)})
if nil != n.NextSibling && nil != n.NextSibling.NextSibling && nil != n.NextSibling.NextSibling.NextSibling &&
nil != n.NextSibling.NextSibling.NextSibling.NextSibling {
n.Parent.RemoveChild(n.NextSibling.NextSibling.NextSibling.NextSibling)
}
break
}
tokens := make([]byte, len(node.Tokens))
copy(tokens, node.Tokens)
// 尝试块级解析
subTree := parse.Parse("", tokens, tree.Context.ParseOption)
if nil != subTree.Root.FirstChild && ast.NodeParagraph == tree.Context.Tip.Type && (ast.NodeCodeBlock == subTree.Root.FirstChild.Type || ast.NodeList == subTree.Root.FirstChild.Type) {
if ast.NodeCodeBlock == subTree.Root.FirstChild.Type {
// 处理列表代码块
node.Tokens = bytes.TrimPrefix(node.Tokens, []byte("\n"))
tree.Context.Tip.AppendChild(node)
} else if ast.NodeList == subTree.Root.FirstChild.Type {
if nil == n.Parent.NextSibling {
node.Tokens = bytes.TrimPrefix(node.Tokens, []byte("\n"))
tree.Context.Tip.AppendChild(node)
} else {
if "" == subTree.Root.FirstChild.Text() && util.Caret == n.Parent.NextSibling.FirstChild.Data {
// 处理空列表
tree.Context.Tip.Type = subTree.Root.FirstChild.Type
node = subTree.Root.FirstChild.FirstChild
tree.Context.Tip.AppendChild(subTree.Root.FirstChild.FirstChild)
node = &ast.Node{Type: ast.NodeParagraph}
tree.Context.Tip.LastChild.AppendChild(node)
tree.Context.Tip = node
}
}
}
} else {
// 尝试行级解析,处理段落图片文本节点转换为图片节点
subTree = parse.Inline("", tokens, tree.Context.ParseOption)
if ast.NodeSoftBreak == subTree.Root.FirstChild.FirstChild.Type || // 软换行
(ast.NodeParagraph == subTree.Root.FirstChild.Type &&
(ast.NodeImage == subTree.Root.FirstChild.FirstChild.Type ||
(ast.NodeSoftBreak == subTree.Root.FirstChild.FirstChild.Type && nil != subTree.Root.FirstChild.FirstChild.Next &&
(ast.NodeText == subTree.Root.FirstChild.FirstChild.Next.Type ||
ast.NodeEmphasis == subTree.Root.FirstChild.FirstChild.Next.Type ||
ast.NodeStrong == subTree.Root.FirstChild.FirstChild.Next.Type ||
ast.NodeStrikethrough == subTree.Root.FirstChild.FirstChild.Next.Type ||
ast.NodeCodeSpan == subTree.Root.FirstChild.FirstChild.Next.Type ||
ast.NodeMark == subTree.Root.FirstChild.FirstChild.Next.Type))) && // 软换行后跟普通文本
nil == subTree.Root.FirstChild.Next) {
appendNextToTip(subTree.Root.FirstChild.FirstChild, tree)
} else {
node.Tokens = bytes.TrimPrefix(node.Tokens, []byte("\n"))
tree.Context.Tip.AppendChild(node)
}
}
case atom.P:
node.Type = ast.NodeParagraph
text := lute.domText(n)
if "\n" == text && ast.NodeBlockquote == tree.Context.Tip.Type && nil == tree.Context.Tip.FirstChild.Next {
// 不允许在 bq 第一个节点前换行
return
} else {
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:
text := lute.domText(n)
if "" == strings.TrimSpace(text) {
return
}
if lute.parentIs(n, atom.Table) {
node.Tokens = []byte(strings.TrimSpace(text))
for bytes.HasPrefix(node.Tokens, []byte("#")) {
node.Tokens = bytes.TrimPrefix(node.Tokens, []byte("#"))
}
tree.Context.Tip.AppendChild(node)
return
}
node.Type = ast.NodeHeading
marker := lute.domAttrValue(n, "data-marker")
node.HeadingSetext = "=" == marker || "-" == marker
if !node.HeadingSetext {
marker := lute.domText(n.FirstChild)
node.HeadingLevel = bytes.Count([]byte(marker), []byte("#"))
} else {
if n.FirstChild == n.LastChild || "" == strings.TrimSpace(strings.ReplaceAll(lute.domText(n.LastChild), util.Caret, "")) {
node.Type = ast.NodeText
node.Tokens = []byte(text)
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
return
}
if "=" == marker {
node.HeadingLevel = 1
} else {
node.HeadingLevel = 2
}
if nil != n.LastChild.PrevSibling {
n.LastChild.PrevSibling.Data = strings.TrimSuffix(n.LastChild.PrevSibling.Data, "\n")
}
}
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:
content := strings.TrimSpace(lute.domText(n))
if "" == content || ">" == content {
return
}
if util.Caret == content {
node.Type = ast.NodeText
node.Tokens = []byte(content)
tree.Context.Tip.AppendChild(node)
}
node.Type = ast.NodeBlockquote
node.AppendChild(&ast.Node{Type: ast.NodeBlockquoteMarker, Tokens: []byte(">")})
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Ol, atom.Ul:
if nil == n.FirstChild {
return
}
node.Type = ast.NodeList
node.ListData = &ast.ListData{}
marker := lute.domAttrValue(n, "data-marker")
if "" == marker {
marker = "*"
}
// 固定标记符,降低复杂度
if atom.Ol == n.DataAtom {
marker = "*"
} else {
marker = strings.ReplaceAll(marker, ")", ".")
}
if atom.Ol == n.DataAtom {
node.ListData.Typ = 1
start := lute.domAttrValue(n, "start")
if "" == start {
start = "1"
}
node.ListData.Start, _ = strconv.Atoi(start)
} else {
node.ListData.BulletChar = marker[0]
}
node.ListData.Marker = []byte(marker)
tight := lute.domAttrValue(n, "data-tight")
if "true" == tight || "" == tight {
node.Tight = true
}
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Li:
if ast.NodeList != tree.Context.Tip.Type {
parent := &ast.Node{}
parent.Type = ast.NodeList
parent.ListData = &ast.ListData{Tight: true}
marker := lute.domAttrValue(n, "data-marker")
if "" == marker {
marker = "*"
}
tree.Context.Tip.AppendChild(parent)
tree.Context.Tip = parent
}
if p := n.FirstChild; nil != p && atom.P == p.DataAtom && nil != p.NextSibling && atom.P == p.NextSibling.DataAtom {
tree.Context.Tip.Tight = false
}
node.Type = ast.NodeListItem
marker := lute.domAttrValue(n, "data-marker")
var bullet byte
if "" == marker {
if nil != n.Parent && atom.Ol == n.Parent.DataAtom {
firstLiMarker := lute.domAttrValue(n.Parent.FirstChild, "data-marker")
if startAttr := lute.domAttrValue(n.Parent, "start"); "" == startAttr {
marker = "1"
} else {
marker = startAttr
}
if "" != firstLiMarker {
marker += firstLiMarker[len(firstLiMarker)-1:]
} else {
marker += "."
}
} else {
marker = lute.domAttrValue(n.Parent, "data-marker")
if "" == marker {
marker = "*"
}
bullet = marker[0]
}
} else {
if nil != n.Parent {
if atom.Ol == n.Parent.DataAtom {
if "*" == marker || "-" == marker || "+" == marker {
marker = "1."
}
if "1." != marker && "1)" != marker && nil != n.PrevSibling && atom.Li != n.PrevSibling.DataAtom &&
nil != n.Parent.Parent && (atom.Ol == n.Parent.Parent.DataAtom || atom.Ul == n.Parent.Parent.DataAtom) {
// 子有序列表第一项必须从 1 开始
marker = "1."
}
if "1." != marker && "1)" != marker && atom.Ol == n.Parent.DataAtom && n.Parent.FirstChild == n && "" == lute.domAttrValue(n.Parent, "start") {
marker = "1."
}
} else {
if "*" != marker && "-" != marker && "+" != marker {
marker = "*"
}
bullet = marker[0]
}
} else {
marker = lute.domAttrValue(n, "data-marker")
if "" == marker {
marker = "*"
}
bullet = marker[0]
}
}
node.ListData = &ast.ListData{Marker: []byte(marker), BulletChar: bullet}
if 0 == bullet {
node.ListData.Num, _ = strconv.Atoi(marker[:len(marker)-1])
node.ListData.Delimiter = marker[len(marker)-1]
}
if "vditor-task" == lute.domAttrValue(n, "class") {
node.ListData.Typ = 3
tree.Context.Tip.ListData.Typ = 3
}
if nil == n.FirstChild {
node.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp)})
}
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Pre:
if atom.Code == n.FirstChild.DataAtom {
var codeTokens []byte
if nil != n.FirstChild.FirstChild {
codeTokens = util.StrToBytes(lute.domText(n.FirstChild.FirstChild))
for next := n.FirstChild.FirstChild.NextSibling; nil != next; next = next.NextSibling {
// YAML Front Matter 中删除问题 https://github.com/siyuan-note/siyuan/issues/109
codeTokens = append(codeTokens, []byte(lute.domText(next))...)
}
}
divDataType := lute.domAttrValue(n.Parent, "data-type")
switch divDataType {
case "math-block":
node.Type = ast.NodeMathBlockContent
node.Tokens = codeTokens
tree.Context.Tip.AppendChild(node)
case "git-conflict":
node.Type = ast.NodeGitConflictContent
node.Tokens = codeTokens
tree.Context.Tip.AppendChild(node)
case "html-block":
tree.Context.Tip.Tokens = codeTokens
case "yaml-front-matter":
node.Type = ast.NodeYamlFrontMatterContent
node.Tokens = codeTokens
tree.Context.Tip.AppendChild(node)
default:
node.Type = ast.NodeCodeBlockCode
node.Tokens = codeTokens
tree.Context.Tip.AppendChild(node)
}
}
return
case atom.Em, atom.I:
if nil == n.FirstChild || atom.Br == n.FirstChild.DataAtom {
return
}
if lute.starstWithNewline(n.FirstChild) {
n.FirstChild.Data = strings.TrimLeft(n.FirstChild.Data, parse.Zwsp+"\n")
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp + "\n")})
}
text := strings.TrimSpace(lute.domText(n))
if lute.isEmptyText(n) {
return
}
if util.Caret == text {
node.Tokens = util.CaretTokens
tree.Context.Tip.AppendChild(node)
return
}
node.Type = ast.NodeEmphasis
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Strong, atom.B:
if nil == n.FirstChild || atom.Br == n.FirstChild.DataAtom {
return
}
if lute.starstWithNewline(n.FirstChild) {
n.FirstChild.Data = strings.TrimLeft(n.FirstChild.Data, parse.Zwsp+"\n")
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp + "\n")})
}
text := strings.TrimSpace(lute.domText(n))
if lute.isEmptyText(n) {
return
}
if util.Caret == text {
node.Tokens = util.CaretTokens
tree.Context.Tip.AppendChild(node)
return
}
node.Type = ast.NodeStrong
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Del, atom.S, atom.Strike:
if nil == n.FirstChild || atom.Br == n.FirstChild.DataAtom {
return
}
if lute.starstWithNewline(n.FirstChild) {
n.FirstChild.Data = strings.TrimLeft(n.FirstChild.Data, parse.Zwsp+"\n")
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp + "\n")})
}
text := strings.TrimSpace(lute.domText(n))
if lute.isEmptyText(n) {
return
}
if util.Caret == text {
node.Tokens = util.CaretTokens
tree.Context.Tip.AppendChild(node)
return
}
node.Type = ast.NodeStrikethrough
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Mark:
if nil == n.FirstChild || atom.Br == n.FirstChild.DataAtom {
return
}
if lute.starstWithNewline(n.FirstChild) {
n.FirstChild.Data = strings.TrimLeft(n.FirstChild.Data, parse.Zwsp+"\n")
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp + "\n")})
}
text := strings.TrimSpace(lute.domText(n))
if lute.isEmptyText(n) {
return
}
if util.Caret == text {
node.Tokens = util.CaretTokens
tree.Context.Tip.AppendChild(node)
return
}
node.Type = ast.NodeMark
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Code:
if nil == n.FirstChild {
return
}
firstChildDataType := lute.domAttrValue(n.FirstChild, "data-type")
if firstChildDataType == "html-inline" {
break
}
contentStr := strings.ReplaceAll(n.FirstChild.Data, parse.Zwsp, "")
if util.Caret == contentStr {
node.Tokens = util.CaretTokens
tree.Context.Tip.AppendChild(node)
return
}
if "" == contentStr {
return
}
codeTokens := []byte(contentStr)
content := &ast.Node{Type: ast.NodeCodeSpanContent, Tokens: codeTokens}
node.Type = ast.NodeCodeSpan
node.AppendChild(content)
tree.Context.Tip.AppendChild(node)
return
case atom.Br:
if nil != n.Parent {
if lute.parentIs(n, atom.Td, atom.Th) {
if (nil == n.PrevSibling || util.Caret == n.PrevSibling.Data) && (nil == n.NextSibling || util.Caret == n.NextSibling.Data) {
return
}
if nil == n.NextSibling {
return // 删掉表格中结尾的 br
}
node.Type = ast.NodeInlineHTML
node.Tokens = []byte("<br />")
tree.Context.Tip.AppendChild(node)
return
}
if atom.P == n.Parent.DataAtom {
if nil != n.Parent.NextSibling && (atom.Ul == n.Parent.NextSibling.DataAtom || atom.Ol == n.Parent.NextSibling.DataAtom || atom.Blockquote == n.Parent.NextSibling.DataAtom) {
tree.Context.Tip.PrependChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(parse.Zwsp)})
return
}
}
}
node.Type = ast.NodeHardBreak
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.A:
node.Type = ast.NodeLink
node.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Img:
imgClass := class
imgAlt := lute.domAttrValue(n, "alt")
if "emoji" == imgClass {
node.Type = ast.NodeEmoji
emojiImg := &ast.Node{Type: ast.NodeEmojiImg, Tokens: tree.EmojiImgTokens(imgAlt, lute.domAttrValue(n, "src"))}
emojiImg.AppendChild(&ast.Node{Type: ast.NodeEmojiAlias, Tokens: []byte(":" + imgAlt + ":")})
node.AppendChild(emojiImg)
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
} else {
return
}
case atom.Input:
if nil == n.Parent || (atom.P != n.Parent.DataAtom && atom.Li != n.Parent.DataAtom) {
// 仅允许 input 出现在任务列表中
return
}
if nil != n.NextSibling && atom.Span == n.NextSibling.DataAtom {
// 在任务列表前退格
n.NextSibling.FirstChild.Data = strings.TrimSpace(n.NextSibling.FirstChild.Data)
break
}
node.Type = ast.NodeTaskListItemMarker
if lute.hasAttr(n, "checked") {
node.TaskListItemChecked = true
}
tree.Context.Tip.AppendChild(node)
if nil != node.Parent.Parent.Parent && nil != node.Parent.Parent.Parent.ListData { // ul.li.p.input
node.Parent.Parent.Parent.ListData.Typ = 3
node.Parent.Parent.ListData.Typ = 3
}
if nil != n.NextSibling && (atom.H1 == n.NextSibling.DataAtom || atom.H2 == n.NextSibling.DataAtom || atom.H3 == n.NextSibling.DataAtom || atom.H4 == n.NextSibling.DataAtom || atom.H5 == n.NextSibling.DataAtom || atom.H6 == n.NextSibling.DataAtom ||
atom.Blockquote == n.NextSibling.DataAtom) {
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
}
case atom.Table:
node.Type = ast.NodeTable
var tableAligns []int
for th := n.FirstChild.FirstChild.FirstChild; nil != th; th = th.NextSibling {
align := lute.domAttrValue(th, "align")
switch align {
case "left":
tableAligns = append(tableAligns, 1)
case "center":
tableAligns = append(tableAligns, 2)
case "right":
tableAligns = append(tableAligns, 3)
default:
tableAligns = append(tableAligns, 0)
}
}
node.TableAligns = tableAligns
node.Tokens = nil
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Thead:
node.Type = ast.NodeTableHead
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Tbody:
case atom.Tr:
node.Type = ast.NodeTableRow
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node