format.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "github.com/88250/lute/ast"
  19. "github.com/88250/lute/render"
  20. "github.com/siyuan-note/logging"
  21. "github.com/siyuan-note/siyuan/kernel/util"
  22. )
  23. func AutoSpace(rootID string) (err error) {
  24. tree, err := LoadTreeByBlockID(rootID)
  25. if nil != err {
  26. return
  27. }
  28. logging.LogInfof("formatting tree [%s]...", rootID)
  29. util.PushProtyleLoading(rootID, Conf.Language(116))
  30. defer util.PushProtyleReload(rootID)
  31. WaitForWritingFiles()
  32. generateOpTypeHistory(tree, HistoryOpFormat)
  33. luteEngine := NewLute()
  34. // 合并相邻的同类行级节点
  35. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  36. if entering {
  37. switch n.Type {
  38. case ast.NodeTextMark:
  39. luteEngine.MergeSameTextMark(n)
  40. }
  41. }
  42. return ast.WalkContinue
  43. })
  44. rootIAL := tree.Root.KramdownIAL
  45. addBlockIALNodes(tree, false)
  46. // 第一次格式化为了合并相邻的文本节点
  47. formatRenderer := render.NewFormatRenderer(tree, luteEngine.RenderOptions)
  48. md := formatRenderer.Render()
  49. newTree := parseKTree(md)
  50. newTree.Root.Spec = "1"
  51. // 第二次格式化启用自动空格
  52. luteEngine.SetAutoSpace(true)
  53. formatRenderer = render.NewFormatRenderer(newTree, luteEngine.RenderOptions)
  54. md = formatRenderer.Render()
  55. newTree = parseKTree(md)
  56. newTree.Root.Spec = "1"
  57. newTree.Root.ID = tree.ID
  58. newTree.Root.KramdownIAL = rootIAL
  59. newTree.ID = tree.ID
  60. newTree.Path = tree.Path
  61. newTree.HPath = tree.HPath
  62. newTree.Box = tree.Box
  63. err = writeTreeUpsertQueue(newTree)
  64. if nil != err {
  65. return
  66. }
  67. logging.LogInfof("formatted tree [%s]", rootID)
  68. util.RandomSleep(500, 700)
  69. return
  70. }