export.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. // SiYuan - Build Your Eternal Digital Garden
  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. "bytes"
  19. "errors"
  20. "fmt"
  21. "net/url"
  22. "os"
  23. "os/exec"
  24. "path"
  25. "path/filepath"
  26. "sort"
  27. "strconv"
  28. "strings"
  29. "unicode/utf8"
  30. "github.com/88250/gulu"
  31. "github.com/88250/lute/ast"
  32. "github.com/88250/lute/editor"
  33. "github.com/88250/lute/html"
  34. "github.com/88250/lute/parse"
  35. "github.com/88250/lute/render"
  36. "github.com/88250/pdfcpu/pkg/api"
  37. "github.com/88250/pdfcpu/pkg/pdfcpu"
  38. "github.com/emirpasic/gods/sets/hashset"
  39. "github.com/emirpasic/gods/stacks/linkedliststack"
  40. "github.com/siyuan-note/filelock"
  41. "github.com/siyuan-note/logging"
  42. "github.com/siyuan-note/siyuan/kernel/sql"
  43. "github.com/siyuan-note/siyuan/kernel/treenode"
  44. "github.com/siyuan-note/siyuan/kernel/util"
  45. )
  46. func ExportSystemLog() (zipPath string) {
  47. exportFolder := filepath.Join(util.TempDir, "export", "system-log")
  48. os.RemoveAll(exportFolder)
  49. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  50. logging.LogErrorf("create export temp folder failed: %s", err)
  51. return
  52. }
  53. appLog := filepath.Join(util.HomeDir, ".config", "siyuan", "app.log")
  54. if gulu.File.IsExist(appLog) {
  55. to := filepath.Join(exportFolder, "app.log")
  56. if err := gulu.File.CopyFile(appLog, to); nil != err {
  57. logging.LogErrorf("copy app log from [%s] to [%s] failed: %s", err, appLog, to)
  58. }
  59. }
  60. kernelLog := filepath.Join(util.TempDir, "siyuan.log")
  61. if gulu.File.IsExist(kernelLog) {
  62. to := filepath.Join(exportFolder, "siyuan.log")
  63. if err := gulu.File.CopyFile(kernelLog, to); nil != err {
  64. logging.LogErrorf("copy kernel log from [%s] to [%s] failed: %s", err, kernelLog, to)
  65. }
  66. }
  67. zipPath = exportFolder + ".zip"
  68. zip, err := gulu.Zip.Create(zipPath)
  69. if nil != err {
  70. logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err)
  71. return ""
  72. }
  73. if err = zip.AddDirectory("log", exportFolder); nil != err {
  74. logging.LogErrorf("create export log zip [%s] failed: %s", exportFolder, err)
  75. return ""
  76. }
  77. if err = zip.Close(); nil != err {
  78. logging.LogErrorf("close export log zip failed: %s", err)
  79. }
  80. os.RemoveAll(exportFolder)
  81. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  82. return
  83. }
  84. func ExportNotebookSY(id string) (zipPath string) {
  85. zipPath = exportBoxSYZip(id)
  86. return
  87. }
  88. func ExportSY(id string) (name, zipPath string) {
  89. block := treenode.GetBlockTree(id)
  90. if nil == block {
  91. logging.LogErrorf("not found block [%s]", id)
  92. return
  93. }
  94. boxID := block.BoxID
  95. box := Conf.Box(boxID)
  96. baseFolderName := path.Base(block.HPath)
  97. if "." == baseFolderName {
  98. baseFolderName = path.Base(block.Path)
  99. }
  100. rootPath := block.Path
  101. docPaths := []string{rootPath}
  102. docFiles := box.ListFiles(strings.TrimSuffix(block.Path, ".sy"))
  103. for _, docFile := range docFiles {
  104. docPaths = append(docPaths, docFile.path)
  105. }
  106. zipPath = exportSYZip(boxID, path.Dir(rootPath), baseFolderName, docPaths)
  107. name = strings.TrimSuffix(filepath.Base(block.Path), ".sy")
  108. return
  109. }
  110. func ExportDataInFolder(exportFolder string) (err error) {
  111. util.PushEndlessProgress(Conf.Language(65))
  112. defer util.ClearPushProgress(100)
  113. WaitForWritingFiles()
  114. writingDataLock.Lock()
  115. defer writingDataLock.Unlock()
  116. exportFolder = filepath.Join(exportFolder, util.CurrentTimeSecondsStr())
  117. err = exportData(exportFolder)
  118. if nil != err {
  119. return
  120. }
  121. return
  122. }
  123. func ExportData() (zipPath string) {
  124. util.PushEndlessProgress(Conf.Language(65))
  125. defer util.ClearPushProgress(100)
  126. WaitForWritingFiles()
  127. writingDataLock.Lock()
  128. defer writingDataLock.Unlock()
  129. baseFolderName := "data-" + util.CurrentTimeSecondsStr()
  130. exportFolder := filepath.Join(util.TempDir, "export", baseFolderName)
  131. zipPath = exportFolder + ".zip"
  132. err := exportData(exportFolder)
  133. if nil != err {
  134. return
  135. }
  136. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  137. return
  138. }
  139. func exportData(exportFolder string) (err error) {
  140. baseFolderName := "data-" + util.CurrentTimeSecondsStr()
  141. if err = os.MkdirAll(exportFolder, 0755); nil != err {
  142. logging.LogErrorf("create export temp folder failed: %s", err)
  143. return
  144. }
  145. err = filelock.ReleaseAllFileLocks()
  146. if nil != err {
  147. return
  148. }
  149. data := filepath.Join(util.WorkspaceDir, "data")
  150. if err = stableCopy(data, exportFolder); nil != err {
  151. logging.LogErrorf("copy data dir from [%s] to [%s] failed: %s", data, baseFolderName, err)
  152. err = errors.New(fmt.Sprintf(Conf.Language(14), formatErrorMsg(err)))
  153. return
  154. }
  155. zipPath := exportFolder + ".zip"
  156. zip, err := gulu.Zip.Create(zipPath)
  157. if nil != err {
  158. logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err)
  159. return
  160. }
  161. if err = zip.AddDirectory(baseFolderName, exportFolder); nil != err {
  162. logging.LogErrorf("create export data zip [%s] failed: %s", exportFolder, err)
  163. return
  164. }
  165. if err = zip.Close(); nil != err {
  166. logging.LogErrorf("close export data zip failed: %s", err)
  167. }
  168. os.RemoveAll(exportFolder)
  169. return
  170. }
  171. func Preview(id string) string {
  172. tree, _ := loadTreeByBlockID(id)
  173. tree = exportTree(tree, false, false)
  174. luteEngine := NewLute()
  175. luteEngine.SetFootnotes(true)
  176. md := treenode.FormatNode(tree.Root, luteEngine)
  177. tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
  178. return luteEngine.ProtylePreview(tree, luteEngine.RenderOptions)
  179. }
  180. func ExportDocx(id, savePath string, removeAssets bool) (err error) {
  181. if !util.IsValidPandocBin(Conf.Export.PandocBin) {
  182. return errors.New(Conf.Language(115))
  183. }
  184. tmpDir := filepath.Join(util.TempDir, "export", gulu.Rand.String(7))
  185. if err = os.MkdirAll(tmpDir, 0755); nil != err {
  186. return
  187. }
  188. defer os.Remove(tmpDir)
  189. name, content := ExportMarkdownHTML(id, tmpDir, true)
  190. tmpDocxPath := filepath.Join(tmpDir, name+".docx")
  191. args := []string{ // pandoc -f html --resource-path=请从这里开始 请从这里开始\index.html -o test.docx
  192. "-f", "html+tex_math_dollars",
  193. "--resource-path", tmpDir,
  194. "-o", tmpDocxPath,
  195. }
  196. pandoc := exec.Command(Conf.Export.PandocBin, args...)
  197. util.CmdAttr(pandoc)
  198. pandoc.Stdin = bytes.NewBufferString(content)
  199. output, err := pandoc.CombinedOutput()
  200. if nil != err {
  201. logging.LogErrorf("export docx failed: %s", gulu.Str.FromBytes(output))
  202. msg := fmt.Sprintf(Conf.Language(14), gulu.Str.FromBytes(output))
  203. return errors.New(msg)
  204. }
  205. if err = gulu.File.Copy(tmpDocxPath, filepath.Join(savePath, name+".docx")); nil != err {
  206. logging.LogErrorf("export docx failed: %s", err)
  207. return errors.New(fmt.Sprintf(Conf.Language(14), err))
  208. }
  209. if tmpAssets := filepath.Join(tmpDir, "assets"); !removeAssets && gulu.File.IsDir(tmpAssets) {
  210. if err = gulu.File.Copy(tmpAssets, filepath.Join(savePath, "assets")); nil != err {
  211. logging.LogErrorf("export docx failed: %s", err)
  212. return errors.New(fmt.Sprintf(Conf.Language(14), err))
  213. }
  214. }
  215. return
  216. }
  217. func ExportMarkdownHTML(id, savePath string, docx bool) (name, dom string) {
  218. tree, _ := loadTreeByBlockID(id)
  219. tree = exportTree(tree, true, true)
  220. name = path.Base(tree.HPath)
  221. name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614
  222. if err := os.MkdirAll(savePath, 0755); nil != err {
  223. logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)
  224. return
  225. }
  226. assets := assetsLinkDestsInTree(tree)
  227. for _, asset := range assets {
  228. if strings.HasPrefix(asset, "assets/") {
  229. srcAbsPath, err := GetAssetAbsPath(asset)
  230. if nil != err {
  231. logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)
  232. continue
  233. }
  234. targetAbsPath := filepath.Join(savePath, asset)
  235. if err = gulu.File.Copy(srcAbsPath, targetAbsPath); nil != err {
  236. logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)
  237. }
  238. }
  239. }
  240. srcs := []string{"stage/build/export", "stage/build/fonts", "stage/protyle"}
  241. for _, src := range srcs {
  242. from := filepath.Join(util.WorkingDir, src)
  243. to := filepath.Join(savePath, src)
  244. if err := gulu.File.Copy(from, to); nil != err {
  245. logging.LogWarnf("copy stage from [%s] to [%s] failed: %s", from, savePath, err)
  246. return
  247. }
  248. }
  249. theme := Conf.Appearance.ThemeLight
  250. if 1 == Conf.Appearance.Mode {
  251. theme = Conf.Appearance.ThemeDark
  252. }
  253. srcs = []string{"icons", "themes/" + theme}
  254. for _, src := range srcs {
  255. from := filepath.Join(util.AppearancePath, src)
  256. to := filepath.Join(savePath, "appearance", src)
  257. if err := gulu.File.Copy(from, to); nil != err {
  258. logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)
  259. return
  260. }
  261. }
  262. // 复制自定义表情图片
  263. emojis := emojisInTree(tree)
  264. for _, emoji := range emojis {
  265. from := filepath.Join(util.DataDir, emoji)
  266. to := filepath.Join(savePath, emoji)
  267. if err := gulu.File.Copy(from, to); nil != err {
  268. logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err)
  269. return
  270. }
  271. }
  272. luteEngine := NewLute()
  273. luteEngine.SetFootnotes(true)
  274. md := treenode.FormatNode(tree.Root, luteEngine)
  275. tree = parse.Parse("", []byte(md), luteEngine.ParseOptions)
  276. if docx {
  277. processIFrame(tree)
  278. }
  279. // 自定义表情图片地址去掉开头的 /
  280. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  281. if !entering {
  282. return ast.WalkContinue
  283. }
  284. if ast.NodeEmojiImg == n.Type {
  285. n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("src=\"/emojis"), []byte("src=\"emojis"))
  286. }
  287. return ast.WalkContinue
  288. })
  289. if docx {
  290. renderer := render.NewProtyleExportDocxRenderer(tree, luteEngine.RenderOptions)
  291. output := renderer.Render()
  292. dom = gulu.Str.FromBytes(output)
  293. } else {
  294. dom = luteEngine.ProtylePreview(tree, luteEngine.RenderOptions)
  295. }
  296. return
  297. }
  298. func ExportHTML(id, savePath string, pdf bool) (name, dom string) {
  299. tree, _ := loadTreeByBlockID(id)
  300. var headings []*ast.Node
  301. if pdf { // 导出 PDF 需要标记目录书签
  302. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  303. if entering && ast.NodeHeading == n.Type && !n.ParentIs(ast.NodeBlockquote) {
  304. headings = append(headings, n)
  305. return ast.WalkSkipChildren
  306. }
  307. return ast.WalkContinue
  308. })
  309. for _, h := range headings {
  310. link := &ast.Node{Type: ast.NodeLink}
  311. link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  312. link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
  313. link.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  314. link.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  315. link.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("pdf-outline://" + h.ID)})
  316. link.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  317. h.PrependChild(link)
  318. }
  319. }
  320. tree = exportTree(tree, true, true)
  321. //if pdf { // TODO: 导出 PDF 时块引转换脚注使用书签跳转 https://github.com/siyuan-note/siyuan/issues/5761
  322. // var footnotesDefs []*ast.Node
  323. // ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  324. // if entering && ast.NodeFootnotesDef == n.Type {
  325. // footnotesDefs = append(footnotesDefs, n)
  326. // }
  327. // return ast.WalkContinue
  328. // })
  329. // for _, f := range footnotesDefs {
  330. // link := &ast.Node{Type: ast.NodeLink}
  331. // link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  332. // link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(" ")})
  333. // link.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  334. // link.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  335. // link.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("pdf-outline://footnotes-def-" + f.FootnotesRefId)})
  336. // link.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  337. // f.PrependChild(link)
  338. // }
  339. //}
  340. name = path.Base(tree.HPath)
  341. name = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614
  342. if "" != savePath {
  343. if err := os.MkdirAll(savePath, 0755); nil != err {
  344. logging.LogErrorf("mkdir [%s] failed: %s", savePath, err)
  345. return
  346. }
  347. assets := assetsLinkDestsInTree(tree)
  348. for _, asset := range assets {
  349. srcAbsPath, err := GetAssetAbsPath(asset)
  350. if nil != err {
  351. logging.LogWarnf("resolve path of asset [%s] failed: %s", asset, err)
  352. continue
  353. }
  354. targetAbsPath := filepath.Join(savePath, asset)
  355. if err = gulu.File.Copy(srcAbsPath, targetAbsPath); nil != err {
  356. logging.LogWarnf("copy asset from [%s] to [%s] failed: %s", srcAbsPath, targetAbsPath, err)
  357. }
  358. }
  359. }
  360. luteEngine := NewLute()
  361. if !pdf && "" != savePath { // 导出 HTML 需要复制静态资源
  362. srcs := []string{"stage/build/export", "stage/build/fonts", "stage/protyle"}
  363. for _, src := range srcs {
  364. from := filepath.Join(util.WorkingDir, src)
  365. to := filepath.Join(savePath, src)
  366. if err := gulu.File.Copy(from, to); nil != err {
  367. logging.LogErrorf("copy stage from [%s] to [%s] failed: %s", from, savePath, err)
  368. return
  369. }
  370. }
  371. theme := Conf.Appearance.ThemeLight
  372. if 1 == Conf.Appearance.Mode {
  373. theme = Conf.Appearance.ThemeDark
  374. }
  375. srcs = []string{"icons", "themes/" + theme}
  376. for _, src := range srcs {
  377. from := filepath.Join(util.AppearancePath, src)
  378. to := filepath.Join(savePath, "appearance", src)
  379. if err := gulu.File.Copy(from, to); nil != err {
  380. logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)
  381. return
  382. }
  383. }
  384. // 复制自定义表情图片
  385. emojis := emojisInTree(tree)
  386. for _, emoji := range emojis {
  387. from := filepath.Join(util.DataDir, emoji)
  388. to := filepath.Join(savePath, emoji)
  389. if err := gulu.File.Copy(from, to); nil != err {
  390. logging.LogErrorf("copy emojis from [%s] to [%s] failed: %s", from, savePath, err)
  391. return
  392. }
  393. }
  394. } else { // 导出 PDF 需要将资源文件路径改为 HTTP 伺服
  395. luteEngine.RenderOptions.LinkBase = "http://127.0.0.1:" + util.ServerPort + "/"
  396. }
  397. if pdf {
  398. processIFrame(tree)
  399. }
  400. luteEngine.SetFootnotes(true)
  401. luteEngine.RenderOptions.ProtyleContenteditable = false
  402. luteEngine.SetProtyleMarkNetImg(false)
  403. renderer := render.NewProtyleExportRenderer(tree, luteEngine.RenderOptions)
  404. dom = gulu.Str.FromBytes(renderer.Render())
  405. return
  406. }
  407. func processIFrame(tree *parse.Tree) {
  408. // 导出 PDF/Word 时 IFrame 块使用超链接 https://github.com/siyuan-note/siyuan/issues/4035
  409. var unlinks []*ast.Node
  410. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  411. if !entering {
  412. return ast.WalkContinue
  413. }
  414. if ast.NodeIFrame == n.Type {
  415. index := bytes.Index(n.Tokens, []byte("src=\""))
  416. if 0 > index {
  417. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: n.Tokens})
  418. } else {
  419. src := n.Tokens[index+len("src=\""):]
  420. src = src[:bytes.Index(src, []byte("\""))]
  421. src = html.UnescapeHTML(src)
  422. link := &ast.Node{Type: ast.NodeLink}
  423. link.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  424. link.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: src})
  425. link.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  426. link.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  427. link.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: src})
  428. link.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  429. n.InsertBefore(link)
  430. }
  431. unlinks = append(unlinks, n)
  432. }
  433. return ast.WalkContinue
  434. })
  435. for _, n := range unlinks {
  436. n.Unlink()
  437. }
  438. }
  439. func AddPDFOutline(id, p string) (err error) {
  440. inFile := p
  441. links, err := api.ListToCLinks(inFile)
  442. if nil != err {
  443. return
  444. }
  445. sort.Slice(links, func(i, j int) bool {
  446. return links[i].Page < links[j].Page
  447. })
  448. bms := map[string]*pdfcpu.Bookmark{}
  449. footnotes := map[string]*pdfcpu.Bookmark{}
  450. for _, link := range links {
  451. linkID := link.URI[strings.LastIndex(link.URI, "/")+1:]
  452. //if strings.HasPrefix(linkID, "footnotes-def-") { // 导出 PDF 时块引转换脚注使用书签跳转 https://github.com/siyuan-note/siyuan/issues/5761
  453. // footnotes[linkID] = &pdfcpu.Bookmark{
  454. // Title: "Footnote [^" + linkID + "]",
  455. // PageFrom: link.Page,
  456. // AbsPos: link.Rect.UR.Y,
  457. // Level: 7,
  458. // }
  459. // continue
  460. //}
  461. title := sql.GetBlock(linkID).Content
  462. title, _ = url.QueryUnescape(title)
  463. bm := &pdfcpu.Bookmark{
  464. Title: title,
  465. PageFrom: link.Page,
  466. AbsPos: link.Rect.UR.Y,
  467. }
  468. bms[linkID] = bm
  469. }
  470. if 1 > len(bms) && 1 > len(footnotes) {
  471. return
  472. }
  473. tree, _ := loadTreeByBlockID(id)
  474. if nil == tree {
  475. return
  476. }
  477. var headings []*ast.Node
  478. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  479. if entering && ast.NodeHeading == n.Type && !n.ParentIs(ast.NodeBlockquote) {
  480. headings = append(headings, n)
  481. return ast.WalkSkipChildren
  482. }
  483. return ast.WalkContinue
  484. })
  485. var topBms []*pdfcpu.Bookmark
  486. stack := linkedliststack.New()
  487. for _, h := range headings {
  488. L:
  489. for ; ; stack.Pop() {
  490. cur, ok := stack.Peek()
  491. if !ok {
  492. bm := bms[h.ID]
  493. bm.Level = h.HeadingLevel
  494. stack.Push(bm)
  495. topBms = append(topBms, bm)
  496. break L
  497. }
  498. tip := cur.(*pdfcpu.Bookmark)
  499. if tip.Level < h.HeadingLevel {
  500. bm := bms[h.ID]
  501. bm.Level = h.HeadingLevel
  502. bm.Parent = tip
  503. tip.Children = append(tip.Children, bm)
  504. stack.Push(bm)
  505. break L
  506. }
  507. }
  508. }
  509. //if 4 == Conf.Export.BlockRefMode { // 块引转脚注
  510. // var footnotesBms []*pdfcpu.Bookmark
  511. // for _, bm := range footnotes {
  512. // footnotesBms = append(footnotesBms, bm)
  513. // }
  514. // sort.Slice(footnotesBms, func(i, j int) bool { return footnotesBms[i].PageFrom < footnotesBms[j].PageFrom })
  515. // for _, bm := range footnotesBms {
  516. // topBms = append(topBms, bm)
  517. // }
  518. //}
  519. outFile := inFile + ".tmp"
  520. err = api.AddBookmarksFile(inFile, outFile, topBms, nil)
  521. if nil != err {
  522. logging.LogErrorf("add bookmark failed: %s", err)
  523. return
  524. }
  525. err = os.Rename(outFile, inFile)
  526. return
  527. }
  528. func CopyStdMarkdown(id string) string {
  529. tree, _ := loadTreeByBlockID(id)
  530. tree = exportTree(tree, false, false)
  531. luteEngine := NewLute()
  532. luteEngine.SetFootnotes(true)
  533. luteEngine.SetKramdownIAL(false)
  534. if IsSubscriber() {
  535. // 订阅用户使用云端图床服务
  536. luteEngine.RenderOptions.LinkBase = "https://assets.b3logfile.com/siyuan/" + Conf.User.UserId + "/"
  537. }
  538. return treenode.FormatNode(tree.Root, luteEngine)
  539. }
  540. func ExportMarkdown(id string) (name, zipPath string) {
  541. block := treenode.GetBlockTree(id)
  542. if nil == block {
  543. logging.LogErrorf("not found block [%s]", id)
  544. return
  545. }
  546. boxID := block.BoxID
  547. box := Conf.Box(boxID)
  548. baseFolderName := path.Base(block.HPath)
  549. if "." == baseFolderName {
  550. baseFolderName = path.Base(block.Path)
  551. }
  552. docPaths := []string{block.Path}
  553. docFiles := box.ListFiles(strings.TrimSuffix(block.Path, ".sy"))
  554. for _, docFile := range docFiles {
  555. docPaths = append(docPaths, docFile.path)
  556. }
  557. zipPath = exportMarkdownZip(boxID, baseFolderName, docPaths)
  558. name = strings.TrimSuffix(filepath.Base(block.Path), ".sy")
  559. return
  560. }
  561. func BatchExportMarkdown(boxID, folderPath string) (zipPath string) {
  562. box := Conf.Box(boxID)
  563. var baseFolderName string
  564. if "/" == folderPath {
  565. baseFolderName = box.Name
  566. } else {
  567. block := treenode.GetBlockTreeRootByHPath(box.ID, folderPath)
  568. if nil == block {
  569. logging.LogErrorf("not found block")
  570. return
  571. }
  572. baseFolderName = path.Base(block.HPath)
  573. }
  574. if "" == baseFolderName {
  575. baseFolderName = "Untitled"
  576. }
  577. docFiles := box.ListFiles(folderPath)
  578. var docPaths []string
  579. for _, docFile := range docFiles {
  580. docPaths = append(docPaths, docFile.path)
  581. }
  582. zipPath = exportMarkdownZip(boxID, baseFolderName, docPaths)
  583. return
  584. }
  585. func exportMarkdownZip(boxID, baseFolderName string, docPaths []string) (zipPath string) {
  586. dir, name := path.Split(baseFolderName)
  587. name = util.FilterFileName(name)
  588. if strings.HasSuffix(name, "..") {
  589. // 文档标题以 `..` 结尾时无法导出 Markdown https://github.com/siyuan-note/siyuan/issues/4698
  590. // 似乎是 os.MkdirAll 的 bug,以 .. 结尾的路径无法创建,所以这里加上 _ 结尾
  591. name += "_"
  592. }
  593. baseFolderName = path.Join(dir, name)
  594. box := Conf.Box(boxID)
  595. exportFolder := filepath.Join(util.TempDir, "export", baseFolderName)
  596. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  597. logging.LogErrorf("create export temp folder failed: %s", err)
  598. return
  599. }
  600. luteEngine := util.NewLute()
  601. for _, p := range docPaths {
  602. docIAL := box.docIAL(p)
  603. if nil == docIAL {
  604. continue
  605. }
  606. id := docIAL["id"]
  607. hPath, md := exportMarkdownContent(id)
  608. dir, name = path.Split(hPath)
  609. dir = util.FilterFilePath(dir) // 导出文档时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/4590
  610. name = util.FilterFileName(name)
  611. hPath = path.Join(dir, name)
  612. p = hPath + ".md"
  613. writePath := filepath.Join(exportFolder, p)
  614. if gulu.File.IsExist(writePath) {
  615. // 重名文档加 ID
  616. p = hPath + "-" + id + ".md"
  617. writePath = filepath.Join(exportFolder, p)
  618. }
  619. writeFolder := filepath.Dir(writePath)
  620. if err := os.MkdirAll(writeFolder, 0755); nil != err {
  621. logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, err)
  622. continue
  623. }
  624. if err := gulu.File.WriteFileSafer(writePath, gulu.Str.ToBytes(md), 0644); nil != err {
  625. logging.LogErrorf("write export markdown file [%s] failed: %s", writePath, err)
  626. continue
  627. }
  628. // 解析导出后的标准 Markdown,汇总 assets
  629. tree := parse.Parse("", gulu.Str.ToBytes(md), luteEngine.ParseOptions)
  630. var assets []string
  631. assets = append(assets, assetsLinkDestsInTree(tree)...)
  632. for _, asset := range assets {
  633. asset = string(html.DecodeDestination([]byte(asset)))
  634. if strings.Contains(asset, "?") {
  635. asset = asset[:strings.LastIndex(asset, "?")]
  636. }
  637. srcPath, err := GetAssetAbsPath(asset)
  638. if nil != err {
  639. logging.LogWarnf("get asset [%s] abs path failed: %s", asset, err)
  640. continue
  641. }
  642. destPath := filepath.Join(writeFolder, asset)
  643. if gulu.File.IsDir(srcPath) {
  644. err = gulu.File.Copy(srcPath, destPath)
  645. } else {
  646. err = gulu.File.CopyFile(srcPath, destPath)
  647. }
  648. if nil != err {
  649. logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, err)
  650. continue
  651. }
  652. }
  653. }
  654. zipPath = exportFolder + ".zip"
  655. zip, err := gulu.Zip.Create(zipPath)
  656. if nil != err {
  657. logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err)
  658. return ""
  659. }
  660. if err = zip.AddDirectory(baseFolderName, exportFolder); nil != err {
  661. logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err)
  662. return ""
  663. }
  664. if err = zip.Close(); nil != err {
  665. logging.LogErrorf("close export markdown zip failed: %s", err)
  666. }
  667. os.RemoveAll(exportFolder)
  668. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  669. return
  670. }
  671. func exportBoxSYZip(boxID string) (zipPath string) {
  672. box := Conf.Box(boxID)
  673. if nil == box {
  674. logging.LogErrorf("not found box [%s]", boxID)
  675. return
  676. }
  677. baseFolderName := box.Name
  678. var docPaths []string
  679. docFiles := box.ListFiles("/")
  680. for _, docFile := range docFiles {
  681. docPaths = append(docPaths, docFile.path)
  682. }
  683. zipPath = exportSYZip(boxID, "/", baseFolderName, docPaths)
  684. return
  685. }
  686. func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string) (zipPath string) {
  687. dir, name := path.Split(baseFolderName)
  688. name = util.FilterFileName(name)
  689. if strings.HasSuffix(name, "..") {
  690. // 文档标题以 `..` 结尾时无法导出 Markdown https://github.com/siyuan-note/siyuan/issues/4698
  691. // 似乎是 os.MkdirAll 的 bug,以 .. 结尾的路径无法创建,所以这里加上 _ 结尾
  692. name += "_"
  693. }
  694. baseFolderName = path.Join(dir, name)
  695. box := Conf.Box(boxID)
  696. exportFolder := filepath.Join(util.TempDir, "export", baseFolderName)
  697. if err := os.MkdirAll(exportFolder, 0755); nil != err {
  698. logging.LogErrorf("create export temp folder failed: %s", err)
  699. return
  700. }
  701. trees := map[string]*parse.Tree{}
  702. refTrees := map[string]*parse.Tree{}
  703. for _, p := range docPaths {
  704. docIAL := box.docIAL(p)
  705. if nil == docIAL {
  706. continue
  707. }
  708. id := docIAL["id"]
  709. tree, err := loadTreeByBlockID(id)
  710. if nil != err {
  711. continue
  712. }
  713. trees[tree.ID] = tree
  714. }
  715. for _, tree := range trees {
  716. refs := exportRefTrees(tree)
  717. for refTreeID, refTree := range refs {
  718. if nil == trees[refTreeID] {
  719. refTrees[refTreeID] = refTree
  720. }
  721. }
  722. }
  723. // 按文件夹结构复制选择的树
  724. for _, tree := range trees {
  725. readPath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  726. data, readErr := filelock.NoLockFileRead(readPath)
  727. if nil != readErr {
  728. logging.LogErrorf("read file [%s] failed: %s", readPath, readErr)
  729. continue
  730. }
  731. writePath := strings.TrimPrefix(tree.Path, rootDirPath)
  732. writePath = filepath.Join(exportFolder, writePath)
  733. writeFolder := filepath.Dir(writePath)
  734. if mkdirErr := os.MkdirAll(writeFolder, 0755); nil != mkdirErr {
  735. logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, mkdirErr)
  736. continue
  737. }
  738. if writeErr := os.WriteFile(writePath, data, 0644); nil != writeErr {
  739. logging.LogErrorf("write export file [%s] failed: %s", writePath, writeErr)
  740. continue
  741. }
  742. }
  743. // 引用树放在导出文件夹根路径下
  744. for treeID, tree := range refTrees {
  745. readPath := filepath.Join(util.DataDir, tree.Box, tree.Path)
  746. data, readErr := filelock.NoLockFileRead(readPath)
  747. if nil != readErr {
  748. logging.LogErrorf("read file [%s] failed: %s", readPath, readErr)
  749. continue
  750. }
  751. writePath := strings.TrimPrefix(tree.Path, rootDirPath)
  752. writePath = filepath.Join(exportFolder, treeID+".sy")
  753. if writeErr := os.WriteFile(writePath, data, 0644); nil != writeErr {
  754. logging.LogErrorf("write export file [%s] failed: %s", writePath, writeErr)
  755. continue
  756. }
  757. }
  758. // 将引用树合并到选择树中,以便后面一次性导出资源文件
  759. for treeID, tree := range refTrees {
  760. trees[treeID] = tree
  761. }
  762. // 导出引用的资源文件
  763. copiedAssets := hashset.New()
  764. for _, tree := range trees {
  765. var assets []string
  766. assets = append(assets, assetsLinkDestsInTree(tree)...)
  767. for _, asset := range assets {
  768. asset = string(html.DecodeDestination([]byte(asset)))
  769. if strings.Contains(asset, "?") {
  770. asset = asset[:strings.LastIndex(asset, "?")]
  771. }
  772. if copiedAssets.Contains(asset) {
  773. continue
  774. }
  775. srcPath, assetErr := GetAssetAbsPath(asset)
  776. if nil != assetErr {
  777. logging.LogWarnf("get asset [%s] abs path failed: %s", asset, assetErr)
  778. continue
  779. }
  780. destPath := filepath.Join(exportFolder, asset)
  781. if gulu.File.IsDir(srcPath) {
  782. assetErr = gulu.File.Copy(srcPath, destPath)
  783. } else {
  784. assetErr = gulu.File.CopyFile(srcPath, destPath)
  785. }
  786. if nil != assetErr {
  787. logging.LogErrorf("copy asset from [%s] to [%s] failed: %s", srcPath, destPath, assetErr)
  788. continue
  789. }
  790. copiedAssets.Add(asset)
  791. }
  792. }
  793. zipPath = exportFolder + ".sy.zip"
  794. zip, err := gulu.Zip.Create(zipPath)
  795. if nil != err {
  796. logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err)
  797. return ""
  798. }
  799. if err = zip.AddDirectory(baseFolderName, exportFolder); nil != err {
  800. logging.LogErrorf("create export markdown zip [%s] failed: %s", exportFolder, err)
  801. return ""
  802. }
  803. if err = zip.Close(); nil != err {
  804. logging.LogErrorf("close export markdown zip failed: %s", err)
  805. }
  806. os.RemoveAll(exportFolder)
  807. zipPath = "/export/" + url.PathEscape(filepath.Base(zipPath))
  808. return
  809. }
  810. func ExportMarkdownContent(id string) (hPath, exportedMd string) {
  811. return exportMarkdownContent(id)
  812. }
  813. func exportMarkdownContent(id string) (hPath, exportedMd string) {
  814. tree, _ := loadTreeByBlockID(id)
  815. hPath = tree.HPath
  816. tree = exportTree(tree, false, true)
  817. luteEngine := NewLute()
  818. luteEngine.SetFootnotes(true)
  819. luteEngine.SetKramdownIAL(false)
  820. renderer := render.NewProtyleExportMdRenderer(tree, luteEngine.RenderOptions)
  821. exportedMd = gulu.Str.FromBytes(renderer.Render())
  822. return
  823. }
  824. func processKaTexMacros(n *ast.Node) {
  825. if ast.NodeInlineMathContent != n.Type && ast.NodeMathBlockContent != n.Type && ast.NodeTextMark != n.Type {
  826. return
  827. }
  828. if ast.NodeTextMark == n.Type && !n.IsTextMarkType("inline-math") {
  829. return
  830. }
  831. var mathContent string
  832. if ast.NodeTextMark == n.Type {
  833. mathContent = n.TextMarkInlineMathContent
  834. } else {
  835. mathContent = string(n.Tokens)
  836. }
  837. mathContent = strings.TrimSpace(mathContent)
  838. if "" == mathContent {
  839. return
  840. }
  841. macros := map[string]string{}
  842. if err := gulu.JSON.UnmarshalJSON([]byte(Conf.Editor.KaTexMacros), &macros); nil != err {
  843. logging.LogWarnf("parse katex macros failed: %s", err)
  844. return
  845. }
  846. var keys []string
  847. for k := range macros {
  848. keys = append(keys, k)
  849. }
  850. useMacro := false
  851. for k := range macros {
  852. if strings.Contains(mathContent, k) {
  853. useMacro = true
  854. break
  855. }
  856. }
  857. if !useMacro {
  858. return
  859. }
  860. sort.Slice(keys, func(i, j int) bool { return len(keys[i]) > len(keys[j]) })
  861. mathContent = escapeKaTexSupportedFunctions(mathContent)
  862. usedMacros := extractUsedMacros(mathContent, &keys)
  863. for _, usedMacro := range usedMacros {
  864. expanded := resolveKaTexMacro(usedMacro, &macros, &keys)
  865. expanded = unescapeKaTexSupportedFunctions(expanded)
  866. mathContent = strings.ReplaceAll(mathContent, usedMacro, expanded)
  867. }
  868. mathContent = unescapeKaTexSupportedFunctions(mathContent)
  869. if ast.NodeTextMark == n.Type {
  870. n.TextMarkInlineMathContent = mathContent
  871. } else {
  872. n.Tokens = []byte(mathContent)
  873. }
  874. }
  875. func exportTree(tree *parse.Tree, wysiwyg, expandKaTexMacros bool) (ret *parse.Tree) {
  876. luteEngine := NewLute()
  877. ret = tree
  878. id := tree.Root.ID
  879. var unlinks []*ast.Node
  880. // 解析查询嵌入节点
  881. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  882. if !entering || ast.NodeBlockQueryEmbed != n.Type {
  883. return ast.WalkContinue
  884. }
  885. var defMd string
  886. stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
  887. stmt = html.UnescapeString(stmt)
  888. blocks := searchEmbedBlock(stmt, nil, 0)
  889. if 1 > len(blocks) {
  890. return ast.WalkContinue
  891. }
  892. defMdBuf := bytes.Buffer{}
  893. for _, def := range blocks {
  894. defMdBuf.WriteString(renderBlockMarkdownR(def.ID))
  895. defMdBuf.WriteString("\n\n")
  896. }
  897. defMd = defMdBuf.String()
  898. buf := &bytes.Buffer{}
  899. lines := strings.Split(defMd, "\n")
  900. for i, line := range lines {
  901. if 0 == Conf.Export.BlockEmbedMode { // 原始文本
  902. buf.WriteString(line)
  903. } else { // Blockquote
  904. buf.WriteString("> " + line)
  905. }
  906. if i < len(lines)-1 {
  907. buf.WriteString("\n")
  908. }
  909. }
  910. buf.WriteString("\n\n")
  911. refTree := parse.Parse("", buf.Bytes(), luteEngine.ParseOptions)
  912. var children []*ast.Node
  913. for c := refTree.Root.FirstChild; nil != c; c = c.Next {
  914. children = append(children, c)
  915. }
  916. for _, c := range children {
  917. if ast.NodeDocument == c.Type {
  918. continue
  919. }
  920. n.InsertBefore(c)
  921. }
  922. unlinks = append(unlinks, n)
  923. return ast.WalkSkipChildren
  924. })
  925. for _, n := range unlinks {
  926. n.Unlink()
  927. }
  928. unlinks = nil
  929. // 收集引用转脚注
  930. var refFootnotes []*refAsFootnotes
  931. if 4 == Conf.Export.BlockRefMode { // 块引转脚注
  932. treeCache := map[string]*parse.Tree{}
  933. treeCache[id] = ret
  934. depth := 0
  935. collectFootnotesDefs(ret.ID, &refFootnotes, &treeCache, &depth)
  936. }
  937. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  938. if !entering {
  939. return ast.WalkContinue
  940. }
  941. switch n.Type {
  942. case ast.NodeTagOpenMarker: // 配置标签开始标记符
  943. if !wysiwyg {
  944. n.Type = ast.NodeText
  945. n.Tokens = []byte(Conf.Export.TagOpenMarker)
  946. return ast.WalkContinue
  947. }
  948. case ast.NodeTagCloseMarker: // 配置标记结束标记符
  949. if !wysiwyg {
  950. n.Type = ast.NodeText
  951. n.Tokens = []byte(Conf.Export.TagCloseMarker)
  952. return ast.WalkContinue
  953. }
  954. case ast.NodeSuperBlockOpenMarker, ast.NodeSuperBlockLayoutMarker, ast.NodeSuperBlockCloseMarker:
  955. if !wysiwyg {
  956. unlinks = append(unlinks, n)
  957. return ast.WalkContinue
  958. }
  959. case ast.NodeHeading:
  960. n.HeadingNormalizedID = n.IALAttr("id")
  961. n.ID = n.HeadingNormalizedID
  962. case ast.NodeInlineMathContent, ast.NodeMathBlockContent:
  963. n.Tokens = bytes.TrimSpace(n.Tokens) // 导出 Markdown 时去除公式内容中的首尾空格 https://github.com/siyuan-note/siyuan/issues/4666
  964. return ast.WalkContinue
  965. case ast.NodeTextMark:
  966. if n.IsTextMarkType("inline-math") {
  967. n.TextMarkInlineMathContent = strings.TrimSpace(n.TextMarkInlineMathContent)
  968. return ast.WalkContinue
  969. } else if n.IsTextMarkType("file-annotation-ref") {
  970. refID := n.TextMarkFileAnnotationRefID
  971. status := processFileAnnotationRef(refID, n)
  972. unlinks = append(unlinks, n)
  973. return status
  974. }
  975. case ast.NodeFileAnnotationRef:
  976. refIDNode := n.ChildByType(ast.NodeFileAnnotationRefID)
  977. if nil == refIDNode {
  978. return ast.WalkSkipChildren
  979. }
  980. refID := refIDNode.TokensStr()
  981. status := processFileAnnotationRef(refID, n)
  982. unlinks = append(unlinks, n)
  983. return status
  984. }
  985. if !treenode.IsBlockRef(n) {
  986. return ast.WalkContinue
  987. }
  988. // 处理引用节点
  989. defID, linkText, _ := treenode.GetBlockRef(n)
  990. if "" == linkText {
  991. linkText = sql.GetRefText(defID)
  992. }
  993. if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(linkText) {
  994. linkText = gulu.Str.SubStr(linkText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."
  995. }
  996. linkText = Conf.Export.BlockRefTextLeft + linkText + Conf.Export.BlockRefTextRight
  997. defTree, _ := loadTreeByBlockID(defID)
  998. if nil == defTree {
  999. return ast.WalkContinue
  1000. }
  1001. switch Conf.Export.BlockRefMode {
  1002. case 2: // 锚文本块链
  1003. var blockRefLink *ast.Node
  1004. blockRefLink = &ast.Node{Type: ast.NodeLink}
  1005. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1006. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(linkText)})
  1007. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1008. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1009. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte("siyuan://blocks/" + defID)})
  1010. blockRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1011. n.InsertBefore(blockRefLink)
  1012. case 3: // 仅锚文本
  1013. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(linkText)})
  1014. case 4: // 脚注
  1015. refFoot := getRefAsFootnotes(defID, &refFootnotes)
  1016. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(linkText)})
  1017. n.InsertBefore(&ast.Node{Type: ast.NodeFootnotesRef, Tokens: []byte("^" + refFoot.refNum), FootnotesRefId: refFoot.refNum, FootnotesRefLabel: []byte("^" + refFoot.refNum)})
  1018. }
  1019. unlinks = append(unlinks, n)
  1020. if nil != n.Next && ast.NodeKramdownSpanIAL == n.Next.Type {
  1021. // 引用加排版标记(比如颜色)重叠时丢弃后面的排版属性节点
  1022. unlinks = append(unlinks, n.Next)
  1023. }
  1024. return ast.WalkSkipChildren
  1025. })
  1026. for _, n := range unlinks {
  1027. n.Unlink()
  1028. }
  1029. if 4 == Conf.Export.BlockRefMode { // 块引转脚注
  1030. if footnotesDefBlock := resolveFootnotesDefs(&refFootnotes, ret.Root.ID); nil != footnotesDefBlock {
  1031. ret.Root.AppendChild(footnotesDefBlock)
  1032. }
  1033. }
  1034. if Conf.Export.AddTitle {
  1035. if root, _ := getBlock(id); nil != root {
  1036. title := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 1}
  1037. content := html.UnescapeString(root.Content)
  1038. title.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(content)})
  1039. ret.Root.PrependChild(title)
  1040. }
  1041. }
  1042. // 导出时支持导出题头图 https://github.com/siyuan-note/siyuan/issues/4372
  1043. titleImgPath := treenode.GetDocTitleImgPath(ret.Root)
  1044. if "" != titleImgPath {
  1045. p := &ast.Node{Type: ast.NodeParagraph}
  1046. titleImg := &ast.Node{Type: ast.NodeImage}
  1047. titleImg.AppendChild(&ast.Node{Type: ast.NodeBang})
  1048. titleImg.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1049. titleImg.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte("image")})
  1050. titleImg.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1051. titleImg.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1052. titleImg.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(titleImgPath)})
  1053. titleImg.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1054. p.AppendChild(titleImg)
  1055. ret.Root.PrependChild(p)
  1056. }
  1057. unlinks = nil
  1058. var emptyParagraphs []*ast.Node
  1059. ast.Walk(ret.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1060. if !entering {
  1061. return ast.WalkContinue
  1062. }
  1063. // 块折叠以后导出 HTML/PDF 固定展开 https://github.com/siyuan-note/siyuan/issues/4064
  1064. n.RemoveIALAttr("fold")
  1065. n.RemoveIALAttr("heading-fold")
  1066. if ast.NodeParagraph == n.Type {
  1067. if nil == n.FirstChild {
  1068. // 空的段落块需要补全文本展位,否则后续格式化后再解析树会语义不一致 https://github.com/siyuan-note/siyuan/issues/5806
  1069. emptyParagraphs = append(emptyParagraphs, n)
  1070. }
  1071. }
  1072. if expandKaTexMacros && (ast.NodeInlineMathContent == n.Type || ast.NodeMathBlockContent == n.Type || (ast.NodeTextMark == n.Type && n.IsTextMarkType("inline-math"))) {
  1073. processKaTexMacros(n)
  1074. }
  1075. if ast.NodeWidget == n.Type {
  1076. // 挂件块导出 https://github.com/siyuan-note/siyuan/issues/3834
  1077. exportMdVal := n.IALAttr("data-export-md")
  1078. exportMdVal = html.UnescapeString(exportMdVal) // 导出 `data-export-md` 时未解析代码块与行内代码内的转义字符 https://github.com/siyuan-note/siyuan/issues/4180
  1079. if "" != exportMdVal {
  1080. exportMdTree := parse.Parse("", []byte(exportMdVal), luteEngine.ParseOptions)
  1081. var insertNodes []*ast.Node
  1082. for c := exportMdTree.Root.FirstChild; nil != c; c = c.Next {
  1083. if ast.NodeKramdownBlockIAL != c.Type {
  1084. insertNodes = append(insertNodes, c)
  1085. }
  1086. }
  1087. for _, insertNode := range insertNodes {
  1088. n.InsertBefore(insertNode)
  1089. }
  1090. unlinks = append(unlinks, n)
  1091. }
  1092. return ast.WalkContinue
  1093. }
  1094. if ast.NodeText != n.Type {
  1095. return ast.WalkContinue
  1096. }
  1097. // Shift+Enter 换行在导出为 Markdown 时使用硬换行 https://github.com/siyuan-note/siyuan/issues/3458
  1098. n.Tokens = bytes.ReplaceAll(n.Tokens, []byte("\n"), []byte(" \n"))
  1099. return ast.WalkContinue
  1100. })
  1101. for _, n := range unlinks {
  1102. n.Unlink()
  1103. }
  1104. for _, emptyParagraph := range emptyParagraphs {
  1105. emptyParagraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(editor.Zwj)})
  1106. }
  1107. return ret
  1108. }
  1109. func resolveFootnotesDefs(refFootnotes *[]*refAsFootnotes, rootID string) (footnotesDefBlock *ast.Node) {
  1110. if 1 > len(*refFootnotes) {
  1111. return nil
  1112. }
  1113. footnotesDefBlock = &ast.Node{Type: ast.NodeFootnotesDefBlock}
  1114. var rendered []string
  1115. for _, foot := range *refFootnotes {
  1116. t, err := loadTreeByBlockID(foot.defID)
  1117. if nil != err {
  1118. continue
  1119. }
  1120. defNode := treenode.GetNodeInTree(t, foot.defID)
  1121. var nodes []*ast.Node
  1122. if ast.NodeHeading == defNode.Type {
  1123. nodes = append(nodes, defNode)
  1124. children := treenode.HeadingChildren(defNode)
  1125. nodes = append(nodes, children...)
  1126. } else if ast.NodeDocument == defNode.Type {
  1127. docTitle := &ast.Node{ID: defNode.ID, Type: ast.NodeHeading, HeadingLevel: 1}
  1128. docTitle.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(defNode.IALAttr("title"))})
  1129. nodes = append(nodes, docTitle)
  1130. for c := defNode.FirstChild; nil != c; c = c.Next {
  1131. nodes = append(nodes, c)
  1132. }
  1133. } else {
  1134. nodes = append(nodes, defNode)
  1135. }
  1136. var newNodes []*ast.Node
  1137. for _, node := range nodes {
  1138. var unlinks []*ast.Node
  1139. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1140. if !entering {
  1141. return ast.WalkContinue
  1142. }
  1143. if treenode.IsBlockRef(n) {
  1144. defID, _, _ := treenode.GetBlockRef(n)
  1145. if f := getRefAsFootnotes(defID, refFootnotes); nil != f {
  1146. n.InsertBefore(&ast.Node{Type: ast.NodeText, Tokens: []byte(Conf.Export.BlockRefTextLeft + f.refAnchorText + Conf.Export.BlockRefTextRight)})
  1147. n.InsertBefore(&ast.Node{Type: ast.NodeFootnotesRef, Tokens: []byte("^" + f.refNum), FootnotesRefId: f.refNum, FootnotesRefLabel: []byte("^" + f.refNum)})
  1148. unlinks = append(unlinks, n)
  1149. }
  1150. return ast.WalkSkipChildren
  1151. } else if ast.NodeBlockQueryEmbed == n.Type {
  1152. stmt := n.ChildByType(ast.NodeBlockQueryEmbedScript).TokensStr()
  1153. stmt = html.UnescapeString(stmt)
  1154. sqlBlocks := sql.SelectBlocksRawStmt(stmt, Conf.Search.Limit)
  1155. for _, b := range sqlBlocks {
  1156. subNodes := renderBlockMarkdownR0(b.ID, &rendered)
  1157. for _, subNode := range subNodes {
  1158. if ast.NodeListItem == subNode.Type {
  1159. parentList := &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: subNode.ListData.Typ}}
  1160. parentList.AppendChild(subNode)
  1161. newNodes = append(newNodes, parentList)
  1162. } else {
  1163. newNodes = append(newNodes, subNode)
  1164. }
  1165. }
  1166. }
  1167. unlinks = append(unlinks, n)
  1168. return ast.WalkSkipChildren
  1169. }
  1170. return ast.WalkContinue
  1171. })
  1172. for _, n := range unlinks {
  1173. n.Unlink()
  1174. }
  1175. if ast.NodeBlockQueryEmbed != node.Type {
  1176. if ast.NodeListItem == node.Type {
  1177. parentList := &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: node.ListData.Typ}}
  1178. parentList.AppendChild(node)
  1179. newNodes = append(newNodes, parentList)
  1180. } else {
  1181. newNodes = append(newNodes, node)
  1182. }
  1183. }
  1184. }
  1185. footnotesDef := &ast.Node{Type: ast.NodeFootnotesDef, Tokens: []byte("^" + foot.refNum), FootnotesRefId: foot.refNum, FootnotesRefLabel: []byte("^" + foot.refNum)}
  1186. for _, node := range newNodes {
  1187. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1188. if !entering {
  1189. return ast.WalkContinue
  1190. }
  1191. if ast.NodeParagraph != n.Type {
  1192. return ast.WalkContinue
  1193. }
  1194. docID := strings.TrimSuffix(path.Base(n.Path), ".sy")
  1195. if rootID == docID { // 在同一个文档的话缩略显示 https://github.com/siyuan-note/siyuan/issues/3299
  1196. if text := sql.GetRefText(n.ID); 64 < utf8.RuneCountInString(text) {
  1197. var unlinkChildren []*ast.Node
  1198. for c := n.FirstChild; nil != c; c = c.Next {
  1199. unlinkChildren = append(unlinkChildren, c)
  1200. }
  1201. for _, c := range unlinkChildren {
  1202. c.Unlink()
  1203. }
  1204. text = gulu.Str.SubStr(text, 64) + "..."
  1205. n.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(text)})
  1206. return ast.WalkSkipChildren
  1207. }
  1208. }
  1209. return ast.WalkContinue
  1210. })
  1211. footnotesDef.AppendChild(node)
  1212. }
  1213. footnotesDefBlock.AppendChild(footnotesDef)
  1214. }
  1215. return
  1216. }
  1217. func collectFootnotesDefs(id string, refFootnotes *[]*refAsFootnotes, treeCache *map[string]*parse.Tree, depth *int) {
  1218. *depth++
  1219. if 4096 < *depth {
  1220. return
  1221. }
  1222. b := treenode.GetBlockTree(id)
  1223. if nil == b {
  1224. return
  1225. }
  1226. t := (*treeCache)[b.RootID]
  1227. if nil == t {
  1228. var err error
  1229. if t, err = loadTreeByBlockID(b.ID); nil != err {
  1230. return
  1231. }
  1232. (*treeCache)[t.ID] = t
  1233. }
  1234. node := treenode.GetNodeInTree(t, b.ID)
  1235. if nil == node {
  1236. logging.LogErrorf("not found node [%s] in tree [%s]", b.ID, t.Root.ID)
  1237. return
  1238. }
  1239. collectFootnotesDefs0(node, refFootnotes, treeCache, depth)
  1240. if ast.NodeHeading == node.Type {
  1241. children := treenode.HeadingChildren(node)
  1242. for _, c := range children {
  1243. collectFootnotesDefs0(c, refFootnotes, treeCache, depth)
  1244. }
  1245. }
  1246. return
  1247. }
  1248. func collectFootnotesDefs0(node *ast.Node, refFootnotes *[]*refAsFootnotes, treeCache *map[string]*parse.Tree, depth *int) {
  1249. ast.Walk(node, func(n *ast.Node, entering bool) ast.WalkStatus {
  1250. if !entering {
  1251. return ast.WalkContinue
  1252. }
  1253. if treenode.IsBlockRef(n) {
  1254. defID, _, _ := treenode.GetBlockRef(n)
  1255. if nil == getRefAsFootnotes(defID, refFootnotes) {
  1256. anchorText := sql.GetRefText(defID)
  1257. if Conf.Editor.BlockRefDynamicAnchorTextMaxLen < utf8.RuneCountInString(anchorText) {
  1258. anchorText = gulu.Str.SubStr(anchorText, Conf.Editor.BlockRefDynamicAnchorTextMaxLen) + "..."
  1259. }
  1260. *refFootnotes = append(*refFootnotes, &refAsFootnotes{
  1261. defID: defID,
  1262. refNum: strconv.Itoa(len(*refFootnotes) + 1),
  1263. refAnchorText: anchorText,
  1264. })
  1265. collectFootnotesDefs(defID, refFootnotes, treeCache, depth)
  1266. }
  1267. return ast.WalkSkipChildren
  1268. }
  1269. return ast.WalkContinue
  1270. })
  1271. }
  1272. func getRefAsFootnotes(defID string, slice *[]*refAsFootnotes) *refAsFootnotes {
  1273. for _, e := range *slice {
  1274. if e.defID == defID {
  1275. return e
  1276. }
  1277. }
  1278. return nil
  1279. }
  1280. type refAsFootnotes struct {
  1281. defID string
  1282. refNum string
  1283. refAnchorText string
  1284. }
  1285. func exportRefTrees(tree *parse.Tree) (ret map[string]*parse.Tree) {
  1286. ret = map[string]*parse.Tree{}
  1287. exportRefTrees0(tree, &ret)
  1288. return
  1289. }
  1290. func exportRefTrees0(tree *parse.Tree, retTrees *map[string]*parse.Tree) {
  1291. if nil != (*retTrees)[tree.ID] {
  1292. return
  1293. }
  1294. (*retTrees)[tree.ID] = tree
  1295. ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
  1296. if !entering {
  1297. return ast.WalkContinue
  1298. }
  1299. if treenode.IsBlockRef(n) {
  1300. defID, _, _ := treenode.GetBlockRef(n)
  1301. if "" == defID {
  1302. return ast.WalkContinue
  1303. }
  1304. defBlock := treenode.GetBlockTree(defID)
  1305. if nil == defBlock {
  1306. return ast.WalkSkipChildren
  1307. }
  1308. defTree, err := loadTreeByBlockID(defBlock.RootID)
  1309. if nil != err {
  1310. return ast.WalkSkipChildren
  1311. }
  1312. exportRefTrees0(defTree, retTrees)
  1313. }
  1314. return ast.WalkContinue
  1315. })
  1316. }
  1317. func processFileAnnotationRef(refID string, n *ast.Node) ast.WalkStatus {
  1318. p := refID[:strings.LastIndex(refID, "/")]
  1319. absPath, err := GetAssetAbsPath(p)
  1320. if nil != err {
  1321. logging.LogWarnf("get assets abs path by rel path [%s] failed: %s", p, err)
  1322. return ast.WalkSkipChildren
  1323. }
  1324. sya := absPath + ".sya"
  1325. syaData, err := os.ReadFile(sya)
  1326. if nil != err {
  1327. logging.LogErrorf("read file [%s] failed: %s", sya, err)
  1328. return ast.WalkSkipChildren
  1329. }
  1330. syaJSON := map[string]interface{}{}
  1331. if err = gulu.JSON.UnmarshalJSON(syaData, &syaJSON); nil != err {
  1332. logging.LogErrorf("unmarshal file [%s] failed: %s", sya, err)
  1333. return ast.WalkSkipChildren
  1334. }
  1335. annotationID := refID[strings.LastIndex(refID, "/")+1:]
  1336. annotationData := syaJSON[annotationID]
  1337. if nil == annotationData {
  1338. logging.LogErrorf("not found annotation [%s] in .sya", annotationID)
  1339. return ast.WalkSkipChildren
  1340. }
  1341. pages := annotationData.(map[string]interface{})["pages"].([]interface{})
  1342. page := int(pages[0].(map[string]interface{})["index"].(float64)) + 1
  1343. pageStr := strconv.Itoa(page)
  1344. var refText string
  1345. if ast.NodeTextMark == n.Type {
  1346. refText = n.TextMarkTextContent
  1347. } else {
  1348. refTextNode := n.ChildByType(ast.NodeFileAnnotationRefText)
  1349. if nil == refTextNode {
  1350. return ast.WalkSkipChildren
  1351. }
  1352. refText = refTextNode.TokensStr()
  1353. }
  1354. ext := filepath.Ext(p)
  1355. file := p[7:len(p)-23-len(ext)] + ext
  1356. fileAnnotationRefLink := &ast.Node{Type: ast.NodeLink}
  1357. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenBracket})
  1358. if 0 == Conf.Export.FileAnnotationRefMode {
  1359. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(file + " - p" + pageStr + " - " + refText)})
  1360. } else {
  1361. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkText, Tokens: []byte(refText)})
  1362. }
  1363. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseBracket})
  1364. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeOpenParen})
  1365. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeLinkDest, Tokens: []byte(p + "?p=" + pageStr)})
  1366. fileAnnotationRefLink.AppendChild(&ast.Node{Type: ast.NodeCloseParen})
  1367. n.InsertBefore(fileAnnotationRefLink)
  1368. return ast.WalkSkipChildren
  1369. }