commit ae3267c0acb8754ba34d332759d561f10d051132
parent ad17f5441ed6be33b0458e8c91dab5c2d041c7f4
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date: Thu, 26 Nov 2026 06:44:07 +0300
feat(bib): add BibTeX parsing, Crossref/doi.org fetch, import and CSL/RIS export
Diffstat:
| A | bib/bib.go | | | 307 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | bib/bib_test.go | | | 179 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | bib/export.go | | | 156 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | bib/fetch.go | | | 196 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | bib/shared.go | | | 77 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
5 files changed, 915 insertions(+), 0 deletions(-)
diff --git a/bib/bib.go b/bib/bib.go
@@ -0,0 +1,307 @@
+package bib
+
+import (
+ "fmt"
+ "os"
+ "regexp"
+ "strings"
+ "unicode"
+)
+
+// Entry is one BibTeX entry. Raw holds the exact source text so files are
+// never rewritten; Fields holds parsed values for lookup and export.
+type Entry struct {
+ Type string
+ Key string
+ Fields map[string]string
+ Order []string
+ Raw string
+}
+
+func (e *Entry) DOI() string { return NormDOI(e.Fields["doi"]) }
+
+var doiPrefix = regexp.MustCompile(`(?i)^\s*(https?://(dx\.)?doi\.org/|doi:\s*)`)
+
+// NormDOI strips resolver prefixes and lowercases a DOI.
+func NormDOI(s string) string {
+ return strings.ToLower(strings.TrimSpace(doiPrefix.ReplaceAllString(s, "")))
+}
+
+var doiRe = regexp.MustCompile(`^10\.\d{4,9}/\S+$`)
+
+func IsDOI(s string) bool { return doiRe.MatchString(NormDOI(s)) }
+
+// Parse extracts entries; @comment, @string and @preamble are skipped.
+func Parse(src string) ([]*Entry, error) {
+ var out []*Entry
+ i := 0
+ for {
+ at := strings.IndexByte(src[i:], '@')
+ if at < 0 {
+ return out, nil
+ }
+ start := i + at
+ j := start + 1
+ for j < len(src) && (unicode.IsLetter(rune(src[j]))) {
+ j++
+ }
+ typ := strings.ToLower(src[start+1 : j])
+ for j < len(src) && unicode.IsSpace(rune(src[j])) {
+ j++
+ }
+ if typ == "" || j >= len(src) || (src[j] != '{' && src[j] != '(') {
+ i = start + 1
+ continue
+ }
+ end, err := matchClose(src, j)
+ if err != nil {
+ return out, fmt.Errorf("entry at offset %d: %v", start, err)
+ }
+ i = end + 1
+ if typ == "comment" || typ == "string" || typ == "preamble" {
+ continue
+ }
+ e, err := parseBody(typ, src[j+1:end])
+ if err != nil {
+ return out, fmt.Errorf("entry at offset %d: %v", start, err)
+ }
+ e.Raw = src[start : end+1]
+ out = append(out, e)
+ }
+}
+
+func matchClose(s string, open int) (int, error) {
+ closer := byte('}')
+ if s[open] == '(' {
+ closer = ')'
+ }
+ depth := 0
+ for k := open + 1; k < len(s); k++ {
+ switch s[k] {
+ case '\\':
+ k++
+ case '{':
+ depth++
+ case '}':
+ if depth == 0 && closer == '}' {
+ return k, nil
+ }
+ depth--
+ case ')':
+ if depth == 0 && closer == ')' {
+ return k, nil
+ }
+ }
+ }
+ return 0, fmt.Errorf("unbalanced braces")
+}
+
+func parseBody(typ, body string) (*Entry, error) {
+ key, rest, ok := strings.Cut(body, ",")
+ if !ok {
+ rest = ""
+ }
+ e := &Entry{Type: typ, Key: strings.TrimSpace(key), Fields: map[string]string{}}
+ if e.Key == "" {
+ return nil, fmt.Errorf("missing key")
+ }
+ p := 0
+ for {
+ for p < len(rest) && (unicode.IsSpace(rune(rest[p])) || rest[p] == ',') {
+ p++
+ }
+ if p >= len(rest) {
+ return e, nil
+ }
+ eq := strings.IndexByte(rest[p:], '=')
+ if eq < 0 {
+ return e, nil
+ }
+ name := strings.ToLower(strings.TrimSpace(rest[p : p+eq]))
+ p += eq + 1
+ var val strings.Builder
+ for {
+ for p < len(rest) && unicode.IsSpace(rune(rest[p])) {
+ p++
+ }
+ if p >= len(rest) {
+ break
+ }
+ switch rest[p] {
+ case '{':
+ end, err := matchClose(rest, p)
+ if err != nil {
+ return nil, fmt.Errorf("field %s: %v", name, err)
+ }
+ val.WriteString(rest[p+1 : end])
+ p = end + 1
+ case '"':
+ q := p + 1
+ depth := 0
+ for q < len(rest) && (rest[q] != '"' || depth > 0) {
+ switch rest[q] {
+ case '{':
+ depth++
+ case '}':
+ depth--
+ case '\\':
+ q++
+ }
+ q++
+ }
+ val.WriteString(rest[p+1 : min(q, len(rest))])
+ p = q + 1
+ default:
+ q := p
+ for q < len(rest) && rest[q] != ',' && rest[q] != '#' && !unicode.IsSpace(rune(rest[q])) {
+ q++
+ }
+ val.WriteString(rest[p:q])
+ p = q
+ }
+ for p < len(rest) && unicode.IsSpace(rune(rest[p])) {
+ p++
+ }
+ if p < len(rest) && rest[p] == '#' {
+ p++
+ continue
+ }
+ break
+ }
+ if _, dup := e.Fields[name]; !dup {
+ e.Order = append(e.Order, name)
+ }
+ e.Fields[name] = strings.Join(strings.Fields(val.String()), " ")
+ }
+}
+
+func ParseFile(path string) ([]*Entry, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ return Parse(string(b))
+}
+
+// Format writes an entry in the tab-indented style of BIBnew.bib.
+func Format(e *Entry) string {
+ var b strings.Builder
+ fmt.Fprintf(&b, "@%s{%s,\n", e.Type, e.Key)
+ for i, k := range e.Order {
+ sep := ","
+ if i == len(e.Order)-1 {
+ sep = ""
+ }
+ fmt.Fprintf(&b, "\t%s = {%s}%s\n", k, e.Fields[k], sep)
+ }
+ b.WriteString("}")
+ return b.String()
+}
+
+// Index maps keys and DOIs of a set of entries.
+type Index struct {
+ Entries []*Entry
+ ByKey map[string]*Entry
+ ByDOI map[string]*Entry
+}
+
+func NewIndex(es []*Entry) *Index {
+ ix := &Index{Entries: es, ByKey: map[string]*Entry{}, ByDOI: map[string]*Entry{}}
+ for _, e := range es {
+ if _, ok := ix.ByKey[e.Key]; !ok {
+ ix.ByKey[e.Key] = e
+ }
+ if d := e.DOI(); d != "" {
+ if _, ok := ix.ByDOI[d]; !ok {
+ ix.ByDOI[d] = e
+ }
+ }
+ }
+ return ix
+}
+
+// FreeKey returns key, or key with a letter suffix if key is taken.
+func (ix *Index) FreeKey(key string) string {
+ if _, ok := ix.ByKey[key]; !ok {
+ return key
+ }
+ for c := 'a'; c <= 'z'; c++ {
+ k := key + string(c)
+ if _, ok := ix.ByKey[k]; !ok {
+ return k
+ }
+ }
+ return key + "_dup"
+}
+
+// Duplicates reports keys and DOIs that occur more than once.
+func Duplicates(es []*Entry) (keys, dois map[string][]string) {
+ keys, dois = map[string][]string{}, map[string][]string{}
+ for _, e := range es {
+ keys[e.Key] = append(keys[e.Key], e.Key)
+ if d := e.DOI(); d != "" {
+ dois[d] = append(dois[d], e.Key)
+ }
+ }
+ for k, v := range keys {
+ if len(v) < 2 {
+ delete(keys, k)
+ }
+ }
+ for k, v := range dois {
+ if len(v) < 2 {
+ delete(dois, k)
+ }
+ }
+ return keys, dois
+}
+
+// Rekey rewrites the key in an entry's raw text.
+func Rekey(e *Entry, key string) {
+ i := strings.Index(e.Raw, e.Key)
+ if i >= 0 {
+ e.Raw = e.Raw[:i] + key + e.Raw[i+len(e.Key):]
+ }
+ e.Key = key
+}
+
+// Append adds entries to the end of a bib file without touching the rest.
+func Append(path string, es []*Entry) error {
+ if len(es) == 0 {
+ return nil
+ }
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+ if err != nil {
+ return err
+ }
+ var b strings.Builder
+ for _, e := range es {
+ b.WriteString("\n" + e.Raw + "\n")
+ }
+ if _, err := f.WriteString(b.String()); err != nil {
+ f.Close()
+ return err
+ }
+ return f.Close()
+}
+
+// Search returns entries whose key, title, author, year or DOI contain all
+// words of q (case-insensitive).
+func Search(es []*Entry, q string) []*Entry {
+ words := strings.Fields(strings.ToLower(q))
+ var out []*Entry
+ for _, e := range es {
+ hay := strings.ToLower(e.Key + " " + e.Fields["title"] + " " + e.Fields["author"] + " " + e.Fields["year"] + " " + e.Fields["doi"] + " " + e.Fields["journal"])
+ ok := true
+ for _, w := range words {
+ if !strings.Contains(hay, w) {
+ ok = false
+ break
+ }
+ }
+ if ok {
+ out = append(out, e)
+ }
+ }
+ return out
+}
diff --git a/bib/bib_test.go b/bib/bib_test.go
@@ -0,0 +1,179 @@
+package bib
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const sample = `% comment line
+@string{jgl = "J. Glaciol."}
+@article{Boulton1993,
+ doi = {10.1017/S0022143000015690},
+ year = 1993,
+ author = {G. S. Boulton and K. E. Dobbie},
+ title = {Consolidation of {sediments} by glaciers},
+ journal = "J. Glaciol."
+}
+
+@Book{Paterson1994,
+ title={The Physics of Glaciers},
+ author={Paterson, W. S. B.},
+ year={1994}
+}
+`
+
+func TestParse(t *testing.T) {
+ es, err := Parse(sample)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(es) != 2 {
+ t.Fatalf("got %d entries", len(es))
+ }
+ e := es[0]
+ if e.Key != "Boulton1993" || e.Fields["year"] != "1993" || e.Fields["title"] != "Consolidation of {sediments} by glaciers" || e.Fields["journal"] != "J. Glaciol." {
+ t.Fatalf("fields = %+v", e.Fields)
+ }
+ if e.DOI() != "10.1017/s0022143000015690" {
+ t.Fatalf("doi = %s", e.DOI())
+ }
+ if !strings.HasPrefix(e.Raw, "@article{Boulton1993,") || !strings.HasSuffix(e.Raw, "}") {
+ t.Fatalf("raw = %q", e.Raw)
+ }
+ if es[1].Type != "book" {
+ t.Fatalf("type = %s", es[1].Type)
+ }
+}
+
+func TestParseUnbalanced(t *testing.T) {
+ if _, err := Parse("@article{x, title={a}"); err == nil {
+ t.Fatal("expected error")
+ }
+}
+
+func TestNormalize(t *testing.T) {
+ cases := map[string]string{
+ "Geoffrey S. Boulton and Kevin E. Dobbie": "G. S. Boulton and K. E. Dobbie",
+ "Boulton, Geoffrey S.": "Boulton, G. S.",
+ "Jean-Pierre van der Veen": "J.-P. van der Veen",
+ }
+ for in, want := range cases {
+ if got := AbbrevAuthors(in); got != want {
+ t.Errorf("AbbrevAuthors(%q) = %q, want %q", in, got, want)
+ }
+ }
+ if got := AbbrevJournal("Journal of Geophysical Research: Earth Surface"); got != "J. Geophys. Res.: Earth Surf." {
+ t.Errorf("journal = %q", got)
+ }
+ if got := AbbrevJournal("Science"); got != "Science" {
+ t.Errorf("single word journal = %q", got)
+ }
+}
+
+func TestIndexAndDuplicates(t *testing.T) {
+ es, _ := Parse(sample + "\n@article{Boulton1993, doi={https://doi.org/10.1017/s0022143000015690}}\n")
+ ix := NewIndex(es)
+ if ix.FreeKey("Boulton1993") != "Boulton1993a" || ix.FreeKey("New2020") != "New2020" {
+ t.Fatal("FreeKey")
+ }
+ keys, dois := Duplicates(es)
+ if len(keys) != 1 || len(dois) != 1 {
+ t.Fatalf("dups keys=%v dois=%v", keys, dois)
+ }
+ e := es[2]
+ Rekey(e, "Boulton1993b")
+ if !strings.HasPrefix(e.Raw, "@article{Boulton1993b,") {
+ t.Fatalf("raw = %q", e.Raw)
+ }
+}
+
+func TestAppend(t *testing.T) {
+ p := filepath.Join(t.TempDir(), "x.bib")
+ os.WriteFile(p, []byte(sample), 0o644)
+ es, _ := Parse("@misc{K, title={t}}")
+ if err := Append(p, es); err != nil {
+ t.Fatal(err)
+ }
+ b, _ := os.ReadFile(p)
+ if !strings.HasPrefix(string(b), sample) || !strings.HasSuffix(string(b), "\n@misc{K, title={t}}\n") {
+ t.Fatalf("file = %q", b)
+ }
+}
+
+func TestClient(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.URL.Path == "/works":
+ if r.URL.Query().Get("query") != "boulton glacier" {
+ t.Errorf("query = %q", r.URL.Query().Get("query"))
+ }
+ w.Write([]byte(`{"message":{"items":[{"DOI":"10.1017/S0022143000015690"}]}}`))
+ case r.URL.Path == "/10.1017/s0022143000015690":
+ if r.Header.Get("Accept") != "application/x-bibtex" {
+ t.Errorf("accept = %q", r.Header.Get("Accept"))
+ }
+ w.Write([]byte(` @article{Boulton_1993, title={Consolidation}, volume={39}, url={http://x}, DOI={10.1017/S0022143000015690}, journal={Journal of Glaciology}, author={Boulton, Geoffrey S. and Dobbie, Kevin E.}, year={1993}, month=jan }`))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ c := &Client{HTTP: srv.Client(), CrossrefURL: srv.URL + "/works", DOIURL: srv.URL}
+ doi, err := c.Lookup("boulton glacier")
+ if err != nil || doi != "10.1017/s0022143000015690" {
+ t.Fatalf("lookup = %q, %v", doi, err)
+ }
+ if d, _ := c.Lookup("https://doi.org/10.5555/ABC"); d != "10.5555/abc" {
+ t.Fatalf("doi passthrough = %q", d)
+ }
+ e, err := c.Fetch(doi)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if e.Key != "Boulton1993" || e.Fields["journal"] != "J. Glaciol." || e.Fields["author"] != "Boulton, G. S. and Dobbie, K. E." {
+ t.Fatalf("entry = %+v", e.Fields)
+ }
+ if strings.Contains(e.Raw, "url") || strings.Contains(e.Raw, "month") || !strings.Contains(e.Raw, "\tdoi = {10.1017/s0022143000015690},") {
+ t.Fatalf("raw = %s", e.Raw)
+ }
+ if _, err := c.Fetch("10.9/missing"); err == nil {
+ t.Fatal("expected error for missing DOI")
+ }
+}
+
+func TestExport(t *testing.T) {
+ es, _ := Parse(`@article{A, author={M{\"u}ller, Hans and {GEUS}}, title={{\O}resund--flow}, journal={J. Glaciol.}, year={2001}, pages={1--5}, doi={10.1/x}}`)
+ b, err := CSL(es)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var items []map[string]any
+ if err := json.Unmarshal(b, &items); err != nil {
+ t.Fatal(err)
+ }
+ if items[0]["title"] != "Øresund–flow" || items[0]["type"] != "article-journal" {
+ t.Fatalf("csl = %s", b)
+ }
+ au := items[0]["author"].([]any)
+ if au[0].(map[string]any)["family"] != "Mu\u0308ller" || au[1].(map[string]any)["literal"] != "GEUS" {
+ t.Fatalf("authors = %v", au)
+ }
+ ris := RIS(es)
+ for _, want := range []string{"TY - JOUR", "AU - Mu\u0308ller, Hans", "SP - 1", "EP - 5", "DO - 10.1/x", "ER - "} {
+ if !strings.Contains(ris, want) {
+ t.Errorf("RIS missing %q:\n%s", want, ris)
+ }
+ }
+}
+
+func TestSearch(t *testing.T) {
+ es, _ := Parse(sample)
+ if r := Search(es, "paterson 1994"); len(r) != 1 || r[0].Key != "Paterson1994" {
+ t.Fatalf("search = %v", r)
+ }
+}
diff --git a/bib/export.go b/bib/export.go
@@ -0,0 +1,156 @@
+package bib
+
+import (
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+var accents = map[byte]string{
+ '"': "̈", '\'': "́", '`': "̀", '^': "̂", '~': "̃",
+ '=': "̄", '.': "̇", 'c': "̧", 'v': "̌", 'u': "̆", 'H': "̋",
+}
+
+var (
+ accentRe = regexp.MustCompile(`\\(["'` + "`" + `^~=.]|[cvuH][\s{])\s*\{?\\?([A-Za-z])\}?`)
+ specialRe = regexp.MustCompile(`\\(o|O|ae|AE|aa|AA|ss|l|L|&|%|_)\b|\\(&|%|_)`)
+ cmdRe = regexp.MustCompile(`\\[a-zA-Z]+\s*`)
+)
+
+var specials = map[string]string{"o": "ø", "O": "Ø", "ae": "æ", "AE": "Æ", "aa": "å", "AA": "Å", "ss": "ß", "l": "ł", "L": "Ł", "&": "&", "%": "%", "_": "_"}
+
+// Plain converts common LaTeX markup to Unicode text for CSL/RIS export.
+func Plain(s string) string {
+ s = accentRe.ReplaceAllStringFunc(s, func(m string) string {
+ sm := accentRe.FindStringSubmatch(m)
+ return sm[2] + accents[strings.TrimSpace(sm[1])[0]]
+ })
+ s = specialRe.ReplaceAllStringFunc(s, func(m string) string {
+ return specials[strings.TrimPrefix(m, `\`)]
+ })
+ s = strings.NewReplacer("---", "—", "--", "–", "~", " ").Replace(s)
+ s = cmdRe.ReplaceAllString(s, "")
+ s = strings.NewReplacer("{", "", "}", "").Replace(s)
+ return strings.Join(strings.Fields(s), " ")
+}
+
+type cslName struct {
+ Family string `json:"family,omitempty"`
+ Given string `json:"given,omitempty"`
+ Literal string `json:"literal,omitempty"`
+}
+
+func splitName(n string) cslName {
+ n = strings.TrimSpace(n)
+ if strings.HasPrefix(n, "{") && strings.HasSuffix(n, "}") {
+ return cslName{Literal: Plain(n)}
+ }
+ if last, first, ok := strings.Cut(n, ","); ok {
+ return cslName{Family: Plain(last), Given: Plain(first)}
+ }
+ w := strings.Fields(n)
+ if len(w) < 2 {
+ return cslName{Family: Plain(n)}
+ }
+ return cslName{Family: Plain(w[len(w)-1]), Given: Plain(strings.Join(w[:len(w)-1], " "))}
+}
+
+func authors(e *Entry) []cslName {
+ var out []cslName
+ if a := e.Fields["author"]; a != "" {
+ for _, n := range strings.Split(a, " and ") {
+ out = append(out, splitName(n))
+ }
+ }
+ return out
+}
+
+var cslType = map[string]string{
+ "article": "article-journal", "book": "book", "incollection": "chapter", "inbook": "chapter",
+ "inproceedings": "paper-conference", "conference": "paper-conference", "phdthesis": "thesis",
+ "mastersthesis": "thesis", "techreport": "report", "misc": "document", "dataset": "dataset",
+}
+
+// CSL renders entries as CSL-JSON (Zotero, pandoc --citeproc).
+func CSL(es []*Entry) ([]byte, error) {
+ var items []map[string]any
+ for _, e := range es {
+ t := cslType[e.Type]
+ if t == "" {
+ t = "document"
+ }
+ it := map[string]any{"id": e.Key, "type": t}
+ if a := authors(e); a != nil {
+ it["author"] = a
+ }
+ set := func(k, f string) {
+ if v := e.Fields[f]; v != "" {
+ it[k] = Plain(v)
+ }
+ }
+ set("title", "title")
+ set("container-title", "journal")
+ if _, ok := it["container-title"]; !ok {
+ set("container-title", "booktitle")
+ }
+ set("volume", "volume")
+ set("issue", "number")
+ set("page", "pages")
+ set("publisher", "publisher")
+ set("DOI", "doi")
+ if y, err := strconv.Atoi(e.Fields["year"]); err == nil {
+ it["issued"] = map[string]any{"date-parts": [][]int{{y}}}
+ }
+ items = append(items, it)
+ }
+ return json.MarshalIndent(items, "", " ")
+}
+
+var risType = map[string]string{
+ "article": "JOUR", "book": "BOOK", "incollection": "CHAP", "inbook": "CHAP",
+ "inproceedings": "CONF", "conference": "CONF", "phdthesis": "THES", "mastersthesis": "THES",
+ "techreport": "RPRT", "dataset": "DATA",
+}
+
+// RIS renders entries in RIS format (Word reference managers, EndNote).
+func RIS(es []*Entry) string {
+ var b strings.Builder
+ for _, e := range es {
+ t := risType[e.Type]
+ if t == "" {
+ t = "GEN"
+ }
+ fmt.Fprintf(&b, "TY - %s\nID - %s\n", t, e.Key)
+ for _, a := range authors(e) {
+ if a.Literal != "" {
+ fmt.Fprintf(&b, "AU - %s\n", a.Literal)
+ } else {
+ fmt.Fprintf(&b, "AU - %s, %s\n", a.Family, a.Given)
+ }
+ }
+ line := func(tag, f string) {
+ if v := e.Fields[f]; v != "" {
+ fmt.Fprintf(&b, "%s - %s\n", tag, Plain(v))
+ }
+ }
+ line("TI", "title")
+ line("JO", "journal")
+ line("T2", "booktitle")
+ line("PY", "year")
+ line("VL", "volume")
+ line("IS", "number")
+ if p := Plain(e.Fields["pages"]); p != "" {
+ sp, ep, _ := strings.Cut(p, "–")
+ fmt.Fprintf(&b, "SP - %s\n", strings.TrimSpace(sp))
+ if ep != "" {
+ fmt.Fprintf(&b, "EP - %s\n", strings.TrimSpace(ep))
+ }
+ }
+ line("PB", "publisher")
+ line("DO", "doi")
+ b.WriteString("ER - \n\n")
+ }
+ return b.String()
+}
diff --git a/bib/fetch.go b/bib/fetch.go
@@ -0,0 +1,196 @@
+package bib
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "os/exec"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+ "unicode"
+)
+
+// Client resolves DOIs via Crossref and fetches BibTeX via doi.org content
+// negotiation, the same services scholarref's getdoi and getref use.
+type Client struct {
+ HTTP *http.Client
+ CrossrefURL string
+ DOIURL string
+}
+
+func NewClient() *Client {
+ return &Client{
+ HTTP: &http.Client{Timeout: 30 * time.Second},
+ CrossrefURL: "https://api.crossref.org/works",
+ DOIURL: "https://doi.org",
+ }
+}
+
+func (c *Client) get(u, accept string) ([]byte, error) {
+ req, err := http.NewRequest("GET", u, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Accept", accept)
+ req.Header.Set("User-Agent", "manus-tracker/0.1")
+ resp, err := c.HTTP.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ b, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return nil, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("%s: %s", u, resp.Status)
+ }
+ return b, nil
+}
+
+var doiInText = regexp.MustCompile(`(?i)\b(10\.\d{4,9}/[^\s"<>,;]+)`)
+
+// Lookup returns a DOI for a DOI string, a PDF file, or a free-text query.
+func (c *Client) Lookup(q string) (string, error) {
+ q = strings.TrimSpace(q)
+ if IsDOI(q) {
+ return NormDOI(q), nil
+ }
+ if fi, err := os.Stat(q); err == nil && !fi.IsDir() {
+ return doiFromPDF(q)
+ }
+ if q == "" {
+ return "", fmt.Errorf("empty query")
+ }
+ b, err := c.get(c.CrossrefURL+"?rows=1&select=DOI&query="+url.QueryEscape(q), "application/json")
+ if err != nil {
+ return "", err
+ }
+ var r struct {
+ Message struct {
+ Items []struct{ DOI string }
+ }
+ }
+ if err := json.Unmarshal(b, &r); err != nil {
+ return "", fmt.Errorf("crossref: %v", err)
+ }
+ if len(r.Message.Items) == 0 {
+ return "", fmt.Errorf("no DOI found for %q", q)
+ }
+ return NormDOI(r.Message.Items[0].DOI), nil
+}
+
+func doiFromPDF(path string) (string, error) {
+ for _, args := range [][]string{{"pdfinfo", path}, {"pdftotext", "-l", "3", path, "-"}} {
+ out, err := exec.Command(args[0], args[1:]...).Output()
+ if err != nil {
+ continue
+ }
+ if m := doiInText.FindString(string(out)); m != "" {
+ return NormDOI(strings.TrimRight(m, ".)")), nil
+ }
+ }
+ return "", fmt.Errorf("no DOI found in %s", path)
+}
+
+// Fetch retrieves and normalises the BibTeX entry for doi.
+func (c *Client) Fetch(doi string) (*Entry, error) {
+ b, err := c.get(c.DOIURL+"/"+NormDOI(doi), "application/x-bibtex")
+ if err != nil {
+ return nil, err
+ }
+ es, err := Parse(string(b))
+ if err != nil || len(es) == 0 {
+ return nil, fmt.Errorf("no BibTeX returned for %s", doi)
+ }
+ e := es[0]
+ Normalize(e)
+ e.Raw = Format(e)
+ return e, nil
+}
+
+var keyYear = regexp.MustCompile(`_(\d)`)
+
+// Normalize applies getref's conventions: Name_2010 keys become Name2010,
+// journal names and author first names are abbreviated, url and month drop.
+func Normalize(e *Entry) {
+ e.Key = keyYear.ReplaceAllString(e.Key, "$1")
+ e.Order = slices.DeleteFunc(e.Order, func(k string) bool { return k == "url" || k == "month" })
+ delete(e.Fields, "url")
+ delete(e.Fields, "month")
+ if j, ok := e.Fields["journal"]; ok {
+ e.Fields["journal"] = AbbrevJournal(j)
+ }
+ if a, ok := e.Fields["author"]; ok {
+ e.Fields["author"] = AbbrevAuthors(a)
+ }
+ if d, ok := e.Fields["doi"]; ok {
+ e.Fields["doi"] = NormDOI(d)
+ }
+}
+
+var journalAbbrev = []string{
+ "Journal", "J.", "Geophysical", "Geophys.", "Research", "Res.", "Geophysics", "Geophys.",
+ "Letters", "Lett.", "Mechanics", "Mech.", "Glaciology", "Glaciol.", "Proceedings", "Proc.",
+ "Royal", "R.", "Society", "Soc.", "Annals", "Ann.", "Resources", "Resour.", "Surface", "Surf.",
+ "Processes", "Proc.", "National", "Nat.", "Computers", "Comput.", "Geotechnics", "Geotech.",
+ "Academy", "Acad.", "Sciences", "Sci.", "Review", "Rev.", "Quaternary", "Quat.",
+ "Physical", "Phys.", "Planetary", "Planet.", "Quarterly", "Q.", "Geological", "Geol.",
+ "Statistical", "Stat.", "Applied", "Appl.", "Physics", "Phys.", "Communications", "Commun.",
+ "Geoscience", "Geosci.", "Landforms", "Land.", "Science", "Sci.", "Annual", "Ann.",
+ "International", "Int.", "Numerical", "Numer.", "Methods", "Meth.", "Geomechanics", "Geomech.",
+ "Analytical", "Anal.", "Advances", "Adv.", "Modeling", "Mod.", "Systems", "Sys.",
+ " for ", " ", " of ", " ", " and ", " ", " in ", " ",
+}
+
+// AbbrevJournal abbreviates a journal title with getref's word list. A
+// single-word title (e.g. "Science", "Geomorphology") is left unchanged.
+func AbbrevJournal(j string) string {
+ if !strings.Contains(strings.TrimSpace(j), " ") {
+ return j
+ }
+ for i := 0; i < len(journalAbbrev); i += 2 {
+ j = strings.ReplaceAll(j, journalAbbrev[i], journalAbbrev[i+1])
+ }
+ return j
+}
+
+// AbbrevAuthors shortens given names to initials: "Geoffrey S. Boulton"
+// becomes "G. S. Boulton"; "Boulton, Geoffrey S." becomes "Boulton, G. S.".
+func AbbrevAuthors(a string) string {
+ names := strings.Split(a, " and ")
+ for i, n := range names {
+ n = strings.TrimSpace(n)
+ if last, first, ok := strings.Cut(n, ","); ok {
+ names[i] = strings.TrimSpace(last) + ", " + initials(strings.Fields(first))
+ continue
+ }
+ w := strings.Fields(n)
+ if len(w) < 2 {
+ names[i] = n
+ continue
+ }
+ names[i] = initials(w[:len(w)-1]) + " " + w[len(w)-1]
+ }
+ return strings.Join(names, " and ")
+}
+
+func initials(words []string) string {
+ out := make([]string, 0, len(words))
+ for _, w := range words {
+ parts := strings.Split(w, "-")
+ for i, p := range parts {
+ r := []rune(p)
+ if len(r) > 0 && unicode.IsUpper(r[0]) && !strings.HasSuffix(p, ".") {
+ parts[i] = string(r[0]) + "."
+ }
+ }
+ out = append(out, strings.Join(parts, "-"))
+ }
+ return strings.Join(out, " ")
+}
diff --git a/bib/shared.go b/bib/shared.go
@@ -0,0 +1,77 @@
+package bib
+
+import (
+ "errors"
+ "os"
+)
+
+func loadIndex(path string) (*Index, error) {
+ es, err := ParseFile(path)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ return NewIndex(es), nil
+}
+
+// Add resolves query to a DOI and appends its entry to path unless the DOI
+// is already present. It returns the entry and whether it was added.
+func (c *Client) Add(path, query string) (*Entry, bool, error) {
+ ix, err := loadIndex(path)
+ if err != nil {
+ return nil, false, err
+ }
+ doi, err := c.Lookup(query)
+ if err != nil {
+ return nil, false, err
+ }
+ if e, ok := ix.ByDOI[doi]; ok {
+ return e, false, nil
+ }
+ e, err := c.Fetch(doi)
+ if err != nil {
+ return nil, false, err
+ }
+ if k := ix.FreeKey(e.Key); k != e.Key {
+ Rekey(e, k)
+ }
+ return e, true, Append(path, []*Entry{e})
+}
+
+type ImportResult struct {
+ Added []*Entry
+ Dups []*Entry
+ Renamed map[string]string
+}
+
+// Import appends entries from es that path lacks. Entries whose DOI, or
+// whose key and title, already exist are skipped; key clashes are renamed.
+func Import(path string, es []*Entry) (ImportResult, error) {
+ r := ImportResult{Renamed: map[string]string{}}
+ ix, err := loadIndex(path)
+ if err != nil {
+ return r, err
+ }
+ for _, e := range es {
+ if d := e.DOI(); d != "" {
+ if _, ok := ix.ByDOI[d]; ok {
+ r.Dups = append(r.Dups, e)
+ continue
+ }
+ }
+ if old, ok := ix.ByKey[e.Key]; ok {
+ if old.Fields["title"] == e.Fields["title"] {
+ r.Dups = append(r.Dups, e)
+ continue
+ }
+ k := ix.FreeKey(e.Key)
+ r.Renamed[e.Key] = k
+ Rekey(e, k)
+ }
+ r.Added = append(r.Added, e)
+ ix.ByKey[e.Key] = e
+ if d := e.DOI(); d != "" {
+ ix.ByDOI[d] = e
+ }
+ }
+ return r, Append(path, r.Added)
+}