-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
vditor_wysiwyg.go
1803 lines (1652 loc) · 54.5 KB
/
vditor_wysiwyg.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"
"strconv"
"strings"
"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/parse"
"github.com/88250/lute/render"
"github.com/88250/lute/util"
)
// Md2HTML 将 markdown 转换为标准 HTML,用于源码模式预览。
func (lute *Lute) Md2HTML(markdown string) (sHTML string) {
sHTML = lute.MarkdownStr("", markdown)
return
}
// SpinVditorDOM 自旋 Vditor DOM,用于所见即所得模式下的编辑。
func (lute *Lute) SpinVditorDOM(ivHTML string) (ovHTML string) {
ivHTML = strings.ReplaceAll(ivHTML, editor.FrontEndCaret, editor.Caret)
markdown := lute.vditorDOM2Md(ivHTML)
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewVditorRenderer(tree, lute.RenderOptions)
output := renderer.Render()
ovHTML = strings.ReplaceAll(string(output), editor.Caret, editor.FrontEndCaret)
return
}
// HTML2VditorDOM 将 HTML 转换为 Vditor DOM,用于所见即所得模式下粘贴。
func (lute *Lute) HTML2VditorDOM(sHTML string) (vHTML string) {
markdown, err := lute.HTML2Markdown(sHTML)
if nil != err {
vHTML = err.Error()
return
}
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewVditorRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.HTML2VditorDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = string(output)
return
}
// VditorDOM2HTML 将 Vditor DOM 转换为 HTML,用于 Vditor.getHTML() 接口。
func (lute *Lute) VditorDOM2HTML(vhtml string) (sHTML string) {
markdown := lute.vditorDOM2Md(vhtml)
sHTML = lute.Md2HTML(markdown)
return
}
// Md2VditorDOM 将 markdown 转换为 Vditor DOM,用于从源码模式切换至所见即所得模式。
func (lute *Lute) Md2VditorDOM(markdown string) (vHTML string) {
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewVditorRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.Md2VditorDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = string(output)
return
}
// VditorDOM2Md 将 Vditor DOM 转换为 markdown,用于从所见即所得模式切换至源码模式。
func (lute *Lute) VditorDOM2Md(htmlStr string) (markdown string) {
htmlStr = strings.ReplaceAll(htmlStr, editor.Zwsp, "")
markdown = lute.vditorDOM2Md(htmlStr)
markdown = strings.ReplaceAll(markdown, editor.Zwsp, "")
return
}
// RenderEChartsJSON 用于渲染 ECharts JSON 格式数据。
func (lute *Lute) RenderEChartsJSON(markdown string) (json string) {
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewEChartsJSONRenderer(tree, lute.RenderOptions)
output := renderer.Render()
json = string(output)
return
}
// RenderKityMinderJSON 用于渲染 KityMinder JSON 格式数据。
func (lute *Lute) RenderKityMinderJSON(markdown string) (json string) {
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
renderer := render.NewKityMinderJSONRenderer(tree, lute.RenderOptions)
output := renderer.Render()
json = string(output)
return
}
// HTML2Md 用于将 HTML 转换为 markdown。
func (lute *Lute) HTML2Md(html string) (markdown string) {
markdown, err := lute.HTML2Markdown(html)
if nil != err {
markdown = err.Error()
return
}
return
}
func (lute *Lute) vditorDOM2Md(htmlStr string) (markdown string) {
// 删掉插入符
htmlStr = strings.ReplaceAll(htmlStr, editor.FrontEndCaret, "")
// 替换结尾空白,否则 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
tree := &parse.Tree{Name: "", Root: &ast.Node{Type: ast.NodeDocument}, Context: &parse.Context{ParseOption: lute.ParseOptions}}
tree.Context.Tip = tree.Root
for c := htmlRoot.FirstChild; nil != c; c = c.NextSibling {
lute.genASTByVditorDOM(c, tree)
}
// 调整树结构
ast.Walk(tree.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 {
// 合并代码节点 https://github.com/Vanessa219/vditor/issues/167
n.FirstChild.Next.Tokens = append(n.FirstChild.Next.Tokens, n.Next.FirstChild.Next.Tokens...)
n.Next.Unlink()
}
case ast.NodeList:
// 浏览器生成的子列表是 ul.ul 形式,需要将其调整为 ul.li.ul
if nil != n.Parent && ast.NodeList == n.Parent.Type {
if previousLi := n.Previous; nil != previousLi {
previousLi.AppendChild(n)
}
}
}
}
return ast.WalkContinue
})
// 将 AST 进行 Markdown 格式化渲染
options := render.NewOptions()
options.AutoSpace = false
options.FixTermTypo = false
renderer := render.NewFormatRenderer(tree, options)
formatted := renderer.Render()
markdown = string(formatted)
return
}
func (lute *Lute) parseHTML(htmlStr string) *html.Node {
reader := strings.NewReader(htmlStr)
doc, err := html.Parse(reader)
if nil != err {
return nil
}
if "html" != doc.FirstChild.Data {
return doc
}
return doc.FirstChild.LastChild // doc.html.body
}
func (lute *Lute) adjustVditorDOM(root *html.Node) {
lute.removeEmptyNodes(root)
lute.removeHighlightJSSpans(root)
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.mergeVditorDOMList0(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustVditorDOMListTight0(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustVditorDOMListList(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustVditorDOMListItemInP(c)
}
for c := root.FirstChild; nil != c; {
next := c.NextSibling
lute.removeCodeCode(c)
c = next
}
for c := root.FirstChild; nil != c; {
next := c.NextSibling
lute.adjustVditorDOMCodeA(c)
c = next
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustCustomTag(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.mergeSameStrong(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustTableCode(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustMath(c)
}
for c := root.FirstChild; nil != c; c = c.NextSibling {
lute.adjustNoscriptImg(c)
}
}
func (lute *Lute) adjustCustomTag(n *html.Node) {
// 将某些自定义标签转换为标准标签
if html.ElementNode == n.Type && 0 == n.DataAtom {
if "ucapcontent" == n.Data {
n.DataAtom = atom.Div
} else if "ucaptitle" == n.Data {
n.DataAtom = atom.H2
n.Data = "h2"
} else if "markerow8" == n.Data {
n.DataAtom = atom.Span
} else if "app-document-text" == n.Data {
n.DataAtom = atom.Div
}
}
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.adjustCustomTag(c)
}
}
func (lute *Lute) adjustNoscriptImg(n *html.Node) {
if nil != n.Parent && atom.Figure == n.Parent.DataAtom &&
atom.Noscript == n.DataAtom && nil != n.FirstChild && strings.HasPrefix(n.FirstChild.Data, "<img ") {
img := n.FirstChild
img.Unlink()
img.DataAtom = atom.Img
fragment, err := html.ParseFragment(strings.NewReader(img.Data), &html.Node{Type: html.ElementNode})
if nil != err || 1 > len(fragment) {
return
}
img = fragment[0]
n.InsertBefore(img)
var unlinks []*html.Node
for c := n; nil != c; c = c.NextSibling {
if atom.Figcaption == c.DataAtom {
continue
}
unlinks = append(unlinks, c)
}
for _, unlink := range unlinks {
unlink.Unlink()
}
}
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.adjustNoscriptImg(c)
}
}
func (lute *Lute) adjustMath(n *html.Node) {
class := util.DomAttrValue(n, "class")
if ((atom.Span == n.DataAtom || atom.Div == n.DataAtom) && strings.Contains(class, "mwe-math-element")) || (strings.Contains(class, "tex") && !strings.Contains(class, "text")) {
if annos := util.DomChildrenByType(n, atom.Annotation); 0 < len(annos) {
anno := annos[0]
if "application/x-tex" == util.DomAttrValue(anno, "encoding") {
util.SetDomAttrValue(n, "data-tex", util.DomText(anno))
return
}
}
if imgs := util.DomChildrenByType(n, atom.Img); 0 < len(imgs) {
img := imgs[0]
if mathContent := util.DomAttrValue(img, "alt"); "" != mathContent {
util.SetDomAttrValue(n, "data-tex", mathContent)
return
}
}
}
formula := util.DomAttrValue(n, "data-formula")
if "" != formula {
if html.ElementNode == n.Type && "mjx-container" == n.Data {
n.DataAtom = atom.Span
}
util.SetDomAttrValue(n, "data-tex", formula)
return
}
if strings.Contains(class, "texhtml") {
if mathContent := util.DomTexhtml(n); "" != mathContent {
util.SetDomAttrValue(n, "data-tex", mathContent)
return
}
}
if strings.Contains(class, "math") {
scripts := util.DomChildrenByType(n, atom.Script)
if 0 < len(scripts) {
script := scripts[0]
if "math/tex" == util.DomAttrValue(script, "type") {
if mathContent := util.DomText(script); "" != mathContent {
util.SetDomAttrValue(n, "data-tex", mathContent)
}
}
}
}
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.adjustMath(c)
}
}
func (lute *Lute) adjustTableCode(n *html.Node) {
if atom.Table == n.DataAtom {
// 表格类型的代码块进行预处理 https://github.com/siyuan-note/siyuan/issues/11540
// 移除 <td class="gutter">
// td class="code"> 下的 <div class="container"> 改为 <pre>
tds := util.DomChildrenByType(n, atom.Td)
var unlinks []*html.Node
for _, td := range tds {
tdClass := util.DomAttrValue(td, "class")
if strings.Contains(tdClass, "gutter") {
unlinks = append(unlinks, td)
continue
}
if strings.Contains(tdClass, "code") {
if c := td.FirstChild; nil != c && atom.Div == c.DataAtom {
c.DataAtom = atom.Pre
c.Data = "pre"
lang := util.DomAttrValue(n, "class")
lang = strings.ReplaceAll(lang, "syntaxhighlighter", "")
lang = strings.TrimSpace(lang)
if "" != lang {
util.SetDomAttrValue(c, "class", lang)
}
for div := c.FirstChild; nil != div; div = div.NextSibling {
div.DataAtom = atom.Code
div.Data = "code"
}
}
}
}
for _, unlink := range unlinks {
unlink.Unlink()
}
}
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.adjustTableCode(c)
}
}
func (lute *Lute) mergeSameStrong(n *html.Node) {
for c := n.FirstChild; nil != c; {
next := c.NextSibling
if nil != next && atom.Strong == c.DataAtom && atom.Strong == next.DataAtom {
for cc := next.FirstChild; nil != cc; {
nextChild := cc.NextSibling
cc.Unlink()
c.AppendChild(cc)
cc = nextChild
}
next.Unlink()
next = c.NextSibling
}
c = next
}
for c := n.FirstChild; nil != c; c = c.NextSibling {
lute.mergeSameStrong(c)
}
}
// adjustVditorDOMListList 用于将 ul.ul 调整为 ul.li.ul。
func (lute *Lute) adjustVditorDOMListList(n *html.Node) {
if atom.Ul != n.DataAtom && atom.Ol != n.DataAtom && atom.Li != n.DataAtom {
return
}
if atom.Li == n.DataAtom {
if nil != n.FirstChild && atom.Br == n.FirstChild.DataAtom {
// 规范化换行时 li 的结构,对调 ZWSP 和 <br> 的位置
n.FirstChild.DataAtom = 0
n.FirstChild.Data = editor.Zwsp
if nextLi := n.NextSibling; nil != n.NextSibling && atom.Li == n.NextSibling.DataAtom {
if caret := nextLi.FirstChild; nil != caret && editor.Caret+editor.Zwsp == caret.Data {
caret.Data = editor.Caret + "\n"
}
}
}
} else {
if nil != n.Parent && (atom.Ul == n.Parent.DataAtom || atom.Ol == n.Parent.DataAtom) {
if prevLi := n.PrevSibling; nil != prevLi {
n.Unlink()
prevLi.AppendChild(n)
}
}
}
for c := n.FirstChild; c != nil; {
next := c.NextSibling
lute.adjustVditorDOMListList(c)
c = next
}
}
func (lute *Lute) removeHighlightJSSpans(node *html.Node) {
var spans []*html.Node
for c := node; nil != c; c = c.NextSibling {
lute.hljsSpans(c, &spans)
}
for _, span := range spans {
span.Unlink()
}
}
func (lute *Lute) hljsSpans(n *html.Node, spans *[]*html.Node) {
if atom.Span == n.DataAtom && strings.HasPrefix(util.DomAttrValue(n, "class"), "hljs-") {
*spans = append(*spans, n)
text := util.DomText(n)
n.InsertBefore(&html.Node{Type: html.TextNode, Data: text})
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.hljsSpans(c, spans)
}
}
func (lute *Lute) removeEmptyNodes(node *html.Node) {
var emptyNodes []*html.Node
for c := node; nil != c; c = c.NextSibling {
lute.searchEmptyNodes(c, &emptyNodes)
}
for _, emptyNode := range emptyNodes {
emptyNode.Unlink()
}
}
func (lute *Lute) searchEmptyNodes(n *html.Node, emptyNodes *[]*html.Node) {
switch n.DataAtom {
case 0:
if lute.isInline(n.PrevSibling) || lute.isInline(n.NextSibling) || lute.isInline(n.Parent) {
// 前节点或者后节点是行级节点的话保留该空白
break
}
if html.TextNode == n.Type {
data := strings.TrimLeft(n.Data, " ")
data = strings.TrimRight(data, " ")
for strings.Contains(data, "\n\n") {
// 浏览器剪藏扩展列表下方段落缩进成为子块 https://github.com/siyuan-note/siyuan/issues/6289
data = strings.ReplaceAll(data, "\n\n", "")
}
if "" == data {
*emptyNodes = append(*emptyNodes, n)
return
}
}
parent := n.Parent
if nil != parent && (atom.Ol == parent.DataAtom || atom.Ul == parent.DataAtom || atom.Li == parent.DataAtom) {
if nil == n.NextSibling || (html.TextNode == n.NextSibling.Type || atom.Ul == n.NextSibling.DataAtom) || "" == strings.TrimSpace(n.Data) {
n.Data = strings.TrimRight(n.Data, "\n\t ")
}
}
if nil != parent && (atom.Table == parent.DataAtom || atom.Thead == parent.DataAtom || atom.Tbody == parent.DataAtom || atom.Tr == parent.DataAtom) {
n.Data = strings.TrimSpace(n.Data)
}
if "" == n.Data {
*emptyNodes = append(*emptyNodes, n)
}
if html.CommentNode == n.Type {
*emptyNodes = append(*emptyNodes, n)
}
case atom.Span:
if lc := n.LastChild; nil != lc && atom.Br == lc.DataAtom {
// 如果行级标记节点最后一个子节点是 <br>,则将该 <br> 移动到该行级标记节点的后面
// 表格内多个连续的超链接无法换行显示 https://github.com/siyuan-note/siyuan/issues/5966
n.InsertAfter(lc)
}
if util.IsTempMarkSpan(n) {
// 将嵌套在临时标记中的节点提升到临时标记节点之前
*emptyNodes = append(*emptyNodes, n)
var children []*html.Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
children = append(children, c)
}
for _, c := range children {
n.InsertBefore(c)
}
return
}
case atom.Strong, atom.B, atom.Em, atom.I, atom.Del, atom.S, atom.Strike, atom.Mark:
if nil != n.FirstChild {
if atom.Br == n.FirstChild.DataAtom {
*emptyNodes = append(*emptyNodes, n.FirstChild)
n.InsertBefore(&html.Node{Type: html.ElementNode, DataAtom: atom.Br, Data: "br"})
}
if html.TextNode == n.FirstChild.Type {
text := n.FirstChild.Data
spaces := lute.prefixSpaces(text)
if "" != spaces {
n.FirstChild.Data = editor.Zwsp + n.FirstChild.Data
}
}
}
if nil != n.LastChild {
if atom.Br == n.LastChild.DataAtom {
*emptyNodes = append(*emptyNodes, n.LastChild)
n.InsertAfter(&html.Node{Type: html.ElementNode, DataAtom: atom.Br, Data: "br"})
}
if html.TextNode == n.LastChild.Type {
text := n.LastChild.Data
spaces := lute.suffixSpaces(text)
if "" != spaces {
n.FirstChild.Data = n.FirstChild.Data + editor.Zwsp
}
}
}
default:
if "katex" == util.DomAttrValue(n, "class") {
*emptyNodes = append(*emptyNodes, n)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.searchEmptyNodes(c, emptyNodes)
}
switch n.DataAtom {
case atom.Ol, atom.Ul:
if dataType := util.DomAttrValue(n, "data-type"); "footnotes-defs-ol" == dataType {
return
}
if nil != n.FirstChild && nil != n.FirstChild.FirstChild && atom.Input != n.FirstChild.FirstChild.DataAtom {
return
}
text := util.DomText(n)
if "" == text {
*emptyNodes = append(*emptyNodes, n)
}
}
}
func (lute *Lute) mergeVditorDOMList0(n *html.Node) {
switch n.DataAtom {
case atom.Ul, atom.Ol:
if nil != n.NextSibling && n.DataAtom == n.NextSibling.DataAtom && 1 == len(n.NextSibling.Attr) {
for c := n.NextSibling.FirstChild; nil != c; {
next := c.NextSibling
c.Unlink()
n.AppendChild(c)
c = next
}
n.NextSibling.Unlink()
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.mergeVditorDOMList0(c)
}
}
func (lute *Lute) adjustVditorDOMListTight0(n *html.Node) {
switch n.DataAtom {
case atom.Ul:
if !lute.parentIs(n, atom.Pre) {
lute.setDOMAttrValue(n, "data-tight", lute.isTightList(n))
}
case atom.Ol:
if !lute.parentIs(n, atom.Pre) {
lute.setDOMAttrValue(n, "data-tight", lute.isTightList(n))
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.adjustVditorDOMListTight0(c)
}
}
func (lute *Lute) adjustVditorDOMListItemInP(n *html.Node) {
switch n.DataAtom {
case atom.Li:
// li 换行时 id 重复需要重新生成
if nil != n.PrevSibling && util.DomAttrValue(n.PrevSibling, "data-node-id") == util.DomAttrValue(n, "data-node-id") {
lute.setDOMAttrValue(n, "data-node-id", ast.NewNodeID())
}
// 松散 li 换行时和上一个 li.last id 重复
if nil != n.PrevSibling && nil != n.FirstChild {
id := util.DomAttrValue(n.FirstChild, "data-node-id") // id 为空的话是行级节点,列表项行级排版自动换行问题 https://github.com/siyuan-note/siyuan/issues/379
if "" != id && nil != n.PrevSibling.LastChild && util.DomAttrValue(n.PrevSibling.LastChild, "data-node-id") == id {
lute.setDOMAttrValue(n.FirstChild, "data-node-id", ast.NewNodeID())
}
}
// 在 li 下的每个非容器块节点用 p 包裹
for c := n.FirstChild; nil != c; c = c.NextSibling {
if lute.listItemEnter(n) {
p := &html.Node{Type: html.ElementNode, Data: "p", DataAtom: atom.P}
p.AppendChild(&html.Node{Type: html.TextNode, Data: editor.Caret})
p.AppendChild(&html.Node{Type: html.ElementNode, Data: "br", DataAtom: atom.Br})
n.FirstChild.Unlink()
n.FirstChild.Unlink()
n.AppendChild(p)
c = p
continue
}
if atom.P != c.DataAtom && atom.Blockquote != c.DataAtom && atom.Ul != c.DataAtom && atom.Ol != c.DataAtom && atom.Div != c.DataAtom {
spans, nextBlock := lute.forwardNextBlock(c)
p := &html.Node{Type: html.ElementNode, Data: "p", DataAtom: atom.P}
c.InsertBefore(p)
for _, span := range spans {
span.Unlink()
p.AppendChild(span)
}
if c = nextBlock; nil == c {
break
}
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.adjustVditorDOMListItemInP(c)
}
}
func (lute *Lute) removeCodeCode(n *html.Node) {
if atom.Code == n.DataAtom && nil != n.FirstChild && atom.Code == n.FirstChild.DataAtom {
// code.code 重复嵌套,则不处理外层 code
for c := n.FirstChild; nil != c; {
next := c.NextSibling
c.Unlink()
n.InsertBefore(c)
c = next
}
n.Unlink()
return
}
for c := n.FirstChild; c != nil; {
next := c.NextSibling
lute.removeCodeCode(c)
c = next
}
}
func (lute *Lute) adjustVditorDOMCodeA(n *html.Node) {
// https://github.com/siyuan-note/siyuan/issues/11370
if atom.Code == n.DataAtom && nil != n.FirstChild && atom.A == n.FirstChild.DataAtom && n.FirstChild == n.LastChild {
// code.a 的情况将 a 移到 code 外层,即 a.code
prev := n.PrevSibling
next := n.NextSibling
parent := n.Parent
a := n.FirstChild
a.Unlink()
n.Unlink()
var anchorTexts []*html.Node
for c := a.FirstChild; nil != c; c = c.NextSibling {
anchorTexts = append(anchorTexts, c)
c.Unlink()
}
for _, anchorText := range anchorTexts {
n.AppendChild(anchorText)
}
a.AppendChild(n)
if nil != prev {
prev.InsertAfter(a)
} else if nil != next {
next.InsertBefore(a)
} else if nil != parent {
parent.AppendChild(a)
}
return
}
for c := n.FirstChild; c != nil; {
next := c.NextSibling
lute.adjustVditorDOMCodeA(c)
c = next
}
}
// forwardNextBlock 向前移动至下一个块级节点,即跳过行级节点。
func (lute *Lute) forwardNextBlock(spanNode *html.Node) (spans []*html.Node, nextBlock *html.Node) {
for next := spanNode; nil != next; next = next.NextSibling {
switch next.DataAtom {
case atom.Ol, atom.Ul, atom.Div, atom.Blockquote:
return
}
spans = append(spans, next)
}
return
}
func (lute *Lute) listItemEnter(li *html.Node) bool {
if nil == li.FirstChild {
return false
}
if editor.Caret == li.FirstChild.Data && "br" == li.LastChild.Data {
return true
}
return false
}
func (lute *Lute) isTightList(list *html.Node) string {
for li := list.FirstChild; nil != li; li = li.NextSibling {
var subLists, subDivs, subBlockquotes, subParagraphs int
for c := li.FirstChild; nil != c; c = c.NextSibling {
switch c.DataAtom {
case atom.Ul, atom.Ol:
subLists++
case atom.Div:
subDivs++
case atom.Blockquote:
subBlockquotes++
case atom.P:
subParagraphs++
}
}
if 1 < subParagraphs || 1 < subBlockquotes || 1 < subDivs || 1 < subLists {
return "false"
}
if 1 < subParagraphs+subDivs || 1 < subParagraphs+subBlockquotes || 1 < subParagraphs+subLists {
return "false"
}
}
return "true"
}
// genASTByVditorDOM 根据指定的 Vditor DOM 节点 n 进行深度优先遍历并逐步生成 Markdown 语法树 tree。
func (lute *Lute) genASTByVditorDOM(n *html.Node, tree *parse.Tree) {
dataRender := util.DomAttrValue(n, "data-render")
if "1" == dataRender || "2" == dataRender { // 1:浮动工具栏,2:preview 代码块、数学公式块
return
}
dataType := util.DomAttrValue(n, "data-type")
if atom.Div == n.DataAtom {
if "code-block" == dataType || "html-block" == dataType || "math-block" == dataType || "yaml-front-matter" == dataType {
for c := n.FirstChild; c != nil; c = c.NextSibling {
lute.genASTByVditorDOM(c, tree)
}
} else if "link-ref-defs-block" == dataType {
text := util.DomText(n)
node := &ast.Node{Type: ast.NodeText, Tokens: []byte(text)}
tree.Context.Tip.AppendChild(node)
} else if "footnotes-block" == dataType {
ol := n.FirstChild
if atom.Ol != ol.DataAtom {
return
}
for li := ol.FirstChild; nil != li; li = li.NextSibling {
if "\n" == li.Data {
continue
}
originalHTML := &bytes.Buffer{}
if err := html.Render(originalHTML, li); nil == err {
md := lute.vditorDOM2Md("<ol data-type=\"footnotes-defs-ol\">" + originalHTML.String() + "</ol>")
label := util.DomAttrValue(li, "data-marker")
md = md[3:] // 去掉列表项标记符 1.
lines := strings.Split(md, "\n")
md = ""
for i, line := range lines {
if 0 < i {
md += " " + line
} else {
md = line
}
md += "\n"
}
md = "[" + label + "]: " + md
node := &ast.Node{Type: ast.NodeText, Tokens: []byte(md)}
tree.Context.Tip.AppendChild(node)
} else {
panic(err)
}
}
} else if "toc-block" == dataType {
node := &ast.Node{Type: ast.NodeToC}
tree.Context.Tip.AppendChild(node)
}
return
}
class := util.DomAttrValue(n, "class")
content := strings.ReplaceAll(n.Data, editor.Zwsp, "")
node := &ast.Node{Type: ast.NodeText, Tokens: []byte(content)}
switch n.DataAtom {
case 0:
if "" == content {
return
}
checkIndentCodeBlock := strings.ReplaceAll(content, editor.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, editor.Caret)
if startCaret {
content = strings.ReplaceAll(content, editor.Caret, "")
}
content = strings.TrimSpace(content)
if startCaret {
content = editor.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
}
tree.Context.Tip.AppendChild(node)
case atom.P, atom.Div:
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 "" == strings.TrimSpace(util.DomText(n)) {
return
}
node.Type = ast.NodeHeading
node.HeadingLevel = int(node.Tokens[1] - byte('0'))
marker := util.DomAttrValue(n, "data-marker")
if id := util.DomAttrValue(n, "data-id"); "" != id {
n.LastChild.InsertAfter(&html.Node{Type: html.TextNode, Data: " {" + id + "}"})
}
node.HeadingSetext = "=" == marker || "-" == marker
if !node.HeadingSetext {
headingC8hMarker := &ast.Node{Type: ast.NodeHeadingC8hMarker}
headingC8hMarker.Tokens = []byte(strings.Repeat("#", node.HeadingLevel))
node.AppendChild(headingC8hMarker)
}
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(util.DomText(n))
if "" == content || ">" == content || editor.Caret == content {
return
}
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{}
if atom.Ol == n.DataAtom {
node.ListData.Typ = 1
}
tight := util.DomAttrValue(n, "data-tight")
if "true" == tight || "" == tight {
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 {
firstLiMarker := util.DomAttrValue(n.Parent.FirstChild, "data-marker")
if startAttr := util.DomAttrValue(n.Parent, "start"); "" == startAttr {
marker = "1"
} else {
marker = startAttr
}
if "" != firstLiMarker {
marker += firstLiMarker[len(firstLiMarker)-1:]
} else {
marker += "."
}
} else {
marker = util.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 && "" == util.DomAttrValue(n.Parent, "start") {
marker = "1."
}
} else {
if "*" != marker && "-" != marker && "+" != marker {
marker = "*"
}
bullet = marker[0]
}
} else {
marker = util.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(string(marker[0]))
node.ListData.Delimiter = marker[len(marker)-1]
}
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case atom.Pre:
if atom.Code == n.FirstChild.DataAtom {
marker := util.DomAttrValue(n.Parent, "data-marker")
if "" == marker {
marker = "```"
}
var codeTokens []byte
if nil != n.FirstChild.FirstChild {
codeTokens = []byte(n.FirstChild.FirstChild.Data)
}
divDataType := util.DomAttrValue(n.Parent, "data-type")
switch divDataType {
case "math-block":
node.Type = ast.NodeMathBlock
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockOpenMarker})
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockContent, Tokens: codeTokens})
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockCloseMarker})
tree.Context.Tip.AppendChild(node)
case "yaml-front-matter":