forked from nickng/bibtex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbibtex.go
301 lines (259 loc) · 7.78 KB
/
bibtex.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package bibtex
import (
"bytes"
"fmt"
"log"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
)
// BibString is a segment of a bib string.
type BibString interface {
RawString() string // Internal representation.
String() string // Displayed string.
}
// BibVar is a string variable.
type BibVar struct {
Key string // Variable key.
Value BibString // Variable actual value.
}
// RawString is the internal representation of the variable.
func (v *BibVar) RawString() string {
return v.Key
}
func (v *BibVar) String() string {
return v.Value.String()
}
// BibConst is a string constant.
type BibConst string
// NewBibConst converts a constant string to BibConst.
func NewBibConst(c string) BibConst {
return BibConst(c)
}
// RawString is the internal representation of the constant (i.e. the string).
func (c BibConst) RawString() string {
return fmt.Sprintf("{%s}", string(c))
}
func (c BibConst) String() string {
return string(c)
}
// BibComposite is a composite string, may contain both variable and string.
type BibComposite []BibString
// NewBibComposite creates a new composite with one element.
func NewBibComposite(s BibString) *BibComposite {
comp := &BibComposite{}
return comp.Append(s)
}
// Append adds a BibString to the composite
func (c *BibComposite) Append(s BibString) *BibComposite {
comp := append(*c, s)
return &comp
}
func (c *BibComposite) String() string {
var buf bytes.Buffer
for _, s := range *c {
buf.WriteString(s.String())
}
return buf.String()
}
// RawString returns a raw (bibtex) representation of the composite string.
func (c *BibComposite) RawString() string {
var buf bytes.Buffer
for i, comp := range *c {
if i > 0 {
buf.WriteString(" # ")
}
switch comp := comp.(type) {
case *BibConst:
buf.WriteString(comp.RawString())
case *BibVar:
buf.WriteString(comp.RawString())
case *BibComposite:
buf.WriteString(comp.RawString())
}
}
return buf.String()
}
// BibEntry is a record of BibTeX record.
type BibEntry struct {
Type string
CiteName string
Fields map[string]BibString
}
// NewBibEntry creates a new BibTeX entry.
func NewBibEntry(entryType string, citeName string) *BibEntry {
spaceStripper := strings.NewReplacer(" ", "")
cleanedType := strings.ToLower(spaceStripper.Replace(entryType))
cleanedName := spaceStripper.Replace(citeName)
return &BibEntry{
Type: cleanedType,
CiteName: cleanedName,
Fields: map[string]BibString{},
}
}
// AddField adds a field (key-value) to a BibTeX entry.
func (entry *BibEntry) AddField(name string, value BibString) {
entry.Fields[strings.TrimSpace(name)] = value
}
// String returns a BibTex entry as a simplified BibTex string.
func (entry *BibEntry) String() string {
var bibtex bytes.Buffer
bibtex.WriteString(fmt.Sprintf("@%s{%s,\n", entry.Type, entry.CiteName))
for key, val := range entry.Fields {
if i, err := strconv.Atoi(strings.TrimSpace(val.String())); err == nil {
bibtex.WriteString(fmt.Sprintf(" %s = %d,\n", key, i))
} else {
bibtex.WriteString(fmt.Sprintf(" %s = {%s},\n", key, strings.TrimSpace(val.String())))
}
}
bibtex.Truncate(bibtex.Len() - 2)
bibtex.WriteString(fmt.Sprintf("\n}\n"))
return bibtex.String()
}
// RawString returns a BibTex entry data structure in its internal representation.
func (entry *BibEntry) RawString() string {
var bibtex bytes.Buffer
bibtex.WriteString(fmt.Sprintf("@%s{%s,\n", entry.Type, entry.CiteName))
for key, val := range entry.Fields {
if i, err := strconv.Atoi(strings.TrimSpace(val.String())); err == nil {
bibtex.WriteString(fmt.Sprintf(" %s = %d,\n", key, i))
} else {
bibtex.WriteString(fmt.Sprintf(" %s = %s,\n", key, val.RawString()))
}
}
bibtex.Truncate(bibtex.Len() - 2)
bibtex.WriteString(fmt.Sprintf("\n}\n"))
return bibtex.String()
}
// BibTex is a list of BibTeX entries.
type BibTex struct {
Preambles []BibString // List of Preambles
Entries []*BibEntry // Items in a bibliography.
StringVar map[string]*BibVar // Map from string variable to string.
// A list of default BibVars that are implicitly
// defined and can be used without defining
defaultVars map[string]string
}
// NewBibTex creates a new BibTex data structure.
func NewBibTex() *BibTex {
// Sets up some default vars
months := map[string]time.Month{
"jan": 1, "feb": 2, "mar": 3,
"apr": 4, "may": 5, "jun": 6,
"jul": 7, "aug": 8, "sep": 9,
"oct": 10, "nov": 11, "dec": 12,
}
defaultVars := make(map[string]string)
for mth, month := range months {
// TODO(nickng): i10n of month name in user's local language
defaultVars[mth] = month.String()
}
return &BibTex{
Preambles: []BibString{},
Entries: []*BibEntry{},
StringVar: make(map[string]*BibVar),
defaultVars: defaultVars,
}
}
// AddPreamble adds a preamble to a bibtex.
func (bib *BibTex) AddPreamble(p BibString) {
bib.Preambles = append(bib.Preambles, p)
}
// AddEntry adds an entry to the BibTeX data structure.
func (bib *BibTex) AddEntry(entry *BibEntry) {
bib.Entries = append(bib.Entries, entry)
}
// AddStringVar adds a new string var (if does not exist).
func (bib *BibTex) AddStringVar(key string, val BibString) {
bib.StringVar[key] = &BibVar{Key: key, Value: val}
}
// GetStringVar looks up a string by its key.
func (bib *BibTex) GetStringVar(key string) *BibVar {
if bv, ok := bib.StringVar[key]; ok {
return bv
}
if v, ok := bib.getDefaultVar(key); ok {
return v
}
// This is undefined.
log.Fatalf("%s: %s", ErrUnknownStringVar, key)
return nil
}
// getDefaultVar is a fallback for looking up keys (e.g. 3-character month)
// and use them even though it hasn't been defined in the bib.
func (bib *BibTex) getDefaultVar(key string) (*BibVar, bool) {
if v, ok := bib.defaultVars[key]; ok {
// if found, add this to the BibTex
bib.StringVar[key] = &BibVar{Key: key, Value: NewBibConst(v)}
return bib.StringVar[key], true
}
return nil, false
}
// String returns a BibTex data structure as a simplified BibTex string.
func (bib *BibTex) String() string {
var bibtex bytes.Buffer
for _, entry := range bib.Entries {
bibtex.WriteString(entry.String())
}
return bibtex.String()
}
// RawString returns a BibTex data structure in its internal representation.
func (bib *BibTex) RawString() string {
var bibtex bytes.Buffer
for k, strvar := range bib.StringVar {
bibtex.WriteString(fmt.Sprintf("@string{%s = {%s}}\n", k, strvar.String()))
}
for _, preamble := range bib.Preambles {
bibtex.WriteString(fmt.Sprintf("@preamble{%s}\n", preamble.RawString()))
}
for _, entry := range bib.Entries {
bibtex.WriteString(entry.RawString())
}
return bibtex.String()
}
// PrettyString pretty prints a BibTex.
func (bib *BibTex) PrettyString() string {
var buf bytes.Buffer
for i, entry := range bib.Entries {
if i != 0 {
fmt.Fprint(&buf, "\n")
}
fmt.Fprintf(&buf, "@%s{%s,\n", entry.Type, entry.CiteName)
// Determine key order.
keys := []string{}
for key := range entry.Fields {
keys = append(keys, key)
}
priority := map[string]int{"title": -3, "author": -2, "url": -1}
sort.Slice(keys, func(i, j int) bool {
pi, pj := priority[keys[i]], priority[keys[j]]
return pi < pj || (pi == pj && keys[i] < keys[j])
})
// Write fields.
tw := tabwriter.NewWriter(&buf, 1, 4, 1, ' ', 0)
for _, key := range keys {
value := entry.Fields[key].String()
format := stringformat(value)
fmt.Fprintf(tw, " %s\t=\t"+format+",\n", key, value)
}
tw.Flush()
// Close.
buf.WriteString("}\n")
}
return buf.String()
}
// stringformat determines the correct formatting verb for the given BibTeX field value.
func stringformat(v string) string {
// Numbers may be represented unquoted.
if _, err := strconv.Atoi(v); err == nil {
return "%s"
}
// Strings with certain characters must be brace quoted.
if strings.ContainsAny(v, "\"{}") {
return "{%s}"
}
// Default to quoted string.
return "%q"
}