manus-tracker

tracker for scientific manuscripts
git clone git://src.adamsgaard.dk/manus-tracker # fast
git clone https://src.adamsgaard.dk/manus-tracker.git # slow
Log | Files | Refs | README Back to index

export.go (4501B)


      1 package bib
      2 
      3 import (
      4 	"encoding/json"
      5 	"fmt"
      6 	"regexp"
      7 	"strconv"
      8 	"strings"
      9 )
     10 
     11 var accents = map[byte]string{
     12 	'"': "̈", '\'': "́", '`': "̀", '^': "̂", '~': "̃",
     13 	'=': "̄", '.': "̇", 'c': "̧", 'v': "̌", 'u': "̆", 'H': "̋",
     14 }
     15 
     16 var (
     17 	accentRe  = regexp.MustCompile(`\\(["'` + "`" + `^~=.]|[cvuH][\s{])\s*\{?\\?([A-Za-z])\}?`)
     18 	specialRe = regexp.MustCompile(`\\(o|O|ae|AE|aa|AA|ss|l|L|&|%|_)\b|\\(&|%|_)`)
     19 	cmdRe     = regexp.MustCompile(`\\[a-zA-Z]+\s*`)
     20 )
     21 
     22 var specials = map[string]string{"o": "ø", "O": "Ø", "ae": "æ", "AE": "Æ", "aa": "å", "AA": "Å", "ss": "ß", "l": "ł", "L": "Ł", "&": "&", "%": "%", "_": "_"}
     23 
     24 // Plain converts common LaTeX markup to Unicode text for CSL/RIS export.
     25 func Plain(s string) string {
     26 	s = accentRe.ReplaceAllStringFunc(s, func(m string) string {
     27 		sm := accentRe.FindStringSubmatch(m)
     28 		return sm[2] + accents[strings.TrimSpace(sm[1])[0]]
     29 	})
     30 	s = specialRe.ReplaceAllStringFunc(s, func(m string) string {
     31 		return specials[strings.TrimPrefix(m, `\`)]
     32 	})
     33 	s = strings.NewReplacer("---", "—", "--", "–", "~", " ").Replace(s)
     34 	s = cmdRe.ReplaceAllString(s, "")
     35 	s = strings.NewReplacer("{", "", "}", "").Replace(s)
     36 	return strings.Join(strings.Fields(s), " ")
     37 }
     38 
     39 type cslName struct {
     40 	Family  string `json:"family,omitempty"`
     41 	Given   string `json:"given,omitempty"`
     42 	Literal string `json:"literal,omitempty"`
     43 }
     44 
     45 func splitName(n string) cslName {
     46 	n = strings.TrimSpace(n)
     47 	if strings.HasPrefix(n, "{") && strings.HasSuffix(n, "}") {
     48 		return cslName{Literal: Plain(n)}
     49 	}
     50 	if last, first, ok := strings.Cut(n, ","); ok {
     51 		return cslName{Family: Plain(last), Given: Plain(first)}
     52 	}
     53 	w := strings.Fields(n)
     54 	if len(w) < 2 {
     55 		return cslName{Family: Plain(n)}
     56 	}
     57 	return cslName{Family: Plain(w[len(w)-1]), Given: Plain(strings.Join(w[:len(w)-1], " "))}
     58 }
     59 
     60 func authors(e *Entry) []cslName {
     61 	var out []cslName
     62 	if a := e.Fields["author"]; a != "" {
     63 		for _, n := range strings.Split(a, " and ") {
     64 			out = append(out, splitName(n))
     65 		}
     66 	}
     67 	return out
     68 }
     69 
     70 var cslType = map[string]string{
     71 	"article": "article-journal", "book": "book", "incollection": "chapter", "inbook": "chapter",
     72 	"inproceedings": "paper-conference", "conference": "paper-conference", "phdthesis": "thesis",
     73 	"mastersthesis": "thesis", "techreport": "report", "misc": "document", "dataset": "dataset",
     74 }
     75 
     76 // CSL renders entries as CSL-JSON (Zotero, pandoc --citeproc).
     77 func CSL(es []*Entry) ([]byte, error) {
     78 	var items []map[string]any
     79 	for _, e := range es {
     80 		t := cslType[e.Type]
     81 		if t == "" {
     82 			t = "document"
     83 		}
     84 		it := map[string]any{"id": e.Key, "type": t}
     85 		if a := authors(e); a != nil {
     86 			it["author"] = a
     87 		}
     88 		set := func(k, f string) {
     89 			if v := e.Fields[f]; v != "" {
     90 				it[k] = Plain(v)
     91 			}
     92 		}
     93 		set("title", "title")
     94 		set("container-title", "journal")
     95 		if _, ok := it["container-title"]; !ok {
     96 			set("container-title", "booktitle")
     97 		}
     98 		set("volume", "volume")
     99 		set("issue", "number")
    100 		set("page", "pages")
    101 		set("publisher", "publisher")
    102 		set("DOI", "doi")
    103 		if y, err := strconv.Atoi(e.Fields["year"]); err == nil {
    104 			it["issued"] = map[string]any{"date-parts": [][]int{{y}}}
    105 		}
    106 		items = append(items, it)
    107 	}
    108 	return json.MarshalIndent(items, "", "  ")
    109 }
    110 
    111 var risType = map[string]string{
    112 	"article": "JOUR", "book": "BOOK", "incollection": "CHAP", "inbook": "CHAP",
    113 	"inproceedings": "CONF", "conference": "CONF", "phdthesis": "THES", "mastersthesis": "THES",
    114 	"techreport": "RPRT", "dataset": "DATA",
    115 }
    116 
    117 // RIS renders entries in RIS format (Word reference managers, EndNote).
    118 func RIS(es []*Entry) string {
    119 	var b strings.Builder
    120 	for _, e := range es {
    121 		t := risType[e.Type]
    122 		if t == "" {
    123 			t = "GEN"
    124 		}
    125 		fmt.Fprintf(&b, "TY  - %s\nID  - %s\n", t, e.Key)
    126 		for _, a := range authors(e) {
    127 			if a.Literal != "" {
    128 				fmt.Fprintf(&b, "AU  - %s\n", a.Literal)
    129 			} else {
    130 				fmt.Fprintf(&b, "AU  - %s, %s\n", a.Family, a.Given)
    131 			}
    132 		}
    133 		line := func(tag, f string) {
    134 			if v := e.Fields[f]; v != "" {
    135 				fmt.Fprintf(&b, "%s  - %s\n", tag, Plain(v))
    136 			}
    137 		}
    138 		line("TI", "title")
    139 		line("JO", "journal")
    140 		line("T2", "booktitle")
    141 		line("PY", "year")
    142 		line("VL", "volume")
    143 		line("IS", "number")
    144 		if p := Plain(e.Fields["pages"]); p != "" {
    145 			sp, ep, _ := strings.Cut(p, "–")
    146 			fmt.Fprintf(&b, "SP  - %s\n", strings.TrimSpace(sp))
    147 			if ep != "" {
    148 				fmt.Fprintf(&b, "EP  - %s\n", strings.TrimSpace(ep))
    149 			}
    150 		}
    151 		line("PB", "publisher")
    152 		line("DO", "doi")
    153 		b.WriteString("ER  - \n\n")
    154 	}
    155 	return b.String()
    156 }