func (m *merger) next() (index, offs int, start bool) {
	offs = infinity
	index = -1
	for i, seg := range m.segments {
		switch {
		case seg.start < offs:
			offs = seg.start
			index = i
			start = true
		case seg.end < offs:
			offs = seg.end
			index = i
			start = false
		}
	}
	if index < 0 {
		return
	}
	m.segments[index].start = infinity
	if start {
		return
	}
	m.segments[index].end = infinity
	seg := m.selections[index]()
	if !seg.isEmpty() {
		m.segments[index] = seg
	}
	return
}
next returns the next segment change: index specifies the Selection
to which the segment belongs, offs is the segment start or end offset
as determined by the start value. If there are no more segment changes,
next returns an index value < 0.
package godoc
import (
	"fmt"
	"go/scanner"
	"go/token"
	"io"
	"regexp"
	"strconv"
	"text/template"
)
type Segment struct {
	start, end int
}
func (seg *Segment) isEmpty() bool { return seg.start >= seg.end }
type Selection func() Segment
type LinkWriter func(w io.Writer, offs int, start bool)
type SegmentWriter func(w io.Writer, text []byte, selections int)
func FormatSelections(w io.Writer, text []byte, lw LinkWriter, links Selection, sw SegmentWriter, selections ...Selection) {
	if lw != nil {
		selections = append(selections, links)
	}
	changes := newMerger(selections)
	bitset := 0
	lastOffs := 0
	var last struct {
		begin, end int  
		bitset     int
	}
	flush := func() {
		if last.begin < last.end {
			sw(w, text[last.begin:last.end], last.bitset)
		}
		last.begin = last.end  
	}
	segment := func(end int) {
		if lastOffs < end {  
			if last.end != lastOffs || last.bitset != bitset {
				flush()
				last.begin = lastOffs
			}
			last.end = end
			last.bitset = bitset
		}
	}
	for {
		index, offs, start := changes.next()
		if index < 0 || offs > len(text) {
			break
		}
		if lw != nil && index == len(selections)-1 {
			segment(offs)
			flush()
			lastOffs = offs
			lw(w, offs, start)
		} else {
			segment(offs)
			lastOffs = offs
			mask := 1 << uint(index)
			if start {
				bitset |= mask
			} else {
				bitset &^= mask
			}
		}
	}
	segment(len(text))
	flush()
}
type merger struct {
	selections []Selection
	segments   []Segment  
}
const infinity int = 2e9
func newMerger(selections []Selection) *merger {
	segments := make([]Segment, len(selections))
	for i, sel := range selections {
		segments[i] = Segment{infinity, infinity}
		if sel != nil {
			if seg := sel(); !seg.isEmpty() {
				segments[i] = seg
			}
		}
	}
	return &merger{selections, segments}
}