-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
protyle.go
2086 lines (1890 loc) · 65.1 KB
/
protyle.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"
"fmt"
"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/lex"
"github.com/88250/lute/parse"
"github.com/88250/lute/render"
"github.com/88250/lute/util"
)
func (lute *Lute) SpinBlockDOM(ivHTML string) (ovHTML string) {
//fmt.Println(ivHTML)
markdown := lute.blockDOM2Md(ivHTML)
markdown = strings.ReplaceAll(markdown, editor.Zwsp, "")
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
firstChild := tree.Root.FirstChild
lastChildMaybeIAL := tree.Root.LastChild.Previous
if ast.NodeParagraph == firstChild.Type && "" == firstChild.ID && nil != lastChildMaybeIAL && firstChild != lastChildMaybeIAL.Previous &&
ast.NodeKramdownBlockIAL == lastChildMaybeIAL.Type {
// 软换行后生成多个块,需要把老 ID 调整到第一个块上
firstChild.ID, lastChildMaybeIAL.Previous.ID = lastChildMaybeIAL.Previous.ID, ""
firstChild.KramdownIAL, lastChildMaybeIAL.Previous.KramdownIAL = lastChildMaybeIAL.Previous.KramdownIAL, nil
firstChild.InsertAfter(lastChildMaybeIAL)
}
if ast.NodeKramdownBlockIAL == firstChild.Type && nil != firstChild.Next && ast.NodeKramdownBlockIAL == firstChild.Next.Type && util.IsDocIAL(firstChild.Next.Tokens) {
// 空段落块还原
ialArray := parse.Tokens2IAL(firstChild.Tokens)
ial := parse.IAL2Map(ialArray)
p := &ast.Node{Type: ast.NodeParagraph, ID: ial["id"], KramdownIAL: ialArray}
firstChild.InsertBefore(p)
}
// 使用 Markdown 标记符嵌套行级元素后被还原为纯文本 https://github.com/siyuan-note/siyuan/issues/7637
// 这里需要将混合嵌套(比如 <strong><span a></span></strong>)的行级元素拆分为多个平铺的行级元素(<span strong> 和 <span strong a>)
parse.NestedInlines2FlattedSpansHybrid(tree, false)
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) HTML2BlockDOM(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.NewProtyleRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.HTML2BlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = util.BytesToStr(output)
return
}
func (lute *Lute) BlockDOM2HTML(vHTML string) (sHTML string) {
markdown := lute.blockDOM2Md(vHTML)
sHTML = lute.Md2HTML(markdown)
return
}
func (lute *Lute) BlockDOM2InlineBlockDOM(vHTML string) (vIHTML string) {
markdown := lute.blockDOM2Md(vHTML)
tree := parse.Parse("", []byte(markdown), lute.ParseOptions)
var inlines []*ast.Node
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if ast.NodeTableCell == n.Type {
n.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
return ast.WalkContinue
}
if !n.IsBlock() && ast.NodeCodeBlockCode != n.Type && ast.NodeMathBlockContent != n.Type && ast.NodeTaskListItemMarker != n.Type &&
ast.NodeTableHead != n.Type && ast.NodeTableRow != n.Type && ast.NodeTableCell != n.Type {
inlines = append(inlines, n)
return ast.WalkSkipChildren
} else if ast.NodeHTMLBlock == n.Type {
inlines = append(inlines, &ast.Node{Type: ast.NodeText, Tokens: n.Tokens})
return ast.WalkSkipChildren
}
return ast.WalkContinue
})
var unlinks []*ast.Node
for n := tree.Root.FirstChild; nil != n; n = n.Next {
unlinks = append(unlinks, n)
}
for _, n := range unlinks {
n.Unlink()
}
for _, n := range inlines {
tree.Root.AppendChild(n)
}
renderer := render.NewProtyleRenderer(tree, lute.RenderOptions)
output := renderer.Render()
vIHTML = util.BytesToStr(output)
vIHTML = strings.TrimSpace(vIHTML)
return
}
func (lute *Lute) Md2BlockDOM(markdown string, reserveEmptyParagraph bool) (vHTML string) {
vHTML, _ = lute.Md2BlockDOMTree(markdown, reserveEmptyParagraph)
return
}
func (lute *Lute) Md2BlockDOMTree(markdown string, reserveEmptyParagraph bool) (vHTML string, tree *parse.Tree) {
tree = parse.Parse("", []byte(markdown), lute.ParseOptions)
parse.NestedInlines2FlattedSpansHybrid(tree, false)
if reserveEmptyParagraph {
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if !entering {
return ast.WalkContinue
}
if n.IsEmptyBlockIAL() {
p := &ast.Node{Type: ast.NodeParagraph}
p.KramdownIAL = parse.Tokens2IAL(n.Tokens)
p.ID = p.IALAttr("id")
n.InsertBefore(p)
return ast.WalkContinue
}
return ast.WalkContinue
})
}
renderer := render.NewProtyleRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.Md2BlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = util.BytesToStr(output)
return
}
func (lute *Lute) InlineMd2BlockDOM(markdown string) (vHTML string) {
tree := parse.Inline("", []byte(markdown), lute.ParseOptions)
parse.NestedInlines2FlattedSpansHybrid(tree, false)
renderer := render.NewProtyleRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.Md2BlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = util.BytesToStr(output)
return
}
func (lute *Lute) BlockDOM2Md(htmlStr string) (kramdown string) {
kramdown = lute.blockDOM2Md(htmlStr)
kramdown = strings.ReplaceAll(kramdown, editor.Zwsp, "")
return
}
func (lute *Lute) BlockDOM2StdMd(htmlStr string) (markdown string) {
htmlStr = strings.ReplaceAll(htmlStr, editor.Zwsp, "")
// DOM 转 AST
tree := lute.BlockDOM2Tree(htmlStr)
// 将 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
})
options := render.NewOptions()
options.AutoSpace = false
options.FixTermTypo = false
options.KramdownBlockIAL = true
options.KramdownSpanIAL = true
options.KeepParagraphBeginningSpace = true
renderer := render.NewProtyleExportMdRenderer(tree, options)
formatted := renderer.Render()
markdown = util.BytesToStr(formatted)
return
}
func (lute *Lute) BlockDOM2Text(htmlStr string) (text string) {
tree := lute.BlockDOM2Tree(htmlStr)
return tree.Root.Text()
}
func (lute *Lute) BlockDOM2TextLen(htmlStr string) int {
tree := lute.BlockDOM2Tree(htmlStr)
return tree.Root.TextLen()
}
func (lute *Lute) BlockDOM2Content(htmlStr string) (text string) {
tree := lute.BlockDOM2Tree(htmlStr)
return tree.Root.Content()
}
func (lute *Lute) BlockDOM2EscapeMarkerContent(htmlStr string) (text string) {
tree := lute.BlockDOM2Tree(htmlStr)
return tree.Root.EscapeMarkerContent()
}
func (lute *Lute) Tree2BlockDOM(tree *parse.Tree, options *render.Options) (vHTML string) {
renderer := render.NewProtyleRenderer(tree, options)
for nodeType, rendererFunc := range lute.Md2BlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
output := renderer.Render()
vHTML = util.BytesToStr(output)
vHTML = strings.ReplaceAll(vHTML, editor.Caret, "<wbr>")
return
}
func (lute *Lute) RenderNodeBlockDOM(node *ast.Node) string {
root := &ast.Node{Type: ast.NodeDocument}
tree := &parse.Tree{Root: root, Context: &parse.Context{ParseOption: lute.ParseOptions}}
renderer := render.NewProtyleRenderer(tree, lute.RenderOptions)
for nodeType, rendererFunc := range lute.Md2BlockDOMRendererFuncs {
renderer.ExtRendererFuncs[nodeType] = rendererFunc
}
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) BlockDOM2Tree(htmlStr string) (ret *parse.Tree) {
htmlStr = strings.ReplaceAll(htmlStr, "\n<wbr>\n</strong>", "</strong>\n<wbr>\n")
htmlStr = strings.ReplaceAll(htmlStr, "\n<wbr>\n</em>", "</em>\n<wbr>\n")
htmlStr = strings.ReplaceAll(htmlStr, "\n<wbr>\n</s>", "</s>\n<wbr>\n")
htmlStr = strings.ReplaceAll(htmlStr, "\n<wbr>\n</u>", "</u>\n<wbr>\n")
htmlStr = strings.ReplaceAll(htmlStr, "\n<wbr>\n</span>", "</span>\n<wbr>\n")
// Improve `inline code` markdown editing https://github.com/siyuan-note/siyuan/issues/9978
// spinBlockDOMTests #212
htmlStr = strings.ReplaceAll(htmlStr, "`<wbr></span>", "</span>`<wbr>")
htmlStr = strings.ReplaceAll(htmlStr, "<wbr>", editor.Caret)
var startSpaces, endSpaces int
for _, c := range htmlStr {
if ' ' == c {
startSpaces++
} else {
break
}
}
for i := len(htmlStr) - 1; i >= 0; i-- {
if ' ' == htmlStr[i] {
endSpaces++
} else {
break
}
}
htmlStr = strings.TrimSpace(htmlStr)
htmlStr = strings.Repeat(" ", startSpaces) + htmlStr + strings.Repeat(" ", endSpaces)
// 替换结尾空白,否则 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.genASTByBlockDOM(c, ret)
}
// 调整树结构
ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
if entering {
switch n.Type {
case ast.NodeInlineHTML, ast.NodeHTMLBlock, ast.NodeCodeSpanContent, ast.NodeCodeBlockCode, ast.NodeInlineMathContent, ast.NodeMathBlockContent,
ast.NodeCodeSpan, ast.NodeInlineMath:
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()
}
case ast.NodeStrong, ast.NodeEmphasis, ast.NodeStrikethrough, ast.NodeUnderline:
lute.MergeSameSpan(n)
case ast.NodeTextMark:
lute.MergeSameTextMark(n)
case ast.NodeText:
n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("\u00a0"), []byte(" "))
}
}
return ast.WalkContinue
})
return
}
func (lute *Lute) MergeSameTextMark(n *ast.Node) {
if nil == n.Previous {
return
}
mergeWithIAL := false
mergeWithZwsp := false
if ast.NodeKramdownSpanIAL == n.Previous.Type {
if nil == n.Next || ast.NodeKramdownSpanIAL != n.Next.Type || nil == n.Previous.Previous {
return
}
if !bytes.Equal(n.Previous.Tokens, n.Next.Tokens) {
return
}
if !n.IsSameTextMarkType(n.Previous.Previous) {
return
}
mergeWithIAL = true
} else {
if ast.NodeText == n.Previous.Type &&
!strings.Contains(n.Previous.TokensStr(), " ") && !strings.Contains(n.Previous.TokensStr(), "\n") &&
"" == strings.TrimSpace(strings.ReplaceAll(n.Previous.TokensStr(), editor.Zwsp, "")) &&
nil != n.Previous.Previous && n.IsSameTextMarkType(n.Previous.Previous) {
mergeWithZwsp = true
} else {
if n.Type != n.Previous.Type || !n.IsSameTextMarkType(n.Previous) {
return
}
}
}
types := strings.Split(n.TextMarkType, " ")
m := map[string]bool{}
for _, t := range types {
m[t] = true
}
var allowMerge []string
for k, _ := range m {
switch k {
case "code", "em", "strong", "s", "mark", "u", "sub", "sup", "kbd", "text", "tag", "block-ref", "a":
allowMerge = append(allowMerge, k)
}
}
for _, k := range allowMerge {
delete(m, k)
}
if 0 < len(m) {
return
}
if mergeWithIAL || mergeWithZwsp {
n.TextMarkTextContent = n.Previous.Previous.TextMarkTextContent + n.TextMarkTextContent
n.Previous.Previous.Unlink()
} else {
n.TextMarkTextContent = n.Previous.TextMarkTextContent + n.TextMarkTextContent
}
n.Previous.Unlink()
n.SortTextMarkDataTypes()
}
func (lute *Lute) MergeSameSpan(n *ast.Node) {
if nil == n.Next || n.Type != n.Next.Type {
return
}
if nil != n.Next.Next && ast.NodeKramdownSpanIAL == n.Next.Next.Type {
return
}
var spanChildren []*ast.Node
n.Next.FirstChild.Unlink() // open marker
n.Next.LastChild.Unlink() // close marker
for c := n.Next.FirstChild; nil != c; c = c.Next {
spanChildren = append(spanChildren, c)
}
for _, c := range spanChildren {
n.LastChild.InsertBefore(c)
}
n.Next.Unlink()
}
func (lute *Lute) CancelSuperBlock(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
if ast.NodeSuperBlock != tree.Root.FirstChild.Type {
return ivHTML
}
sb := tree.Root.FirstChild
var blocks []*ast.Node
for b := sb.FirstChild; nil != b; b = b.Next {
blocks = append(blocks, b)
}
for _, b := range blocks {
tree.Root.AppendChild(b)
}
sb.Unlink()
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) CancelList(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
if ast.NodeList != tree.Root.FirstChild.Type {
return ivHTML
}
list := tree.Root.FirstChild
var appends, unlinks []*ast.Node
for li := list.FirstChild; nil != li; li = li.Next {
for c := li.FirstChild; nil != c; c = c.Next {
if ast.NodeTaskListItemMarker != c.Type {
appends = append(appends, c)
}
}
unlinks = append(unlinks, li)
}
for _, c := range appends {
tree.Root.AppendChild(c)
}
for _, n := range unlinks {
n.Unlink()
}
list.Unlink()
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) CancelBlockquote(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
if ast.NodeBlockquote != tree.Root.FirstChild.Type {
return ivHTML
}
bq := tree.Root.FirstChild
var appends, unlinks []*ast.Node
for sub := bq.FirstChild; nil != sub; sub = sub.Next {
if ast.NodeBlockquoteMarker != sub.Type {
appends = append(appends, sub)
}
unlinks = append(unlinks, sub)
}
for _, c := range appends {
tree.Root.AppendChild(c)
}
bq.Unlink()
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) Blocks2Ps(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
node := tree.Root.FirstChild
var appends, unlinks []*ast.Node
for n := node; nil != n; n = n.Next {
switch n.Type {
case ast.NodeHeading:
n.Type = ast.NodeParagraph
case ast.NodeBlockquote:
for c := n.FirstChild; nil != c; c = c.Next {
if ast.NodeBlockquoteMarker == c.Type {
unlinks = append(unlinks, c)
continue
}
appends = append(appends, c)
}
unlinks = append(unlinks, n)
case ast.NodeList:
for li := n.FirstChild; nil != li; li = li.Next {
for c := li.FirstChild; nil != c; c = c.Next {
if ast.NodeTaskListItemMarker != c.Type {
appends = append(appends, c)
}
}
unlinks = append(unlinks, li)
}
unlinks = append(unlinks, n)
}
}
for _, n := range unlinks {
n.Unlink()
}
for _, c := range appends {
tree.Root.AppendChild(c)
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) Blocks2Hs(ivHTML, level string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
node := tree.Root.FirstChild
for p := node; nil != p; p = p.Next {
if ast.NodeParagraph == p.Type || ast.NodeHeading == p.Type {
p.Type = ast.NodeHeading
p.HeadingLevel, _ = strconv.Atoi(level)
}
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) OL2TL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
tree.Root.FirstChild.ListData.Typ = 3
for li := tree.Root.FirstChild.FirstChild; nil != li; li = li.Next {
if ast.NodeListItem == li.Type {
li.ListData.Typ = 3
li.PrependChild(&ast.Node{Type: ast.NodeTaskListItemMarker})
}
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) UL2TL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
tree.Root.FirstChild.ListData.Typ = 3
for li := tree.Root.FirstChild.FirstChild; nil != li; li = li.Next {
if ast.NodeListItem == li.Type {
li.ListData.Typ = 3
li.PrependChild(&ast.Node{Type: ast.NodeTaskListItemMarker})
}
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) TL2OL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
list := tree.Root.FirstChild
if ast.NodeList != list.Type || 3 != list.ListData.Typ {
return ivHTML
}
num := 1
list.ListData.Typ = 1
var unlinks []*ast.Node
for li := list.FirstChild; nil != li; li = li.Next {
if ast.NodeKramdownBlockIAL == li.Type {
continue
}
unlinks = append(unlinks, li.FirstChild) // task marker
li.ListData.Typ = 1
li.ListData.Num = num
num++
}
for _, n := range unlinks {
n.Unlink()
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) TL2UL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
list := tree.Root.FirstChild
if ast.NodeList != list.Type || 3 != list.ListData.Typ {
return ivHTML
}
list.ListData.Typ = 0
var unlinks []*ast.Node
for li := list.FirstChild; nil != li; li = li.Next {
if ast.NodeKramdownBlockIAL == li.Type {
continue
}
unlinks = append(unlinks, li.FirstChild) // task marker
li.ListData.Typ = 0
}
for _, n := range unlinks {
n.Unlink()
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) OL2UL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
list := tree.Root.FirstChild
if ast.NodeList != list.Type {
return ivHTML
}
list.ListData.Typ = 0
for li := list.FirstChild; nil != li; li = li.Next {
if ast.NodeKramdownBlockIAL == li.Type {
continue
}
li.ListData.Typ = 0
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) UL2OL(ivHTML string) (ovHTML string) {
tree := lute.BlockDOM2Tree(ivHTML)
list := tree.Root.FirstChild
if ast.NodeList != list.Type {
return ivHTML
}
num := 1
list.ListData.Typ = 1
for li := list.FirstChild; nil != li; li = li.Next {
if ast.NodeKramdownBlockIAL == li.Type {
continue
}
li.ListData.Typ = 1
li.ListData.Num = num
num++
}
ovHTML = lute.Tree2BlockDOM(tree, lute.RenderOptions)
return
}
func (lute *Lute) blockDOM2Md(htmlStr string) (markdown string) {
tree := lute.BlockDOM2Tree(htmlStr)
// 将 AST 进行 Markdown 格式化渲染
options := render.NewOptions()
options.AutoSpace = false
options.FixTermTypo = false
options.KramdownBlockIAL = true
options.KramdownSpanIAL = true
options.KeepParagraphBeginningSpace = true
options.ProtyleWYSIWYG = true
options.SuperBlock = true
renderer := render.NewFormatRenderer(tree, options)
formatted := renderer.Render()
markdown = string(formatted)
return
}
func (lute *Lute) genASTByBlockDOM(n *html.Node, tree *parse.Tree) {
class := util.DomAttrValue(n, "class")
if "protyle-attr" == class ||
strings.Contains(class, "__copy") ||
strings.Contains(class, "protyle-linenumber__rows") {
return
}
if "1" == util.DomAttrValue(n, "spin") {
return
}
if strings.Contains(class, "protyle-action") {
if ast.NodeCodeBlock == tree.Context.Tip.Type {
languageNode := n.FirstChild
language := ""
if nil != languageNode.FirstChild {
language = languageNode.FirstChild.Data
}
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceInfoMarker, CodeBlockInfo: util.StrToBytes(language)})
code := util.DomText(n.NextSibling)
if strings.HasSuffix(code, "\n\n"+editor.Caret) {
code = strings.TrimSuffix(code, "\n\n"+editor.Caret)
code += "\n" + editor.Caret + "\n"
}
lines := strings.Split(code, "\n")
buf := bytes.Buffer{}
for i, line := range lines {
if strings.Contains(line, "```") {
line = strings.ReplaceAll(line, "```", editor.Zwj+"```")
} else {
line = strings.ReplaceAll(line, editor.Zwj, "")
}
buf.WriteString(line)
if i < len(lines)-1 {
buf.WriteByte('\n')
}
}
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeCodeBlockCode, Tokens: buf.Bytes()})
} else if ast.NodeListItem == tree.Context.Tip.Type {
if 3 == tree.Context.Tip.ListData.Typ { // 任务列表
tree.Context.Tip.AppendChild(&ast.Node{Type: ast.NodeTaskListItemMarker, TaskListItemChecked: strings.Contains(util.DomAttrValue(n.Parent, "class"), "protyle-task--done")})
}
}
return
}
if "true" == util.DomAttrValue(n, "contenteditable") {
lute.genASTContenteditable(n, tree)
return
}
dataType := ast.Str2NodeType(util.DomAttrValue(n, "data-type"))
nodeID := util.DomAttrValue(n, "data-node-id")
node := &ast.Node{ID: nodeID}
if "" != node.ID && !lute.parentIs(n, atom.Table) {
node.KramdownIAL = [][]string{{"id", node.ID}}
ialTokens := lute.setBlockIAL(n, node)
ial := &ast.Node{Type: ast.NodeKramdownBlockIAL, Tokens: ialTokens}
defer tree.Context.TipAppendChild(ial)
}
switch dataType {
case ast.NodeBlockQueryEmbed:
node.Type = ast.NodeBlockQueryEmbed
node.AppendChild(&ast.Node{Type: ast.NodeOpenBrace})
node.AppendChild(&ast.Node{Type: ast.NodeOpenBrace})
content := util.DomAttrValue(n, "data-content")
// 嵌入块中存在换行 SQL 语句时会被转换为段落文本 https://github.com/siyuan-note/siyuan/issues/5728
content = strings.ReplaceAll(content, "\n", editor.IALValEscNewLine)
node.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript, Tokens: util.StrToBytes(content)})
node.AppendChild(&ast.Node{Type: ast.NodeCloseBrace})
node.AppendChild(&ast.Node{Type: ast.NodeCloseBrace})
tree.Context.Tip.AppendChild(node)
return
case ast.NodeTable:
node.Type = ast.NodeTable
var tableAligns []int
if nil == n.FirstChild {
node.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
tree.Context.ParentTip()
return
}
if lute.parentIs(n, atom.Table) {
text := util.DomText(n)
node.Tokens = []byte(strings.TrimSpace(text))
tree.Context.Tip.AppendChild(node)
return
}
tableDiv := n.FirstChild
table := lute.domChild(tableDiv, atom.Table)
if nil == table {
node.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
tree.Context.ParentTip()
return
}
thead := lute.domChild(table, atom.Thead)
if nil == thead || nil == thead.FirstChild || nil == thead.FirstChild.FirstChild {
node.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
tree.Context.ParentTip()
return
}
for th := thead.FirstChild.FirstChild; nil != th; th = th.NextSibling {
align := util.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()
lute.genASTContenteditable(table, tree)
return
case ast.NodeParagraph:
node.Type = ast.NodeParagraph
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeHeading:
text := util.DomText(n)
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
}
level := util.DomAttrValue(n, "data-subtype")[1:]
tmp := strings.TrimPrefix(text, " ")
if strings.HasPrefix(tmp, "#") {
// Allow changing headings with `#` https://github.com/siyuan-note/siyuan/issues/7924
if idx := strings.Index(tmp, " "+editor.Caret); 0 < idx {
tmp = tmp[:idx]
if nil != n.FirstChild && nil != n.FirstChild.FirstChild {
headingContent := strings.TrimPrefix(strings.TrimPrefix(n.FirstChild.FirstChild.Data, tmp), " ")
n.FirstChild.FirstChild.Data = headingContent
}
level = fmt.Sprintf("%d", strings.Count(tmp, "#"))
}
}
node.Type = ast.NodeHeading
node.HeadingLevel, _ = strconv.Atoi(level)
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeBlockquote:
content := strings.TrimSpace(util.DomText(n))
if editor.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 ast.NodeList:
node.Type = ast.NodeList
marker := util.DomAttrValue(n, "data-marker")
node.ListData = &ast.ListData{}
subType := util.DomAttrValue(n, "data-subtype")
if "u" == subType {
node.ListData.Typ = 0
} else if "o" == subType {
node.ListData.Typ = 1
} else if "t" == subType {
node.ListData.Typ = 3
}
node.ListData.Marker = []byte(marker)
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeListItem:
marker := util.DomAttrValue(n, "data-marker")
if ast.NodeList != tree.Context.Tip.Type {
parent := &ast.Node{}
parent.Type = ast.NodeList
parent.ListData = &ast.ListData{}
subType := util.DomAttrValue(n, "data-subtype")
if "u" == subType {
parent.ListData.Typ = 0
parent.ListData.BulletChar = '*'
} else if "o" == subType {
parent.ListData.Typ = 1
parent.ListData.Num, _ = strconv.Atoi(marker[:len(marker)-1])
parent.ListData.Delimiter = '.'
} else if "t" == subType {
parent.ListData.Typ = 3
parent.ListData.BulletChar = '*'
}
tree.Context.Tip.AppendChild(parent)
tree.Context.Tip = parent
}
node.Type = ast.NodeListItem
node.ListData = &ast.ListData{}
subType := util.DomAttrValue(n, "data-subtype")
if "u" == subType {
node.ListData.Typ = 0
node.ListData.BulletChar = '*'
} else if "o" == subType {
node.ListData.Typ = 1
node.ListData.Num, _ = strconv.Atoi(marker[:len(marker)-1])
node.ListData.Delimiter = '.'
} else if "t" == subType {
node.ListData.Typ = 3
node.ListData.BulletChar = '*'
}
node.ListData.Marker = []byte(marker)
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeGitConflict:
node.Type = ast.NodeGitConflict
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeSuperBlock:
node.Type = ast.NodeSuperBlock
tree.Context.Tip.AppendChild(node)
node.AppendChild(&ast.Node{Type: ast.NodeSuperBlockOpenMarker})
layout := util.DomAttrValue(n, "data-sb-layout")
node.AppendChild(&ast.Node{Type: ast.NodeSuperBlockLayoutMarker, Tokens: []byte(layout)})
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeMathBlock:
node.Type = ast.NodeMathBlock
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockOpenMarker})
content := util.DomAttrValue(n, "data-content")
content = html.UnescapeHTMLStr(content)
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockContent, Tokens: util.StrToBytes(content)})
node.AppendChild(&ast.Node{Type: ast.NodeMathBlockCloseMarker})
tree.Context.Tip.AppendChild(node)
return
case ast.NodeCodeBlock:
node.Type = ast.NodeCodeBlock
node.IsFencedCodeBlock = true
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceOpenMarker, Tokens: util.StrToBytes("```")})
if language := util.DomAttrValue(n, "data-subtype"); "" != language {
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceInfoMarker, CodeBlockInfo: util.StrToBytes(language)})
content := util.DomAttrValue(n, "data-content")
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockCode, Tokens: util.StrToBytes(content)})
node.AppendChild(&ast.Node{Type: ast.NodeCodeBlockFenceCloseMarker, Tokens: util.StrToBytes("```")})
tree.Context.Tip.AppendChild(node)
return
}
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeHTMLBlock:
node.Type = ast.NodeHTMLBlock
content := util.DomAttrValue(n.FirstChild.NextSibling.FirstChild, "data-content")
content = html.UnescapeHTMLStr(content)
node.Tokens = util.StrToBytes(content)
tree.Context.Tip.AppendChild(node)
return
case ast.NodeYamlFrontMatter:
node.Type = ast.NodeYamlFrontMatter
tree.Context.Tip.AppendChild(node)
tree.Context.Tip = node
defer tree.Context.ParentTip()
case ast.NodeThematicBreak:
node.Type = ast.NodeThematicBreak
tree.Context.Tip.AppendChild(node)
return
case ast.NodeIFrame:
node.Type = ast.NodeIFrame
n = lute.domChild(n.FirstChild, atom.Iframe)
node.Tokens = util.DomHTML(n)
tree.Context.Tip.AppendChild(node)
return
case ast.NodeWidget:
node.Type = ast.NodeWidget
n = lute.domChild(n.FirstChild, atom.Iframe)
node.Tokens = util.DomHTML(n)
tree.Context.Tip.AppendChild(node)
return
case ast.NodeVideo:
node.Type = ast.NodeVideo
n = lute.domChild(n.FirstChild, atom.Video)
node.Tokens = util.DomHTML(n)
tree.Context.Tip.AppendChild(node)
return
case ast.NodeAudio:
node.Type = ast.NodeAudio
n = lute.domChild(n.FirstChild, atom.Audio)
node.Tokens = util.DomHTML(n)
tree.Context.Tip.AppendChild(node)
return
case ast.NodeAttributeView:
node.Type = ast.NodeAttributeView
node.AttributeViewID = util.DomAttrValue(n, "data-av-id")
if "" == node.AttributeViewID {
node.AttributeViewID = ast.NewNodeID()
}
node.AttributeViewType = util.DomAttrValue(n, "data-av-type")