toc.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. package docx
  2. /*
  3. A table of contents
  4. The editor keeps a table of contents as ordinary paragraphs: a title
  5. (p.doc-toc.doc-toc-title) and one line per heading (p.doc-toc with
  6. data-toc-level, the heading's text, a right tab with a dot leader and
  7. the page number). That is what Word holds once its TOC field has been
  8. updated, so the writer wraps a run of those lines in the same frame
  9. Word does - a Table of Contents building-block control with a TOC
  10. field around the entries - and Word offers its own Update Table on
  11. it. The lines use Word's style names (TOC Heading, toc 1..9), which
  12. is how the reader recognises a table of contents Word wrote.
  13. */
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. "golang.org/x/net/html"
  21. "imuslab.com/arozos/mod/office/internal/htmlutil"
  22. )
  23. // tocHeadingStyle is Word's style id of a table of contents' title
  24. const tocHeadingStyle = "TOCHeading"
  25. const (
  26. tocSdtOpen = `<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique/></w:docPartObj></w:sdtPr><w:sdtContent>`
  27. tocSdtEnd = `</w:sdtContent></w:sdt>`
  28. tocFieldEnd = `<w:r><w:fldChar w:fldCharType="end"/></w:r>`
  29. )
  30. // tocField is what a table's TOC field says: the heading levels it lists
  31. // and whether its entries carry page numbers
  32. type tocField struct {
  33. from, to int
  34. noPages bool
  35. }
  36. // tocFieldBegin opens the field: the headings the table lists, as
  37. // hyperlinks, without tab leaders or page numbers in Web view, keeping
  38. // outline levels (and no page numbers at all when the table shows none)
  39. func tocFieldBegin(f tocField) string {
  40. instr := ` TOC \o "` + strconv.Itoa(f.from) + `-` + strconv.Itoa(f.to) + `" \h \z \u `
  41. if f.noPages {
  42. instr += `\n `
  43. }
  44. return `<w:r><w:fldChar w:fldCharType="begin"/></w:r>` +
  45. `<w:r><w:instrText xml:space="preserve">` + instr + `</w:instrText></w:r>` +
  46. `<w:r><w:fldChar w:fldCharType="separate"/></w:r>`
  47. }
  48. // tocCfg is the look the editor stores on every entry (data-toc-cfg)
  49. type tocCfg struct {
  50. PageNumbers *bool `json:"pn"`
  51. Levels []int `json:"lv"`
  52. }
  53. // tocFieldOf reads the field of the table whose entries start at c: the
  54. // editor's data-toc-cfg, else data-toc-max (an imported field's range),
  55. // else Heading 1-3
  56. func tocFieldOf(c *html.Node) tocField {
  57. f := tocField{from: 1, to: 3}
  58. max := 0
  59. for n := c; isTocEntry(n); n = nextBlockSibling(n) {
  60. var cfg tocCfg
  61. if raw := htmlutil.Attr(n, "data-toc-cfg"); raw != "" && json.Unmarshal([]byte(raw), &cfg) == nil {
  62. lo, hi := 0, 0
  63. for _, l := range cfg.Levels {
  64. if l < 1 || l > 9 {
  65. continue
  66. }
  67. if lo == 0 || l < lo {
  68. lo = l
  69. }
  70. if l > hi {
  71. hi = l
  72. }
  73. }
  74. if lo > 0 {
  75. f.from, f.to = lo, hi
  76. }
  77. f.noPages = cfg.PageNumbers != nil && !*cfg.PageNumbers
  78. return f
  79. }
  80. if v, err := strconv.Atoi(htmlutil.Attr(n, "data-toc-max")); err == nil && v > max {
  81. max = v
  82. }
  83. }
  84. if max >= 1 {
  85. f.to = max
  86. if f.to > 9 {
  87. f.to = 9
  88. }
  89. }
  90. return f
  91. }
  92. // isTocPara reports a line of a table of contents (title or entry)
  93. func isTocPara(n *html.Node) bool {
  94. return n != nil && n.Type == html.ElementNode && n.Data == "p" && hasClass(n, "doc-toc")
  95. }
  96. // isTocEntry reports a line that lists a heading (not the title)
  97. func isTocEntry(n *html.Node) bool {
  98. return isTocPara(n) && !hasClass(n, "doc-toc-title")
  99. }
  100. // tocStyleOf names the Word paragraph style of a table of contents line
  101. func tocStyleOf(n *html.Node) string {
  102. if hasClass(n, "doc-toc-title") {
  103. return tocHeadingStyle
  104. }
  105. lvl, err := strconv.Atoi(htmlutil.Attr(n, "data-toc-level"))
  106. if err != nil || lvl < 1 {
  107. lvl = 1
  108. } else if lvl > 9 {
  109. lvl = 9
  110. }
  111. return fmt.Sprintf("TOC%d", lvl)
  112. }
  113. // nextBlockSibling is the element after n, past whitespace and comments
  114. func nextBlockSibling(n *html.Node) *html.Node {
  115. for c := n.NextSibling; c != nil; c = c.NextSibling {
  116. switch c.Type {
  117. case html.TextNode:
  118. if strings.TrimSpace(c.Data) != "" {
  119. return c
  120. }
  121. case html.ElementNode:
  122. return c
  123. }
  124. }
  125. return nil
  126. }
  127. // tocRun tracks one table of contents while blocks writes its lines
  128. type tocRun struct {
  129. open bool // inside the building-block control
  130. field bool // inside the TOC field
  131. }
  132. // before is called ahead of every block: it opens the control at a
  133. // table's first line and hands the paragraph writer the field's begin
  134. // (first entry) and end (last entry)
  135. func (t *tocRun) before(c *html.Node, sb *strings.Builder, b *docxBuilder) {
  136. if !isTocPara(c) {
  137. return
  138. }
  139. if !t.open {
  140. sb.WriteString(tocSdtOpen)
  141. t.open = true
  142. }
  143. if !isTocEntry(c) {
  144. return
  145. }
  146. if !t.field {
  147. b.paraPre = tocFieldBegin(tocFieldOf(c))
  148. t.field = true
  149. }
  150. if !isTocEntry(nextBlockSibling(c)) {
  151. b.paraPost = tocFieldEnd
  152. t.field = false
  153. }
  154. }
  155. // close ends the control after a table's last line
  156. func (t *tocRun) close(sb *strings.Builder) {
  157. if !t.open {
  158. return
  159. }
  160. if t.field {
  161. // never left open: Word refuses a field that does not end
  162. sb.WriteString(`<w:p>` + tocFieldEnd + `</w:p>`)
  163. t.field = false
  164. }
  165. sb.WriteString(tocSdtEnd)
  166. t.open = false
  167. }
  168. /* ---------------- reading ----------------
  169. Word styles its entries "toc 1".."toc 9" (tocLevel). Google Docs uses
  170. no style at all: its entries are known only by sitting in the result of
  171. a TOC field, each a link to the heading it lists. Such an entry gets its
  172. level from that heading once the whole body is read (resolveTocLevels). */
  173. // tocLevelUnknown marks an entry whose level is not known yet
  174. const tocLevelUnknown = 99
  175. // tocFieldOpen reports a TOC field whose result is being read
  176. func (cv *docxConv) tocFieldOpen() bool {
  177. for _, f := range cv.fields {
  178. if f.inResult && isTocInstr(f.instr) {
  179. return true
  180. }
  181. }
  182. return false
  183. }
  184. // isTocInstr reports a TOC field instruction (upper-cased by the reader)
  185. func isTocInstr(instr string) bool {
  186. w := strings.Fields(instr)
  187. return len(w) > 0 && strings.EqualFold(w[0], "TOC")
  188. }
  189. var (
  190. tocOutlineSwitch = regexp.MustCompile(`(?i)\\o\s*"\s*(\d+)\s*-\s*(\d+)\s*"`)
  191. tocStylesSwitch = regexp.MustCompile(`(?i)\\t\s*"([^"]*)"`)
  192. tocHeadingName = regexp.MustCompile(`(?i)^\s*heading\s*(\d)\s*$`)
  193. )
  194. // tocInstrMaxLevel reads the deepest heading a TOC field lists: the end of
  195. // its outline range (\o "1-3") or the deepest "Heading N" its style list
  196. // names (\t "Heading 1,1,Heading 2,2,"); 3 when it says neither, as the
  197. // editor's own table does
  198. func tocInstrMaxLevel(instr string) int {
  199. max := 0
  200. if m := tocOutlineSwitch.FindStringSubmatch(instr); m != nil {
  201. if n, err := strconv.Atoi(m[2]); err == nil {
  202. max = n
  203. }
  204. }
  205. if m := tocStylesSwitch.FindStringSubmatch(instr); m != nil {
  206. parts := strings.Split(m[1], ",")
  207. for i := 0; i < len(parts); i += 2 {
  208. if h := tocHeadingName.FindStringSubmatch(parts[i]); h != nil {
  209. if n, _ := strconv.Atoi(h[1]); n > max {
  210. max = n
  211. }
  212. }
  213. }
  214. }
  215. if max < 1 {
  216. return 3
  217. }
  218. if max > 6 {
  219. return 6
  220. }
  221. return max
  222. }
  223. // looksLikeTocEntry tells an entry of a TOC field's result from the empty
  224. // paragraph Word ends the field in: it has text, and a page number after
  225. // a tab or a link to its heading
  226. func looksLikeTocEntry(inner string) bool {
  227. if strings.TrimSpace(stripTags(inner)) == "" {
  228. return false
  229. }
  230. return strings.Contains(inner, "doc-tab") || strings.Contains(inner, `href="#`)
  231. }
  232. var (
  233. tocUnresolvedEntry = regexp.MustCompile(`<p\s[^>]*\bclass="doc-toc"[^>]*>`)
  234. tocEntryLink = regexp.MustCompile(`href="#([^"]+)"`)
  235. headingWithID = regexp.MustCompile(`<h([1-6])\b[^>]*\bid="([^"]+)"`)
  236. )
  237. // resolveTocLevels gives each table of contents entry that has no level
  238. // the level of the heading its link points at
  239. func resolveTocLevels(body string) string {
  240. if !strings.Contains(body, `class="doc-toc"`) {
  241. return body
  242. }
  243. levels := map[string]string{}
  244. for _, m := range headingWithID.FindAllStringSubmatch(body, -1) {
  245. levels[m[2]] = m[1]
  246. }
  247. var sb strings.Builder
  248. last := 0
  249. for _, loc := range tocUnresolvedEntry.FindAllStringIndex(body, -1) {
  250. tag := body[loc[0]:loc[1]]
  251. if strings.Contains(tag, "data-toc-level=") {
  252. continue
  253. }
  254. end := strings.Index(body[loc[1]:], "</p>")
  255. if end < 0 {
  256. continue
  257. }
  258. link := tocEntryLink.FindStringSubmatch(body[loc[1] : loc[1]+end])
  259. if link == nil {
  260. continue
  261. }
  262. lvl, ok := levels[link[1]]
  263. if !ok {
  264. continue
  265. }
  266. sb.WriteString(body[last : loc[1]-1])
  267. sb.WriteString(` data-toc-level="` + lvl + `">`)
  268. last = loc[1]
  269. }
  270. if last == 0 {
  271. return body
  272. }
  273. sb.WriteString(body[last:])
  274. return sb.String()
  275. }
  276. // tocStyleLevel reports which table of contents line a paragraph style
  277. // is: 1-9 for "toc 1".."toc 9", -1 for "TOC Heading", 0 for none
  278. func tocStyleLevel(id, name string) int {
  279. n := strings.ToLower(id)
  280. if name != "" {
  281. n = strings.ToLower(name)
  282. }
  283. compact := strings.ReplaceAll(n, " ", "")
  284. switch {
  285. case compact == "tocheading":
  286. return -1
  287. case len(compact) == 4 && strings.HasPrefix(compact, "toc") && compact[3] >= '1' && compact[3] <= '9':
  288. return int(compact[3] - '0')
  289. }
  290. return 0
  291. }
  292. // tocLevel reports the table of contents line a paragraph style is,
  293. // nearest style first: "TOC Heading" is based on Heading 1 in Word, and
  294. // is a title, not a heading
  295. func (ss *docxStyleSheet) tocLevel(id string) int {
  296. if id == "" {
  297. return 0
  298. }
  299. chain := ss.chain(id)
  300. for i := len(chain) - 1; i >= 0; i-- {
  301. if lvl := tocStyleLevel(chain[i].id, chain[i].name); lvl != 0 {
  302. return lvl
  303. }
  304. }
  305. if len(chain) == 0 {
  306. return tocStyleLevel(id, "")
  307. }
  308. return 0
  309. }