66 lines
1.9 KiB
Go
66 lines
1.9 KiB
Go
package shared
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
|
)
|
|
|
|
// CitationResolver resolves cited ranges against one source document.
|
|
type CitationResolver struct {
|
|
doc *source.SourceDocument
|
|
index source.DocumentIndex
|
|
}
|
|
|
|
// NewCitationResolver prepares citation resolution for doc.
|
|
func NewCitationResolver(doc *source.SourceDocument) (*CitationResolver, error) {
|
|
if doc == nil {
|
|
return nil, fmt.Errorf("source document must not be nil")
|
|
}
|
|
return &CitationResolver{doc: doc, index: source.NewDocumentIndex(doc)}, nil
|
|
}
|
|
|
|
// CitedText resolves cited source ranges in document order, including each
|
|
// source unit once, and joins the resulting text with newlines.
|
|
func (r *CitationResolver) CitedText(refs []source.SourceRef) (string, error) {
|
|
type interval struct{ start, end int }
|
|
intervals := make([]interval, 0, len(refs))
|
|
for _, ref := range refs {
|
|
if err := r.index.ValidateRef(ref); err != nil {
|
|
return "", fmt.Errorf("resolve cited source range: %w", err)
|
|
}
|
|
start, _ := r.index.Position(ref.StartUnitID)
|
|
end, _ := r.index.Position(ref.EndUnitID)
|
|
intervals = append(intervals, interval{start: start, end: end})
|
|
}
|
|
sort.Slice(intervals, func(i, j int) bool {
|
|
if intervals[i].start != intervals[j].start {
|
|
return intervals[i].start < intervals[j].start
|
|
}
|
|
return intervals[i].end < intervals[j].end
|
|
})
|
|
merged := intervals[:0]
|
|
for _, item := range intervals {
|
|
if len(merged) == 0 || item.start > merged[len(merged)-1].end+1 {
|
|
merged = append(merged, item)
|
|
} else {
|
|
previous := &merged[len(merged)-1]
|
|
previous.end = max(previous.end, item.end)
|
|
}
|
|
}
|
|
var text strings.Builder
|
|
first := true
|
|
for _, item := range merged {
|
|
for position := item.start; position <= item.end; position++ {
|
|
if !first {
|
|
text.WriteByte('\n')
|
|
}
|
|
first = false
|
|
text.WriteString(r.doc.Units[position].Text)
|
|
}
|
|
}
|
|
return text.String(), nil
|
|
}
|