export.go 48 KB

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