Преглед изворни кода

Add Docs table of contents with DOCX round-trip

The Docs editor's table of contents is now a titled, updatable table framed by an "Update table" tab. Ctrl+click on an entry jumps to its heading, and the table keeps the heading range of an imported field instead of resetting it.

DOCX writer: wraps TOC lines in Word's Table of Contents building-block control with a `TOC \o "1-N" \h \z \u` field. It also emits the `TOC Heading` and `toc 1..9` styles so Word can update the table itself.

DOCX reader: recognises Word's TOC styles, so `TOC Heading` is read as a title rather than a Heading 1. Google Docs writes no TOC styles, so entries inside a TOC field are detected by their content and take their level from the heading they link to. The field's range is preserved as `data-toc-max`.

Also adds tests and README docs, skips the overlay in PDF export and print, and adds locale strings to file_explorer.json for drag-and-drop messages and column resizing.
Toby Chui пре 3 недеља
родитељ
комит
0e269f1b5a

+ 42 - 4
src/mod/office/docx/reader.go

@@ -159,7 +159,7 @@ func Parse(data []byte) (*model.Document, error) {
 		cv.markSpanSections(body)
 	}
 	cv.collectSectionBreaks(body)
-	doc.HTML = cv.blocks(body, docPart, blockCtx{top: true})
+	doc.HTML = resolveTocLevels(cv.blocks(body, docPart, blockCtx{top: true}))
 
 	// footnotes, in the order the text references them
 	if len(cv.fnOrder) > 0 {
@@ -336,9 +336,13 @@ type docxConv struct {
 	marginL   float64 // pt
 	textW     float64 // pt
 	fields    []fieldFrame
-	fnNumber  map[string]int
-	fnOrder   []string
-	parts     map[string]*docxPartCtx
+	// a TOC field was shown or ended in the paragraph at hand, and the
+	// heading levels the last one lists (toc.go)
+	tocTouched bool
+	tocMax     int
+	fnNumber   map[string]int
+	fnOrder    []string
+	parts      map[string]*docxPartCtx
 	// Google Docs exports: a handful of its layout habits are imitated so
 	// the import matches its own PDF (see the gdocs uses)
 	gdocs bool
@@ -781,6 +785,12 @@ func (cv *docxConv) paragraph(p *xmltree.Node, part *docxPartCtx, ctx blockCtx,
 	if direct.style == "" {
 		level = cv.ss.headingLevel(cv.ss.defPara)
 	}
+	// a table of contents line; Word's TOC Heading is based on Heading 1
+	// but titles the table, it is no heading of the document
+	tocLvl := cv.ss.tocLevel(direct.style)
+	if tocLvl != 0 {
+		level = 0
+	}
 
 	// list membership (numbering from the paragraph or its style)
 	var li *docxListItem
@@ -832,7 +842,10 @@ func (cv *docxConv) paragraph(p *xmltree.Node, part *docxPartCtx, ctx blockCtx,
 	// paragraph mark's rPr formats only the mark (the empty line's height,
 	// a list number), so runs must not inherit it - but they are written
 	// against the block, which does
+	inTocField := cv.tocFieldOpen()
+	cv.tocTouched = false
 	runs := cv.runs(p, part, *styleR, baseR)
+	inTocField = inTocField || cv.tocTouched || cv.tocFieldOpen()
 
 	tag := "p"
 	var classes []string
@@ -848,6 +861,18 @@ func (cv *docxConv) paragraph(p *xmltree.Node, part *docxPartCtx, ctx blockCtx,
 	if spanAll {
 		classes = append(classes, "col-span-all")
 	}
+	// a line of a TOC field's result that names no TOC style (Google Docs
+	// writes none): an entry, when it reads like one
+	if tocLvl == 0 && inTocField && level == 0 && looksLikeTocEntry(strings.Join(runs.segments, "")) {
+		tocLvl = tocLevelUnknown
+	}
+	isToc := tocLvl != 0 && li == nil && !ctx.cell && !ctx.hf
+	if isToc {
+		classes = append(classes, "doc-toc")
+		if tocLvl < 0 {
+			classes = append(classes, "doc-toc-title")
+		}
+	}
 
 	style, data := cv.blockStyle(tag, eff, baseR, li != nil, level, runs.preWrap)
 	// CJK text whose East Asian font is a Latin face falls back to a
@@ -869,6 +894,12 @@ func (cv *docxConv) paragraph(p *xmltree.Node, part *docxPartCtx, ctx blockCtx,
 		attrs += ` style="` + style + `"`
 	}
 	attrs += data
+	if isToc && tocLvl > 0 && tocLvl != tocLevelUnknown {
+		attrs += ` data-toc-level="` + strconv.Itoa(tocLvl) + `"`
+	}
+	if isToc && tocLvl > 0 && inTocField && cv.tocMax > 0 {
+		attrs += ` data-toc-max="` + strconv.Itoa(cv.tocMax) + `"`
+	}
 
 	if li != nil {
 		inner := strings.Join(runs.segments, "")
@@ -1481,9 +1512,16 @@ func (cv *docxConv) run(r *xmltree.Node, part *docxPartCtx, baseR docxRPr, block
 			case "separate":
 				if n := len(cv.fields); n > 0 {
 					cv.fields[n-1].inResult = true
+					if isTocInstr(cv.fields[n-1].instr) {
+						cv.tocTouched = true
+						cv.tocMax = tocInstrMaxLevel(cv.fields[n-1].instr)
+					}
 				}
 			case "end":
 				if n := len(cv.fields); n > 0 {
+					if isTocInstr(cv.fields[n-1].instr) {
+						cv.tocTouched = true
+					}
 					// a page number with no stored result (Google Docs
 					// writes none) is still a page number: the layout fills
 					// in each page's own

+ 299 - 0
src/mod/office/docx/toc.go

@@ -0,0 +1,299 @@
+package docx
+
+/*
+	A table of contents
+
+	The editor keeps a table of contents as ordinary paragraphs: a title
+	(p.doc-toc.doc-toc-title) and one line per heading (p.doc-toc with
+	data-toc-level, the heading's text, a right tab with a dot leader and
+	the page number). That is what Word holds once its TOC field has been
+	updated, so the writer wraps a run of those lines in the same frame
+	Word does - a Table of Contents building-block control with a TOC
+	field around the entries - and Word offers its own Update Table on
+	it. The lines use Word's style names (TOC Heading, toc 1..9), which
+	is how the reader recognises a table of contents Word wrote.
+*/
+
+import (
+	"fmt"
+	"regexp"
+	"strconv"
+	"strings"
+
+	"golang.org/x/net/html"
+
+	"imuslab.com/arozos/mod/office/internal/htmlutil"
+)
+
+// tocHeadingStyle is Word's style id of a table of contents' title
+const tocHeadingStyle = "TOCHeading"
+
+const (
+	tocSdtOpen  = `<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique/></w:docPartObj></w:sdtPr><w:sdtContent>`
+	tocSdtEnd   = `</w:sdtContent></w:sdt>`
+	tocFieldEnd = `<w:r><w:fldChar w:fldCharType="end"/></w:r>`
+)
+
+// tocFieldBegin opens the field: the headings the table lists (Heading 1
+// to maxLevel), as hyperlinks, without tab leaders or page numbers in Web
+// view, keeping outline levels
+func tocFieldBegin(maxLevel int) string {
+	return `<w:r><w:fldChar w:fldCharType="begin"/></w:r>` +
+		`<w:r><w:instrText xml:space="preserve"> TOC \o "1-` + strconv.Itoa(maxLevel) + `" \h \z \u </w:instrText></w:r>` +
+		`<w:r><w:fldChar w:fldCharType="separate"/></w:r>`
+}
+
+// tocMaxLevel is the deepest heading level the entries from c on list
+// (data-toc-max, an imported field's range; 3 when none says)
+func tocMaxLevel(c *html.Node) int {
+	max := 0
+	for n := c; isTocEntry(n); n = nextBlockSibling(n) {
+		if v, err := strconv.Atoi(htmlutil.Attr(n, "data-toc-max")); err == nil && v > max {
+			max = v
+		}
+	}
+	if max < 1 {
+		return 3
+	}
+	if max > 9 {
+		return 9
+	}
+	return max
+}
+
+// isTocPara reports a line of a table of contents (title or entry)
+func isTocPara(n *html.Node) bool {
+	return n != nil && n.Type == html.ElementNode && n.Data == "p" && hasClass(n, "doc-toc")
+}
+
+// isTocEntry reports a line that lists a heading (not the title)
+func isTocEntry(n *html.Node) bool {
+	return isTocPara(n) && !hasClass(n, "doc-toc-title")
+}
+
+// tocStyleOf names the Word paragraph style of a table of contents line
+func tocStyleOf(n *html.Node) string {
+	if hasClass(n, "doc-toc-title") {
+		return tocHeadingStyle
+	}
+	lvl, err := strconv.Atoi(htmlutil.Attr(n, "data-toc-level"))
+	if err != nil || lvl < 1 {
+		lvl = 1
+	} else if lvl > 9 {
+		lvl = 9
+	}
+	return fmt.Sprintf("TOC%d", lvl)
+}
+
+// nextBlockSibling is the element after n, past whitespace and comments
+func nextBlockSibling(n *html.Node) *html.Node {
+	for c := n.NextSibling; c != nil; c = c.NextSibling {
+		switch c.Type {
+		case html.TextNode:
+			if strings.TrimSpace(c.Data) != "" {
+				return c
+			}
+		case html.ElementNode:
+			return c
+		}
+	}
+	return nil
+}
+
+// tocRun tracks one table of contents while blocks writes its lines
+type tocRun struct {
+	open  bool // inside the building-block control
+	field bool // inside the TOC field
+}
+
+// before is called ahead of every block: it opens the control at a
+// table's first line and hands the paragraph writer the field's begin
+// (first entry) and end (last entry)
+func (t *tocRun) before(c *html.Node, sb *strings.Builder, b *docxBuilder) {
+	if !isTocPara(c) {
+		return
+	}
+	if !t.open {
+		sb.WriteString(tocSdtOpen)
+		t.open = true
+	}
+	if !isTocEntry(c) {
+		return
+	}
+	if !t.field {
+		b.paraPre = tocFieldBegin(tocMaxLevel(c))
+		t.field = true
+	}
+	if !isTocEntry(nextBlockSibling(c)) {
+		b.paraPost = tocFieldEnd
+		t.field = false
+	}
+}
+
+// close ends the control after a table's last line
+func (t *tocRun) close(sb *strings.Builder) {
+	if !t.open {
+		return
+	}
+	if t.field {
+		// never left open: Word refuses a field that does not end
+		sb.WriteString(`<w:p>` + tocFieldEnd + `</w:p>`)
+		t.field = false
+	}
+	sb.WriteString(tocSdtEnd)
+	t.open = false
+}
+
+/* ---------------- reading ----------------
+
+   Word styles its entries "toc 1".."toc 9" (tocLevel). Google Docs uses
+   no style at all: its entries are known only by sitting in the result of
+   a TOC field, each a link to the heading it lists. Such an entry gets its
+   level from that heading once the whole body is read (resolveTocLevels). */
+
+// tocLevelUnknown marks an entry whose level is not known yet
+const tocLevelUnknown = 99
+
+// tocFieldOpen reports a TOC field whose result is being read
+func (cv *docxConv) tocFieldOpen() bool {
+	for _, f := range cv.fields {
+		if f.inResult && isTocInstr(f.instr) {
+			return true
+		}
+	}
+	return false
+}
+
+// isTocInstr reports a TOC field instruction (upper-cased by the reader)
+func isTocInstr(instr string) bool {
+	w := strings.Fields(instr)
+	return len(w) > 0 && strings.EqualFold(w[0], "TOC")
+}
+
+var (
+	tocOutlineSwitch = regexp.MustCompile(`(?i)\\o\s*"\s*(\d+)\s*-\s*(\d+)\s*"`)
+	tocStylesSwitch  = regexp.MustCompile(`(?i)\\t\s*"([^"]*)"`)
+	tocHeadingName   = regexp.MustCompile(`(?i)^\s*heading\s*(\d)\s*$`)
+)
+
+// tocInstrMaxLevel reads the deepest heading a TOC field lists: the end of
+// its outline range (\o "1-3") or the deepest "Heading N" its style list
+// names (\t "Heading 1,1,Heading 2,2,"); 3 when it says neither, as the
+// editor's own table does
+func tocInstrMaxLevel(instr string) int {
+	max := 0
+	if m := tocOutlineSwitch.FindStringSubmatch(instr); m != nil {
+		if n, err := strconv.Atoi(m[2]); err == nil {
+			max = n
+		}
+	}
+	if m := tocStylesSwitch.FindStringSubmatch(instr); m != nil {
+		parts := strings.Split(m[1], ",")
+		for i := 0; i < len(parts); i += 2 {
+			if h := tocHeadingName.FindStringSubmatch(parts[i]); h != nil {
+				if n, _ := strconv.Atoi(h[1]); n > max {
+					max = n
+				}
+			}
+		}
+	}
+	if max < 1 {
+		return 3
+	}
+	if max > 6 {
+		return 6
+	}
+	return max
+}
+
+// looksLikeTocEntry tells an entry of a TOC field's result from the empty
+// paragraph Word ends the field in: it has text, and a page number after
+// a tab or a link to its heading
+func looksLikeTocEntry(inner string) bool {
+	if strings.TrimSpace(stripTags(inner)) == "" {
+		return false
+	}
+	return strings.Contains(inner, "doc-tab") || strings.Contains(inner, `href="#`)
+}
+
+var (
+	tocUnresolvedEntry = regexp.MustCompile(`<p\s[^>]*\bclass="doc-toc"[^>]*>`)
+	tocEntryLink       = regexp.MustCompile(`href="#([^"]+)"`)
+	headingWithID      = regexp.MustCompile(`<h([1-6])\b[^>]*\bid="([^"]+)"`)
+)
+
+// resolveTocLevels gives each table of contents entry that has no level
+// the level of the heading its link points at
+func resolveTocLevels(body string) string {
+	if !strings.Contains(body, `class="doc-toc"`) {
+		return body
+	}
+	levels := map[string]string{}
+	for _, m := range headingWithID.FindAllStringSubmatch(body, -1) {
+		levels[m[2]] = m[1]
+	}
+	var sb strings.Builder
+	last := 0
+	for _, loc := range tocUnresolvedEntry.FindAllStringIndex(body, -1) {
+		tag := body[loc[0]:loc[1]]
+		if strings.Contains(tag, "data-toc-level=") {
+			continue
+		}
+		end := strings.Index(body[loc[1]:], "</p>")
+		if end < 0 {
+			continue
+		}
+		link := tocEntryLink.FindStringSubmatch(body[loc[1] : loc[1]+end])
+		if link == nil {
+			continue
+		}
+		lvl, ok := levels[link[1]]
+		if !ok {
+			continue
+		}
+		sb.WriteString(body[last : loc[1]-1])
+		sb.WriteString(` data-toc-level="` + lvl + `">`)
+		last = loc[1]
+	}
+	if last == 0 {
+		return body
+	}
+	sb.WriteString(body[last:])
+	return sb.String()
+}
+
+// tocStyleLevel reports which table of contents line a paragraph style
+// is: 1-9 for "toc 1".."toc 9", -1 for "TOC Heading", 0 for none
+func tocStyleLevel(id, name string) int {
+	n := strings.ToLower(id)
+	if name != "" {
+		n = strings.ToLower(name)
+	}
+	compact := strings.ReplaceAll(n, " ", "")
+	switch {
+	case compact == "tocheading":
+		return -1
+	case len(compact) == 4 && strings.HasPrefix(compact, "toc") && compact[3] >= '1' && compact[3] <= '9':
+		return int(compact[3] - '0')
+	}
+	return 0
+}
+
+// tocLevel reports the table of contents line a paragraph style is,
+// nearest style first: "TOC Heading" is based on Heading 1 in Word, and
+// is a title, not a heading
+func (ss *docxStyleSheet) tocLevel(id string) int {
+	if id == "" {
+		return 0
+	}
+	chain := ss.chain(id)
+	for i := len(chain) - 1; i >= 0; i-- {
+		if lvl := tocStyleLevel(chain[i].id, chain[i].name); lvl != 0 {
+			return lvl
+		}
+	}
+	if len(chain) == 0 {
+		return tocStyleLevel(id, "")
+	}
+	return 0
+}

+ 267 - 0
src/mod/office/docx/toc_test.go

@@ -0,0 +1,267 @@
+package docx
+
+import (
+	"strings"
+	"testing"
+
+	"imuslab.com/arozos/mod/office/internal/officetest"
+	"imuslab.com/arozos/mod/office/model"
+)
+
+const tocTestHTML = `<p class="doc-toc doc-toc-title" style="font-size:16pt;margin-bottom:6pt;">Contents</p>` +
+	`<p class="doc-toc" data-toc-level="1" data-tabs="right:451.3:dot" style="margin-left:0pt;margin-bottom:3pt;">Intro<span class="doc-tab"></span>2</p>` +
+	`<p class="doc-toc" data-toc-level="2" data-tabs="right:451.3:dot" style="margin-left:14pt;margin-bottom:3pt;">Scope<span class="doc-tab"></span>3</p>` +
+	`<p>After the table</p><h1>Intro</h1><p>text</p><h2>Scope</h2>`
+
+func buildTocDocx(t *testing.T, html string) (body, styles string) {
+	t.Helper()
+	data, err := Build(&model.Document{HTML: html})
+	if err != nil {
+		t.Fatalf("Build: %v", err)
+	}
+	return string(officetest.ZipPart(t, data, "word/document.xml")), string(officetest.ZipPart(t, data, "word/styles.xml"))
+}
+
+func TestDocxTocExport(t *testing.T) {
+	body, styles := buildTocDocx(t, tocTestHTML)
+	order := []string{
+		`<w:docPartGallery w:val="Table of Contents"/>`,
+		`<w:pStyle w:val="TOCHeading"/>`, "Contents",
+		`<w:pStyle w:val="TOC1"/>`, `w:fldCharType="begin"`, `TOC \o "1-3" \h \z \u`, `w:fldCharType="separate"`, "Intro",
+		`<w:pStyle w:val="TOC2"/>`, "Scope", `w:fldCharType="end"`,
+		`</w:sdtContent></w:sdt>`, "After the table",
+	}
+	at := 0
+	for _, want := range order {
+		i := strings.Index(body[at:], want)
+		if i < 0 {
+			t.Fatalf("missing or out of order: %q after offset %d in %s", want, at, body)
+		}
+		at += i + len(want)
+	}
+	for _, want := range []string{"<w:sdt>", `w:fldCharType="begin"`, `w:fldCharType="end"`} {
+		if n := strings.Count(body, want); n != 1 {
+			t.Errorf("%q written %d times, want once", want, n)
+		}
+	}
+	for _, want := range []string{`w:styleId="TOCHeading"`, `<w:name w:val="TOC Heading"/>`, `w:styleId="TOC1"`, `<w:name w:val="toc 2"/>`} {
+		if !strings.Contains(styles, want) {
+			t.Errorf("styles.xml lacks %s", want)
+		}
+	}
+	if strings.Contains(body, "doc-toc") {
+		t.Error("the editor class leaked into document.xml")
+	}
+}
+
+func TestDocxTocFieldEdges(t *testing.T) {
+	tests := []struct {
+		name               string
+		html               string
+		sdts, begins, ends int
+	}{
+		{"one entry opens and closes the field", `<p class="doc-toc" data-toc-level="1">Only<span class="doc-tab"></span>1</p>`, 1, 1, 1},
+		{"title alone has no field", `<p class="doc-toc doc-toc-title">Contents</p><p>x</p>`, 1, 0, 0},
+		{"two tables are two controls", `<p class="doc-toc" data-toc-level="1">A</p><p>gap</p><p class="doc-toc" data-toc-level="1">B</p>`, 2, 2, 2},
+		{"no table, no control", `<p>plain</p><h1>Head</h1>`, 0, 0, 0},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			body, _ := buildTocDocx(t, tc.html)
+			if n := strings.Count(body, "<w:sdt>"); n != tc.sdts {
+				t.Errorf("sdt count = %d, want %d", n, tc.sdts)
+			}
+			if n := strings.Count(body, "</w:sdt>"); n != tc.sdts {
+				t.Errorf("sdt end count = %d, want %d", n, tc.sdts)
+			}
+			if n := strings.Count(body, `w:fldCharType="begin"`); n != tc.begins {
+				t.Errorf("field begins = %d, want %d", n, tc.begins)
+			}
+			if n := strings.Count(body, `w:fldCharType="end"`); n != tc.ends {
+				t.Errorf("field ends = %d, want %d", n, tc.ends)
+			}
+		})
+	}
+}
+
+func TestDocxTocRoundTrip(t *testing.T) {
+	data, err := Build(&model.Document{HTML: tocTestHTML})
+	if err != nil {
+		t.Fatalf("Build: %v", err)
+	}
+	back, err := Parse(data)
+	if err != nil {
+		t.Fatalf("Parse: %v", err)
+	}
+	h := back.HTML
+	for _, want := range []string{`class="doc-toc doc-toc-title"`, `data-toc-level="1"`, `data-toc-level="2"`, "Scope"} {
+		if !strings.Contains(h, want) {
+			t.Errorf("round trip lost %s: %s", want, h)
+		}
+	}
+	if strings.Contains(h, `TOC \o`) || strings.Contains(h, "TOC \\O") {
+		t.Errorf("field instruction leaked into the text: %s", h)
+	}
+	// the title is a line of the table, not a heading it would list
+	if strings.Count(h, "<h1") != 1 {
+		t.Errorf("want only the document's own Heading 1, got: %s", h)
+	}
+}
+
+// a table of contents as Word writes it: TOC Heading based on Heading 1,
+// hyperlinked entries with PAGEREF page numbers
+func TestDocxReadsWordToc(t *testing.T) {
+	styles := `<?xml version="1.0" encoding="UTF-8"?><w:styles ` + wNS + `>` +
+		`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:pPr><w:outlineLvl w:val="0"/></w:pPr></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="TOCHeading"><w:name w:val="TOC Heading"/><w:basedOn w:val="Heading1"/><w:pPr><w:outlineLvl w:val="9"/></w:pPr></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="TOC1"><w:name w:val="toc 1"/><w:basedOn w:val="Normal"/></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="MyToc2"><w:name w:val="toc 2"/><w:basedOn w:val="Normal"/></w:style>` +
+		`</w:styles>`
+	body := `<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Table of Contents"/></w:docPartObj></w:sdtPr><w:sdtContent>` +
+		`<w:p><w:pPr><w:pStyle w:val="TOCHeading"/></w:pPr><w:r><w:t>Table of Contents</w:t></w:r></w:p>` +
+		`<w:p><w:pPr><w:pStyle w:val="TOC1"/><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="9350"/></w:tabs></w:pPr>` +
+		`<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> TOC \o "1-3" \h \z \u </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r>` +
+		`<w:hyperlink w:anchor="_Toc1"><w:r><w:t>Chapter One</w:t></w:r><w:r><w:tab/></w:r>` +
+		`<w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> PAGEREF _Toc1 \h </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>4</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:hyperlink></w:p>` +
+		`<w:p><w:pPr><w:pStyle w:val="MyToc2"/></w:pPr><w:r><w:t>Part A</w:t></w:r><w:r><w:tab/></w:r><w:r><w:t>5</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>` +
+		`</w:sdtContent></w:sdt>` +
+		`<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Chapter One</w:t></w:r></w:p>`
+	doc := parseTestDocx(t, body, map[string]string{"word/styles.xml": styles})
+	h := doc.HTML
+	for _, want := range []string{`class="doc-toc doc-toc-title"`, `data-toc-level="1"`, `data-toc-level="2"`, "Chapter One", ">4<", "Part A"} {
+		if !strings.Contains(h, want) {
+			t.Errorf("Word table of contents lost %s: %s", want, h)
+		}
+	}
+	if strings.Count(h, "<h1") != 1 {
+		t.Errorf("TOC Heading must not read as a heading: %s", h)
+	}
+	if strings.Contains(h, "PAGEREF") {
+		t.Errorf("field instruction leaked into the text: %s", h)
+	}
+}
+
+func TestTocStyleLevel(t *testing.T) {
+	tests := []struct {
+		id, name string
+		want     int
+	}{
+		{"TOC1", "toc 1", 1},
+		{"TOC3", "", 3},
+		{"Custom", "toc 9", 9},
+		{"TOCHeading", "TOC Heading", -1},
+		{"TOCHeading", "", -1},
+		{"Heading1", "heading 1", 0},
+		{"TOC10", "", 0},
+		{"Normal", "Normal", 0},
+		{"TOC", "", 0},
+	}
+	for _, tc := range tests {
+		if got := tocStyleLevel(tc.id, tc.name); got != tc.want {
+			t.Errorf("tocStyleLevel(%q, %q) = %d, want %d", tc.id, tc.name, got, tc.want)
+		}
+	}
+}
+
+// a table of contents as Google Docs exports it: no TOC styles, only a TOC
+// field listing Heading 1-6 whose entries link to the headings' bookmarks,
+// and a "Table of Contents" Heading 3 above the control
+func TestDocxReadsGoogleDocsToc(t *testing.T) {
+	entry := func(anchor, text, page string, first, last bool) string {
+		s := `<w:p><w:pPr><w:tabs><w:tab w:val="right" w:leader="none" w:pos="9025"/></w:tabs></w:pPr>`
+		if first {
+			s += `<w:r><w:fldChar w:fldCharType="begin"/><w:instrText xml:space="preserve"> TOC \h \u \z \t &quot;Heading 1,1,Heading 2,2,Heading 3,3,Heading 4,4,Heading 5,5,Heading 6,6,&quot;</w:instrText><w:fldChar w:fldCharType="separate"/></w:r>`
+		}
+		s += `<w:hyperlink w:anchor="` + anchor + `"><w:r><w:t>` + text + `</w:t></w:r></w:hyperlink><w:r><w:tab/></w:r>` +
+			`<w:r><w:fldChar w:fldCharType="begin"/><w:instrText xml:space="preserve"> PAGEREF ` + anchor + ` \h </w:instrText><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>` + page + `</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r>`
+		if last {
+			s += `<w:r><w:fldChar w:fldCharType="end"/></w:r>`
+		}
+		return s + `</w:p>`
+	}
+	heading := func(style, anchor, text string) string {
+		return `<w:p><w:pPr><w:pStyle w:val="` + style + `"/></w:pPr><w:bookmarkStart w:id="1" w:name="` + anchor + `"/><w:bookmarkEnd w:id="1"/><w:r><w:t>` + text + `</w:t></w:r></w:p>`
+	}
+	styles := `<?xml version="1.0" encoding="UTF-8"?><w:styles ` + wNS + `>` +
+		`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="Heading3"><w:name w:val="heading 3"/><w:basedOn w:val="Normal"/></w:style>` +
+		`<w:style w:type="paragraph" w:styleId="Heading4"><w:name w:val="heading 4"/><w:basedOn w:val="Normal"/></w:style>` +
+		`</w:styles>`
+	body := heading("Heading3", "_toc", "Table of Contents") +
+		`<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val="Table of Contents"/><w:docPartUnique w:val="1"/></w:docPartObj></w:sdtPr><w:sdtContent>` +
+		entry("_a", "Overview", "1", true, false) +
+		entry("_b", "Goals", "2", false, false) +
+		entry("_c", "Minimal", "3", false, true) +
+		`</w:sdtContent></w:sdt>` +
+		`<w:p><w:r><w:t>Body text</w:t></w:r></w:p>` +
+		heading("Heading2", "_a", "Overview") + heading("Heading3", "_b", "Goals") + heading("Heading4", "_c", "Minimal")
+	h := parseTestDocx(t, body, map[string]string{"word/styles.xml": styles}).HTML
+	if n := strings.Count(h, `class="doc-toc"`); n != 3 {
+		t.Fatalf("want 3 entries, got %d: %s", n, h)
+	}
+	for _, want := range []string{`data-toc-level="2"`, `data-toc-level="3"`, `data-toc-level="4"`, `data-toc-max="6"`} {
+		if !strings.Contains(h, want) {
+			t.Errorf("entry attributes lack %s: %s", want, h)
+		}
+	}
+	// the heading above the control is a heading of the document, and the
+	// paragraphs after the field are no entries
+	if !strings.Contains(h, ">Table of Contents</h3>") {
+		t.Errorf("the Heading 3 title must stay a heading: %s", h)
+	}
+	if i := strings.Index(h, "Body text"); i < 0 || strings.Contains(h[i-80:i], "doc-toc") {
+		t.Errorf("text after the field read as an entry: %s", h)
+	}
+}
+
+func TestDocxTocFieldLevelRange(t *testing.T) {
+	tests := []struct {
+		html, want string
+	}{
+		{`<p class="doc-toc" data-toc-level="2">A</p>`, `TOC \o "1-3"`},
+		{`<p class="doc-toc" data-toc-level="2" data-toc-max="6">A</p><p class="doc-toc" data-toc-level="5" data-toc-max="6">B</p>`, `TOC \o "1-6"`},
+	}
+	for _, tc := range tests {
+		body, _ := buildTocDocx(t, tc.html)
+		if !strings.Contains(body, tc.want) {
+			t.Errorf("%s: want %s in %s", tc.html, tc.want, body)
+		}
+	}
+}
+
+func TestTocInstrMaxLevel(t *testing.T) {
+	tests := []struct {
+		instr string
+		want  int
+	}{
+		{`TOC \O "1-3" \H \Z \U`, 3},
+		{`TOC \o "1-4"`, 4},
+		{`TOC \H \U \Z \T "HEADING 1,1,HEADING 2,2,HEADING 3,3,HEADING 4,4,HEADING 5,5,HEADING 6,6,"`, 6},
+		{`TOC \T "MY STYLE,1,HEADING 2,2"`, 2},
+		{`TOC \H \Z`, 3},
+		{`TOC \O "1-9"`, 6},
+	}
+	for _, tc := range tests {
+		if got := tocInstrMaxLevel(tc.instr); got != tc.want {
+			t.Errorf("tocInstrMaxLevel(%q) = %d, want %d", tc.instr, got, tc.want)
+		}
+	}
+}
+
+func TestResolveTocLevels(t *testing.T) {
+	tests := []struct {
+		name, in, want string
+	}{
+		{"by link", `<p class="doc-toc" style="x"><a href="#_a">A</a></p><h2 id="_a">A</h2>`, `<p class="doc-toc" style="x" data-toc-level="2">`},
+		{"level kept", `<p class="doc-toc" data-toc-level="1"><a href="#_a">A</a></p><h4 id="_a">A</h4>`, `data-toc-level="1">`},
+		{"no target", `<p class="doc-toc"><a href="#_zz">A</a></p><h2 id="_a">A</h2>`, `<p class="doc-toc"><a`},
+		{"no toc", `<p>x</p>`, `<p>x</p>`},
+	}
+	for _, tc := range tests {
+		if got := resolveTocLevels(tc.in); !strings.Contains(got, tc.want) {
+			t.Errorf("%s: got %s, want it to contain %s", tc.name, got, tc.want)
+		}
+	}
+}

+ 23 - 0
src/mod/office/docx/writer.go

@@ -731,6 +731,9 @@ type docxBuilder struct {
 	lastSpan    bool
 	anyBlock    bool
 	usedDivider bool
+	// runs the next paragraph writes before and after its text: the
+	// begin and end of a table of contents' TOC field
+	paraPre, paraPost string
 }
 
 // Build serializes a Document into a complete .docx file; pictures
@@ -1309,6 +1312,9 @@ func (b *docxBuilder) blockStyleOf(n *html.Node, parent wRunStyle) (pProps, wRun
 	if id := htmlutil.Attr(n, "id"); id != "" {
 		pp.bookmark = id
 	}
+	if hasClass(n, "doc-toc") {
+		pp.style = tocStyleOf(n)
+	}
 	return pp, rs
 }
 
@@ -1344,6 +1350,7 @@ func tabsXML(v string) string {
 
 // blocks emits the block-level children of an element
 func (b *docxBuilder) blocks(n *html.Node, part *docxPart, rs wRunStyle, sb *strings.Builder, top bool) {
+	var toc tocRun
 	var pending *html.Node // first of a run of stray inline nodes
 	flushInline := func(stop *html.Node) {
 		if pending == nil {
@@ -1370,6 +1377,9 @@ func (b *docxBuilder) blocks(n *html.Node, part *docxPart, rs wRunStyle, sb *str
 			continue
 		}
 		flushInline(c)
+		if !isTocPara(c) {
+			toc.close(sb)
+		}
 		if top && b.multiCol {
 			span := hasClass(c, "col-span-all")
 			if b.anyBlock && b.lastSpan && !span {
@@ -1383,9 +1393,11 @@ func (b *docxBuilder) blocks(n *html.Node, part *docxPart, rs wRunStyle, sb *str
 			}
 		}
 		b.anyBlock = true
+		toc.before(c, sb, b)
 		b.block(c, part, rs, sb)
 	}
 	flushInline(nil)
+	toc.close(sb)
 }
 
 func isBlockElement(n *html.Node) bool {
@@ -1511,6 +1523,11 @@ func (b *docxBuilder) paragraph(first, stop *html.Node, pp pProps, rs wRunStyle,
 		sb.WriteString(fmt.Sprintf(`<w:bookmarkStart w:id="%d" w:name="%s"/><w:bookmarkEnd w:id="%d"/>`,
 			b.bookmarkN, xmltree.Escape(pp.bookmark), b.bookmarkN))
 	}
+	if b.paraPre != "" || b.paraPost != "" {
+		runs = b.paraPre + runs + b.paraPost
+		rb.any = true
+		b.paraPre, b.paraPost = "", ""
+	}
 	sb.WriteString(runs)
 	if !rb.any {
 		// the paragraph mark carries the size an empty line is laid out in
@@ -2387,6 +2404,12 @@ func docxStylesXML(doc *model.Document) string {
 			`<w:pPr>%s<w:spacing w:before="%d" w:after="%d"/></w:pPr><w:rPr>%s</w:rPr></w:style>`,
 			d.style, n.name, keep, twip(d.beforePt), twip(d.afterPt), rpr))
 	}
+	// a table of contents: Word's own style names, so Word and the reader
+	// know the lines for what they are (the look is on each paragraph)
+	sb.WriteString(`<w:style w:type="paragraph" w:styleId="` + tocHeadingStyle + `"><w:name w:val="TOC Heading"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="39"/><w:unhideWhenUsed/><w:qFormat/></w:style>`)
+	for lvl := 1; lvl <= 9; lvl++ {
+		sb.WriteString(fmt.Sprintf(`<w:style w:type="paragraph" w:styleId="TOC%d"><w:name w:val="toc %d"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="39"/><w:unhideWhenUsed/></w:style>`, lvl, lvl))
+	}
 	sb.WriteString(`<w:style w:type="paragraph" w:customStyle="1" w:styleId="` + autoRuleStyle + `"><w:name w:val="Horizontal Rule"/></w:style>`)
 	sb.WriteString(`<w:style w:type="paragraph" w:customStyle="1" w:styleId="` + autoPageNumberStyle + `"><w:name w:val="Page Number Line"/><w:pPr><w:jc w:val="center"/></w:pPr></w:style>`)
 	sb.WriteString(`<w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style>`)

+ 42 - 0
src/system/locale/file_explorer.json

@@ -235,6 +235,13 @@
                 "message/folderCannotOpen": "無法開啟此資料夾",
                 "message/folderCannotOpen/codedesc": "伺服器端回傳以下錯誤訊息: ",
                 "message/destIdentical": "檔案來源與目的地相同",
+                "message/drop/intoItself": "無法將資料夾移動到其本身",
+                "message/drop/intoSubfolder": "無法將資料夾移動到其子資料夾內",
+                "message/drop/alreadyHere": "項目已在此資料夾內",
+                "drop/uploadTo": "上傳至「{name}」",
+                "drop/moveTo": "移動至「{name}」",
+                "drop/copyTo": "複製至「{name}」",
+                "list/resizeColumn": "拖曳以調整寬度,按兩下以重設",
                 "message/decodeFilelistFail": "載案置入失敗:無法讀取檔案列表",
                 "message/uploadFailed": "載案上載失敗:檔案太大或目標儲存裝置已滿",
                 "message/newFilenameIdentical": "重新命名失敗:新舊檔案名稱相同",
@@ -596,6 +603,13 @@
                 "message/noMatchResultsDesc": "伺服器找不到與此關鍵字匹配的檔案",
                 "message/noMatchResultsInst": "請檢查你的關鍵字或通配符是否正確。",
                 "message/destIdentical": "檔案來源與目的地相同",
+                "message/drop/intoItself": "無法將資料夾移動到其本身",
+                "message/drop/intoSubfolder": "無法將資料夾移動到其子資料夾內",
+                "message/drop/alreadyHere": "項目已在此資料夾內",
+                "drop/uploadTo": "上傳至「{name}」",
+                "drop/moveTo": "移動至「{name}」",
+                "drop/copyTo": "複製至「{name}」",
+                "list/resizeColumn": "拖曳以調整闊度,按兩下以重設",
                 "message/decodeFilelistFail": "載案置入失敗:無法讀取檔案列表",
                 "message/uploadFailed": "載案上載失敗:檔案太大或目標儲存裝置已滿",
                 "message/newFilenameIdentical": "重新命名失敗:新舊檔案名稱相同",
@@ -958,6 +972,13 @@
                 "message/noMatchResultsDesc": "服务器找不到与此关键词匹配的文件",
                 "message/noMatchResultsInst": "请检查你的关键词或通配符是否正确。",
                 "message/destIdentical": "文件来源及目标相同",
+                "message/drop/intoItself": "无法将文件夹移动到其自身",
+                "message/drop/intoSubfolder": "无法将文件夹移动到其子文件夹中",
+                "message/drop/alreadyHere": "项目已在此文件夹中",
+                "drop/uploadTo": "上传至“{name}”",
+                "drop/moveTo": "移动至“{name}”",
+                "drop/copyTo": "复制至“{name}”",
+                "list/resizeColumn": "拖动以调整宽度,双击以重置",
                 "message/decodeFilelistFail": "文件加载失败:无法读取文件列表",
                 "message/uploadFailed": "文件上传失败:文件太大或目标存储设备已满",
                 "message/newFilenameIdentical": "重命名失败:新旧文件名称相同",
@@ -1322,6 +1343,13 @@
                 "message/noMatchResultsDesc": "The server could not find any files that match the keyword.",
                 "message/noMatchResultsInst": "Please check that your keyword or wildcard is correct.",
                 "message/destIdentical": "Source and destination are identical",
+                "message/drop/intoItself": "A folder cannot be moved into itself",
+                "message/drop/intoSubfolder": "A folder cannot be moved into its own subfolder",
+                "message/drop/alreadyHere": "Already in this folder",
+                "drop/uploadTo": "Upload to “{name}”",
+                "drop/moveTo": "Move to “{name}”",
+                "drop/copyTo": "Copy to “{name}”",
+                "list/resizeColumn": "Drag to resize, double click to reset",
                 "message/decodeFilelistFail": "Failed to load folder: could not read the file list.",
                 "message/uploadFailed": "File upload failed: file is too large or the storage device is full.",
                 "message/newFilenameIdentical": "Failed to rename file: new name is identical to the old name.",
@@ -1687,6 +1715,13 @@
                 "message/noMatchResultsDesc": "サーバーがキーワードに一致するファイルを見つけられませんでした。",
                 "message/noMatchResultsInst": "キーワードまたはワイルドカードが正しいかどうかを確認してください。",
                 "message/destIdentical": "ソースと宛先が同じです",
+                "message/drop/intoItself": "フォルダーをそれ自体に移動することはできません",
+                "message/drop/intoSubfolder": "フォルダーをそのサブフォルダーに移動することはできません",
+                "message/drop/alreadyHere": "既にこのフォルダーにあります",
+                "drop/uploadTo": "「{name}」にアップロード",
+                "drop/moveTo": "「{name}」に移動",
+                "drop/copyTo": "「{name}」にコピー",
+                "list/resizeColumn": "ドラッグで幅を変更、ダブルクリックでリセット",
                 "message/decodeFilelistFail": "フォルダを読み込めませんでした:ファイルリストを読み込めませんでした",
                 "message/uploadFailed": "ファイルのアップロードに失敗しました:ファイルが大きすぎるか、ストレージデバイスがいっぱいです。",
                 "message/newFilenameIdentical": "ファイル名の変更に失敗しました:新しい名前が古い名前と同じです。",
@@ -2056,6 +2091,13 @@
                 "message/folderCannotOpen": "이 폴더를 열 수 없습니다",
                 "message/folderCannotOpen/codedesc": "서버 측에서 다음 오류 메시지를 반환했습니다: ",
                 "message/destIdentical": "소스 및 대상 경로가 동일합니다",
+                "message/drop/intoItself": "폴더를 자기 자신으로 이동할 수 없습니다",
+                "message/drop/intoSubfolder": "폴더를 하위 폴더로 이동할 수 없습니다",
+                "message/drop/alreadyHere": "이미 이 폴더에 있습니다",
+                "drop/uploadTo": "“{name}”(으)로 업로드",
+                "drop/moveTo": "“{name}”(으)로 이동",
+                "drop/copyTo": "“{name}”(으)로 복사",
+                "list/resizeColumn": "드래그하여 크기 조정, 더블 클릭하여 초기화",
                 "message/decodeFilelistFail": "파일 목록을 읽을 수 없어 파일 로드 실패",
                 "message/uploadFailed": "파일 업로드 실패: 파일이 너무 크거나 대상 저장 장치가 가득 찼습니다",
                 "message/newFilenameIdentical": "이름 변경 실패: 새로운 파일 이름이 기존과 동일합니다",

+ 47 - 3
src/web/Office/README.md

@@ -173,9 +173,9 @@ every format keeps it):
   superscript (Ctrl+, / Ctrl+.), paragraph shading and borders (the .docx
   writer's `w:shd` / `w:pBdr`), sort paragraphs, formatting marks (an
   absolutely positioned pilcrow, so it cannot move a line), format painter,
-  footnotes (Ctrl+Alt+F), a table of contents (heading text, a right tab with
-  a dot leader and the page number as laid out now - Update table redoes
-  it), margin / orientation / size presets, word count, page-width zoom.
+  footnotes (Ctrl+Alt+F), a table of contents (see
+  [Docs: table of contents](#docs-table-of-contents)), margin / orientation
+  / size presets, word count, page-width zoom.
 - Sheets: font family, size in points, strikethrough (Ctrl+5) and vertical
   alignment (`s.ff`, `s.st`, `s.va` - written to and read from .xlsx and
   .ods), merge and center, the number-format box and comma style, cell
@@ -1213,6 +1213,50 @@ horizontal offset: `text-align` cannot move a block image, so the Home
 align buttons call `alignPicture` while a picture is selected, and a
 centred or right-set picture is placed again whenever its width changes.
 
+### Docs: table of contents
+
+References > Table of contents inserts a "Contents" title and one line
+per Heading 1-3 (not the Title): the heading's text, a right tab with a
+dot leader at the margin and the page it is on as laid out now. They are
+**ordinary paragraphs** - `p.doc-toc` (`.doc-toc-title` for the title,
+`data-toc-level` on an entry, `data-toc-max` the deepest heading the
+table lists when it is not 3) - so the layout, the PDF and every writer
+handle them like any text, and nothing new had to be taught to the
+paginator: a long table splits across pages like any paragraphs.
+
+- **The area and its tab** are editor chrome, not content:
+  `drawTocOverlay()` in `docs.js` puts a `.doc-toc-frame` in `#page`
+  (layout px, zoomed with the page) with one box per page the table covers
+  and an "Update table" tab above the first, while the caret is in the
+  table (solid) or the mouse is over it (dashed). It is never saved, print
+  hides it and `docs_pdf.js` skips it. A table is a run of `.doc-toc`
+  paragraphs that follow each other (`tocGroups()`), so two tables are
+  updated separately.
+- **Update** (the tab, or Update table on the ribbon, which does every
+  table) undoes the page splits first, replaces the entry lines and lays
+  the document out again until the page numbers stop changing (the new
+  lines can push a heading onto the next page). The title and anything
+  the user typed outside the entries stay. Ctrl+click an entry goes to its
+  heading (matched by level and text).
+- **DOCX**: the writer ([`mod/office/docx/toc.go`](../../mod/office/docx/toc.go))
+  wraps a table in Word's Table of Contents building-block control
+  (`w:sdt` with `docPartGallery`) and the entries in a
+  `TOC \o "1-3" \h \z \u` field, and styles the lines with Word's
+  `TOC Heading` / `toc 1..9` styles, so Word offers its own Update Table.
+  The reader maps those styles back to `.doc-toc` - Word's `TOC Heading`
+  is based on Heading 1, so `tocLevel` is asked before `headingLevel`
+  would call the title a heading. **Google Docs** writes no TOC styles:
+  its entries are only the result of a `TOC \t "Heading 1,1,...Heading
+  6,6,"` field, each a link to its heading's bookmark (and its "Table of
+  Contents" title is a real Heading 3 outside the control, listed in the
+  table itself). So a paragraph shown inside a TOC field that has text
+  and a tab or a `#` link is an entry too; its level comes from the
+  heading its link points at once the body is read (`resolveTocLevels`),
+  and the field's range becomes `data-toc-max` (an update must not drop
+  the Heading 4-6 lines). An update indents from the top level present,
+  so a document whose chapters are Heading 2 still starts at the margin.
+  ODT has no table of contents element yet (the lines export as text).
+
 ### Header / footer
 
 The header and footer are one editable pair per **simulated** page: the

+ 49 - 0
src/web/Office/docs/docs.css

@@ -305,6 +305,55 @@ span.doc-tab[data-leader="underscore"]::after { top: 0.44em; border-top: 1px sol
     outline: 2px solid var(--of-accent);
     outline-offset: 1px;
 }
+/* Table of contents: the frame and "Update table" tab of the table the
+   caret or the mouse is in (docs.js drawTocOverlay; editor chrome, never
+   saved, printed or exported). Dashed while hovered, solid with the caret
+   inside. The paper is white in both themes, so are these colours. */
+.doc-toc-frame {
+    position: absolute;
+    left: 0;
+    top: 0;
+    width: 0;
+    height: 0;
+    /* above the header band (6): a table at the top of a page has its
+       tab in the margin */
+    z-index: 7;
+}
+.doc-toc-box {
+    position: absolute;
+    box-sizing: border-box;
+    border: 1px dashed rgba(33, 133, 208, 0.55);
+    border-radius: 2px;
+    pointer-events: none;
+}
+.doc-toc-frame.active .doc-toc-box {
+    border-style: solid;
+    border-color: var(--of-accent);
+}
+.doc-toc-tab {
+    position: absolute;
+    transform: translateY(-100%);
+}
+.doc-toc-update {
+    display: inline-flex;
+    align-items: center;
+    gap: 2px;
+    height: 22px;
+    padding: 0 8px 0 5px;
+    font: 12px/1 "Segoe UI", Arial, sans-serif;
+    color: #1f2328;
+    background: #eef4fb;
+    border: 1px solid rgba(33, 133, 208, 0.55);
+    border-bottom: none;
+    border-radius: 4px 4px 0 0;
+    cursor: pointer;
+    white-space: nowrap;
+}
+.doc-toc-frame.active .doc-toc-update { border-color: var(--of-accent); }
+.doc-toc-update:hover { background: #dbe9f7; }
+.doc-toc-update i.icon { margin: 0 2px 0 0; height: auto; font-size: 11px; color: var(--of-accent); }
+@media print { .doc-toc-frame { display: none !important; } }
+
 /* Picture Format: the crop dialog and size & properties */
 .doc-crop { display: flex; flex-direction: column; align-items: center; gap: 12px; }
 .doc-crop-stage {

+ 320 - 36
src/web/Office/docs/docs.js

@@ -146,6 +146,9 @@
                 if (editor.contains(r.commonAncestorContainer)) {
                     savedRange = r.cloneRange();
                     scheduleToolbarState();
+                    scheduleTocOverlay();
+                } else if (tocOverlay && tocOverlay.style.display !== "none") {
+                    scheduleTocOverlay();
                 }
             }
         });
@@ -1400,65 +1403,338 @@
         } catch (err) { }
         fn.scrollIntoView({ block: "nearest" });
     }
-    /* A table of contents is ordinary paragraphs: each heading's text, a
-       right tab with a dot leader at the margin, and the page it is on as
-       the layout has it now. That is what Word stores once a TOC field is
-       updated, so it round-trips as plain text with real tab stops. The
-       .doc-toc class marks the lines Update table replaces. */
+    /* A table of contents is ordinary paragraphs: a "Contents" title, then
+       each heading's text, a right tab with a dot leader at the margin, and
+       the page it is on as the layout has it now. That is what Word stores
+       once a TOC field is updated, so the layout, the PDF and the writers
+       treat it as plain text with real tab stops (the DOCX writer wraps it
+       in a TOC field Word can update). The .doc-toc class marks the lines,
+       data-toc-level the heading level of an entry and data-toc-max the
+       deepest heading the table lists (3 when absent; an imported table
+       keeps its own range, Google Docs lists 1-6); a run of them is one
+       table, which the editor frames with an "Update table" tab on top
+       while the caret or the mouse is in it (tocOverlay, not saved). */
+    var ZWSP = String.fromCharCode(0x200B);
+    function tocSelector(max) {
+        var sel = ["h1:not(.doc-title)"];
+        for (var l = 2; l <= max; l++) sel.push("h" + l);
+        return sel.join(", ");
+    }
+    // the deepest heading level a table lists
+    function tocMaxOf(lines) {
+        var max = 0;
+        (lines || []).forEach(function (p) {
+            var v = parseInt(p.getAttribute("data-toc-max"), 10);
+            if (v > max) max = v;
+        });
+        return max >= 1 ? Math.min(6, max) : 3;
+    }
     function hasToc() { return !!editor.querySelector("p.doc-toc"); }
-    function tocHtml() {
-        var heads = editor.querySelectorAll("h1, h2, h3");
-        var geo = pageGeometry();
-        var tabPt = Math.round(geo.contentW * 0.75 * 10) / 10;
-        var html = "";
+    // a heading's text, all of it when a page boundary divides it
+    function headingText(h) {
+        var parts = [];
+        var el = h;
+        for (var guard = 0; el && guard < 50; guard++) {
+            var c = el.cloneNode(true);
+            var drop = c.querySelectorAll("sup.doc-fnref, .doc-autobreak");
+            for (var i = 0; i < drop.length; i++) drop[i].parentNode.removeChild(drop[i]);
+            parts.push(c.textContent || "");
+            var tok = el.getAttribute("data-split");
+            el = tok ? editor.querySelector('[data-split-of="' + tok + '"]') : null;
+        }
+        return parts.join("").split(ZWSP).join("").replace(/\s+/g, " ").trim();
+    }
+    function tocEntries(max) {
+        var heads = editor.querySelectorAll(tocSelector(max || 3));
+        var out = [];
         for (var i = 0; i < heads.length; i++) {
             var h = heads[i];
-            if (h.closest(".doc-fn-area") || h.classList.contains("doc-split-tail")) continue;
-            var text = (h.textContent || "").replace(/\s+/g, " ").trim();
+            if (h.closest(".doc-fn-area, .doc-hf") || h.classList.contains("doc-split-tail")) continue;
+            var text = headingText(h);
             if (!text) continue;
-            var level = h.classList.contains("doc-title") ? 1 : parseInt(h.tagName.substring(1), 10);
-            var page = pageIndexAt(offsetTopInPage(h)) + 1;
-            var indent = (level - 1) * 14;
-            html += '<p class="doc-toc" data-tabs="right:' + tabPt + ':dot" style="margin-left:' + indent + 'pt;margin-bottom:3pt;">' +
-                esc(text) + '<span class="doc-tab"></span>' + page + "</p>";
+            out.push({
+                level: parseInt(h.tagName.substring(1), 10),
+                text: text,
+                page: pageIndexAt(offsetTopInPage(h)) + 1
+            });
+        }
+        return out;
+    }
+    function tocLinesHtml(entries, max) {
+        max = max || 3;
+        var geo = pageGeometry();
+        var tabPt = Math.round(geo.contentW * 0.75 * 10) / 10;
+        var maxAttr = max !== 3 ? ' data-toc-max="' + max + '"' : "";
+        if (!entries.length) {
+            return '<p class="doc-toc" data-toc-level="0"' + maxAttr + ' style="margin-bottom:3pt;color:#80868b;">' +
+                esc("No headings found - use Heading 1-" + max + " for the lines this table should list") + "</p>";
+        }
+        // the top level present starts at the margin (a document whose
+        // chapters are Heading 2 has no empty first step)
+        var top = 9;
+        entries.forEach(function (e) { top = Math.min(top, e.level); });
+        var html = "";
+        for (var i = 0; i < entries.length; i++) {
+            var e = entries[i];
+            html += '<p class="doc-toc" data-toc-level="' + e.level + '"' + maxAttr + ' data-tabs="right:' + tabPt + ':dot" style="margin-left:' +
+                ((e.level - top) * 14) + 'pt;margin-bottom:3pt;">' + esc(e.text) + '<span class="doc-tab"></span>' + e.page + "</p>";
         }
         return html;
     }
+    function tocSignature(entries) {
+        return entries.map(function (e) { return e.level + "|" + e.page + "|" + e.text; }).join("\n");
+    }
+    /* the tables in the document: each a run of .doc-toc paragraphs that
+       follow one another (a page spacer between two of them is the layout's) */
+    function tocGroups() {
+        var groups = [];
+        var cur = null, last = null;
+        var lines = editor.querySelectorAll("p.doc-toc");
+        for (var i = 0; i < lines.length; i++) {
+            var p = lines[i];
+            if (p.closest(".doc-hf")) continue;
+            var prev = p.previousElementSibling;
+            while (prev && prev.classList.contains("doc-autobreak")) prev = prev.previousElementSibling;
+            if (!cur || prev !== last) {
+                cur = [];
+                groups.push(cur);
+            }
+            cur.push(p);
+            last = p;
+        }
+        return groups;
+    }
+    function tocGroupOf(node) {
+        var p = node && node.nodeType === 1 ? node : (node ? node.parentNode : null);
+        p = p && p.closest ? p.closest("p.doc-toc") : null;
+        if (!p || !editor.contains(p)) return null;
+        var groups = tocGroups();
+        for (var i = 0; i < groups.length; i++) {
+            if (groups[i].indexOf(p) >= 0) return groups[i];
+        }
+        return null;
+    }
     function insertToc() {
         if (inHeaderFooter()) return;
         if (hasToc()) { updateToc(); return; }
-        var body = tocHtml();
-        if (!body) {
-            OfficeApp.setStatus("Add some headings first (Heading 1-3) - the table lists them", "info", 5000);
-            return;
-        }
+        var entries = tocEntries();
         restoreSel();
         try {
             document.execCommand("insertHTML", false,
-                '<p class="doc-toc doc-toc-title" style="font-size:16pt;margin-bottom:6pt;">Contents</p>' + body + "<p><br></p>");
+                '<p class="doc-toc doc-toc-title" style="font-size:16pt;margin-bottom:6pt;">Contents</p>' +
+                tocLinesHtml(entries) + "<p><br></p>");
         } catch (e) { return; }
         afterEdit(true);
         updatePageGuides();
         // the table itself moved the headings: number it again
-        setTimeout(updateTocQuiet, 80);
+        updateToc(true);
+        if (!entries.length) OfficeApp.setStatus("Table of contents added - give your headings a Heading 1-3 style, then click Update table", "info", 6000);
     }
     function updateTocQuiet() { updateToc(true); }
-    function updateToc(quiet) {
-        var lines = editor.querySelectorAll("p.doc-toc:not(.doc-toc-title)");
-        if (!lines.length) return;
-        var html = tocHtml();
-        var holder = document.createElement("div");
-        holder.innerHTML = html;
-        var first = lines[0];
-        var parent = first.parentNode;
-        while (holder.firstChild) parent.insertBefore(holder.firstChild, first);
-        for (var i = 0; i < lines.length; i++) {
-            if (lines[i].parentNode) lines[i].parentNode.removeChild(lines[i]);
+    /* updateToc rebuilds every table (or only `only`, one group) from the
+       headings. The new lines can push the headings to other pages, so the
+       numbers are taken again until they stop changing. */
+    function updateToc(quiet, only) {
+        if (!hasToc()) return;
+        var groups = tocGroups();
+        if (only) {
+            var first = only[0];
+            groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
+        }
+        if (!groups.length) return;
+        // the headings each table lists, from the pages as laid out now
+        var maxes = groups.map(tocMaxOf);
+        function entriesByMax() {
+            var out = {};
+            maxes.forEach(function (m) { if (!out[m]) out[m] = tocEntries(m); });
+            return out;
+        }
+        var entries = entriesByMax();
+        // then every page split is undone: the lines replaced may be cut in two
+        removeAutoBreaks(editor);
+        groups = tocGroups();
+        if (only) groups = groups.filter(function (g) { return g.indexOf(first) >= 0; });
+        if (!groups.length) return;
+        // where each table goes once its lines are gone: the first old line
+        var anchors = groups.map(function (g, i) {
+            var lines = g.filter(function (p) { return !p.classList.contains("doc-toc-title"); });
+            var title = g.filter(function (p) { return p.classList.contains("doc-toc-title"); })[0] || null;
+            return { lines: lines, after: title, before: lines.length ? lines[0] : null, max: maxes[i] || 3 };
+        });
+        var caretInside = groups.some(function (g) {
+            var sel = window.getSelection();
+            return sel && sel.rangeCount && g.some(function (p) { return p.contains(sel.anchorNode); });
+        });
+        var sig = null;
+        for (var pass = 0; pass < 4; pass++) {
+            if (pass > 0) entries = entriesByMax();
+            var s = Object.keys(entries).sort().map(function (m) { return m + ":" + tocSignature(entries[m]); }).join("\n");
+            if (s === sig) break;
+            sig = s;
+            anchors.forEach(function (a) {
+                var holder = document.createElement("div");
+                holder.innerHTML = tocLinesHtml(entries[a.max], a.max);
+                var fresh = Array.prototype.slice.call(holder.children);
+                var ref = a.before || (a.after ? a.after.nextSibling : null);
+                var parent = (a.before || a.after).parentNode;
+                fresh.forEach(function (n) { parent.insertBefore(n, ref); });
+                a.lines.forEach(function (p) { if (p.parentNode) p.parentNode.removeChild(p); });
+                a.lines = fresh;
+                a.before = fresh[0] || null;
+            });
+            dirtyFromY = null;
+            updatePageGuides();
+        }
+        if (caretInside && anchors[0].lines[0]) {
+            // the caret's line is gone: put it at the start of the new table
+            try {
+                var r = document.createRange();
+                r.setStart(anchors[0].lines[0], 0);
+                r.collapse(true);
+                var sel = window.getSelection();
+                sel.removeAllRanges();
+                sel.addRange(r);
+                savedRange = r.cloneRange();
+            } catch (err) { }
         }
         afterEdit(true);
-        updatePageGuides();
+        scheduleTocOverlay();
         if (quiet !== true) OfficeApp.setStatus("Table of contents updated");
     }
+    // Ctrl+click on an entry: go to the heading it lists
+    function followTocEntry(p) {
+        if (p.classList.contains("doc-toc-title")) return false;
+        var level = parseInt(p.getAttribute("data-toc-level"), 10);
+        if (level === 0) return false;   // the "no headings" line
+        var hit = null;
+        // an imported entry links to its heading's bookmark
+        var link = p.querySelector('a[href^="#"]');
+        if (link) {
+            try {
+                var target = editor.querySelector("#" + CSS.escape(decodeURIComponent(link.getAttribute("href").substring(1))));
+                if (target && /^H[1-6]$/.test(target.tagName)) hit = target;
+            } catch (err) { }
+        }
+        var c = p.cloneNode(true);
+        var tabs = c.querySelectorAll(".doc-tab");
+        if (tabs.length) {
+            // the text before the tab; the page number follows it
+            var t = tabs[tabs.length - 1];
+            var cut = document.createRange();
+            cut.setStartBefore(t);
+            cut.setEndAfter(c.lastChild);
+            cut.deleteContents();
+        }
+        var want = (c.textContent || "").split(ZWSP).join("").replace(/\s+/g, " ").trim();
+        var heads = editor.querySelectorAll("h1, h2, h3, h4, h5, h6");
+        for (var i = 0; i < heads.length && !hit; i++) {
+            var h = heads[i];
+            if (h.classList.contains("doc-split-tail") || headingText(h) !== want) continue;
+            if (!(level > 0) || parseInt(h.tagName.substring(1), 10) === level) hit = h;
+        }
+        if (!hit) {
+            OfficeApp.setStatus("That heading is not in the document any more - update the table", "info", 4000);
+            return true;
+        }
+        try {
+            var r = document.createRange();
+            r.setStart(hit, 0);
+            r.collapse(true);
+            var sel = window.getSelection();
+            sel.removeAllRanges();
+            sel.addRange(r);
+            savedRange = r.cloneRange();
+        } catch (err) { }
+        hit.scrollIntoView({ block: "start" });
+        return true;
+    }
+
+    /* The frame and tab of the table the caret or the mouse is in: drawn
+       in #page (layout px, zoomed with it) above the text, one box per
+       page the table covers, the tab above the first. Editor chrome only -
+       the PDF exporter skips .doc-toc-frame and print hides it. */
+    var tocOverlay = null, tocHover = null, tocHoverTimer = null, tocOverlayTimer = null;
+    function scheduleTocOverlay() {
+        if (tocOverlayTimer) return;
+        tocOverlayTimer = setTimeout(function () {
+            tocOverlayTimer = null;
+            drawTocOverlay();
+        }, 0);
+    }
+    function caretTocGroup() {
+        var sel = window.getSelection();
+        if (!sel || !sel.rangeCount || !editor.contains(sel.anchorNode)) return null;
+        return tocGroupOf(sel.anchorNode);
+    }
+    function drawTocOverlay() {
+        if (!pageEl) return;
+        var group = caretTocGroup();
+        var active = !!group;
+        if (!group && tocHover && tocHover[0] && tocHover[0].isConnected) group = tocGroupOf(tocHover[0]);
+        if (!group) {
+            if (tocOverlay) tocOverlay.style.display = "none";
+            return;
+        }
+        if (!tocOverlay) {
+            tocOverlay = document.createElement("div");
+            tocOverlay.className = "doc-toc-frame of-noprint";
+            tocOverlay.addEventListener("mouseenter", function () { clearTimeout(tocHoverTimer); });
+            tocOverlay.addEventListener("mouseleave", leaveTocHover);
+            pageEl.appendChild(tocOverlay);
+        }
+        tocOverlay.style.display = "";
+        tocOverlay.classList.toggle("active", active);
+        // one box per page the table is on
+        var boxes = [];
+        group.forEach(function (p) {
+            var top = offsetTopInPage(p);
+            var pg = pageIndexAt(top);
+            var b = boxes.length ? boxes[boxes.length - 1] : null;
+            if (!b || b.page !== pg) boxes.push(b = { page: pg, top: top, bottom: top });
+            b.bottom = Math.max(b.bottom, top + p.offsetHeight);
+        });
+        var left = editor.offsetLeft - 6;
+        var width = editor.offsetWidth + 12;
+        var html = "";
+        boxes.forEach(function (b, i) {
+            html += '<div class="doc-toc-box" style="left:' + left + "px;top:" + (b.top - 4) + "px;width:" + width +
+                "px;height:" + (b.bottom - b.top + 8) + 'px;"></div>';
+            if (i === 0) {
+                html += '<div class="doc-toc-tab" style="left:' + left + "px;top:" + (b.top - 4) + 'px;">' +
+                    '<button type="button" class="doc-toc-update" title="Update the table from the headings (Ctrl+click an entry to go to its heading)">' +
+                    '<i class="sync alternate icon"></i>Update table</button></div>';
+            }
+        });
+        tocOverlay.innerHTML = html;
+        var btn = tocOverlay.querySelector(".doc-toc-update");
+        // keep the caret where it is: the button never takes the focus
+        btn.addEventListener("mousedown", function (e) { e.preventDefault(); });
+        btn.addEventListener("click", function (e) {
+            e.preventDefault();
+            var g = caretTocGroup() || (tocHover && tocHover[0] && tocHover[0].isConnected ? tocGroupOf(tocHover[0]) : null);
+            updateToc(false, g || undefined);
+        });
+    }
+    function leaveTocHover() {
+        clearTimeout(tocHoverTimer);
+        // time to cross from the lines to the tab above them
+        tocHoverTimer = setTimeout(function () {
+            tocHover = null;
+            scheduleTocOverlay();
+        }, 400);
+    }
+    function trackTocHover(e) {
+        var p = e.target && e.target.closest ? e.target.closest("p.doc-toc") : null;
+        if (p && editor.contains(p)) {
+            clearTimeout(tocHoverTimer);
+            if (!tocHover || tocHover.indexOf(p) < 0) {
+                tocHover = tocGroupOf(p);
+                scheduleTocOverlay();
+            }
+        } else if (tocHover && !(e.target.closest && e.target.closest(".doc-toc-frame"))) {
+            leaveTocHover();
+        }
+    }
 
     /* ---------- Review / View ---------- */
     function toggleSpellcheck() {
@@ -3391,6 +3667,7 @@
         } finally {
             relayoutH = editor.offsetHeight;
             relayouting = false;
+            if (tocOverlay || tocHover) scheduleTocOverlay();
         }
     }
     function layoutPages() {
@@ -4922,6 +5199,11 @@
                 showCommentsPanel(true);
                 renderCommentsPanel(cmtHit.getAttribute("data-cid"));
             }
+            var tocLine = (e.ctrlKey || e.metaKey) && t.closest ? t.closest("p.doc-toc") : null;
+            if (tocLine && editor.contains(tocLine) && followTocEntry(tocLine)) {
+                e.preventDefault();
+                return;
+            }
             var a = t.closest ? t.closest("a") : null;
             if (a && editor.contains(a)) {
                 e.preventDefault();
@@ -4932,6 +5214,8 @@
                 }
             }
         });
+        pageEl.addEventListener("mousemove", trackTocHover);
+        pageEl.addEventListener("mouseleave", function () { if (tocHover) leaveTocHover(); });
         editor.addEventListener("dblclick", function (e) {
             if (e.target.tagName === "IMG") {
                 selectImage(e.target);

+ 1 - 1
src/web/Office/docs/docs_pdf.js

@@ -39,7 +39,7 @@ var DocsPdf = (function () {
     var PT = 96 / 72;
 
     // subtrees that are editor chrome, not page content
-    var SKIP_SELECTOR = "#pageSheets, .doc-fn-measure, .of-img-handle, .doc-autobreak";
+    var SKIP_SELECTOR = "#pageSheets, .doc-fn-measure, .of-img-handle, .doc-autobreak, .doc-toc-frame";
 
     function skipped(el) {
         return !!(el && el.closest && el.closest(SKIP_SELECTOR));