File: footnotes.go

package info (click to toggle)
git-sizer 1.5.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 616 kB
  • sloc: sh: 100; makefile: 61
file content (54 lines) | stat: -rw-r--r-- 1,224 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package sizes

import (
	"bytes"
	"fmt"
)

// Footnotes collects and numbers footnotes for a `table`.
type Footnotes struct {
	footnotes []string
	indexes   map[string]int
}

// NewFootnotes creates and returns a new `Footnotes` instance.
func NewFootnotes() *Footnotes {
	return &Footnotes{
		indexes: make(map[string]int),
	}
}

// CreateCitation adds a footnote with the specified text and returns
// the string that should be used to refer to it (e.g., "[2]"). If
// there is already a footnote with the exact same text, reuse its
// number.
func (f *Footnotes) CreateCitation(footnote string) string {
	if footnote == "" {
		return ""
	}

	index, ok := f.indexes[footnote]
	if !ok {
		index = len(f.indexes) + 1
		f.footnotes = append(f.footnotes, footnote)
		f.indexes[footnote] = index
	}
	return fmt.Sprintf("[%d]", index)
}

// String returns a string representation of the footnote, including a
// trailing LF.
func (f *Footnotes) String() string {
	if len(f.footnotes) == 0 {
		return ""
	}

	buf := &bytes.Buffer{}
	buf.WriteByte('\n')
	for i, footnote := range f.footnotes {
		index := i + 1
		citation := fmt.Sprintf("[%d]", index)
		fmt.Fprintf(buf, "%-4s %s\n", citation, footnote)
	}
	return buf.String()
}