feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
package markdown
import (
"sync"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// The icons of GitHub's alerts: Octicons' info, light-bulb, report, alert
// and stop, 16 px (https://github.com/primer/octicons, MIT License,
// Copyright (c) GitHub Inc.).
var alertPaths = [5]string{
"M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8Zm8-6.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13ZM6.5 7.75A.75.75 0 0 1 7.25 7h1a.75.75 0 0 1 .75.75v2.75h.25a.75.75 0 0 1 0 1.5h-2a.75.75 0 0 1 0-1.5h.25v-2h-.25a.75.75 0 0 1-.75-.75ZM8 6a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z",
"M8 1.5c-2.363 0-4 1.69-4 3.75 0 .984.424 1.625.984 2.304l.214.253c.223.264.47.556.673.848.284.411.537.896.621 1.49a.75.75 0 0 1-1.484.211c-.04-.282-.163-.547-.37-.847a8.456 8.456 0 0 0-.542-.68c-.084-.1-.173-.205-.268-.32C3.201 7.75 2.5 6.766 2.5 5.25 2.5 2.31 4.863 0 8 0s5.5 2.31 5.5 5.25c0 1.516-.701 2.5-1.328 3.259-.095.115-.184.22-.268.319-.207.245-.383.453-.541.681-.208.3-.33.565-.37.847a.751.751 0 0 1-1.485-.212c.084-.593.337-1.078.621-1.489.203-.292.45-.584.673-.848.075-.088.147-.173.213-.253.561-.679.985-1.32.985-2.304 0-2.06-1.637-3.75-4-3.75ZM5.75 12h4.5a.75.75 0 0 1 0 1.5h-4.5a.75.75 0 0 1 0-1.5ZM6 15.25a.75.75 0 0 1 .75-.75h2.5a.75.75 0 0 1 0 1.5h-2.5a.75.75 0 0 1-.75-.75Z",
"M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v9.5A1.75 1.75 0 0 1 14.25 13H8.06l-2.573 2.573A1.458 1.458 0 0 1 3 14.543V13H1.75A1.75 1.75 0 0 1 0 11.25Zm1.75-.25a.25.25 0 0 0-.25.25v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25Zm7 2.25v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 9a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z",
"M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z",
"M4.47.22A.749.749 0 0 1 5 0h6c.199 0 .389.079.53.22l4.25 4.25c.141.14.22.331.22.53v6a.749.749 0 0 1-.22.53l-4.25 4.25A.749.749 0 0 1 11 16H5a.749.749 0 0 1-.53-.22L.22 11.53A.749.749 0 0 1 0 11V5c0-.199.079-.389.22-.53Zm.84 1.28L1.5 5.31v5.38l3.81 3.81h5.38l3.81-3.81V5.31L10.69 1.5ZM8 4a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 4Zm0 8a1 1 0 1 1 0-2 1 1 0 0 1 0 2Z",
}
// alertIcons are parsed the first time an alert shows.
var alertIcons = sync.OnceValue(func() (icons [5]*ui.SVG) {
for k, d := range alertPaths {
icons[k], _ = ui.ParseSVG([]byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="` + d + `"/></svg>`))
}
return icons
})
// alertIcon returns the icon of an alert's kind, or nil.
func alertIcon(a parser.Alert) *ui.SVG {
if a == parser.NoAlert || int(a) > len(alertPaths) {
return nil
}
return alertIcons()[a-1]
}
+139
View File
@@ -0,0 +1,139 @@
package markdown
import (
"slices"
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
func TestViewAlert(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) { View(c, "> [!WARNING]\n> Mind the gap.", nil) }, 600, 400)
for _, s := range []string{"Warning", "Mind the gap."} {
if !tt.HasText(s) {
t.Errorf("no %q in %q", s, tt.Texts())
}
}
if tt.HasText("[!WARNING]") {
t.Errorf("the marker shows: %q", tt.Texts())
}
// A marker alone in its paragraph shows nothing either.
tt = ui.NewTester(func(c *ui.Context) { View(c, "> [!TIP]\n>\n> - one", nil) }, 600, 400)
if !tt.HasText("Tip") || tt.HasText("[!TIP]") {
t.Errorf("got %q", tt.Texts())
}
}
// resolver knows octocat and issue 12 of the document's repository, as
// paths of the app, and whom it knows once told.
type resolver struct{ known []string }
func (r *resolver) resolve(in parser.Inline) (string, bool) {
switch in.Kind {
case parser.Mention:
if slices.Contains(r.known, in.Login()) {
return "/users/" + in.Login(), true
}
case parser.Reference:
if repo, n := in.Ref(); repo == "" && n == 12 {
return "/pulls/12", true
}
}
return "", false
}
func TestViewMentions(t *testing.T) {
r := &resolver{known: []string{"octocat"}}
var opened []string
o := &Options{Resolve: r.resolve, OnLink: func(url string) { opened = append(opened, url) }}
src := "Thanks @octocat and @nobody, see #12 and #13."
tt := ui.NewTester(func(c *ui.Context) { View(c, src, o) }, 600, 400)
for _, s := range []string{"@octocat", "#12"} {
if err := tt.Click(s); err != nil {
t.Fatalf("%s: %v in %q", s, err, tt.Texts())
}
}
if !slices.Equal(opened, []string{"/users/octocat", "/pulls/12"}) {
t.Errorf("opened %q", opened)
}
// Those it does not know stay text.
if err := tt.Click("@nobody"); err == nil {
t.Error("@nobody is a link")
}
// Once the app knows them, they link.
r.known = append(r.known, "nobody")
tt.Frame()
if err := tt.Click("@nobody"); err != nil || opened[len(opened)-1] != "/users/nobody" {
t.Errorf("@nobody once known: %v, opened %q", err, opened)
}
// Resolve set later makes them links, and cleared, text again.
var o2 Options
tt = ui.NewTester(func(c *ui.Context) { View(c, src, &o2) }, 600, 400)
if err := tt.Click("@octocat"); err == nil {
t.Error("@octocat is a link without Resolve")
}
o2.Resolve, o2.OnLink = r.resolve, o.OnLink
tt.Frame()
if err := tt.Click("@octocat"); err != nil {
t.Errorf("@octocat once Resolve is set: %v in %q", err, tt.Texts())
}
o2.Resolve = nil
tt.Frame()
if err := tt.Click("@octocat"); err == nil {
t.Error("@octocat is still a link once Resolve is cleared")
}
// Without Resolve, they are text.
tt = ui.NewTester(func(c *ui.Context) { View(c, src, nil) }, 600, 400)
if !tt.HasText(src) {
t.Errorf("not one text: %q", tt.Texts())
}
}
func TestViewPreview(t *testing.T) {
r := &resolver{known: []string{"octocat"}}
var asked []string
o := &Options{Resolve: r.resolve, Preview: func(c *ui.Context, dest string) func(tip ui.Element) {
asked = append(asked, dest)
if !strings.HasPrefix(dest, "/users/") {
return nil
}
return func(tip ui.Element) {
tip.Padding(8).Children(func() { ui.Text(c, "The Octocat") })
}
}}
tt := ui.NewTester(func(c *ui.Context) { View(c, "Hi @octocat, see [docs](https://go.dev).", o) }, 600, 400)
at, ok := tt.Find("@octocat")
if !ok {
t.Fatalf("no @octocat in %q", tt.Texts())
}
tt.Move(at.X+at.W/2, at.Y+at.H/2)
for range 10 {
tt.Advance(100 * time.Millisecond)
tt.Frame()
}
if !tt.HasText("The Octocat") {
t.Errorf("no card while the pointer rests: %q", tt.Texts())
}
if !slices.Contains(asked, "https://go.dev") {
t.Errorf("Preview not asked of every link: %q", asked)
}
}
// Part of a mention written with an entity copies as that part of its
// source, as text does.
func TestViewCopyMentionEntity(t *testing.T) {
src := "Thanks &#64;octocat now"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
if text != "Thanks @octocat now" {
t.Fatalf("text %q", text)
}
if got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 8, 12)}); got != "octo" {
t.Errorf("copied %q, want %q", got, "octo")
}
}
+49
View File
@@ -0,0 +1,49 @@
package markdown
import (
"os"
"testing"
"github.com/egoist/mygo/ui"
)
func llm(b *testing.B) string {
data, err := os.ReadFile("parser/testdata/llm.md")
if err != nil {
b.Fatal(err)
}
return string(data)
}
// BenchmarkViewSteady draws frames of the 50 KB answer shown whole, in a
// window of 800 by 1000, as nothing changes.
func BenchmarkViewSteady(b *testing.B) {
src := llm(b)
tt := ui.NewTester(func(c *ui.Context) {
ui.Scroll(c).Fill().Children(func() { View(c, src, nil) })
}, 800, 1000)
b.ReportAllocs()
for b.Loop() {
tt.Frame()
}
}
// BenchmarkViewStream draws the frames of the 50 KB answer streaming in,
// 16 bytes a frame, as a chat follows a reply's end; it reports the time
// of a frame with its token.
func BenchmarkViewStream(b *testing.B) {
src := llm(b)
o := &Options{Reveal: &Reveal{Unit: AtOnce}}
n := 0
tt := ui.NewTester(func(c *ui.Context) {
ui.Scroll(c).Fill().Children(func() { Stream(c, src[:n], o) })
}, 800, 1000)
b.ReportAllocs()
for b.Loop() {
n += 16
if n > len(src) {
n = 16
}
tt.Frame()
}
}
+269
View File
@@ -0,0 +1,269 @@
package markdown
import (
"time"
"github.com/egoist/mygo/internal/l10n"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
)
// CodeBlockView is a code block as Options.CodeBlock and Options.Code build
// it.
type CodeBlockView struct {
// Language is the language its fence names, as "go", and Info the
// whole info string after the fence.
Language, Info string
// Open tells a block still being written, whose closing fence has not
// come: heavy renderers, as of diagrams, wait for it to close.
Open bool
// Index is the block's in the Document.
Index int
st *viewState
}
// Code returns the block's code, its lines ending with newlines.
func (b *CodeBlockView) Code() string { return b.st.doc.Lines(b.Index) }
// SourceLine returns the line of the view's source the block starts on,
// from 1: its opening fence, or indented code's first line. Line k of a
// fenced block's Code, from 1, is line SourceLine()+k of the source, and
// of indented code line SourceLine()+k-1: an app that builds the block as
// a view of its own, as of the Markdown in it, maps that view's lines
// (Options.OnTask's) back to the source so.
func (b *CodeBlockView) SourceLine() int {
return lineAt(b.st.doc.Source(), b.st.doc.Block(b.Index).Start)
}
// codeState is what a view keeps of a code block: the tokens of its lines
// and the spans of its chunks of lines, to highlight only what changed.
type codeState struct {
lang string
tok editor.Tokenizer
lines []string
ends []uint64
toks [][]editor.Token
chunks []codeChunk
copiedAt time.Time
seen bool
}
// codeChunk is chunkLines lines of a code block, laid out as one text, so
// that a block growing as it streams lays out only its last chunk anew.
type codeChunk struct {
spans []ui.Span
n int // lines
ok bool
}
const chunkLines = 32
func (st *viewState) codeState(i int) *codeState {
b := st.doc.Block(i)
if st.codes == nil {
st.codes = map[int]*codeState{}
}
cs := st.codes[b.Start]
lang := b.Language()
if cs == nil || cs.lang != lang {
cs = &codeState{lang: lang}
if l := editor.LanguageNamed(lang); l != nil && lang != "" {
cs.tok = l.Tokenizer
}
st.codes[b.Start] = cs
}
cs.seen = true
return cs
}
// codeBlock builds code block i, through the hooks of the options.
func (st *viewState) codeBlock(c *ui.Context, i int) ui.Element {
b := st.doc.Block(i)
cb := &CodeBlockView{Language: b.Language(), Info: b.Info(), Open: b.Open, Index: i, st: st}
if f := st.o.Code[cb.Language]; f != nil {
box := ui.Column(c)
return box.Children(func() { f(c, cb) })
}
if st.o.CodeBlock != nil {
box := ui.Column(c)
return box.Children(func() { st.o.CodeBlock(c, cb) })
}
return DefaultCodeBlock(c, cb)
}
// DefaultCodeBlock builds a code block as views do without hooks: a box
// with the language and a copy button above the highlighted code.
func DefaultCodeBlock(c *ui.Context, b *CodeBlockView) ui.Element {
th := &b.st.th
box := ui.Column(c).Direction(ui.LeftToRight).Background(th.CodeBlockBackground).Border(1, th.CodeBlockBorder).Radius(th.CodeBlockRadius).AlignSelf(ui.Stretch).Clip()
box.Role(ui.RoleGroup).Label(codeLabel(b.Language))
return box.Children(func() {
head := ui.Row(c).AlignItems(ui.Center).Padding(th.em(0.35), th.em(0.4), 0, th.em(th.CodeBlockPadding))
head.Children(func() {
ui.Text(c, b.Language).FontSize(th.em(0.8)).TextColor(th.Muted).Unselectable()
ui.Spacer(c)
b.CopyButton(c)
})
b.Body(c)
})
}
func codeLabel(lang string) string {
if lang == "" {
return "Code"
}
return "Code, " + lang
}
var (
copyIcon = ui.MustParseSVG([]byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><rect x="5.5" y="5.5" width="8" height="8" rx="1.6"/><path d="M10.5 3.6V3.2A1.7 1.7 0 0 0 8.8 1.5H4.2A1.7 1.7 0 0 0 2.5 3.2v4.6a1.7 1.7 0 0 0 1.7 1.7h.4"/></svg>`))
checkIcon = ui.MustParseSVG([]byte(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 8.5l3 3 6-7"/></svg>`))
)
// CopyButton builds a button copying the block's code, which shows that
// it did for two seconds, and waits for a block being written to close.
func (b *CodeBlockView) CopyButton(c *ui.Context) ui.Element {
st := b.st
th := &st.th
cs := st.codeState(b.Index)
copied := !cs.copiedAt.IsZero() && c.Now().Sub(cs.copiedAt) < 2*time.Second
tx := l10n.In(c.Locale())
btn := ui.ButtonBase(c).Padding(th.em(0.2), th.em(0.45)).Radius(5).Gap(th.em(0.3)).Label(tx.CopyCode()).Disabled(b.Open)
if btn.Hovered() && !b.Open {
btn.Background(th.Text.Alpha(0.08))
}
btn.Children(func() {
icon, label := copyIcon, tx.Copy()
if copied {
icon, label = checkIcon, tx.Copied()
}
size := th.em(0.95)
ui.Icon(c, icon).Size(size, size).TextColor(th.Muted)
ui.Text(c, label).FontSize(th.em(0.8)).TextColor(th.Muted)
})
if btn.Clicked() {
c.WriteClipboard(b.Code())
cs.copiedAt = c.Now()
c.After(2 * time.Second)
}
return btn
}
// Body builds the block's code, highlighted, selectable with the view's
// text, scrolling sideways unless Options.WrapCode.
func (b *CodeBlockView) Body(c *ui.Context) ui.Element {
st := b.st
th := &st.th
cs := st.codeState(b.Index)
st.highlight(cs, b.Index)
pad := th.em(th.CodeBlockPadding)
var outer ui.Element
if st.o.WrapCode {
outer = ui.Column(c)
} else {
outer = ui.ScrollHorizontal(c)
}
// Code reads left to right in a right-to-left interface too, as in
// editors.
outer.Direction(ui.LeftToRight).AlignSelf(ui.Stretch).Font(th.CodeFont).FontSize(th.em(th.CodeSize)).LineHeight(th.CodeLineHeight)
return outer.Children(func() {
col := ui.Column(c).Padding(th.em(0.25), pad, pad, pad)
if !st.o.WrapCode {
col.Shrink(0)
}
col.Children(func() {
for k := range cs.chunks {
ch := &cs.chunks[k]
el := ui.RichText(c, ch.spans...)
if !st.o.WrapCode {
el.NoWrap()
}
st.note(el.ID(), b.Index, k*chunkLines)
}
})
})
}
// highlight tokenizes the lines of code block i that changed, and makes
// the spans of the chunks they are in anew.
func (st *viewState) highlight(cs *codeState, i int) {
d := st.doc
n := d.LineCount(i)
// The first line that differs from those tokenized.
k0 := 0
for k0 < n && k0 < len(cs.lines) {
line, _ := d.Line(i, k0)
if line != cs.lines[k0] {
break
}
k0++
}
if k0 == n && len(cs.lines) == n && len(cs.chunks) == (n+chunkLines-1)/chunkLines {
return
}
cs.lines, cs.ends, cs.toks = cs.lines[:k0], cs.ends[:k0], cs.toks[:k0]
state := uint64(0)
if k0 > 0 {
state = cs.ends[k0-1]
}
for k := k0; k < n; k++ {
line, _ := d.Line(i, k)
var toks []editor.Token
if cs.tok != nil {
toks, state = cs.tok.Tokenize(line, state, nil)
}
cs.lines = append(cs.lines, line)
cs.ends = append(cs.ends, state)
cs.toks = append(cs.toks, toks)
}
chunks := (n + chunkLines - 1) / chunkLines
if n == 0 {
chunks = 1
}
for len(cs.chunks) < chunks {
cs.chunks = append(cs.chunks, codeChunk{})
}
cs.chunks = cs.chunks[:chunks]
for k := k0 / chunkLines; k < chunks; k++ {
cs.chunks[k].ok = false
}
ct := st.th.CodeColors
for k := range cs.chunks {
ch := &cs.chunks[k]
if ch.ok {
continue
}
ch.spans = ch.spans[:0]
first := k * chunkLines
last := min(first+chunkLines, n)
for l := first; l < last; l++ {
if l > first {
ch.spans = append(ch.spans, ui.Span{Text: "\n"})
}
line := cs.lines[l]
start := 0
for _, t := range cs.toks[l] {
end := min(t.End, len(line))
if end > start {
sp := ui.Span{Text: line[start:end], Color: ct.TokenColor(t.Kind)}
if s := ct.Tokens[t.Kind]; s.Bold {
sp.Weight = 600
} else if s.Italic {
sp.Italic = true
}
ch.spans = append(ch.spans, sp)
}
start = max(start, end)
}
if start < len(line) {
ch.spans = append(ch.spans, ui.Span{Text: line[start:], Color: ct.Text})
}
}
if len(ch.spans) == 0 {
ch.spans = append(ch.spans, ui.Span{Text: " "})
}
ch.n = last - first
ch.ok = true
}
}
+70
View File
@@ -0,0 +1,70 @@
package markdown
import (
"slices"
"strings"
"testing"
"github.com/egoist/mygo/ui"
)
func TestViewCodeLink(t *testing.T) {
files := map[string]string{"src/app.go:12": "file:src/app.go#L12"}
var opened []string
o := &Options{
CodeLink: func(code string) (string, bool) { d, ok := files[code]; return d, ok },
OnLink: func(url string) { opened = append(opened, url) },
}
src := "See `src/app.go:12` and `go test`, and @octocat."
tt := ui.NewTester(func(c *ui.Context) { View(c, src, o) }, 600, 400)
if err := tt.Click("src/app.go:12"); err != nil {
t.Fatalf("%v in %q", err, tt.Texts())
}
if !slices.Equal(opened, []string{"file:src/app.go#L12"}) {
t.Errorf("opened %q", opened)
}
// Code it doesn't know, and mentions without Resolve, stay text.
for _, s := range []string{"go test", "@octocat"} {
if err := tt.Click(s); err == nil {
t.Errorf("%s is a link", s)
}
}
// It's asked again as the view builds: code it learns of links.
files["go test"] = "cmd:go-test"
tt.Frame()
if err := tt.Click("go test"); err != nil || opened[len(opened)-1] != "cmd:go-test" {
t.Errorf("go test once known: %v, opened %q", err, opened)
}
// Cleared, it's all text again, as one run.
o.CodeLink = nil
tt.Frame()
if err := tt.Click("src/app.go:12"); err == nil {
t.Error("still a link once CodeLink is cleared")
}
if !tt.HasText("See src/app.go:12 and go test, and @octocat.") {
t.Errorf("text %q", tt.Texts())
}
}
func TestViewCodeLinkStreaming(t *testing.T) {
asked := 0
o := &Options{Reveal: &Reveal{Unit: AtOnce, Fade: -1}, CodeLink: func(code string) (string, bool) {
asked++
return "file:" + code, strings.Contains(code, "/")
}}
var src string
tt := ui.NewTester(func(c *ui.Context) { Stream(c, src, o) }, 600, 400)
for _, part := range []string{"Open `a/b", ".go` now", " and `c/d.go`."} {
src += part
tt.Frame()
}
if err := tt.Click("c/d.go"); err != nil {
t.Fatalf("%v in %q", err, tt.Texts())
}
if err := tt.Click("a/b.go"); err != nil {
t.Fatalf("%v in %q", err, tt.Texts())
}
if asked == 0 {
t.Error("never asked")
}
}
+427
View File
@@ -0,0 +1,427 @@
package markdown
import (
"slices"
"strings"
"unicode"
"unicode/utf8"
"github.com/egoist/mygo/transfer"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// Copying: as text, a view joins its paragraphs with blank lines, a code
// block's lines and a tight list's items with newlines and a table's
// cells with tabs; as Markdown, it copies the source between the
// selection's ends, with the syntax of emphasis, code and links cut by
// them completed.
func (st *viewState) elem(id uint64) (elemInfo, bool) {
for _, e := range st.elems {
if e.id == id {
return e, true
}
}
return elemInfo{}, false
}
// copyText returns the text of the selected parts.
func (st *viewState) copyText(parts []ui.SelectedText) string {
var b strings.Builder
var prev elemInfo
for k, p := range parts {
inf, ok := st.elem(p.ID)
if k > 0 {
if ok {
b.WriteString(st.separator(prev, inf))
} else {
b.WriteString("\n")
}
}
if ok {
st.writeText(&b, inf, p)
} else {
b.WriteString(runeSlice(p.Text, p.Start, p.End))
}
prev = inf
}
return b.String()
}
// writeText writes the text of a selected part, with the source of the
// math drawn as objects, as $x_i$, in place of their characters, and
// without links' icons, which have no source, or their joiners.
func (st *viewState) writeText(b *strings.Builder, inf elemInfo, p ui.SelectedText) {
text := runeSlice(p.Text, p.Start, p.End)
if inf.line != -1 || inf.block >= len(st.paras) || !st.paras[inf.block].ok || len(st.paras[inf.block].p.objects) == 0 {
b.WriteString(text)
return
}
objects := st.paras[inf.block].p.objects
src := st.doc.Source()
r := p.Start
for _, c := range text {
if c == linkIconJoiner {
if k, found := slices.BinarySearchFunc(objects, r-1, func(o mathObject, r int) int { return o.rune - r }); found && objects[k].src == objects[k].end {
r++
continue
}
}
k, found := slices.BinarySearchFunc(objects, r, func(o mathObject, r int) int { return o.rune - r })
if found && c == '\uFFFC' && objects[k].end <= len(src) {
b.WriteString(src[objects[k].src:objects[k].end])
} else {
b.WriteRune(c)
}
r++
}
}
// copyData returns the selection as Copy puts it on the clipboard: as
// text, as HTML and as Markdown.
func (st *viewState) copyData(parts []ui.SelectedText) transfer.Data {
md := st.copyMarkdown(parts)
d := parser.New(st.doc.Extensions())
d.Set(md)
return transfer.New(transfer.NewItem(
transfer.Bytes(transfer.Text, []byte(st.copyText(parts))),
transfer.Bytes(transfer.HTML, []byte(`<meta charset="utf-8">`+d.HTML())),
transfer.Bytes(transfer.Markdown, []byte(md)),
))
}
// markdownData returns Markdown as Copy as Markdown puts it on the
// clipboard: as text, and as Markdown.
func markdownData(md string) transfer.Data {
return transfer.New(transfer.NewItem(
transfer.Bytes(transfer.Text, []byte(md)),
transfer.Bytes(transfer.Markdown, []byte(md)),
))
}
func runeSlice(s string, from, to int) string {
i, n := 0, 0
a, z := len(s), len(s)
for i < len(s) {
if n == from {
a = i
}
if n == to {
z = i
break
}
_, w := utf8.DecodeRuneInString(s[i:])
i += w
n++
}
if from >= n && a == len(s) {
a = len(s)
}
return s[a:max(a, z)]
}
// separator returns what goes between the text of two blocks copied.
func (st *viewState) separator(a, b elemInfo) string {
d := st.doc
if a.block == b.block {
return "\n"
}
ab, bb := d.Block(a.block), d.Block(b.block)
if ab.Kind == parser.TableCell && bb.Kind == parser.TableCell {
if ab.Parent == bb.Parent {
return "\t"
}
return "\n"
}
// Items of the same tight list.
if l := st.listOf(b.block); l > 0 && d.Block(l).Tight && st.listOf(a.block) == l || st.listOf(a.block) > 0 && d.Block(st.listOf(a.block)).Tight && st.within(b.block, st.listOf(a.block)) {
return "\n"
}
return "\n\n"
}
// listOf returns the nearest list around block i, or 0.
func (st *viewState) listOf(i int) int {
for p := st.doc.Block(i).Parent; p > 0; p = st.doc.Block(p).Parent {
if st.doc.Block(p).Kind == parser.List {
return p
}
}
return 0
}
func (st *viewState) within(i, anc int) bool {
for p := st.doc.Block(i).Parent; p >= 0; p = st.doc.Block(p).Parent {
if p == anc {
return true
}
}
return false
}
// srcAt returns the source offset of rune r of an element's text, for
// the end of a selection when end.
func (st *viewState) srcAt(inf elemInfo, r int, end bool) int {
d := st.doc
b := d.Block(inf.block)
switch b.Kind {
case parser.CodeBlock, parser.HTMLBlock, parser.MathBlock:
// Lines from inf.line on, each followed by a newline.
n := d.LineCount(inf.block)
for k := max(inf.line, 0); k < n; k++ {
line, at := d.Line(inf.block, k)
c := utf8.RuneCountInString(line)
if r <= c || k == n-1 {
// Spaces standing for a tab partly taken by indentation
// are not the source's.
pad := linePad(d.Source(), line, at)
off := at
for j := pad; j < r && off < len(d.Source()); j++ {
_, w := utf8.DecodeRuneInString(d.Source()[off:])
off += w
}
return off
}
r -= c + 1
}
return b.Start
}
if inf.block < len(st.paras) && st.paras[inf.block].ok {
return st.paras[inf.block].p.sourceAt(d.Source(), r, end)
}
return b.Start
}
// copyMarkdown returns the Markdown of the selected parts, or of the
// whole document when none is selected. The parts of views sharing the
// selection (Options.ShareSelection) built within this one's blocks copy
// as those views copy them, each as the Markdown of its own source,
// between this one's.
func (st *viewState) copyMarkdown(parts []ui.SelectedText) string {
if len(parts) == 0 {
return st.doc.Source()
}
runs := st.runs(parts)
if len(runs) == 1 && runs[0].st == st {
// This view's alone, with what it does not know at its ends.
return st.ownMarkdown(parts)
}
if len(runs) == 0 {
return st.copyText(parts)
}
var b strings.Builder
for k, r := range runs {
if k > 0 {
b.WriteString(st.separator(runs[k-1].last, r.first))
}
b.WriteString(r.st.copyMarkdown(parts[r.from:r.to]))
}
return b.String()
}
// mdRun is a run of selected parts that one view copies as Markdown:
// this one, or a view sharing its selection within it. first and last
// are where the run starts and ends among this view's blocks.
type mdRun struct {
st *viewState
from, to int
first, last elemInfo
}
// runs splits the selected parts into runs of the views that know them.
// Parts no view knows within a run (the text of blocks built by
// Options.Block, Math or HTML) stay in it, and those between runs or at
// the ends go.
func (st *viewState) runs(parts []ui.SelectedText) []mdRun {
var runs []mdRun
for k, p := range parts {
owner, at, ok := st.owner(p.ID)
if !ok {
continue
}
if n := len(runs); n > 0 && runs[n-1].st == owner {
runs[n-1].to, runs[n-1].last = k+1, at
continue
}
runs = append(runs, mdRun{st: owner, from: k, to: k + 1, first: at, last: at})
}
return runs
}
// owner returns the view that copies element id, this one or a view
// sharing its selection within it, and where the element is among this
// view's blocks.
func (st *viewState) owner(id uint64) (*viewState, elemInfo, bool) {
if inf, ok := st.elem(id); ok {
return st, inf, true
}
for _, n := range st.nested {
if n.st.knows(id) {
return n.st, elemInfo{id: id, block: n.block, line: -1}, true
}
}
return nil, elemInfo{}, false
}
// knows reports whether the view, or a view sharing its selection within
// it, built element id.
func (st *viewState) knows(id uint64) bool {
_, _, ok := st.owner(id)
return ok
}
// ownMarkdown returns the Markdown of the selected parts of this view's
// own text.
func (st *viewState) ownMarkdown(parts []ui.SelectedText) string {
d := st.doc
first, last := parts[0], parts[len(parts)-1]
fi, ok1 := st.elem(first.ID)
li, ok2 := st.elem(last.ID)
if !ok1 || !ok2 {
return st.copyText(parts)
}
fb, lb := d.Block(fi.block), d.Block(li.block)
a := st.srcAt(fi, first.Start, false)
b := st.srcAt(li, last.End, true)
atStart := first.Start == 0 && fi.line <= 0
atEnd := last.End >= utf8.RuneCountInString(last.Text)
if lb.Kind == parser.CodeBlock && atEnd {
// Only the last chunk of lines ends the block.
atEnd = li.line+chunkLines >= d.LineCount(li.block)
}
// From a block's start, or to its end, its syntax too: a heading's #,
// a list's marker, a quote's >, a table row's pipes, a code block's
// fences when it is selected whole.
switch {
case !atStart:
case fb.Kind == parser.TableCell:
// A row's pipes go with it when cells after it are selected too.
if fi.block == fb.Parent+1 && li.block != fi.block {
a = lineStartOf(d.Source(), fb.Start)
}
case fb.Kind == parser.CodeBlock:
if fb.Fenced && atEnd && fi.block == li.block {
a = lineStartOf(d.Source(), fb.Start)
}
default:
a = lineStartOf(d.Source(), fb.Start)
}
switch {
case !atEnd:
case lb.Kind == parser.TableCell:
if lb.Next == d.Block(lb.Parent).Next && li.block != fi.block {
b = lineEndOf(d.Source(), lb.End)
}
case lb.Kind == parser.CodeBlock:
if lb.Fenced && !lb.Open && atStart && fi.block == li.block {
b = lb.End
}
default:
b = lineEndOf(d.Source(), lb.End)
}
if b < a {
a, b = b, a
}
prefix := st.openAt(fi.block, a)
suffix := st.closeAt(li.block, b)
return prefix + d.Source()[a:b] + suffix
}
func lineEndOf(src string, off int) int {
for off < len(src) && src[off] != '\n' && src[off] != '\r' {
off++
}
return off
}
// openAt returns the opening syntax of the inline spans of block i that
// offset at falls inside, outermost first.
func (st *viewState) openAt(i, at int) string {
in := st.doc.Inlines(i)
var b strings.Builder
for k := range in {
n := &in[k]
if n.Start < at && at < n.End {
if open := st.openSyntax(in, k); open != "" {
b.WriteString(open)
}
}
}
return b.String()
}
// closeAt returns the closing syntax of the inline spans of block i that
// offset at falls inside, innermost first.
func (st *viewState) closeAt(i, at int) string {
in := st.doc.Inlines(i)
var closes []string
for k := range in {
n := &in[k]
if n.Start < at && at < n.End {
if c := st.closeSyntax(in, k); c != "" {
closes = append(closes, c)
}
}
}
slices.Reverse(closes)
return strings.Join(closes, "")
}
func (st *viewState) openSyntax(in []parser.Inline, k int) string {
n := &in[k]
src := st.doc.Source()
switch n.Kind {
case parser.Emphasis, parser.Strong, parser.Strikethrough, parser.Link:
if k+1 < n.Next {
return src[n.Start:in[k+1].Start]
}
case parser.Code:
return src[n.Start:codeStart(src, n)]
}
return ""
}
func (st *viewState) closeSyntax(in []parser.Inline, k int) string {
n := &in[k]
src := st.doc.Source()
switch n.Kind {
case parser.Emphasis, parser.Strong, parser.Strikethrough, parser.Link:
if k+1 < n.Next {
// The end of its last child.
end := in[k+1].End
for j := k + 1; j < n.Next; j = in[j].Next {
end = in[j].End
}
return src[end:n.End]
}
case parser.Code:
ticks := codeStart(src, n) - n.Start
return src[n.End-ticks : n.End]
}
return ""
}
// linePad returns how many spaces a code line starts with that are not
// the source's at, standing for a tab partly taken by indentation.
func linePad(src, line string, at int) int {
pad := 0
for pad < len(line) && line[pad] == ' ' && !strings.HasPrefix(src[at:], line[pad:]) {
pad++
}
return pad
}
func lineStartOf(src string, off int) int {
for off > 0 && src[off-1] != '\n' && src[off-1] != '\r' {
off--
}
return off
}
// isEscapable reports whether a backslash escapes c: ASCII punctuation.
func isEscapable(c byte) bool {
return c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~'
}
func isAlnum(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
+110
View File
@@ -0,0 +1,110 @@
package markdown
import (
"os"
"path/filepath"
"strings"
"sync"
"github.com/egoist/mygo/internal/l10n"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// imageEntry is an image loading or loaded.
type imageEntry struct {
mu sync.Mutex
src ui.ImageSource
err error
done bool
}
// FileImages returns a LoadImage for the files of directory dir, which
// paths without a scheme are relative to: PNG, JPEG, GIF, WebP, BMP and
// SVG. Other addresses do not load.
func FileImages(dir string) func(url string) (ui.ImageSource, error) {
return func(url string) (ui.ImageSource, error) {
if strings.Contains(url, "://") || strings.HasPrefix(url, "data:") {
return nil, os.ErrNotExist
}
path := strings.TrimPrefix(url, "file:")
if !filepath.IsAbs(path) {
path = filepath.Join(dir, filepath.FromSlash(path))
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
if strings.EqualFold(filepath.Ext(path), ".svg") {
return ui.ParseSVG(data)
}
return ui.DecodeBitmap(data)
}
}
// image returns the image at url once loaded, starting to load it the
// first time.
func (st *viewState) image(c *ui.Context, url string) ui.ImageSource {
o := st.o
if o.LoadImage == nil || url == "" {
return nil
}
v, loaded := o.images.LoadOrStore(url, &imageEntry{})
e := v.(*imageEntry)
if !loaded {
load, services := o.LoadImage, c.Services()
go func() {
src, err := load(url)
e.mu.Lock()
e.src, e.err, e.done = src, err, true
e.mu.Unlock()
services.Invalidate()
}()
}
e.mu.Lock()
defer e.mu.Unlock()
return e.src
}
// images builds a paragraph of images alone: each as large as it is, at
// most as wide as the view, its description showing until it loads.
func (st *viewState) images(c *ui.Context, i int) ui.Element {
th := &st.th
in := st.doc.Inlines(i)
row := ui.Row(c).Wrap().Gap(th.em(0.5)).AlignSelf(ui.Stretch)
return row.Children(func() {
for k := 0; k < len(in); k = in[k].Next {
n := &in[k]
if n.Kind != parser.Image {
continue
}
alt := parser.PlainText(in[k+1 : n.Next])
src := st.image(c, n.Dest)
if src == nil || n.Pending {
label := alt
if label == "" {
label = l10n.In(c.Locale()).Image()
}
ph := ui.Row(c).Padding(th.em(0.5), th.em(0.75)).Radius(th.em(0.3)).Background(th.CodeBackground)
ph.Role(ui.RoleImage).Label(alt)
ph.Children(func() { ui.Text(c, label).TextColor(th.Muted).FontSize(th.em(0.875)) })
continue
}
img := ui.Image(c, src).Radius(th.em(0.3)).MaxWidthPercent(100).Label(alt)
var w, h float32
switch s := src.(type) {
case *ui.Bitmap:
iw, ih := s.Size()
w, h = float32(iw), float32(ih)
case *ui.SVG:
w, h = s.Size()
}
if w > 0 && h > 0 {
img.AspectRatio(w / h)
}
if n.Title != "" {
img.Tooltip(n.Title)
}
}
})
}
+134
View File
@@ -0,0 +1,134 @@
package markdown
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
)
// linkIcons makes an object for links but those to anchors, and notes
// the box the last one drew in.
func linkIcons(drawn *ui.Rect) *Options {
return &Options{LinkIcon: func(dest string, size float32) (InlineObject, bool) {
if strings.HasPrefix(dest, "#") {
return InlineObject{}, false
}
return InlineObject{Width: size, Height: size * 0.8, Depth: size * 0.2, Draw: func(p *ui.Painter, r ui.Rect) {
if drawn != nil {
*drawn = r
}
}}, true
}}
}
// TestLinkIconCopy copies a link's icon, and the joiner after it, as
// nothing, as text and as Markdown, wherever the selection ends.
func TestLinkIconCopy(t *testing.T) {
src := "See [docs](a.md) now\n"
tt, get := rvView(&src, linkIcons(nil))
st := get()
text := "See \uFFFC\u2060docs now"
if !tt.HasText(text) {
t.Fatalf("no %q in %q", text, tt.Texts())
}
k := rvElemOf(t, st, 1)
for _, c := range []struct {
from, to int
text, md string
}{
{0, 14, "See docs now", "See [docs](a.md) now"},
{4, 10, "docs", "[docs](a.md)"}, // from the icon
{5, 10, "docs", "[docs](a.md)"}, // from the joiner
{6, 8, "do", "[do](a.md)"}, // within the text
{0, 5, "See ", "See "}, // to the icon
{4, 6, "", ""}, // the icon alone
{8, 14, "cs now", "[cs](a.md) now"},
} {
parts := []ui.SelectedText{rvPart(st, k, text, c.from, c.to)}
if got := st.copyText(parts); got != c.text {
t.Errorf("[%d,%d) as text %q, want %q", c.from, c.to, got, c.text)
}
if got := st.copyMarkdown(parts); got != c.md {
t.Errorf("[%d,%d) as Markdown %q, want %q", c.from, c.to, got, c.md)
}
}
if got := st.copyMarkdown(nil); got != src {
t.Errorf("the document as Markdown %q, want %q", got, src)
}
}
// TestLinkIconSelectAll copies the whole view without its icons.
func TestLinkIconSelectAll(t *testing.T) {
src := "See [docs](a.md) now\n"
tt, _ := rvView(&src, linkIcons(nil))
r, ok := tt.Find("See \uFFFC\u2060docs now")
if !ok {
t.Fatalf("no text in %q", tt.Texts())
}
tt.ClickAt(r.X+2, r.Y+r.H/2)
tt.Command("selectAll")
tt.Command("copy")
if got, want := tt.Clipboard(), "See docs now"; got != want {
t.Errorf("copied %q, want %q", got, want)
}
}
// TestLinkIconWraps keeps an icon on the line of the link's first word
// wherever the line ends, and asks for it inside the link: a click on
// it opens the link.
func TestLinkIconWraps(t *testing.T) {
for n := range 40 {
src := strings.Repeat("i", 2*n) + " aaaa bbbb cccc dddd [Supercali](x.md)\n"
var icon ui.Rect
var clicked string
o := linkIcons(&icon)
o.OnLink = func(url string) { clicked = url }
tt := ui.NewTester(func(c *ui.Context) {
ui.Column(c).Width(260).Children(func() { View(c, src, o) })
}, 300, 200)
link, ok := tt.Find("\uFFFC\u2060Supercali")
if !ok {
t.Fatalf("no link in %q", tt.Texts())
}
if link.H > 2*icon.H || icon.Y < link.Y-1 || icon.X > link.X+1 {
t.Fatalf("n=%d: icon at %+v, link at %+v: not on one line", n, icon, link)
}
tt.ClickAt(icon.X+icon.W/2, icon.Y+icon.H/2)
if clicked != "x.md" {
t.Fatalf("n=%d: a click on the icon opened %q", n, clicked)
}
}
}
// TestLinkIconNone leaves out icons where LinkIcon makes none, in code,
// and in links still being written.
func TestLinkIconNone(t *testing.T) {
src := "[up](#top) and `[x](x.md)` and https://go.dev\n"
tt, _ := rvView(&src, linkIcons(nil))
if !tt.HasText("up") || !tt.HasText("\uFFFC\u2060https://go.dev") {
t.Errorf("anchors or autolinks wrong in %q", tt.Texts())
}
for _, s := range tt.Texts() {
if strings.Contains(s, "\uFFFC\u2060[x]") {
t.Errorf("code has an icon in %q", s)
}
}
stream := "See [do"
o := linkIcons(nil)
tt = ui.NewTester(func(c *ui.Context) { Stream(c, stream, o) }, 700, 300)
for _, s := range tt.Texts() {
if strings.ContainsRune(s, '\uFFFC') {
t.Errorf("a pending link has an icon in %q", s)
}
}
}
// TestLinkIconNil keeps links as they are without LinkIcon.
func TestLinkIconNil(t *testing.T) {
src := "See [docs](a.md) now\n"
tt, _ := rvView(&src, &Options{})
if !tt.HasText("See docs now") {
t.Errorf("text in %q", tt.Texts())
}
}
+132
View File
@@ -0,0 +1,132 @@
package markdown
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// mathRecorder makes inline math objects of every TeX but "bad", and
// notes the TeX and sizes asked for and the boxes drawn.
type mathRecorder struct {
asked []string
sizes []float32
drawn map[string]ui.Rect
}
func (m *mathRecorder) options() *Options {
return &Options{
Extensions: parser.Default | parser.ExtDollarMath,
InlineMath: func(tex string, size float32) (InlineObject, bool) {
m.asked = append(m.asked, tex)
m.sizes = append(m.sizes, size)
if tex == "bad" {
return InlineObject{}, false
}
return InlineObject{Width: 20, Height: 10, Depth: 6, Draw: func(p *ui.Painter, r ui.Rect) {
if m.drawn == nil {
m.drawn = map[string]ui.Rect{}
}
m.drawn[tex] = r
}}, true
},
}
}
// TestInlineMath shows math within text as the objects InlineMath makes,
// in links and strong text too, and as TeX where it makes none.
func TestInlineMath(t *testing.T) {
var m mathRecorder
src := "Let $x_i$ be **big $y$**, [see $z$](https://go.dev) and $bad$ or \\(w\\).\n\n# Head $h$\n"
tt, get := rvView(&src, m.options())
st := get()
if got, want := rvParaText(st, 1), "Let  be big , see  and bad or ."; got != want {
t.Errorf("text %q, want %q", got, want)
}
for _, tex := range []string{"x_i", "y", "z", "w", "h"} {
r, ok := m.drawn[tex]
if !ok || r.W != 20 || r.H != 16 {
t.Errorf("%s drawn in %+v (%v)", tex, r, ok)
}
}
if _, ok := m.drawn["bad"]; ok || !tt.HasText("bad") {
t.Errorf("bad drawn, or not shown as TeX in %q", tt.Texts())
}
// The size of the text around: the heading's is larger.
for k, tex := range m.asked {
if want := st.th.FontSize; tex != "h" && m.sizes[k] != want || tex == "h" && m.sizes[k] <= want {
t.Errorf("%s asked at %v DIPs, text of %v", tex, m.sizes[k], want)
}
}
// Each on the baseline of its line: x_i's box holds its descent.
if x, y := m.drawn["x_i"], m.drawn["y"]; x.Y != y.Y {
t.Errorf("x_i at %+v, y at %+v: not on one baseline", x, y)
}
}
// TestInlineMathCopy copies math drawn as objects as its source, with
// its delimiters, amid the text selected.
func TestInlineMathCopy(t *testing.T) {
var m mathRecorder
src := "Let $x_i$ be **big $y$** or \\(w\\) — café.\n"
tt, get := rvView(&src, m.options())
st := get()
r, ok := tt.Find("Let \uFFFC be big \uFFFC or \uFFFC — café.")
if !ok {
t.Fatalf("no text in %q", tt.Texts())
}
tt.ClickAt(r.X+2, r.Y+r.H/2)
tt.Command("selectAll")
tt.Command("copy")
if got, want := tt.Clipboard(), "Let $x_i$ be big $y$ or \\(w\\) — café."; got != want {
t.Errorf("copied %q, want %q", got, want)
}
text := rvParaText(st, 1)
k := rvElemOf(t, st, 1)
for _, c := range []struct {
from, to int
text, md string
}{
{4, 7, "$x_i$ b", "$x_i$ b"},
{2, 5, "t $x_i$", "t $x_i$"},
{4, 5, "$x_i$", "$x_i$"},
{9, 19, "big $y$ or \\(w\\)", "**big $y$** or \\(w\\)"},
} {
part := []ui.SelectedText{rvPart(st, k, text, c.from, c.to)}
if got := st.copyText(part); got != c.text {
t.Errorf("runes %d to %d copied %q, want %q", c.from, c.to, got, c.text)
}
if got := st.copyMarkdown(part); got != c.md {
t.Errorf("runes %d to %d copied as Markdown %q, want %q", c.from, c.to, got, c.md)
}
}
}
// TestInlineMathStreaming asks for math a single dollar leaves open as
// it streams in, healed, and leaves money as text.
func TestInlineMathStreaming(t *testing.T) {
var m mathRecorder
o := m.options()
o.Reveal = &Reveal{Unit: AtOnce, Fade: -1}
src := "Costs $5, so $x_i"
tt := ui.NewTester(func(c *ui.Context) { Stream(c, src, o) }, 600, 400)
tt.Frame()
if len(m.asked) == 0 || m.asked[len(m.asked)-1] != "x_i" || strings.Contains(strings.Join(m.asked, " "), "5") {
t.Errorf("asked for %q", m.asked)
}
if !tt.HasText("Costs $5, so ") {
t.Errorf("shows %q", tt.Texts())
}
}
// TestInlineMathNil keeps math as TeX without InlineMath.
func TestInlineMathNil(t *testing.T) {
src := "Let $x_i$ be.\n"
o := &Options{Extensions: parser.Default | parser.ExtDollarMath}
_, get := rvView(&src, o)
if got := rvParaText(get(), 1); got != "Let x_i be." {
t.Errorf("text %q", got)
}
}
+110
View File
@@ -0,0 +1,110 @@
package parser
import (
"strings"
"testing"
)
// The cases are GitHub's, as its Markdown API rendered them.
func TestAlerts(t *testing.T) {
alert := func(kind, title, body string) string {
return `<div class="markdown-alert markdown-alert-` + kind + `">` + "\n" +
`<p class="markdown-alert-title">` + title + "</p>\n" + body + "</div>\n"
}
quote := func(body string) string { return "<blockquote>\n" + body + "</blockquote>\n" }
for _, c := range []struct{ name, src, want string }{
{"note", "> [!NOTE]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"every kind", "> [!TIP]\n> a\n\n> [!IMPORTANT]\n> a\n\n> [!WARNING]\n> a\n\n> [!CAUTION]\n> a",
alert("tip", "Tip", "<p>a</p>\n") + alert("important", "Important", "<p>a</p>\n") +
alert("warning", "Warning", "<p>a</p>\n") + alert("caution", "Caution", "<p>a</p>\n")},
{"any case", "> [!note]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"spaces around the marker", "> [!WARNING] \n> Body.", alert("warning", "Warning", "<p>Body.</p>\n")},
{"a blank line first", ">\n> [!NOTE]\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"a lazy line", "> [!NOTE]\nlazy line", alert("note", "Note", "<p>lazy line</p>\n")},
{"a blank line after", "> [!NOTE]\n>\n> Body.", alert("note", "Note", "<p>Body.</p>\n")},
{"a list after", "> [!NOTE]\n> - one", alert("note", "Note", "<ul>\n<li>one</li>\n</ul>\n")},
{"a heading after", "> [!CAUTION]\n> # Head", alert("caution", "Caution", "<h1>Head</h1>\n")},
{"a second marker is text", "> [!NOTE]\n> [!TIP]\n> Body.", alert("note", "Note", "<p>[!TIP]\nBody.</p>\n")},
{"text after the marker", "> [!NOTE] Body.", quote("<p>[!NOTE] Body.</p>\n")},
{"the marker alone", "> [!TIP]", quote("<p>[!TIP]</p>\n")},
{"an unknown kind", "> [!FOO]\n> Body.", quote("<p>[!FOO]\nBody.</p>\n")},
{"nested in a quote", "> > [!NOTE]\n> > Body.", quote(quote("<p>[!NOTE]\nBody.</p>\n"))},
{"in a list", "- item\n\n > [!NOTE]\n > Body.", "<ul>\n<li>\n<p>item</p>\n" + quote("<p>[!NOTE]\nBody.</p>\n") + "</li>\n</ul>\n"},
{"after a paragraph", "> a\n> [!NOTE]\n> Body.", quote("<p>a\n[!NOTE]\nBody.</p>\n")},
{"a marker after the marker", "> [!NOTE]\n>\n> [!TIP]\n> x", alert("note", "Note", "<p>[!TIP]\nx</p>\n")},
{"a definition after the marker", "> [!NOTE]\n>\n> [a]: /u", quote("<p>[!NOTE]</p>\n")},
{"a footnote after the marker", "> [!NOTE]\n> [^1]: x\n\ny[^1]", quote("<p>[!NOTE]</p>\n") + "<p>y<sup class=\"footnote-ref\"><a href=\"#fn-1\" id=\"fnref-1\" data-footnote-ref>1</a></sup></p>\n" +
"<section class=\"footnotes\" data-footnotes>\n<ol>\n<li id=\"fn-1\">\n<p>x</p>\n<a href=\"#fnref-1\" class=\"footnote-backref\">↩</a>\n</li>\n</ol>\n</section>\n"},
} {
d := New(Default)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("%s: %q gives\n%s\nwant\n%s", c.name, c.src, got, c.want)
}
off := New(Default &^ ExtAlerts)
off.Set(c.src)
for i := range off.Len() {
if off.Block(i).Alert != NoAlert {
t.Errorf("%s: an alert without ExtAlerts", c.name)
}
}
}
}
// An alert written a byte at a time, as a reply streams in, ends as it
// parses at once, and is one as soon as its text starts.
func TestAlertStreaming(t *testing.T) {
src := "Intro.\n\n> [!WARNING]\n>\n> Mind the **gap**.\n> - and this\n\nAfter."
want := New(Default)
want.Set(src)
d := New(Default)
d.SetStreaming(true)
for k := range len(src) {
d.Append(src[k : k+1])
if got := d.Source(); len(got) == len("Intro.\n\n> [!WARNING]\n>\n> M") {
if q := d.Block(2); q.Kind != Quote || q.Alert != AlertWarning {
t.Errorf("at %q: block 2 is %v, alert %v", got, q.Kind, q.Alert)
}
}
}
d.SetStreaming(false)
if got, w := d.HTML(), want.HTML(); got != w {
t.Errorf("streamed\n%s\nwant\n%s", got, w)
}
}
// While streaming, a marker alone shows as the alert its quote will
// most likely become; once the text is complete, it is text as GitHub
// has it.
func TestAlertMarkerStreaming(t *testing.T) {
d := New(Default)
d.SetStreaming(true)
d.Set("> [!WARNING]")
if q := d.Block(1); q.Kind != Quote || q.Alert != AlertWarning {
t.Errorf("streaming: %v, alert %v", q.Kind, q.Alert)
}
if got := d.HTML(); strings.Contains(got, "[!WARNING]") {
t.Errorf("the marker shows while streaming: %s", got)
}
d.SetStreaming(false)
if q := d.Block(1); q.Alert != NoAlert {
t.Errorf("complete: alert %v in %s", q.Alert, d.HTML())
}
}
// Editing the marker away, or back, changes the quote.
func TestAlertEdit(t *testing.T) {
d := New(Default)
d.Set("a\n\n> [!NOTE]\n> Body.\n\nb")
if d.Block(2).Alert != AlertNote {
t.Fatalf("no alert in %s", d.HTML())
}
d.Set("a\n\n> [NOTE]\n> Body.\n\nb")
if d.Block(2).Alert != NoAlert {
t.Errorf("an alert without its marker: %s", d.HTML())
}
d.Set("a\n\n> [!TIP]\n> Body.\n\nb")
if d.Block(2).Alert != AlertTip {
t.Errorf("no tip once edited back: %s", d.HTML())
}
}
+352
View File
@@ -0,0 +1,352 @@
package parser
import (
"strings"
"unicode"
"unicode/utf8"
)
// GitHub's extended autolinks, as cmark-gfm finds them (autolink.c):
// www. and http(s):// links as the inline parser comes to their w and :,
// email addresses in the text once parsed.
func isHostChar(s string) bool {
r, n := utf8.DecodeRuneInString(s)
if n == 0 || r == utf8.RuneError && n == 1 {
return false
}
if unicode.IsSpace(r) {
return false
}
if r < utf8.RuneSelf {
return !isEscapable(byte(r))
}
return !unicode.IsPunct(r)
}
// autolinkDelim returns where a link ends once trailing punctuation, an
// entity-like ending and unbalanced parentheses are left out.
func autolinkDelim(data string, end int) int {
open, closing := 0, 0
for i := 0; i < end; i++ {
switch data[i] {
case '<':
end = i
case '(':
open++
case ')':
closing++
}
}
for end > 0 {
switch data[end-1] {
case ')':
if closing <= open {
return end
}
closing--
end--
case '?', '!', '.', ',', ':', '*', '_', '~', '\'', '"':
end--
case ';':
k := end - 2
for k > 0 && isASCIILetter(data[k]) {
k--
}
if k < end-2 && data[k] == '&' {
end = k
} else {
end--
}
default:
return end
}
}
return end
}
// checkDomain returns the length of the domain at the start of data, 0
// if it has an underscore in its last two segments, or, unless short,
// no dot.
func checkDomain(data string, short bool) int {
np, us1, us2 := 0, 0, 0
i := 1
for ; i < len(data)-1; i++ {
if data[i] == '\\' && i < len(data)-2 {
i++
}
switch {
case data[i] == '_':
us2++
case data[i] == '.':
us1, us2 = us2, 0
np++
case !isHostChar(data[i:]) && data[i] != '-':
goto done
}
}
done:
if (us1 > 0 || us2 > 0) && np <= 10 {
return 0
}
if short || np > 0 {
return i
}
return 0
}
// inBracket reports whether a link's or an image's text is open.
func (ip *inlineParser) inBracket() bool { return ip.lastB >= 0 }
// wwwLink reads a link starting with www. at pos.
func (ip *inlineParser) wwwLink() bool {
s := ip.s
pos := ip.pos
if ip.inBracket() || !strings.HasPrefix(s[pos:], "www.") {
return false
}
if pos > 0 && strings.IndexByte("*_~(", s[pos-1]) < 0 && !isUnicodeSpaceByte(s[pos-1]) {
// Beyond ASCII, after a space or punctuation such as “ or (.
if r, _ := utf8.DecodeLastRuneInString(s[:pos]); r < utf8.RuneSelf || !isUnicodeSpace(r) && !endsAutolink(r) {
return false
}
}
data := s[pos:]
end := checkDomain(data, false)
if end == 0 {
return false
}
end = autolinkEnd(data, end)
ip.d.steps += end
end = autolinkDelim(data, end)
if end == 0 {
return false
}
ip.addAutolink(pos, pos+end, "http://"+data[:end])
ip.pos = pos + end
return true
}
// autolinkEnd returns where a link's text starting at data[:end] runs
// out: at a space, a <, or punctuation beyond ASCII, such as the CJK ,
// and 。 or curly quotes, which text written without spaces puts right
// after a link. Letters beyond ASCII, as in IDN hosts and paths, go on.
func autolinkEnd(data string, end int) int {
for end < len(data) && !isUnicodeSpaceByte(data[end]) && data[end] != '<' {
if data[end] < utf8.RuneSelf {
end++
continue
}
r, n := utf8.DecodeRuneInString(data[end:])
if isUnicodeSpace(r) || endsAutolink(r) {
break
}
end += n
}
return end
}
// endsAutolink reports whether r, beyond ASCII, ends an extended
// autolink: any space, line and paragraph separators included, and
// punctuation but dashes and connectors, which paths such as Wikipedia's
// use.
func endsAutolink(r rune) bool {
return unicode.IsSpace(r) || unicode.IsPunct(r) && !unicode.In(r, unicode.Pd, unicode.Pc)
}
func isUnicodeSpaceByte(c byte) bool {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
}
// urlLink reads a link of http, https or ftp at the colon at pos, taking
// back the scheme from the text before it.
func (ip *inlineParser) urlLink() bool {
s := ip.s
pos := ip.pos
if ip.inBracket() || !strings.HasPrefix(s[pos:], "://") {
return false
}
// The scheme, from the text just added.
last := ip.nodes[0].last
if last < 0 {
return false
}
ln := &ip.nodes[last]
if ln.kind != Text || !ln.plain || ln.end != pos {
return false
}
rewind := 0
for rewind < len(ln.text) && isASCIILetter(ln.text[len(ln.text)-1-rewind]) {
rewind++
}
ip.d.steps += rewind
start := pos - rewind
scheme := strings.ToLower(s[start:pos])
if scheme != "http" && scheme != "https" && scheme != "ftp" {
return false
}
if len(s) <= pos+3 || !isHostChar(s[pos+3:]) {
return false
}
data := s[pos:]
n := checkDomain(data[3:], true)
if n == 0 {
return false
}
end := 3 + n
end = autolinkEnd(data, end)
ip.d.steps += end
end = autolinkDelim(data, end)
if end == 0 {
return false
}
// Take the scheme off the text.
ln.end = start
ln.text = s[ln.start:start]
ip.addAutolink(start, pos+end, s[start:pos+end])
ip.pos = pos + end
return true
}
func (ip *inlineParser) addAutolink(a, b int, dest string) {
l := ip.newNode(Link, "", a, b)
ip.nodes[l].dest = dest
ip.nodes[l].auto = true
ip.appendChild(0, l)
t := ip.newNode(Text, ip.s[a:b], a, b)
ip.appendChild(l, t)
}
// emailLinks finds email addresses in the text below node n, outside
// links, after joining text that follows text.
func (ip *inlineParser) emailLinks(n int32, inLink bool) {
for c := ip.nodes[n].first; c >= 0; c = ip.nodes[c].next {
nd := &ip.nodes[c]
switch nd.kind {
case Link, Image:
continue
case Text:
if strings.IndexByte(ip.nodes[c].text, '@') >= 0 {
ip.splitEmails(c)
}
default:
ip.emailLinks(c, inLink)
}
}
}
// splitEmails turns the email addresses in text node c into links.
func (ip *inlineParser) splitEmails(c int32) {
for {
nd := &ip.nodes[c]
data := nd.text
a, b, mailto, ok := findEmail(data)
if !ok {
ip.d.steps += len(data)
return
}
ip.d.steps += b
source := ip.s[nd.start:min(nd.end, len(ip.s))]
off := func(i int) int { return nd.start + literalToSource(source, data, i) }
start, end := nd.start, nd.end
la, lb := off(a), off(b)
dest := data[a:b]
if mailto {
dest = "mailto:" + dest
}
l := ip.newNode(Link, "", la, lb)
ip.nodes[l].dest = dest
ip.nodes[l].auto = true
t := ip.newNode(Text, data[a:b], la, lb)
ip.appendChild(l, t)
post := ip.newNode(Text, data[b:], lb, end)
nd = &ip.nodes[c]
nd.text, nd.start, nd.end = data[:a], start, la
ip.insertAfter(c, l)
ip.insertAfter(l, post)
c = post
}
}
// findEmail finds the first email address in data, as cmark-gfm does:
// its bytes, and whether its link needs mailto: (not when written with
// mailto: or xmpp:).
func findEmail(data string) (a, b int, mailto, ok bool) {
offset := 0
for offset < len(data) {
at := strings.IndexByte(data[offset:], '@')
if at < 0 {
return
}
maxRewind := at
auto, xmpp := true, false
foundAt:
base := offset + maxRewind // the @
rewind := 0
for ; rewind < maxRewind; rewind++ {
ch := data[base-rewind-1]
if isASCIILetter(ch) || isASCIIDigit(ch) || strings.IndexByte(".+-_", ch) >= 0 {
continue
}
if ch == ':' {
if validProtocol("mailto:", data, base, rewind) {
auto = false
continue
}
if validProtocol("xmpp:", data, base, rewind) {
auto, xmpp = false, true
continue
}
}
break
}
if rewind == 0 {
offset += maxRewind + 1
continue
}
np := 0
linkEnd := 1
for ; linkEnd < len(data)-base; linkEnd++ {
ch := data[base+linkEnd]
switch {
case isASCIILetter(ch) || isASCIIDigit(ch):
case ch == '@':
offset += maxRewind + 1
maxRewind = linkEnd - 1
goto foundAt
case ch == '.' && linkEnd < len(data)-base-1 && (isASCIILetter(data[base+linkEnd+1]) || isASCIIDigit(data[base+linkEnd+1])):
np++
case ch == '/' && xmpp:
case ch != '-' && ch != '_':
goto ended
}
}
ended:
if last := data[base+linkEnd-1]; linkEnd < 2 || np == 0 || !isASCIILetter(last) && last != '.' {
offset += maxRewind + linkEnd
continue
}
linkEnd = autolinkDelim(data[base:], linkEnd)
if linkEnd == 0 {
offset += maxRewind + 1
continue
}
return base - rewind, base + linkEnd, auto, true
}
return
}
// validProtocol reports whether protocol ends rewind bytes before the @
// at base, after something other than a letter or a digit.
func validProtocol(protocol, data string, base, rewind int) bool {
end := base - rewind
start := end - len(protocol)
if start < 0 || data[start:end] != protocol {
return false
}
if start == 0 {
return true
}
c := data[start-1]
return !isASCIILetter(c) && !isASCIIDigit(c)
}
+89
View File
@@ -0,0 +1,89 @@
package parser
import (
"os"
"testing"
)
func llm(b *testing.B) string {
data, err := os.ReadFile("testdata/llm.md")
if err != nil {
b.Fatal(err)
}
return string(data)
}
// inlinesAll parses the inlines of every block, as showing them does.
func inlinesAll(d *Document) {
for i := range d.Len() {
d.Inlines(i)
}
}
// BenchmarkParse parses the 50 KB answer whole, inlines included.
func BenchmarkParse(b *testing.B) {
src := llm(b)
b.SetBytes(int64(len(src)))
b.ReportAllocs()
for b.Loop() {
inlinesAll(Parse(src))
}
}
// BenchmarkPathological parses the inputs of TestLinearTime, which
// counts the parser's steps; this times them.
func BenchmarkPathological(b *testing.B) {
srcs := make([]string, len(pathological))
for i, c := range pathological {
srcs[i] = c.src(5000)
}
b.ReportAllocs()
for b.Loop() {
for i, c := range pathological {
d := New(c.ext)
d.Set(srcs[i])
inlinesAll(d)
}
}
}
// benchStream streams the answer in chunks of n bytes, with healing, the
// inlines of the tail parsed after each, as a frame shows them; it
// reports the time per chunk.
func benchStream(b *testing.B, n int) {
src := llm(b)
b.ReportAllocs()
chunks := 0
for b.Loop() {
d := New(Default)
d.SetStreaming(true)
for i := 0; i < len(src); i += n {
d.Append(src[i:min(i+n, len(src))])
inlinesAll(d)
chunks++
}
}
b.ReportMetric(float64(b.Elapsed().Nanoseconds())/float64(chunks), "ns/chunk")
}
func BenchmarkStream4(b *testing.B) { benchStream(b, 4) }
func BenchmarkStream64(b *testing.B) { benchStream(b, 64) }
// BenchmarkEdit types a character in the middle of the answer and takes
// it back, as an editor's preview.
func BenchmarkEdit(b *testing.B) {
src := llm(b)
d := Parse(src)
inlinesAll(d)
mid := len(src) / 2
for mid < len(src) && src[mid] != ' ' {
mid++
}
b.ReportAllocs()
for b.Loop() {
d.Edit(mid, mid, "x")
inlinesAll(d)
d.Edit(mid, mid+1, "")
inlinesAll(d)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,26 @@
package parser
import "testing"
// Emphasis closed by CJK punctuation and followed by CJK text, as
// Chinese writes it without spaces.
func TestCJKEmphasis(t *testing.T) {
for src, want := range map[string]string{
"**五种方式都能承载。**下面是判断": "<p><strong>五种方式都能承载。</strong>下面是判断</p>\n",
"**已有可靠内网:直接 HTTP。**接入成本最低。": "<p><strong>已有可靠内网:直接 HTTP。</strong>接入成本最低。</p>\n",
"针对你强调的**“简单”**,我会这样选": "<p>针对你强调的<strong>“简单”</strong>,我会这样选</p>\n",
"~~删除。~~保留": "<p><del>删除。</del>保留</p>\n",
"snake_case_name": "<p>snake_case_name</p>\n",
"a **b** c": "<p>a <strong>b</strong> c</p>\n",
// _ and a single ~ keep CommonMark's rule next to CJK text.
"中文__粗体。__后文": "<p>中文__粗体。__后文</p>\n",
"第1章~“附录”和“序”~第3章": "<p>第1章~“附录”和“序”~第3章</p>\n",
// Latin text with curly quotes reads as before.
"He said “*hello*” to me.": "<p>He said “<em>hello</em>” to me.</p>\n",
"**Alice**’s and **Bob**’s toys": "<p><strong>Alice</strong>’s and <strong>Bob</strong>’s toys</p>\n",
} {
if got := render(src, Default); got != want {
t.Errorf("%q: got %q, want %q", src, got, want)
}
}
}
+494
View File
@@ -0,0 +1,494 @@
package parser
import (
"iter"
"slices"
"strings"
"unsafe"
)
// Extensions are the syntax a Document reads beyond CommonMark.
type Extensions uint32
const (
// ExtTables are GitHub's tables, of cells between pipes.
ExtTables Extensions = 1 << iota
// ExtTaskLists are list items starting with [ ] or [x].
ExtTaskLists
// ExtStrikethrough is text between one or two tildes.
ExtStrikethrough
// ExtAutolinks are links without angle brackets: www.example.com,
// https://example.com and someone@example.com.
ExtAutolinks
// ExtFootnotes are references as [^1], defined by [^1]: lines.
ExtFootnotes
// ExtMath is TeX between $$ and $$, \[ and \], or \( and \), in blocks
// of their own or within text.
ExtMath
// ExtDollarMath is TeX between single dollar signs, as $x^2$, except
// where the dollars read as amounts of money: not after an opening
// dollar followed by a space or a digit, nor before a closing one
// following a space or followed by a digit. It needs ExtMath.
ExtDollarMath
// ExtAlerts are GitHub's alerts: a block quote at the top level whose
// first line is [!NOTE], [!TIP], [!IMPORTANT], [!WARNING] or
// [!CAUTION] alone, followed by its text (Block.Alert).
ExtAlerts
// ExtMentions are GitHub's mentions of people and teams, as @octocat
// and @github/docs, in text outside code and links (Mention).
ExtMentions
// ExtReferences are GitHub's references to issues and pull requests,
// as #123, GH-123 and octocat/hello#123, in text outside code and
// links (Reference).
ExtReferences
// GFM is GitHub Flavored Markdown, as its spec has it.
GFM = ExtTables | ExtTaskLists | ExtStrikethrough | ExtAutolinks
// Default is GitHub Flavored Markdown with footnotes and math, as
// language models write it, and the alerts, mentions and references
// of GitHub's comments. Mentions and references are text until a
// view resolves them.
Default = GFM | ExtFootnotes | ExtMath | ExtAlerts | ExtMentions | ExtReferences
)
// Kind is what a block is.
type Kind uint8
// Kinds of blocks.
const (
// Root holds the top-level blocks: block 0 of a document.
Root Kind = iota
Paragraph
// Heading has a Level from 1 to 6.
Heading
ThematicBreak
// CodeBlock is fenced or indented code, whose Info string names the
// language of a fence.
CodeBlock
// HTMLBlock is raw HTML, whose lines are its content.
HTMLBlock
// Quote is a block quote, holding blocks.
Quote
// List holds items, Ordered or not, Tight or not.
List
// Item is an item of a list, holding blocks, with a Task state.
Item
// Table holds rows, the first its Header, whose cells align as Align
// says.
Table
TableRow
// TableCell holds inline content.
TableCell
// FootnoteDefinition holds the blocks of a footnote, its Label the
// footnote's.
FootnoteDefinition
// MathBlock is display math, whose lines are its TeX.
MathBlock
)
var kindNames = [...]string{"root", "paragraph", "heading", "thematic break", "code block", "HTML block", "quote", "list", "item", "table", "table row", "table cell", "footnote definition", "math block"}
func (k Kind) String() string {
if int(k) < len(kindNames) {
return kindNames[k]
}
return "unknown"
}
// Task is the check box of a task list item.
type Task uint8
const (
NoTask Task = iota
Unchecked
Checked
)
// Align is how a table's column aligns its cells.
type Align uint8
const (
AlignNone Align = iota
AlignLeft
AlignCenter
AlignRight
)
// Alert is the kind of a GitHub alert.
type Alert uint8
const (
NoAlert Alert = iota
AlertNote
AlertTip
AlertImportant
AlertWarning
AlertCaution
)
var alertNames = [...]string{"", "Note", "Tip", "Important", "Warning", "Caution"}
// String returns the alert's title, as GitHub shows it: Note, Tip,
// Important, Warning or Caution.
func (a Alert) String() string {
if int(a) < len(alertNames) {
return alertNames[a]
}
return ""
}
// alertOf returns the alert a line marks, as [!NOTE], in any case and
// with spaces or tabs around it, or NoAlert.
func alertOf(line string) Alert {
line = strings.Trim(line, " \t")
if len(line) < 6 || line[0] != '[' || line[1] != '!' || line[len(line)-1] != ']' {
return NoAlert
}
name := line[2 : len(line)-1]
for a := AlertNote; a <= AlertCaution; a++ {
if strings.EqualFold(name, alertNames[a]) {
return a
}
}
return NoAlert
}
// Block is a block of a document: blocks are in document order, a block's
// children right after it, up to its Next.
type Block struct {
Kind Kind
// Parent is the index of the block holding it, -1 for the root.
Parent int
// Next is the index after the block and its descendants.
Next int
// Start and End are the offsets of the block's bytes in the source,
// from its first character to the end of its last line.
Start, End int
// Open reports that the block is still open at the end of the
// source, so that more text can continue it: a fence without its
// closing fence, or the paragraph being written.
Open bool
// Level is a heading's, from 1 to 6.
Level int
// Ordered, Number (an ordered list's first), Marker (*, - or + for
// a bullet list, . or ) after an ordered list's numbers) and Tight
// (no blank lines between its items and their blocks) describe a
// list.
Ordered bool
Number int
Marker byte
Tight bool
// Task is an item's check box.
Task Task
// Fenced tells a fenced code block from an indented one.
Fenced bool
// Header tells a table's header row.
Header bool
// Alert is the kind of a block quote that is a GitHub alert, its
// [!NOTE] line not in its text (ExtAlerts): a marker alone in its
// paragraph leaves a paragraph without lines (LineCount 0), which
// shows nothing.
Alert Alert
// Align is the alignment of a table's columns.
Align []Align
// info is a fenced code block's info string or a footnote's label.
info string
// What the parser and the inline parser keep.
parse blockState
// segA and segB are the block's content lines in the document's
// segs, and segMark how many lines it held as the block began.
segA, segB, segMark int32
text string
textS int32 // the source offset of text[0] when text is a slice of the source, else -1
inl []Inline
inlOK bool
// labels are those its inlines looked up as references, to parse
// them anew when a definition of one comes or goes.
labels []string
rev uint32
// healed tells inlines parsed completed, as the end of a streaming
// document's.
healed bool
}
// seg is a line of a leaf block's content: pad spaces (from a tab partly
// consumed by indentation), the source's bytes [start, end), and a
// newline unless cell.
type seg struct {
start, end int32
pad int8
cell bool // a table cell: no newline, and \| is |
}
// Info returns a fenced code block's info string, unescaped, its
// language first (see Language).
func (b *Block) Info() string {
if b.Kind != CodeBlock {
return ""
}
return b.info
}
// Label returns a footnote definition's label.
func (b *Block) Label() string {
if b.Kind != FootnoteDefinition {
return ""
}
return b.info
}
// Language returns the language of a fenced code block, the first word
// of its info string.
func (b *Block) Language() string {
s := b.Info()
if i := strings.IndexAny(s, " \t"); i >= 0 {
s = s[:i]
}
return s
}
// Revision changes when the block's inlines are parsed anew, as when a
// link reference defined later in the document resolves its links: views
// keep what they made of a block while it stays the same.
func (b *Block) Revision() uint32 { return b.rev }
// Healed reports whether the block's inlines were completed as the tail
// of a streaming document: their closers are not in the source, and
// change as it grows.
func (b *Block) Healed() bool { return b.healed }
// Document is Markdown parsed, which takes text appended to it, or edits,
// and parses only what they change.
type Document struct {
src string
// buf holds the source as text is appended: its bytes before the
// source's length never change, so that the source is a string over
// them, and appending copies only the text appended.
buf []byte
ext Extensions
blocks []Block
segs []seg
refs map[string]linkRef
// defs are the link reference definitions in order, duplicates
// included, which take over as edits remove those before them.
defs []definition
notes map[string]int // footnote label → definition block
// restart is the offset of the line where parsing restarts as text
// is appended: the start of the outermost block open after the last
// complete line, or that line's end; restartAt is the index of the
// first block parsed from there.
restart int
restartAt int
// streaming completes unclosed syntax at the end of the source (see
// SetStreaming), and tail is the block holding the end.
streaming bool
tail int
// cut is where the source parsed for display ends: text held back
// while streaming lies past it.
cut int
// oldInl keeps the inlines of blocks parsed again as text is
// appended, to reuse.
oldInl []oldInline
// healedAt is the block whose inlines were parsed healed, or -1.
healedAt int
// revs counts the inlines parsed, to give each a Revision of its own.
revs uint32
inp inlineParser
// steps counts the work parsing does beyond reading the source once:
// the bytes scanned ahead or back, and the delimiters, brackets, nodes
// and lines walked, as the loops that could take quadratic time do it.
// Tests check that it grows linearly with the source.
steps int
// marks is the buffer of the last sourceMap.
marks []int
}
type oldInline struct {
at int // the offset of the block's content
rev uint32
text string
segs []seg // its lines, as offsets move with them
inl []Inline
labels []string
healed bool
}
// definition is a link reference definition of a label.
type definition struct {
key string
linkRef
}
// define adds a definition, which defines its label unless one before
// it did.
func (d *Document) define(df definition) {
d.defs = append(d.defs, df)
if _, ok := d.refs[df.key]; !ok {
d.refs[df.key] = df.linkRef
}
}
// linkRef is a link reference definition.
type linkRef struct {
dest, title string
at int // the offset of the definition
}
// Parse parses src with the Default extensions.
func Parse(src string) *Document {
d := New(Default)
d.Set(src)
return d
}
// New returns an empty document reading ext.
func New(ext Extensions) *Document {
d := &Document{ext: ext, healedAt: -1}
d.inp.d = d
d.reset()
return d
}
func (d *Document) reset() {
d.blocks = append(d.blocks[:0], Block{Kind: Root, Parent: -1, Next: 1, textS: -1})
d.segs = d.segs[:0]
d.blocks[0].parse.open = true
d.blocks[0].parse.lastChild = -1
d.refs = map[string]linkRef{}
d.defs = d.defs[:0]
d.notes = map[string]int{}
d.restart, d.restartAt = 0, 1
}
// Source returns the text of the document.
func (d *Document) Source() string { return d.src }
// Footnote returns the FootnoteDefinition block of a label, as a
// FootnoteRef's Text holds it.
func (d *Document) Footnote(label string) (int, bool) {
i, ok := d.notes[normalizeLabel(label)]
return i, ok
}
// Extensions returns what the document reads beyond CommonMark.
func (d *Document) Extensions() Extensions { return d.ext }
// Len returns the number of blocks, the root's included.
func (d *Document) Len() int { return len(d.blocks) }
// Block returns block i, 0 being the root. The block stays valid until
// the document changes.
func (d *Document) Block(i int) *Block { return &d.blocks[i] }
// Children returns the indices of the children of block i.
func (d *Document) Children(i int) iter.Seq[int] {
return func(yield func(int) bool) {
end := d.blocks[i].Next
for j := i + 1; j < end; j = d.blocks[j].Next {
if !yield(j) {
return
}
}
}
}
// Streaming reports whether the document completes unclosed syntax at
// its end (see SetStreaming).
func (d *Document) Streaming() bool { return d.streaming }
// SetStreaming sets whether the document is text still being written, as
// a language model's reply: its end then shows what it will most likely
// become rather than the half-written syntax it is. The last paragraph
// closes its emphasis, code spans, strikethrough and math (a single $'s
// too, with ExtDollarMath), within which _ and * open no emphasis; a
// link whose destination is being written is a link (Inline.Pending), a
// tag being written is left out, and lines that could still turn into
// something else are held back: a line of only a few markers, as - or
// ==, which would make the paragraph above a heading, and a table's
// header until its delimiter row comes. Finished blocks are never
// changed. Turn it off once the text is complete, to parse its end
// exactly as CommonMark does.
func (d *Document) SetStreaming(on bool) {
if d.streaming == on {
return
}
d.streaming = on
d.parseTail()
}
// Set makes src the text of the document, parsing only what changed
// since the last: text appended to it, or else the blocks around the
// change (see Edit).
func (d *Document) Set(src string) {
old := d.src
switch {
case src == old:
return
case len(src) > len(old) && src[:len(old)] == old:
// The new source is the string given, copied nowhere.
d.reserve(src[len(old):])
d.src = src
d.parseTail()
return
}
// The common prefix and suffix bound the change.
p := 0
for p < len(old) && p < len(src) && old[p] == src[p] {
p++
}
s := 0
for s < len(old)-p && s < len(src)-p && old[len(old)-1-s] == src[len(src)-1-s] {
s++
}
d.Edit(p, len(old)-s, src[p:len(src)-s])
}
// Append adds text to the end of the document, parsing again only the
// outermost block still open before it, or nothing but the new lines
// when no block is.
func (d *Document) Append(text string) {
if text == "" {
return
}
d.reserve(text)
if len(d.buf) != len(d.src) || len(d.src) > 0 && unsafe.StringData(d.src) != unsafe.SliceData(d.buf) {
d.buf = append(make([]byte, 0, max(2*len(d.src)+len(text), 512)), d.src...)
}
if cap(d.buf)-len(d.buf) < len(text) {
d.buf = append(make([]byte, 0, 2*cap(d.buf)+len(text)), d.buf...)
}
d.buf = append(d.buf, text...)
d.src = unsafe.String(unsafe.SliceData(d.buf), len(d.buf))
d.parseTail()
}
// reserve makes room for the blocks of text, a large part of a document
// parsed at once.
func (d *Document) reserve(text string) {
if len(text) < 4096 {
return
}
n := strings.Count(text, "\n")
d.blocks = slices.Grow(d.blocks, n+n/4+8)
}
// Edit replaces the source's bytes [from, to) with text. Parsing restarts
// at the top-level block before the change and goes on until a top-level
// block starts where one started before it, from which the blocks parsed
// before are kept.
func (d *Document) Edit(from, to int, text string) {
if from == to && text == "" {
return
}
if from == len(d.src) && to == from {
d.Append(text)
return
}
d.edit(from, to, text)
}
// String returns the source of the document.
func (d *Document) String() string { return d.src }
+127
View File
@@ -0,0 +1,127 @@
package parser
import (
"fmt"
"runtime"
"strings"
"testing"
)
// TestEditKeepsTailInlines checks that incremental edits that resync a
// later block keep the inlines and offsets a parse of the whole source
// gives, including when a reference definition comes or goes.
func TestEditKeepsTailInlines(t *testing.T) {
src := "first [docs] **bold**\n\n" +
"[docs]: /one\n\n" +
"# middle\n\n" +
"tail [docs] *emphasis*\n\n" +
"last line\n"
const tail = "tail [docs] *emphasis*"
for _, c := range []struct {
name, from, text string
length int
preserve bool
}{
{"insert", "middle", "X", 0, true},
{"replace", "middle", "middles", len("middle"), true},
{"delete", "m", "", 1, true},
{"same length", "middle", "Middle", len("middle"), true},
{"add definition", "last line", "[docs]: /two\n\nlast line", len("last line"), false},
{"change definition", "/one", "/changed", len("/one"), false},
} {
t.Run(c.name, func(t *testing.T) {
from := strings.Index(src, c.from)
if from < 0 {
t.Fatalf("%q is not in the source", c.from)
}
to := from + c.length
next := src[:from] + c.text + src[to:]
d := New(Default)
d.Set(src)
inlinesAll(d)
rev := uint32(0)
if c.preserve {
rev = d.Block(blockWithText(d, tail)).Revision()
}
d.Edit(from, to, c.text)
if d.Source() != next {
t.Fatalf("source = %q, want %q", d.Source(), next)
}
fresh := Parse(next)
if c.preserve {
if got := d.Block(blockWithText(d, tail)).Revision(); got != rev {
t.Errorf("resynced tail was parsed again: revision %d, want %d", got, rev)
}
}
got, want := dumpEditedDocument(d), dumpEditedDocument(fresh)
if got != want {
t.Errorf("edited document:\n%s\nwhole parse:\n%s", got, want)
}
})
}
}
func blockWithText(d *Document, text string) int {
for i := range d.Children(0) {
if d.LineCount(i) > 0 {
line, _ := d.Line(i, 0)
if line == text {
return i
}
}
}
return -1
}
// TestEditWorkScalesWithTail checks that editing near the end does not
// copy all the segments and inlines of the document before the edit.
func TestEditWorkScalesWithTail(t *testing.T) {
editBytes := func(src string) uint64 {
var before, after runtime.MemStats
d := New(Default)
d.Set(src)
inlinesAll(d)
at := strings.Index(src, "two")
runtime.ReadMemStats(&before)
d.Edit(at, at, "x")
inlinesAll(d)
runtime.ReadMemStats(&after)
return after.TotalAlloc - before.TotalAlloc
}
many, few := editSources(2000)
if len(many) != len(few) {
t.Fatalf("sources differ in length: %d and %d", len(many), len(few))
}
withManySegs, withFewSegs := editBytes(many), editBytes(few)
if withManySegs > withFewSegs*2 {
t.Errorf("prefix of many segments: %d B, of few segments: %d B", withManySegs, withFewSegs)
}
}
// editSources gives two sources of the same length: the first has many
// segments before the edit, the second has one long line instead.
func editSources(n int) (string, string) {
tail := "one\n\ntwo\n\ntail [docs]\n\n[docs]: /u\n"
return strings.Repeat("a\n", n) + "\n" + tail,
strings.Repeat("a", 2*n-1) + "\n\n" + tail
}
func dumpEditedDocument(d *Document) string {
var out strings.Builder
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
fmt.Fprintf(&out, "%d %v [%d,%d) parent %d next %d\n", i, b.Kind, b.Start, b.End, b.Parent, b.Next)
for k := 0; k < d.LineCount(i); k++ {
line, at := d.Line(i, k)
if got := d.Source()[at : at+len(line)]; got != line {
fmt.Fprintf(&out, " line %d %q at %d is %q\n", k, line, at, got)
} else {
fmt.Fprintf(&out, " line %d %q at %d\n", k, line, at)
}
}
for _, in := range d.Inlines(i) {
fmt.Fprintf(&out, " %v %q %q [%d,%d) next %d\n", in.Kind, in.Text, in.Dest, in.Start, in.End, in.Next)
}
}
return out.String()
}
+207
View File
@@ -0,0 +1,207 @@
package parser
import (
"slices"
"strings"
)
// Healing completes what the end of a streaming document leaves open in
// the inline content of its last block, as Vercel's remend does to the
// text, but from the parser's own delimiters, and only for that block:
// the source never changes. It returns the text to parse and the length
// of what came from the source, past which the text was added.
// heal returns s completed, and whether the tree the parser holds is
// already that of the text returned.
func (ip *inlineParser) heal(s string) (string, int, bool) {
s = trimTrailingMarkers(s)
from := len(s)
// A link whose destination is being written: [text](http…
s += pendingLink(s)
// A code span not closed.
if ticks := openCodeSpan(s); ticks > 0 {
run := 0
for run < len(s) && s[len(s)-1-run] == '`' {
run++
}
if run >= ticks || run == 0 {
run = 0
}
s += strings.Repeat("`", ticks-run)
}
// The closing tildes of strikethrough half written: ~~struck~.
if strings.HasSuffix(s, "~") && !strings.HasSuffix(s, "~~") && strings.Contains(s, "~~") {
s += "~"
}
// Emphasis, strikethrough and math not closed: the openers the parser
// leaves, innermost first; and the text of a link being written shows
// without its bracket.
ip.run(s)
type opener struct {
at int
closer string
}
var open []opener
// Math not closed, by $$ or a single $ (ExtDollarMath), runs to the
// end: what follows is TeX, whose _ and * open no emphasis.
math, closer := len(s), ""
if ip.ext&ExtMath != 0 && ip.openMath >= 0 {
math, closer = ip.openMath, "$$"
}
if ip.ext&ExtDollarMath != 0 && ip.openDollar >= 0 && ip.openDollar < math {
math, closer = ip.openDollar, "$"
}
if closer != "" {
open = append(open, opener{math, closer})
}
for _, d := range ip.leftover {
if d.c == '*' && wordInside(s, d.at, d.orig) || d.c == '~' && d.orig == 1 || d.at > math {
continue // 2*3, a tilde for "about", as ~200, or TeX
}
open = append(open, opener{d.at, strings.Repeat(string(d.c), d.n)})
}
if ip.lastB >= 0 && ip.nodes[ip.br[ip.lastB].node].start < math {
ip.hide = ip.nodes[ip.br[ip.lastB].node].start
}
if len(open) == 0 && ip.hide < 0 {
return s, from, true
}
slices.SortStableFunc(open, func(a, b opener) int { return b.at - a.at })
var b strings.Builder
b.WriteString(s)
for _, o := range open {
b.WriteString(o.closer)
}
return b.String(), from, false
}
// wordInside reports whether a run of n delimiters at i has letters or
// digits of ASCII on both sides, as 2*3, which is not emphasis being
// written.
func wordInside(s string, i, n int) bool {
if i == 0 || i+n >= len(s) {
return false
}
isWord := func(c byte) bool { return isASCIILetter(c) || isASCIIDigit(c) }
return isWord(s[i-1]) && isWord(s[i+n])
}
// trimTrailingMarkers drops what the end of s may be starting, with
// nothing after it yet: a run of delimiters opening emphasis, a code span
// or math, a bracket, or a backslash.
func trimTrailingMarkers(s string) string {
for {
t := strings.TrimRight(s, " \t")
if t == "" {
return t
}
c := t[len(t)-1]
k := len(t)
for k > 0 && t[k-1] == c {
k--
}
run := len(t) - k
opening := k == 0 || t[k-1] == ' ' || t[k-1] == '\t' || t[k-1] == '\n'
switch {
case strings.HasSuffix(t, "!["):
t = t[:len(t)-2]
case c == '[':
t = t[:k]
case (c == '*' || c == '_' || c == '~' || c == '$') && opening:
t = t[:k]
case c == '`' && !closesSpan(t[:k], run):
t = t[:k]
case c == '\\' && run%2 == 1:
t = t[:len(t)-1]
default:
return t
}
s = t
}
}
// closesSpan reports whether a run of n backticks after s closes a code
// span s opens.
func closesSpan(s string, n int) bool { return openCodeSpan(s) == n }
// pendingLink returns what closes the destination of a link being
// written at the end of s, after ](, or nothing: the parentheses it
// opened, and the link's, or > and ) for one in angle brackets.
func pendingLink(s string) string {
k := strings.LastIndex(s, "](")
if k < 0 || !strings.Contains(s[:k], "[") {
return ""
}
// Not inside a code span.
if strings.Count(s[:k], "`")%2 == 1 {
return ""
}
rest := s[k+2:]
if strings.HasPrefix(rest, "<") {
if strings.ContainsAny(rest, ">\n") {
return ""
}
return ">)"
}
depth := 0
for i := 0; i < len(rest); i++ {
switch rest[i] {
case '\\':
i++
case '(':
depth++
case ')':
if depth == 0 {
return "" // the link is closed
}
depth--
case ' ', '\t', '\n':
return ""
}
}
return strings.Repeat(")", depth+1)
}
// openCodeSpan returns the length of the run of backticks opening a code
// span that s leaves open, or 0.
func openCodeSpan(s string) int {
for i := 0; i < len(s); i++ {
switch s[i] {
case '\\':
i++
case '`':
j := i
for j < len(s) && s[j] == '`' {
j++
}
n := j - i
// Its closer: the next run of as many.
k := j
found := false
for k < len(s) {
m := strings.IndexByte(s[k:], '`')
if m < 0 {
break
}
k += m
e := k
for e < len(s) && s[e] == '`' {
e++
}
if e-k == n {
found = true
i = e - 1
break
}
k = e
}
if !found {
if j == len(s) {
return 0 // a run at the very end opens nothing yet
}
return n
}
}
}
return 0
}
+117
View File
@@ -0,0 +1,117 @@
package parser
import "testing"
func streamed(src string) string {
d := New(Default)
d.SetStreaming(true)
d.Set(src)
return d.HTML()
}
func TestHealing(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"Some **bol", "<p>Some <strong>bol</strong></p>\n"},
{"Some **bold** and *ita", "<p>Some <strong>bold</strong> and <em>ita</em></p>\n"},
{"**a *b", "<p><strong>a <em>b</em></strong></p>\n"},
{"a ~~gone", "<p>a <del>gone</del></p>\n"},
{"run `go te", "<p>run <code>go te</code></p>\n"},
{"run ``a`", "<p>run <code>a</code></p>\n"},
{"hello **", "<p>hello</p>\n"},
{"hello *", "<p>hello</p>\n"},
{"hello `", "<p>hello</p>\n"},
{"2*3 is", "<p>2*3 is</p>\n"},
{"snake_case_name", "<p>snake_case_name</p>\n"},
{"see [the docs](https://exa", `<p>see <a href="https://exa">the docs</a></p>` + "\n"},
{"see [the docs](", `<p>see <a href="">the docs</a></p>` + "\n"},
{"math $$x^2", `<p>math <span class="math display">x^2</span></p>` + "\n"},
{"A paragraph\n-", "<p>A paragraph</p>\n"},
{"A paragraph\n==", "<p>A paragraph</p>\n"},
{"A paragraph\n---\n", "<h2>A paragraph</h2>\n"},
{"Intro\n\n| a | b |\n", "<p>Intro</p>\n"},
{"Intro\n\n| a | b |\n|--", "<p>Intro</p>\n"},
{"| a | b |\n|---|---|\n| 1 | 2", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>2</td>\n</tr>\n</tbody>\n</table>\n"},
{"| a | b |\n|---|---|\n| 1 | **2", "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td><strong>2</strong></td>\n</tr>\n</tbody>\n</table>\n"},
{"```go\nfunc main() {", "<pre><code class=\"language-go\">func main() {\n</code></pre>\n"},
{"caf\xc3", "<p>caf</p>\n"},
{"Done **bold**\n\nnext", "<p>Done <strong>bold</strong></p>\n<p>next</p>\n"},
} {
if got := streamed(c.src); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
// TestHealingOnlyTail checks that blocks already finished show as
// written.
func TestHealingOnlyTail(t *testing.T) {
got := streamed("a **b\n\nc **d")
want := "<p>a **b</p>\n<p>c <strong>d</strong></p>\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestPendingLink(t *testing.T) {
d := New(Default)
d.SetStreaming(true)
d.Set("see [docs](https://exa")
in := d.Inlines(1)
if len(in) < 2 || in[1].Kind != Link || !in[1].Pending {
t.Fatalf("inlines %+v", in)
}
d.Append("mple.com) now")
in = d.Inlines(1)
if in[1].Kind != Link || in[1].Pending || in[1].Dest != "https://example.com" {
t.Fatalf("inlines %+v", in)
}
}
// TestHealingDollarMath heals math a single dollar opens (ExtDollarMath)
// as it streams, whose _ and * are TeX rather than emphasis, while money,
// escaped dollars and finished text read as before.
func TestHealingDollarMath(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"where $x_i", `<p>where <span class="math inline">x_i</span></p>` + "\n"},
{"where $a*b", `<p>where <span class="math inline">a*b</span></p>` + "\n"},
{"where $x_i^2 + y_", `<p>where <span class="math inline">x_i^2 + y_</span></p>` + "\n"},
{"where $\\frac{a}{b", `<p>where <span class="math inline">\frac{a}{b</span></p>` + "\n"},
{"where $x \\", `<p>where <span class="math inline">x</span></p>` + "\n"},
{"where $x $", `<p>where <span class="math inline">x</span></p>` + "\n"},
{"*see $x_i", `<p><em>see <span class="math inline">x_i</span></em></p>` + "\n"},
{"**see $a_b", `<p><strong>see <span class="math inline">a_b</span></strong></p>` + "\n"},
{"$a$ and $b_", `<p><span class="math inline">a</span> and <span class="math inline">b_</span></p>` + "\n"},
{"see [link $x", `<p>see link <span class="math inline">x</span></p>` + "\n"},
{"math $$x^2", `<p>math <span class="math display">x^2</span></p>` + "\n"},
{"math $$x_i *y", `<p>math <span class="math display">x_i *y</span></p>` + "\n"},
// Money and escapes open no math.
{"costs $5 and *more", "<p>costs $5 and <em>more</em></p>\n"},
{"costs $ 5 and _more", "<p>costs $ 5 and <em>more</em></p>\n"},
{"costs \\$x and *more", "<p>costs $x and <em>more</em></p>\n"},
{"costs $", "<p>costs</p>\n"},
{"costs 5$", "<p>costs 5$</p>\n"},
} {
d := New(Default | ExtDollarMath)
d.SetStreaming(true)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
// Without ExtDollarMath, a dollar is text.
if got := streamed("where $x_i *y"); got != "<p>where $x_i <em>y</em></p>\n" {
t.Errorf("without ExtDollarMath: %q", got)
}
// Finished, unclosed math is text, as before.
for _, c := range []struct{ src, want string }{
{"where $x_i", "<p>where $x_i</p>\n"},
{"where $a *b*", "<p>where $a <em>b</em></p>\n"},
{"costs $5 and $x$", `<p>costs $5 and <span class="math inline">x</span></p>` + "\n"},
} {
d := New(Default | ExtDollarMath)
d.Set(c.src)
if got := d.HTML(); got != c.want {
t.Errorf("finished %q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
+404
View File
@@ -0,0 +1,404 @@
package parser
import (
"strconv"
"strings"
)
// HTML returns the document as HTML, as cmark-gfm renders it, raw HTML
// included as written.
func (d *Document) HTML() string {
var w htmlWriter
w.d = d
w.blocks(0)
w.footnotes()
return w.b.String()
}
type htmlWriter struct {
d *Document
b strings.Builder
notes []string // footnote labels in the order of their first reference
}
func (w *htmlWriter) cr() {
if s := w.b.Len(); s > 0 {
str := w.b.String()
if str[s-1] != '\n' {
w.b.WriteByte('\n')
}
}
}
func (w *htmlWriter) blocks(parent int) {
for i := range w.d.Children(parent) {
if b := w.d.Block(i); b.Kind == Paragraph && b.segB == b.segA {
continue // an alert's marker
}
w.block(i)
}
}
func (w *htmlWriter) tight(i int) bool {
b := w.d.Block(i)
if b.Parent <= 0 {
return false
}
p := w.d.Block(b.Parent)
if p.Kind != Item || p.Parent < 0 {
return false
}
return w.d.Block(p.Parent).Tight
}
func (w *htmlWriter) block(i int) {
d := w.d
b := d.Block(i)
switch b.Kind {
case Paragraph:
if w.tight(i) {
w.inlines(i)
return
}
w.cr()
w.b.WriteString("<p>")
w.inlines(i)
w.b.WriteString("</p>\n")
case Heading:
w.cr()
tag := "h" + strconv.Itoa(b.Level)
w.b.WriteString("<" + tag + ">")
w.inlines(i)
w.b.WriteString("</" + tag + ">\n")
case ThematicBreak:
w.cr()
w.b.WriteString("<hr />\n")
case CodeBlock:
w.cr()
w.b.WriteString("<pre><code")
if lang := b.Language(); lang != "" {
w.b.WriteString(` class="language-`)
escapeHTML(&w.b, lang)
w.b.WriteString(`"`)
}
w.b.WriteString(">")
escapeHTML(&w.b, d.Lines(i))
w.b.WriteString("</code></pre>\n")
case HTMLBlock:
w.cr()
w.b.WriteString(d.Lines(i))
w.cr()
case MathBlock:
w.cr()
w.b.WriteString(`<div class="math display">`)
escapeHTML(&w.b, strings.TrimSuffix(d.Lines(i), "\n"))
w.b.WriteString("</div>\n")
case Quote:
w.cr()
if a := b.Alert; a != NoAlert {
// As GitHub writes alerts, without its icons.
name := strings.ToLower(a.String())
w.b.WriteString(`<div class="markdown-alert markdown-alert-` + name + `">` + "\n")
w.b.WriteString(`<p class="markdown-alert-title">` + a.String() + "</p>\n")
w.blocks(i)
w.cr()
w.b.WriteString("</div>\n")
break
}
w.b.WriteString("<blockquote>\n")
w.blocks(i)
w.cr()
w.b.WriteString("</blockquote>\n")
case List:
w.cr()
if b.Ordered {
if b.Number != 1 {
w.b.WriteString(`<ol start="` + strconv.Itoa(b.Number) + `">` + "\n")
} else {
w.b.WriteString("<ol>\n")
}
} else {
w.b.WriteString("<ul>\n")
}
w.blocks(i)
if b.Ordered {
w.b.WriteString("</ol>\n")
} else {
w.b.WriteString("</ul>\n")
}
case Item:
w.cr()
w.b.WriteString("<li>")
switch b.Task {
case Unchecked:
w.b.WriteString(`<input type="checkbox" disabled="" /> `)
case Checked:
w.b.WriteString(`<input type="checkbox" checked="" disabled="" /> `)
}
w.blocks(i)
w.b.WriteString("</li>\n")
case Table:
w.cr()
w.b.WriteString("<table>\n")
body := false
for r := range d.Children(i) {
row := d.Block(r)
if row.Header {
w.b.WriteString("<thead>\n")
} else if !body {
w.b.WriteString("<tbody>\n")
body = true
}
w.b.WriteString("<tr>\n")
k := 0
for c := range d.Children(r) {
tag := "td"
if row.Header {
tag = "th"
}
w.b.WriteString("<" + tag)
if k < len(b.Align) {
switch b.Align[k] {
case AlignLeft:
w.b.WriteString(` align="left"`)
case AlignCenter:
w.b.WriteString(` align="center"`)
case AlignRight:
w.b.WriteString(` align="right"`)
}
}
w.b.WriteString(">")
w.inlines(c)
w.b.WriteString("</" + tag + ">\n")
k++
}
w.b.WriteString("</tr>\n")
if row.Header {
w.b.WriteString("</thead>\n")
}
}
if body {
w.b.WriteString("</tbody>\n")
}
w.b.WriteString("</table>\n")
case FootnoteDefinition:
// Listed at the end, in the order of their references.
}
}
// Lines returns the content of a code, HTML or math block, each line
// ending with a newline.
func (d *Document) Lines(i int) string {
segs := d.segsOf(&d.blocks[i])
n := 0
for _, s := range segs {
n += int(s.pad) + int(s.end-s.start) + 1
}
var sb strings.Builder
sb.Grow(n)
for _, s := range segs {
for range s.pad {
sb.WriteByte(' ')
}
sb.WriteString(d.src[s.start:s.end])
sb.WriteByte('\n')
}
return sb.String()
}
// LineCount returns the number of lines of a code, HTML or math block.
func (d *Document) LineCount(i int) int { b := &d.blocks[i]; return int(b.segB - b.segA) }
// Line returns line k of a code, HTML or math block, without its newline,
// and the offset in the source of its first byte.
func (d *Document) Line(i, k int) (string, int) {
s := d.segs[int(d.blocks[i].segA)+k]
line := d.src[s.start:s.end]
if s.pad > 0 {
line = strings.Repeat(" ", int(s.pad)) + line
}
return line, int(s.start)
}
func (w *htmlWriter) inlines(i int) {
in := w.d.Inlines(i)
w.inline(in, 0, len(in))
}
func (w *htmlWriter) inline(in []Inline, from, to int) {
for k := from; k < to; k = in[k].Next {
n := &in[k]
switch n.Kind {
case Text, Mention, Reference:
// Mentions and references are links only where a host
// resolves them.
escapeHTML(&w.b, n.Text)
case SoftBreak:
w.b.WriteString("\n")
case LineBreak:
w.b.WriteString("<br />\n")
case Code:
w.b.WriteString("<code>")
escapeHTML(&w.b, n.Text)
w.b.WriteString("</code>")
case Emphasis:
w.b.WriteString("<em>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</em>")
case Strong:
w.b.WriteString("<strong>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</strong>")
case Strikethrough:
w.b.WriteString("<del>")
w.inline(in, k+1, n.Next)
w.b.WriteString("</del>")
case Link:
w.b.WriteString(`<a href="`)
escapeHref(&w.b, n.Dest)
w.b.WriteString(`"`)
if n.Title != "" {
w.b.WriteString(` title="`)
escapeHTML(&w.b, n.Title)
w.b.WriteString(`"`)
}
w.b.WriteString(">")
w.inline(in, k+1, n.Next)
w.b.WriteString("</a>")
case Image:
w.b.WriteString(`<img src="`)
escapeHref(&w.b, n.Dest)
w.b.WriteString(`" alt="`)
escapeHTML(&w.b, PlainText(in[k+1:n.Next]))
w.b.WriteString(`"`)
if n.Title != "" {
w.b.WriteString(` title="`)
escapeHTML(&w.b, n.Title)
w.b.WriteString(`"`)
}
w.b.WriteString(" />")
case HTML:
w.b.WriteString(n.Text)
case Math:
if n.Display {
w.b.WriteString(`<span class="math display">`)
} else {
w.b.WriteString(`<span class="math inline">`)
}
escapeHTML(&w.b, n.Text)
w.b.WriteString("</span>")
case FootnoteRef:
num := w.note(n.Text)
id := strconv.Itoa(num)
w.b.WriteString(`<sup class="footnote-ref"><a href="#fn-` + id + `" id="fnref-` + id + `" data-footnote-ref>` + id + `</a></sup>`)
}
}
}
// note returns the number of footnote label, numbering it at its first
// reference.
func (w *htmlWriter) note(label string) int {
key := normalizeLabel(label)
for i, l := range w.notes {
if l == key {
return i + 1
}
}
w.notes = append(w.notes, key)
return len(w.notes)
}
func (w *htmlWriter) footnotes() {
if len(w.notes) == 0 {
return
}
w.cr()
w.b.WriteString("<section class=\"footnotes\" data-footnotes>\n<ol>\n")
for k := 0; k < len(w.notes); k++ {
i := w.d.notes[w.notes[k]]
id := strconv.Itoa(k + 1)
w.b.WriteString(`<li id="fn-` + id + `">` + "\n")
w.blocks(i)
w.cr()
w.b.WriteString(`<a href="#fnref-` + id + `" class="footnote-backref">↩</a>` + "\n</li>\n")
}
w.b.WriteString("</ol>\n</section>\n")
}
// PlainText returns the text of inlines without their markup: the text
// of links and emphasis, code as its text, line breaks as spaces.
func PlainText(in []Inline) string {
var b strings.Builder
for k := range in {
switch n := &in[k]; n.Kind {
case Text, Code, HTML, Math, Mention, Reference:
b.WriteString(n.Text)
case SoftBreak, LineBreak:
b.WriteByte(' ')
case FootnoteRef:
b.WriteString("[^" + n.Text + "]")
}
}
return b.String()
}
func escapeHTML(b *strings.Builder, s string) {
last := 0
for i := 0; i < len(s); i++ {
var r string
switch s[i] {
case '&':
r = "&amp;"
case '<':
r = "&lt;"
case '>':
r = "&gt;"
case '"':
r = "&quot;"
case 0:
r = "�"
default:
continue
}
b.WriteString(s[last:i])
b.WriteString(r)
last = i + 1
}
b.WriteString(s[last:])
}
// hrefSafe are the bytes a URL keeps as they are, as cmark's houdini.
var hrefSafe = func() (t [256]bool) {
for c := 'a'; c <= 'z'; c++ {
t[c] = true
}
for c := 'A'; c <= 'Z'; c++ {
t[c] = true
}
for c := '0'; c <= '9'; c++ {
t[c] = true
}
for _, c := range "-_.+!*(),%#@?=;:/,+$~" {
t[c] = true
}
return
}()
func escapeHref(b *strings.Builder, s string) {
const hex = "0123456789ABCDEF"
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case hrefSafe[c]:
b.WriteByte(c)
case c == '&':
b.WriteString("&amp;")
case c == '\'':
b.WriteString("&#x27;")
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&15])
}
}
}
File diff suppressed because it is too large. Load diff
+116
View File
@@ -0,0 +1,116 @@
package parser
import (
"runtime"
"strings"
"testing"
)
// pathological are inputs that take quadratic time in parsers without
// cmark's guards, or took it in this one, made of n repeats.
var pathological = []struct {
name string
ext Extensions
src func(n int) string
}{
{"mismatched openers", Default, repeat("*a_ ")},
{"emphasis openers", Default, repeat("*a ")},
{"many emphasis", Default, repeat("**a** ")},
{"underscores", Default, func(n int) string { return strings.Repeat("_a ", n) + strings.Repeat("a_ ", n) }},
{"strikethrough openers", Default, repeat("~~a ")},
{"unclosed links", Default, repeat("[a](<b")},
{"unclosed titles", Default, repeat(`[a](b "`)},
{"brackets", Default, repeat("[")},
{"unclosed brackets", Default, func(n int) string { return strings.Repeat("[", n) + "a" + strings.Repeat("]", n) }},
{"image brackets", Default, func(n int) string { return strings.Repeat("![", n) + strings.Repeat("]", n) }},
{"backticks", Default, repeat("`a``")},
{"backtick runs", Default, backtickRuns},
{"escapes", Default, repeat(`\*`)},
{"unclosed comments", Default, func(n int) string { return "a " + strings.Repeat("<!--", n) }},
{"math spans", Default, func(n int) string { return "a " + strings.Repeat("$$a ", n) }},
{"emails", Default, repeat("a@b.")},
{"urls", Default, repeat("x://")},
{"nested quotes", Default, func(n int) string { return strings.Repeat(">", n) + " a" }},
{"nested lists", Default, func(n int) string { return strings.Repeat("* ", n) + "a" }},
{"link definitions", Default, repeat("[a]: u\n")},
{"tables", Default, func(n int) string { return "| a |\n|---|\n" + strings.Repeat("|\n", n) }},
{"pipes", Default, func(n int) string { return strings.Repeat("| ", n) + "\n|" + strings.Repeat("-|", n) }},
{"lines ending in CR", Default, repeat("a\r")},
{"indented lines", Default, repeat("a\n ")},
{"quoted lines", Default, repeat("> a\n")},
{"openers then links", Default, func(n int) string { return strings.Repeat("[", n) + strings.Repeat("[a](b)", n) }},
{"escaped pipes", Default, func(n int) string { return "| a |\n|---|\n| " + strings.Repeat(`\| *a* `, n) + "|" }},
{"mentions", Default, repeat("@a ")},
{"repository references", Default, repeat("aaaaaaaa/bbbbbbbb#")},
{"words before references", Default, repeat("a#")},
{"alerts", Default, repeat("> [!NOTE]\n")},
}
func repeat(unit string) func(int) string {
return func(n int) string { return strings.Repeat(unit, n) }
}
// backtickRuns returns runs of backticks of every length up to n/40,
// none closed, as cmark's pathological tests.
func backtickRuns(n int) string {
var b strings.Builder
for k := 1; k <= n/40; k++ {
b.WriteString("e")
b.WriteString(strings.Repeat("`", k))
}
return b.String()
}
// work parses src, and the inlines of every block with inlines, and
// returns the steps it took (Document.steps) and the bytes it allocated,
// which grow quadratically where text is copied over and over, as steps
// do not show.
func work(src string, ext Extensions, inlines bool) (steps, bytes int) {
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
d := New(ext)
d.Set(src)
if inlines {
inlinesAll(d)
}
runtime.ReadMemStats(&after)
return d.steps, int(after.TotalAlloc - before.TotalAlloc)
}
// checkLinear checks that parsing src(n), inlines included, takes work
// that grows linearly with the input: about the same a byte for src(4n)
// as for src(n), where a quadratic parser takes four times as much, and
// a few steps a byte. It counts what the parser does rather than timing
// it, so that a quadratic regression fails on every machine and a busy
// machine never fails.
func checkLinear(t *testing.T, name string, ext Extensions, src func(n int) string) {
t.Helper()
checkLinearWork(t, name, ext, true, src)
}
// checkLinearWork is checkLinear, the inlines parsed with inlines.
func checkLinearWork(t *testing.T, name string, ext Extensions, inlines bool, src func(n int) string) {
t.Helper()
// The steps of linear inputs are an affine function of the input's
// length, under 5 a byte; allocations grow less evenly, as slices
// double.
const n, stepsPerByte = 5000, 8
small, large := src(n), src(4*n)
sa, ba := work(small, ext, inlines)
sb, bb := work(large, ext, inlines)
perByte := func(w int, src string) float64 { return float64(w) / float64(len(src)) }
if perByte(sb, large) > 1.25*perByte(sa, small) || sb > stepsPerByte*len(large) {
t.Errorf("%s: %d steps for %d bytes, %d for %d", name, sa, len(small), sb, len(large))
}
if perByte(bb, large) > 1.5*perByte(ba, small)+16 {
t.Errorf("%s: %d bytes allocated for %d bytes, %d for %d", name, ba, len(small), bb, len(large))
}
}
// TestLinearTime checks that inputs quadratic in parsers without cmark's
// guards take linear work.
func TestLinearTime(t *testing.T) {
for _, c := range pathological {
checkLinear(t, c.name, c.ext, c.src)
}
}
+344
View File
@@ -0,0 +1,344 @@
package parser
import (
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// GitHub's mentions (@octocat, @github/docs) and references to issues
// and pull requests (#123, GH-123, octocat/hello#123), found in the text
// once parsed, as email addresses are: never in code or links. Whether
// the person, team or issue exists is for a view to resolve.
const (
maxLogin = 39 // the longest GitHub login
maxRepo = 100 // the longest repository name
maxDigit = 10 // the most digits of an issue number
)
// Login returns whom a Mention mentions: a login, as octocat, or a team,
// as github/docs.
func (in Inline) Login() string {
if in.Kind != Mention || in.Text == "" {
return ""
}
return in.Text[1:]
}
// Ref returns the repository a Reference is in, as owner/name, or "" for
// the document's own, and the number of the issue or pull request.
func (in Inline) Ref() (repo string, number int) {
if in.Kind != Reference {
return "", 0
}
i := strings.LastIndexAny(in.Text, "#-")
if i < 0 {
return "", 0
}
if in.Text[i] == '#' {
repo = in.Text[:i]
}
number, _ = strconv.Atoi(in.Text[i+1:])
return repo, number
}
// references turns the mentions and references in the text of node n's
// descendants into nodes of their own, but in links and images, and in
// raw HTML's a, code, pre, style and script elements, as GitHub does.
// open counts those elements open before n's first child; it returns
// how many are open after its last.
func (ip *inlineParser) references(n int32, open int) int {
for c := ip.nodes[n].first; c >= 0; c = ip.nodes[c].next {
nd := &ip.nodes[c]
switch nd.kind {
case Link, Image:
case HTML:
open = max(open+skipElement(nd.text), 0)
case Text:
if open == 0 {
// A text's start is a word's start unless text before it
// ends in a word, as formatting ends none (_a_#1).
prev := nd.prev >= 0 && ip.nodes[nd.prev].kind == Text && endsInWord(ip.nodes[nd.prev].text)
c = ip.splitReferences(c, prev)
}
default:
open = ip.references(c, open)
}
}
return open
}
// skipElement returns 1 for raw HTML opening an element whose text has
// no mentions or references, -1 for HTML closing one, else 0.
func skipElement(tag string) int {
closing := strings.HasPrefix(tag, "</")
name := strings.TrimPrefix(strings.TrimPrefix(tag, "<"), "/")
end := 0
for end < len(name) && isASCIIAlnum(name[end]) {
end++
}
switch strings.ToLower(name[:end]) {
case "a", "code", "pre", "style", "script":
default:
return 0
}
switch {
case closing:
return -1
case strings.HasSuffix(tag, "/>"):
return 0
}
return 1
}
// splitReferences splits text node c at its mentions and references,
// which a word precedes when prevWord, and returns the last node of the
// text.
func (ip *inlineParser) splitReferences(c int32, prevWord bool) int32 {
// The text's @, # and - are found once each, as offsets in the text
// whose rest each split leaves: origin is where node c's text starts.
sc := refScan{next: [3]int{-1, -1, -1}, has: ip.refBytes}
origin := 0
for {
nd := &ip.nodes[c]
data := nd.text
a, b, kind, steps := findReference(data, origin, &sc, prevWord, ip.ext)
ip.d.steps += steps
if kind == Text {
return c
}
source := ip.s[nd.start:min(nd.end, len(ip.s))]
start, end := nd.start, nd.end
la := start + literalToSource(source, data, a)
lb := start + literalToSource(source, data, b)
r := ip.newNode(kind, data[a:b], la, lb)
post := ip.newNode(Text, data[b:], lb, end)
nd = &ip.nodes[c]
nd.text, nd.start, nd.end = data[:a], start, la
ip.insertAfter(c, r)
ip.insertAfter(r, post)
c, prevWord = post, endsInWord(data[:b])
origin += b
}
}
// refScan is where the next @, # and - of a text are, as offsets in it,
// -1 before they are looked for, and the text's length when there is none
// or the paragraph has none (has, as referenceBytes returns).
type refScan struct {
next [3]int
has uint8
}
// findReference finds the first mention or reference in data, the text
// from origin on, which a word character precedes when prevWord: its
// bytes and kind, or Text when there is none, and the bytes it scanned.
func findReference(data string, origin int, sc *refScan, prevWord bool, ext Extensions) (a, b int, kind InlineKind, steps int) {
mentions, refs := ext&ExtMentions != 0, ext&ExtReferences != 0
wordBefore := func(i int) bool {
if i == 0 {
return prevWord
}
return endsInWord(data[:i])
}
// The next @, # and - at or after i, each found with the vectorized
// IndexByte, which IndexAny is not, and kept across the text's splits.
find := func(k int, c byte, i int) int {
if sc.next[k] < origin+i {
if j := strings.IndexByte(data[i:], c); j < 0 {
sc.next[k] = origin + len(data)
} else {
sc.next[k] = origin + i + j
}
steps += sc.next[k] - origin - i
}
return sc.next[k] - origin
}
for i := 0; i < len(data); i++ {
j := len(data)
if sc.has&hasAt != 0 {
j = find(0, '@', i)
}
if sc.has&hasHash != 0 {
j = min(j, find(1, '#', i))
}
if sc.has&hasGH != 0 {
j = min(j, find(2, '-', i))
}
if j == len(data) {
return 0, 0, Text, steps
}
i = j
switch data[i] {
case '@':
if mentions && !wordBefore(i) {
if e := scanMention(data, i+1); e > 0 {
return i, e, Mention, steps + e - i
}
}
case '#':
if !refs {
continue
}
from := i
if wordBefore(i) {
var n int
from, n = repoBefore(data, i, prevWord)
steps += n
if from < 0 {
continue
}
}
if e := scanNumber(data, i+1); e > 0 {
return from, e, Reference, steps + e - i
}
default: // GH-123, found at its hyphen, as letters are many
if refs && isGH(data, i) && !wordBefore(i-2) {
if e := scanNumber(data, i+1); e > 0 {
return i - 2, e, Reference, steps + e - i
}
}
}
}
return 0, 0, Text, steps
}
// scanMention returns the end of the login, or team, at data[i:], after
// an @, or 0: a login is letters, digits and hyphens, from a letter or a
// digit, and a team a login, a slash and its name. No word follows it,
// nor a dot and a word, as in @example.com.
func scanMention(data string, i int) int {
j := i
if j >= len(data) || !isASCIIAlnum(data[j]) {
return 0
}
for j < len(data) && (isASCIIAlnum(data[j]) || data[j] == '-') {
j++
}
if j-i > maxLogin {
return 0
}
if j+1 < len(data) && data[j] == '/' && isASCIIAlnum(data[j+1]) {
j += 2
for j < len(data) && (isASCIIAlnum(data[j]) || data[j] == '-' || data[j] == '_') {
j++
}
}
if startsWithWord(data[j:]) || j+1 < len(data) && data[j] == '.' && isASCIIAlnum(data[j+1]) {
return 0
}
return j
}
// scanNumber returns the end of the issue number at data[i:], or 0: no
// more than maxDigit digits, from 1 to 9, which no word follows.
func scanNumber(data string, i int) int {
j := i
if j >= len(data) || data[j] < '1' || data[j] > '9' {
return 0
}
for j < len(data) && isASCIIDigit(data[j]) {
j++
}
if j-i > maxDigit || startsWithWord(data[j:]) {
return 0
}
return j
}
// repoBefore returns where owner/name ends at data[h], a #, begins, or
// -1, and the bytes it scanned: no word, slash or dot precedes it.
func repoBefore(data string, h int, prevWord bool) (int, int) {
j := h
for j > 0 && h-j < maxRepo && isRepoChar(data[j-1]) {
j--
}
if j == h || j == 0 || data[j-1] != '/' {
return -1, h - j
}
o := j - 1
k := o
for k > 0 && o-k < maxLogin && (isASCIIAlnum(data[k-1]) || data[k-1] == '-') {
k--
}
steps := h - k
if k == o || !isASCIIAlnum(data[k]) {
return -1, steps
}
if k == 0 {
if prevWord {
return -1, steps
}
return 0, steps
}
if c := data[k-1]; c == '/' || c == '.' || endsInWord(data[:k]) {
return -1, steps
}
return k, steps
}
func isRepoChar(c byte) bool { return isASCIIAlnum(c) || c == '-' || c == '_' || c == '.' }
// isWordRune reports whether r is of a word: a letter, a digit or _.
func isWordRune(r rune) bool {
if r < utf8.RuneSelf {
return isASCIIAlnum(byte(r)) || r == '_'
}
return unicode.IsLetter(r) || unicode.IsDigit(r)
}
func endsInWord(s string) bool {
r, _ := utf8.DecodeLastRuneInString(s)
return s != "" && isWordRune(r)
}
func startsWithWord(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return s != "" && isWordRune(r)
}
// isGH reports whether data[i], a hyphen, follows GH, in any case.
func isGH(data string, i int) bool {
return i >= 2 && data[i-2]|0x20 == 'g' && data[i-1]|0x20 == 'h'
}
// Which of a text's bytes may start a mention or a reference, as
// referenceBytes finds them.
const (
hasAt = 1 << iota // @, of a mention
hasHash // #, of a reference
hasGH // the - of GH-
)
// referenceBytes returns which bytes that may start a mention or a
// reference s holds, of those ext reads, so that text without them is not
// scanned again, nor scanned for those it lacks.
func referenceBytes(s string, ext Extensions) uint8 {
var has uint8
// IndexByte is vectorized, which ContainsAny is not.
if ext&ExtMentions != 0 && strings.IndexByte(s, '@') >= 0 {
has |= hasAt
}
if ext&ExtReferences == 0 {
return has
}
if strings.IndexByte(s, '#') >= 0 {
has |= hasHash
}
for i := strings.IndexByte(s, '-'); i >= 0; {
if isGH(s, i) {
has |= hasGH
break
}
j := strings.IndexByte(s[i+1:], '-')
if j < 0 {
break
}
i += 1 + j
}
return has
}
func isASCIIAlnum(c byte) bool { return isASCIIDigit(c) || isASCIILetter(c) }
+105
View File
@@ -0,0 +1,105 @@
package parser
import (
"fmt"
"strings"
"testing"
)
// refsOf lists the mentions and references of src's blocks, each as
// kind:text@start, checking that its offsets are its source.
func refsOf(t *testing.T, ext Extensions, src string) string {
t.Helper()
d := New(ext)
d.Set(src)
var out []string
for i := range d.Len() {
for _, in := range d.Inlines(i) {
if in.Kind != Mention && in.Kind != Reference {
continue
}
if got := src[in.Start:in.End]; got != in.Text {
t.Errorf("%q: %v %q is %q in the source", src, in.Kind, in.Text, got)
}
out = append(out, fmt.Sprintf("%v:%s@%d", in.Kind, in.Text, in.Start))
}
}
return strings.Join(out, " ")
}
// The cases are GitHub's, as its Markdown API rendered them, but for
// whether the person or the issue exists, which a view resolves.
func TestMentions(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"hi @octocat and @hubot.", "mention:@octocat@3 mention:@hubot@16"},
{"foo@octocat x@y _@octocat", ""},
{"(@a) \"@b\" /@c .@d", "mention:@a@1 mention:@b@6 mention:@c@11 mention:@d@15"},
{"@a, @b! @c? @d: @e.", "mention:@a@0 mention:@b@4 mention:@c@8 mention:@d@12 mention:@e@16"},
{"@foo- @foo_bar @-foo", "mention:@foo-@0"},
{"cc @github/docs", "mention:@github/docs@3"},
{"@octocat@x @octocat.dev", "mention:@octocat@0"},
{"mail me@example.com", ""},
{"`@octocat` [@octocat](https://x.y) **@octocat** <@octocat>", "mention:@octocat@37 mention:@octocat@49"},
{"é@octocat", ""},
{"@" + strings.Repeat("a", 39) + " @" + strings.Repeat("a", 40), "mention:@" + strings.Repeat("a", 39) + "@0"},
{"# Hi @octocat", "mention:@octocat@5"},
{"| @octocat |\n|---|", "mention:@octocat@2"},
{"_a_@octocat **b**@octocat", "mention:@octocat@3 mention:@octocat@17"},
{`<a href="u">@octocat</a> <code>@octocat</code> <b>@octocat</b> <br/>@octocat`, "mention:@octocat@50 mention:@octocat@68"},
{"<pre>\n@a</pre>", ""},
} {
if got := refsOf(t, Default, c.src); got != c.want {
t.Errorf("%q gives %q, want %q", c.src, got, c.want)
}
}
if got := refsOf(t, Default&^ExtMentions, "hi @octocat #1"); got != "reference:#1@12" {
t.Errorf("without ExtMentions: %q", got)
}
}
func TestReferences(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"see #874, (#871). a#874 #874abc #874. #0", "reference:#874@4 reference:#871@11 reference:#874@32"},
{"GH-874 gh-874 xGH-1", "reference:GH-874@0 reference:gh-874@7"},
{"octocat/hello-world#12 (b/c_d.e#3) (a.b/c#3)", "reference:octocat/hello-world#12@0 reference:b/c_d.e#3@24"},
{"x.org/a/b#1 /a/b#1 _#874", ""},
{"`#1` [#1](u) *#1*", "reference:#1@14"},
{"#12345678901 #1234567890", "reference:#1234567890@13"},
{"_a_#1 me@x.com#2 #3#4", "reference:#1@3 reference:#2@14 reference:#3@17"},
{"<code>#1</code> <A HREF=u>#2</a> #3", "reference:#3@33"},
} {
if got := refsOf(t, Default, c.src); got != c.want {
t.Errorf("%q gives %q, want %q", c.src, got, c.want)
}
}
if got := refsOf(t, Default&^ExtReferences, "hi @octocat #1"); got != "mention:@octocat@3" {
t.Errorf("without ExtReferences: %q", got)
}
}
func TestLoginAndRef(t *testing.T) {
d := New(Default)
d.Set("@octocat @github/docs #12 GH-7 octocat/hello#3")
type ref struct {
login, repo string
n int
}
var got []ref
for _, in := range d.Inlines(1) {
if in.Kind == Mention || in.Kind == Reference {
r, n := in.Ref()
got = append(got, ref{in.Login(), r, n})
}
}
want := []ref{{"octocat", "", 0}, {"github/docs", "", 0}, {"", "", 12}, {"", "", 7}, {"", "octocat/hello", 3}}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Errorf("got %v, want %v", got, want)
}
// Inlines made by hand do not panic.
if login := (Inline{Kind: Mention}).Login(); login != "" {
t.Errorf("an empty mention's login is %q", login)
}
if repo, n := (Inline{Kind: Reference, Text: "x"}).Ref(); repo != "" || n != 0 {
t.Errorf("a reference without a number is %q, %d", repo, n)
}
}
@@ -0,0 +1,91 @@
package parser
import (
"strings"
"testing"
)
// Bugs found reviewing the inline parser; each test fails on 088606d5.
// An email autolink in text after an entity or an escape gets the
// offsets of the decoded text, not of the source.
func TestReviewEmailOffsets(t *testing.T) {
for _, src := range []string{"a &amp; b x@y.com", `a \* b x@y.com`} {
d := Parse(src)
for _, in := range d.Inlines(1) {
if in.Kind == Link {
if got := d.Source()[in.Start:in.End]; got != "x@y.com" {
t.Errorf("%q: link [%d,%d) is %q, want %q", src, in.Start, in.End, got, "x@y.com")
}
}
}
}
}
// Quadratic time: nested footnote-like brackets, $ math with
// ExtDollarMath, and \( without \).
func TestReviewQuadratic(t *testing.T) {
checkLinear(t, "footnote brackets", Default, func(n int) string { return strings.Repeat("[^a", n) + strings.Repeat("]", n) })
checkLinear(t, "dollar openers", Default|ExtDollarMath, repeat("$a "))
checkLinear(t, "\\( openers", Default, repeat(`\(`))
}
// HTML entities are only names of the table followed by ;, not a
// legacy name's prefix.
func TestReviewEntityPrefix(t *testing.T) {
if got, want := render("&copyright; &notit;", Default), "<p>&amp;copyright; &amp;notit;</p>\n"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestReviewHealing(t *testing.T) {
for _, c := range []struct{ src, want string }{
// A tilde for "about" strikes the rest of the paragraph through.
{"about ~200 keys. See", "<p>about ~200 keys. See</p>\n"},
// Strong next to CJK text is not healed: ** shows.
{"这是**重要", "<p>这是<strong>重要</strong></p>\n"},
// An open code span skips healing emphasis: ** shows.
{"Edit **`config.ya", "<p>Edit <strong><code>config.ya</code></strong></p>\n"},
// $$ inside a code span counts as open math: $$ shows.
{"Use `$$` for display math", "<p>Use <code>$$</code> for display math</p>\n"},
// A destination with parentheses: raw syntax, and the added ) shows.
{"See [Go](https://en.wikipedia.org/wiki/Go_(lang", `<p>See <a href="https://en.wikipedia.org/wiki/Go_(lang)">Go</a></p>` + "\n"},
// The text of a link being written shows its [.
{"See the [Go blog", "<p>See the Go blog</p>\n"},
// Strikethrough being closed shows its tildes.
{"a ~~struck~", "<p>a <del>struck</del></p>\n"},
// A < destination: the added ) shows.
{"see [a](<htt", `<p>see <a href="htt">a</a></p>` + "\n"},
} {
if got := streamed(c.src); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
// Extended autolinks end at punctuation beyond ASCII, such as the CJK
// comma, and at spaces beyond ASCII, but not at letters beyond ASCII.
func TestReviewAutolinkUnicodePunct(t *testing.T) {
for _, c := range []struct{ src, want string }{
{"信中附上链接:https://vishnuai.in/mediakit,并留下电话联系方式。", `<p>信中附上链接:<a href="https://vishnuai.in/mediakit">https://vishnuai.in/mediakit</a>,并留下电话联系方式。</p>` + "\n"},
{"见 https://example.com/a。", `<p>见 <a href="https://example.com/a">https://example.com/a</a>。</p>` + "\n"},
{"“www.example.com”", `<p>“<a href="http://www.example.com">www.example.com</a>”</p>` + "\n"},
{"(www.example.com/路径)", `<p>(<a href="http://www.example.com/%E8%B7%AF%E5%BE%84">www.example.com/路径</a>)</p>` + "\n"},
{"https://例子.测试/页面", `<p><a href="https://%E4%BE%8B%E5%AD%90.%E6%B5%8B%E8%AF%95/%E9%A1%B5%E9%9D%A2">https://例子.测试/页面</a></p>` + "\n"},
{"https://en.wikipedia.org/wiki/1990–91_season", `<p><a href="https://en.wikipedia.org/wiki/1990%E2%80%9391_season">https://en.wikipedia.org/wiki/1990–91_season</a></p>` + "\n"},
{"https://example.com\u3000下一句", `<p><a href="https://example.com">https://example.com</a>` + "\u3000下一句</p>\n"},
{"https://example.com\u2028下一句", `<p><a href="https://example.com">https://example.com</a>` + "\u2028下一句</p>\n"},
{"https://example.com/a\u2028下一句", `<p><a href="https://example.com/a">https://example.com/a</a>` + "\u2028下一句</p>\n"},
{"见\u2029www.example.com", "<p>见\u2029" + `<a href="http://www.example.com">www.example.com</a></p>` + "\n"},
{"邮箱:a@example.com,谢谢", `<p>邮箱:<a href="mailto:a@example.com">a@example.com</a>,谢谢</p>` + "\n"},
// Written links keep their whole destination and text.
{"[文档,下载](https://example.org/文档,下载)", `<p><a href="https://example.org/%E6%96%87%E6%A1%A3%EF%BC%8C%E4%B8%8B%E8%BD%BD">文档,下载</a></p>` + "\n"},
{"[https://example.org/文档,下载](https://example.org/文档,下载)", `<p><a href="https://example.org/%E6%96%87%E6%A1%A3%EF%BC%8C%E4%B8%8B%E8%BD%BD">https://example.org/文档,下载</a></p>` + "\n"},
{"<https://example.org/x,y>", `<p><a href="https://example.org/x%EF%BC%8Cy">https://example.org/x,y</a></p>` + "\n"},
{"[见 https://example.org/a,b](https://c.org)", `<p><a href="https://c.org">见 https://example.org/a,b</a></p>` + "\n"},
} {
if got := render(c.src, Default); got != c.want {
t.Errorf("%q:\ngot %q\nwant %q", c.src, got, c.want)
}
}
}
@@ -0,0 +1,891 @@
package parser
import (
"fmt"
"math/rand/v2"
"os"
"strconv"
"strings"
"testing"
"time"
"unicode/utf8"
)
// checkInvariants checks Next, Parent and segs ranges.
func checkInvariants(t *testing.T, d *Document, ctx string) {
t.Helper()
n := len(d.blocks)
if d.blocks[0].Next != n {
t.Fatalf("%s: root.Next %d, len %d", ctx, d.blocks[0].Next, n)
}
for i := 1; i < n; i++ {
b := &d.blocks[i]
if b.Parent < 0 || b.Parent >= i {
t.Fatalf("%s: block %d parent %d", ctx, i, b.Parent)
}
p := &d.blocks[b.Parent]
if b.Next <= i || b.Next > p.Next {
t.Fatalf("%s: block %d (%v) Next %d, parent %d Next %d", ctx, i, b.Kind, b.Next, b.Parent, p.Next)
}
if b.segA > b.segB || int(b.segB) > len(d.segs) {
t.Fatalf("%s: block %d segs [%d,%d) of %d", ctx, i, b.segA, b.segB, len(d.segs))
}
for _, s := range d.segsOf(b) {
if s.start > s.end || int(s.end) > len(d.src) {
t.Fatalf("%s: block %d seg %v src %d", ctx, i, s, len(d.src))
}
}
}
for k, i := range d.notes {
if i <= 0 || i >= n || d.blocks[i].Kind != FootnoteDefinition || normalizeLabel(d.blocks[i].info) != k {
t.Fatalf("%s: notes[%q]=%d bad", ctx, k, i)
}
}
}
var zzExt = func() Extensions {
if os.Getenv("ZZTABLES") != "" {
return Default
}
return Default &^ ExtTables
}()
func zzSeed() uint64 {
n, _ := strconv.ParseUint(os.Getenv("ZZSEED"), 10, 64)
return n
}
// zzKnown filters sources hitting a bug already reported: a label defined
// twice.
func zzKnown(src string) bool {
zzSeen = zzSeen || strings.Count(src, "[a]:") > 1 || strings.Count(src, "[b]:") > 1 || strings.Count(src, "[a]") > 1 && strings.Contains(src, "[a]:") || strings.Count(src, "[b]") > 1 && strings.Contains(src, "[b]:")
return zzSeen
}
var zzSeen bool
// zzFuzzOnly skips the random differential tests and probes unless
// ZZFUZZ is set (ZZSEED, ZZTABLES and ZZSTRUCT vary them).
func zzFuzzOnly(t *testing.T) {
if os.Getenv("ZZFUZZ") == "" {
t.Skip("set ZZFUZZ=1")
}
}
var zzStruct = os.Getenv("ZZSTRUCT") != ""
// zzDump describes blocks and their inlines with offsets.
func zzDump(d *Document) string {
var sb strings.Builder
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
fmt.Fprintf(&sb, "%d %v p%d n%d [%d,%d) open=%v L%d %v%d%c t%v task%d f%v h%v %v %q\n", i, b.Kind, b.Parent, b.Next, b.Start, b.End, b.Open, b.Level, b.Ordered, b.Number, b.Marker, b.Tight, b.Task, b.Fenced, b.Header, b.Align, b.info)
if b.Kind == CodeBlock || b.Kind == MathBlock || b.Kind == HTMLBlock {
for k := 0; k < d.LineCount(i); k++ {
l, o := d.Line(i, k)
fmt.Fprintf(&sb, " line %q @%d\n", l, o)
}
}
for _, in := range d.Inlines(i) {
fmt.Fprintf(&sb, " %v %q %q [%d,%d) n%d\n", in.Kind, in.Text, in.Dest, in.Start, in.End, in.Next)
}
}
return sb.String()
}
func zzStructFails(d *Document, ext Extensions) bool {
f := New(ext)
f.Set(d.Source())
return zzDump(d) != zzDump(f)
}
var zzPieces = []string{
"", "\n", "\n\n", "\r\n", "\r", "\t", "- ", "* ", "+ ", "> ", ">", "# ", "## ", "```", "~~~", "**", "*", "_", "[a]", "[a]: /u\n", "[b]: /v \"t\"\n",
"|", "| a | b |\n", "|---|---|\n", "a | b\n", "--- | ---\n", " ", " ", "1. ", "2) ", "---\n", "===\n", "text", "word ", "`", "<div>", "</div>\n", "<!-- ", "-->", "<pre>",
"$$", "$$\n", "\\[", "\\]", "\\[\n", "\\]\n", "[^1]", "[^1]: ", "[^x]: note\n", " more\n", "é", "日本", "\u00a0", "[ ] ", "[x] ", "<http://a.b>", "www.x.com ", "$x$", "\\(y\\)",
}
func zzRandDoc(r *rand.Rand, n int) string {
var sb strings.Builder
for range n {
sb.WriteString(zzPieces[r.IntN(len(zzPieces))])
}
return sb.String()
}
func zzCheck(t *testing.T, d *Document, ext Extensions, ctx string) {
t.Helper()
checkInvariants(t, d, ctx)
if want := render(d.Source(), ext); d.HTML() != want && !zzKnown(d.Source()) {
t.Fatalf("%s:\nsrc %q\ngot %q\nwant %q", ctx, d.Source(), d.HTML(), want)
}
}
func zzAppendFails(chunks []string, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
d.SetStreaming(stream)
src := ""
for _, c := range chunks {
d.Append(c)
src += c
d.HTML()
if !stream && d.HTML() != render(src, ext) && !zzKnown(src) {
return true
}
}
d.SetStreaming(false)
return (d.HTML() != render(src, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(src)
}
func zzMinChunks(chunks []string, stream bool, ext Extensions) []string {
for changed := true; changed; {
changed = false
for i := 0; i < len(chunks); i++ {
ns := append(append([]string(nil), chunks[:i]...), chunks[i+1:]...)
if zzAppendFails(ns, stream, ext) {
chunks, changed, i = ns, true, i-1
continue
}
if i+1 < len(chunks) {
ns = append(append(append([]string(nil), chunks[:i]...), chunks[i]+chunks[i+1]), chunks[i+2:]...)
if zzAppendFails(ns, stream, ext) {
chunks, changed, i = ns, true, i-1
continue
}
}
}
for i := range chunks {
for k := 0; k < len(chunks[i]); k++ {
ns := append([]string(nil), chunks...)
ns[i] = chunks[i][:k] + chunks[i][k+1:]
if ns[i] != "" && utf8.ValidString(ns[i]) && zzAppendFails(ns, stream, ext) {
chunks, changed, k = ns, true, k-1
}
}
}
}
return chunks
}
func zzStreamFails(chunks []string, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
d.SetStreaming(true)
src := ""
for _, c := range chunks {
d.Append(c)
src += c
f := New(ext)
f.SetStreaming(true)
f.Set(src)
if d.HTML() != f.HTML() && !zzKnown(src) {
return true
}
}
return false
}
func TestParserReviewStreamMatchesFreshStream(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(51+zzSeed(), 52))
for iter := range 20000 {
ext := zzExt
src := zzRandDoc(r, 1+r.IntN(14))
var chunks []string
for i := 0; i < len(src); {
k := min(1+r.IntN(6), len(src)-i)
chunks = append(chunks, src[i:i+k])
i += k
}
if zzStreamFails(chunks, ext) {
// Minimize.
for changed := true; changed; {
changed = false
for i := 0; i < len(chunks); i++ {
ns := append(append([]string(nil), chunks[:i]...), chunks[i+1:]...)
if zzStreamFails(ns, ext) {
chunks, changed, i = ns, true, i-1
}
}
for i := range chunks {
for k := 0; k < len(chunks[i]); k++ {
ns := append([]string(nil), chunks...)
ns[i] = chunks[i][:k] + chunks[i][k+1:]
if ns[i] != "" && utf8.ValidString(ns[i]) && zzStreamFails(ns, ext) {
chunks, changed, k = ns, true, k-1
}
}
}
}
t.Fatalf("iter %d: streaming %q differs from a fresh streaming parse", iter, chunks)
}
}
}
func zzTimeAppend(src string, chunk int) time.Duration {
d := New(Default)
t0 := time.Now()
for i := 0; i < len(src); i += chunk {
d.Append(src[i:min(i+chunk, len(src))])
}
return time.Since(t0)
}
func TestParserReviewLineEndings(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(61+zzSeed(), 62))
norm := func(s string) string {
return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n")
}
found := 0
for iter := 0; iter < 30000 && found < 8; iter++ {
var sb strings.Builder
for range 1 + r.IntN(10) {
p := zzPieces[r.IntN(len(zzPieces))]
if strings.Contains(p, "\r") {
continue
}
sb.WriteString(p)
}
s := sb.String()
for _, eol := range []string{"\r\n", "\r"} {
c := strings.ReplaceAll(s, "\n", eol)
if want, got := render(s, Default), norm(render(c, Default)); got != want {
// Minimize s.
f := func(s string) bool {
c := strings.ReplaceAll(s, "\n", eol)
return render(s, Default) != norm(render(c, Default))
}
for changed := true; changed; {
changed = false
for k := 0; k < len(s); k++ {
n := s[:k] + s[k+1:]
if utf8.ValidString(n) && f(n) {
s, changed, k = n, true, k-1
}
}
}
c = strings.ReplaceAll(s, "\n", eol)
t.Errorf("eol %q: %q\n lf %q\n eol %q", eol, s, render(s, Default), render(c, Default))
found++
break
}
}
}
}
func TestParserReviewRandomAppend(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(11+zzSeed(), 12))
for iter := range 30000 {
ext := zzExt
if r.IntN(3) == 0 {
ext = zzExt | ExtDollarMath
}
src := zzRandDoc(r, 1+r.IntN(14))
stream := r.IntN(2) == 0
var chunks []string
for i := 0; i < len(src); {
k := min(1+r.IntN(6), len(src)-i)
chunks = append(chunks, src[i:i+k])
i += k
}
if zzAppendFails(chunks, stream, ext) {
t.Fatalf("iter %d stream=%v ext=%b minimal chunks %q", iter, stream, ext, zzMinChunks(chunks, stream, ext))
}
}
}
// zzEditFails reports whether Set(prev) then Edit(from, to, text) differs from a whole parse.
func zzEditFails(prev string, from, to int, text string, ext Extensions) bool {
d := New(ext)
d.Set(prev)
d.HTML()
failed := false
func() {
defer func() {
if recover() != nil {
failed = true
}
}()
d.Edit(from, to, text)
failed = d.HTML() != render(d.Source(), ext)
}()
return failed
}
func zzMinEdit(prev string, from, to int, text string, ext Extensions) (string, int, int) {
for changed := true; changed; {
changed = false
for i := 0; i < len(prev); i++ {
if i >= from && i < to {
continue
}
np := prev[:i] + prev[i+1:]
nf, nt := from, to
if i < from {
nf--
nt--
}
if utf8.ValidString(np) && zzEditFails(np, nf, nt, text, ext) {
prev, from, to = np, nf, nt
changed = true
i--
}
}
for to > from {
np := prev[:from] + prev[from+1:]
if utf8.ValidString(np) && zzEditFails(np, from, to-1, text, ext) {
prev, to = np, to-1
changed = true
} else {
break
}
}
}
return prev, from, to
}
// zzReplay sets each state in turn (streaming around it when stream), and
// reports whether any step differs from a whole parse.
func zzReplay(states []string, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
zzSeen = false
d := New(ext)
for _, s := range states {
if stream {
d.SetStreaming(true)
}
d.Set(s)
if stream {
d.HTML()
d.SetStreaming(false)
}
if (d.HTML() != render(s, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(s) {
return true
}
}
return false
}
func zzMinStates(states []string, stream bool, ext Extensions) []string {
for changed := true; changed; {
changed = false
for i := 0; i < len(states); i++ {
ns := append(append([]string(nil), states[:i]...), states[i+1:]...)
if len(ns) > 0 && zzReplay(ns, stream, ext) {
states = ns
changed = true
i--
}
}
// Shrink each state by dropping bytes.
for i := range states {
for k := 0; k < len(states[i]); k++ {
ns := append([]string(nil), states...)
ns[i] = states[i][:k] + states[i][k+1:]
if utf8.ValidString(ns[i]) && zzReplay(ns, stream, ext) {
states = ns
changed = true
k--
}
}
}
}
return states
}
func zzShow(t *testing.T, states []string, stream bool, ext Extensions) {
d := New(ext)
for _, s := range states {
if stream {
d.SetStreaming(true)
}
d.Set(s)
if stream {
t.Logf("streaming: %q", d.HTML())
d.SetStreaming(false)
}
t.Logf("set %q\n got %q\n want %q", s, d.HTML(), render(s, ext))
}
}
// An edit shrinking a heading before a quiet block shifts a restart point
// that lay before the splice: restart goes negative and the next Append
// panics.
func TestParserReviewEditStaleRestartPanics(t *testing.T) {
defer func() {
if r := recover(); r != nil {
t.Fatalf("panic: %v", r)
}
}()
d := New(0)
d.Set("# a\nb")
d.Set("c\n\nb") // Edit(0, 3, "c\n"): delta -1
t.Logf("restart %d restartAt %d", d.restart, d.restartAt)
d.Append("x")
if want := render("c\n\nbx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
func TestParserReviewEditStaleRestartWrong(t *testing.T) {
d := New(0)
d.Set("# a\nb")
d.Set("# a\n\nb") // insert a blank line: delta +1, restart stays 0 -> 1
t.Logf("restart %d restartAt %d", d.restart, d.restartAt)
d.Append("x")
if want := render("# a\n\nbx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// A setext heading whose paragraph began with a definition moves its
// Start past the definition, so the restart point noted from it skips
// the paragraph's first lines.
func TestParserReviewSetextAfterDefinitionAppend(t *testing.T) {
d := New(0)
d.Append("[a]: /u\n b\n=\n")
d.Append("x")
if want := render("[a]: /u\n b\n=\nx", 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// A table whose header was a later line of a paragraph starts at the
// header line, where parsing restarts: alone, "2) a|b" is a list item.
func TestParserReviewTableFromParagraphRestart(t *testing.T) {
d := New(GFM)
d.Append("e\n2) a|b\n-|-\n")
d.Append("x")
if want := render(d.Source(), GFM); d.HTML() != want {
t.Errorf("append: got %q want %q", d.HTML(), want)
}
d = New(GFM)
d.Set("e\n2) a|b\n-|-\n\nz\n")
d.Edit(14, 15, "y")
if want := render(d.Source(), GFM); d.HTML() != want {
t.Errorf("edit: got %q want %q", d.HTML(), want)
}
}
// A second definition of a label, in the blocks an edit keeps, is lost
// when the edit removes the first: refs keeps only the first, so the
// splice has no record of the second.
func TestParserReviewDuplicateDefinitionLost(t *testing.T) {
d := New(0)
d.Set("[b]: /1\n\n[b]\n\n[b]: /2\n")
d.Edit(0, 1, "")
if want := render(d.Source(), 0); d.HTML() != want {
t.Fatalf("got %q want %q", d.HTML(), want)
}
}
// An edit that changes only a continuation line's indentation reuses the
// paragraph's old inlines (same first offset, same text) with the old
// offsets.
func TestParserReviewReusedInlinesStaleOffsets(t *testing.T) {
d := New(0)
d.Set("a\nb\n\nc\n")
d.HTML()
d.Edit(2, 2, " ")
f := New(0)
f.Set(d.Source())
if got, want := zzDump(d), zzDump(f); got != want {
t.Fatalf("got\n%s\nwant\n%s", got, want)
}
}
// An HTML block of type 7 cannot interrupt a paragraph, a lazy
// continuation line included (commonmark.js's "maybe lazy", cmark's
// !maybe_lazy): the tag continues the item's paragraph.
func TestParserReviewHTMLBlock7InterruptsLazyParagraph(t *testing.T) {
for src, want := range map[string]string{
"- a\n<x y=\"\">\n": "<ul>\n<li>a\n<x y=\"\"></li>\n</ul>\n",
"> a\n<x>\n": "<blockquote>\n<p>a\n<x></p>\n</blockquote>\n",
} {
if got := render(src, 0); got != want {
t.Errorf("%q: got %q want %q", src, got, want)
}
}
}
// A math block's opening line adds an empty line (or a second, empty
// line after the TeX on it) to its content.
func TestParserReviewMathBlockOpeningLine(t *testing.T) {
for src, want := range map[string]string{
"$$\ny\n$$\n": "y\n",
"$$ x\ny\n$$\n": "x\ny\n",
} {
d := Parse(src)
if got := d.Lines(1); got != want {
t.Errorf("%q: lines %q (%d), want %q", src, got, d.LineCount(1), want)
}
}
}
// Lines ending in \r alone make the parser look for \n to the end of the
// source on every line.
func TestParserReviewCROnlyQuadratic(t *testing.T) {
checkLinearWork(t, "lines ending in CR", Default, false, repeat("a\r"))
}
// \[ display math never closes at \]: mathBracket compares with the raw
// string `\\]`, three bytes.
func TestParserReviewBracketMathNeverCloses(t *testing.T) {
got := render("\\[\na\n\\]\n\ntext\n", Default)
want := "<div class=\"math display\">a</div>\n<p>text</p>\n"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
}
// A childless list item spans its own marker line through that line's
// end, rather than truncating Block.End to Start+1 inside multi-byte
// markers such as "1. " or "10. ".
func TestParserReviewEmptyItemEndsAtLineEnd(t *testing.T) {
for _, tt := range []struct {
src string
start, end int
}{
{"- \n\n", 0, 2},
{"-\t\n\n", 0, 2},
{"1. \n\n", 0, 3},
{"10. \n\n", 0, 4},
{"1. \n2. a\n", 0, 3},
{"1. a\n2. \n\n", 5, 8},
{"1. a\n2. \n3. b\n", 5, 8},
{"- - \n\n", 2, 4},
{"1. ", 0, 3},
{"- \r\n\n", 0, 2},
{"- \n\n", 0, 4},
{"-\n", 0, 1},
{"1.\n", 0, 2},
} {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
d.Set(tt.src)
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item || b.Start != tt.start {
continue
}
found = true
if b.End != tt.end {
t.Errorf("ext=%v %q: item span [%d,%d), want [%d,%d)", ext, tt.src, b.Start, b.End, tt.start, tt.end)
}
if p := d.Block(b.Parent); p.Kind == List && p.End < b.End {
t.Errorf("ext=%v %q: parent list End=%d < item End=%d", ext, tt.src, p.End, b.End)
}
}
if !found {
t.Errorf("ext=%v %q: no item starting at %d", ext, tt.src, tt.start)
}
}
}
}
// Partial and streaming parses (where d.src holds bytes past end) must
// never scan past end when finalizing a childless list item.
func TestParserReviewEmptyItemEndsAtPartialEnd(t *testing.T) {
for _, ext := range []Extensions{0, Default} {
// Streaming trims the incomplete trailing UTF-8 sequence at end=5
// ("100. "), while d.src still contains the trailing bytes.
d := New(ext)
d.SetStreaming(true)
d.Set("100. \xe2\x82")
if d.cut != 5 {
t.Fatalf("ext=%v streaming cut=%d, want 5", ext, d.cut)
}
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item {
continue
}
found = true
if b.Start != 0 || b.End != 5 {
t.Errorf("ext=%v streaming: item span [%d,%d), want [0,5)", ext, b.Start, b.End)
}
if p := d.Block(b.Parent); p.Kind != List || p.End > 5 || p.End < b.End {
t.Errorf("ext=%v streaming: parent list span [%d,%d) exceeds cut 5", ext, p.Start, p.End)
}
}
if !found {
t.Errorf("ext=%v streaming: no item found", ext)
}
}
for _, tt := range []struct {
src string
end int
start, want int
}{
{"100. \xe2\x82", 5, 0, 5},
{"100. \xe2\x82", 4, 0, 4},
{"10. \xe2\x82", 4, 0, 4},
{"- \xe2\x82", 2, 0, 2},
{"1. a\n2. \xe2\x82", 8, 5, 8},
} {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
d.src = tt.src
d.parse(0, tt.end, nil)
found := false
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != Item || b.Start != tt.start {
continue
}
found = true
if b.End != tt.want || b.End > tt.end {
t.Errorf("ext=%v %q end=%d: item span [%d,%d), want [%d,%d)", ext, tt.src, tt.end, b.Start, b.End, tt.start, tt.want)
}
if p := d.Block(b.Parent); p.Kind != List || p.End > tt.end || p.End < b.End {
t.Errorf("ext=%v %q end=%d: parent list End=%d, item End=%d", ext, tt.src, tt.end, p.End, b.End)
}
}
if !found {
t.Errorf("ext=%v %q end=%d: no item starting at %d", ext, tt.src, tt.end, tt.start)
}
}
}
}
// A closed math block's End includes its closing delimiter line rather
// than stopping at its last content segment.
func TestParserReviewMathBlockEnd(t *testing.T) {
for _, c := range []struct {
name string
src string
wantStart int
wantEnd int
wantOpen bool
}{
{"dollar multiline", "$$\nx\n$$\n", 0, len("$$\nx\n$$"), false},
{"dollar multiline with trailing para", "$$\nx\ny\n$$\n\nafter\n", 0, len("$$\nx\ny\n$$"), false},
{"dollar closing line content", "$$\nx $$\n", 0, len("$$\nx $$"), false},
{"dollar single line", "$$ x $$\n", 0, len("$$ x $$"), false},
{"bracket multiline", "\\[\nx\n\\]\n", 0, len("\\[\nx\n\\]"), false},
{"bracket multiline with trailing para", "\\[\nx\ny \\]\n\nafter\n", 0, len("\\[\nx\ny \\]"), false},
{"bracket single line", "\\[ x \\]\n", 0, len("\\[ x \\]"), false},
{"dollar unclosed", "$$\nx\n", 0, len("$$\nx"), true},
} {
d := Parse(c.src)
if d.Len() < 2 {
t.Fatalf("%s: expected at least 2 blocks, got %d", c.name, d.Len())
}
b := d.Block(1)
if b.Kind != MathBlock {
t.Fatalf("%s: block 1 kind = %v, want MathBlock", c.name, b.Kind)
}
if b.Start != c.wantStart || b.End != c.wantEnd || b.Open != c.wantOpen {
t.Errorf("%s: got Start=%d End=%d Open=%v (%q), want Start=%d End=%d Open=%v (%q)",
c.name, b.Start, b.End, b.Open, c.src[b.Start:b.End],
c.wantStart, c.wantEnd, c.wantOpen, c.src[c.wantStart:c.wantEnd])
}
}
}
func TestParserReviewRandomSetStates(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(31+zzSeed(), 32))
for iter := range 6000 {
ext := zzExt
stream := r.IntN(2) == 0
states := []string{zzRandDoc(r, 1+r.IntN(12))}
for range 12 {
cur := states[len(states)-1]
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(10))
if r.IntN(3) == 0 {
to = from
}
next := cur[:from] + zzPieces[r.IntN(len(zzPieces))] + cur[to:]
if utf8.ValidString(next) {
states = append(states, next)
}
}
if zzReplay(states, stream, ext) {
m := zzMinStates(states, stream, ext)
t.Fatalf("iter %d stream=%v minimal states %q", iter, stream, m)
}
}
}
type zzOp struct {
from, to int
text string
}
func zzOpsFail(init string, ops []zzOp, stream bool, ext Extensions) (failed bool) {
defer func() {
if recover() != nil {
failed = true
}
}()
d := New(ext)
d.Set(init)
zzSeen = false
zzKnown(init)
cur := init
for _, o := range ops {
if o.to > len(cur) || o.from > o.to {
return false
}
next := cur[:o.from] + o.text + cur[o.to:]
if !utf8.ValidString(next) {
return false
}
if stream {
d.SetStreaming(true)
}
d.Edit(o.from, o.to, o.text)
if stream {
d.HTML()
d.SetStreaming(false)
}
cur = next
if (d.HTML() != render(cur, ext) || zzStruct && zzStructFails(d, ext)) && !zzKnown(cur) {
return true
}
}
return false
}
func zzMinOps(init string, ops []zzOp, stream bool, ext Extensions) (string, []zzOp) {
for changed := true; changed; {
changed = false
for i := 0; i < len(ops); i++ {
ns := append(append([]zzOp(nil), ops[:i]...), ops[i+1:]...)
if zzOpsFail(init, ns, stream, ext) {
ops, changed, i = ns, true, i-1
}
}
for k := 0; k < len(init); k++ {
ni := init[:k] + init[k+1:]
ns := append([]zzOp(nil), ops...)
for x := range ns {
// Shift ops naively: only valid for the first op.
if x == 0 {
if ns[0].from > k {
ns[0].from--
}
if ns[0].to > k {
ns[0].to--
}
}
}
if zzOpsFail(ni, ns, stream, ext) {
init, ops, changed, k = ni, ns, true, k-1
}
}
for x := range ops {
for k := 0; k < len(ops[x].text); k++ {
ns := append([]zzOp(nil), ops...)
ns[x].text = ops[x].text[:k] + ops[x].text[k+1:]
if zzOpsFail(init, ns, stream, ext) {
ops, changed, k = ns, true, k-1
}
}
if ops[x].to > ops[x].from {
ns := append([]zzOp(nil), ops...)
ns[x].to--
if zzOpsFail(init, ns, stream, ext) {
ops, changed = ns, true
}
}
}
}
return init, ops
}
func TestParserReviewRandomEditOps(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(41+zzSeed(), 42))
for iter := range 6000 {
ext := zzExt
stream := r.IntN(3) == 0
init := zzRandDoc(r, 1+r.IntN(20))
cur := init
var ops []zzOp
for range 20 {
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(12))
if r.IntN(3) == 0 {
to = from
}
text := zzPieces[r.IntN(len(zzPieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
ops = append(ops, zzOp{from, to, text})
cur = next
}
if zzOpsFail(init, ops, stream, ext) {
mi, mo := zzMinOps(init, ops, stream, ext)
t.Fatalf("iter %d stream=%v init %q ops %+v", iter, stream, mi, mo)
}
}
}
func TestParserReviewRandomEdit(t *testing.T) {
zzFuzzOnly(t)
r := rand.New(rand.NewPCG(21+zzSeed(), 22))
for iter := range 4000 {
ext := zzExt
src := zzRandDoc(r, 1+r.IntN(20))
d := New(ext)
d.Set(src)
zzSeen = false
zzKnown(src)
stream := r.IntN(3) == 0
for e := range 30 {
cur := d.Source()
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(12))
if r.IntN(3) == 0 {
to = from
}
text := zzPieces[r.IntN(len(zzPieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
if stream {
d.SetStreaming(true)
}
switch r.IntN(3) {
case 0:
d.Set(next)
default:
d.Edit(from, to, text)
}
if stream {
d.HTML()
d.SetStreaming(false)
}
if d.Source() != next {
t.Fatalf("source mismatch")
}
zzCheck(t, d, ext, fmt.Sprintf("iter %d edit %d [%d,%d)->%q prev %q", iter, e, from, to, text, cur))
}
}
}
+577
View File
@@ -0,0 +1,577 @@
package parser
import (
"html"
"strings"
"unicode/utf8"
)
// scanATXStart returns the length of an ATX heading's opening sequence
// at i with the spaces after it, or 0.
func scanATXStart(ln string, i int) int {
j := i
for j < len(ln) && ln[j] == '#' && j-i < 7 {
j++
}
n := j - i
if n == 0 || n > 6 {
return 0
}
if j == len(ln) {
return n
}
if !isSpaceOrTab(ln[j]) {
return 0
}
for j < len(ln) && isSpaceOrTab(ln[j]) {
j++
}
return j - i
}
// scanOpenFence returns the length of an opening code fence at i, or 0.
func scanOpenFence(ln string, i int) int {
c := ln[i]
j := i
for j < len(ln) && ln[j] == c {
j++
}
n := j - i
if n < 3 {
return 0
}
if c == '`' && strings.IndexByte(ln[j:], '`') >= 0 {
return 0
}
return n
}
// scanCloseFence returns the length of a closing code fence at i, or 0.
func scanCloseFence(ln string, i int) int {
c := ln[i]
if c != '`' && c != '~' {
return 0
}
j := i
for j < len(ln) && ln[j] == c {
j++
}
n := j - i
if n < 3 {
return 0
}
for ; j < len(ln); j++ {
if !isSpaceOrTab(ln[j]) {
return 0
}
}
return n
}
// scanSetextLine returns 1 for a line of =, 2 for one of -, or 0.
func scanSetextLine(ln string, i int) int {
c := ln[i]
j := i
for j < len(ln) && ln[j] == c {
j++
}
for ; j < len(ln); j++ {
if !isSpaceOrTab(ln[j]) {
return 0
}
}
if c == '=' {
return 1
}
return 2
}
// scanFootnoteDef returns the length of a footnote definition's start at
// i, [^label]: and the spaces after it, or 0.
func scanFootnoteDef(ln string, i int) int {
if !strings.HasPrefix(ln[i:], "[^") {
return 0
}
j := i + 2
for j < len(ln) && ln[j] != ']' {
switch ln[j] {
case ' ', '\t', '\r', '\n', 0:
return 0
}
j++
}
if j == i+2 || j+1 >= len(ln) || ln[j+1] != ':' {
return 0
}
j += 2
for j < len(ln) && isSpaceOrTab(ln[j]) {
j++
}
return j - i
}
var htmlBlockTags = map[string]bool{
"address": true, "article": true, "aside": true, "base": true, "basefont": true, "blockquote": true, "body": true,
"caption": true, "center": true, "col": true, "colgroup": true, "dd": true, "details": true, "dialog": true, "dir": true,
"div": true, "dl": true, "dt": true, "fieldset": true, "figcaption": true, "figure": true, "footer": true, "form": true,
"frame": true, "frameset": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true,
"header": true, "hr": true, "html": true, "iframe": true, "legend": true, "li": true, "link": true, "main": true,
"menu": true, "menuitem": true, "nav": true, "noframes": true, "ol": true, "optgroup": true, "option": true, "p": true,
"param": true, "search": true, "section": true, "summary": true, "table": true, "tbody": true, "td": true, "tfoot": true,
"th": true, "thead": true, "title": true, "tr": true, "track": true, "ul": true,
}
// hasPrefixFold reports whether s starts with prefix, ignoring ASCII case.
func hasPrefixFold(s, prefix string) bool {
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
}
// scanHTMLBlockStart returns the type (1 to 6) of an HTML block starting
// at i, or 0.
func scanHTMLBlockStart(ln string, i int) int {
s := ln[i:]
if len(s) < 2 || s[0] != '<' {
return 0
}
for _, tag := range [...]string{"<script", "<pre", "<style", "<textarea"} {
if hasPrefixFold(s, tag) {
if len(s) == len(tag) || s[len(tag)] == ' ' || s[len(tag)] == '\t' || s[len(tag)] == '>' {
return 1
}
}
}
switch {
case strings.HasPrefix(s, "<!--"):
return 2
case strings.HasPrefix(s, "<?"):
return 3
case strings.HasPrefix(s, "<![CDATA["):
return 5
case len(s) > 2 && s[1] == '!' && isASCIILetter(s[2]):
return 4
}
j := 1
if s[j] == '/' {
j++
}
k := j
for k < len(s) && (isASCIILetter(s[k]) || isASCIIDigit(s[k])) {
k++
}
if k == j || !htmlBlockTags[strings.ToLower(s[j:k])] {
return 0
}
if k == len(s) || s[k] == ' ' || s[k] == '\t' || s[k] == '>' || strings.HasPrefix(s[k:], "/>") {
return 6
}
return 0
}
// scanHTMLBlockStart7 returns 7 for a line that is a complete open or
// closing tag, other than script, style, pre and textarea, followed only
// by spaces, or 0.
func scanHTMLBlockStart7(ln string, i int) int {
s := ln[i:]
var n int
if strings.HasPrefix(s, "</") {
n = scanClosingTag(s, 0)
} else {
n = scanOpenTag(s, 0)
if n > 0 {
name := s[1:]
k := 0
for k < len(name) && (isASCIILetter(name[k]) || isASCIIDigit(name[k]) || name[k] == '-') {
k++
}
switch strings.ToLower(name[:k]) {
case "script", "style", "pre", "textarea":
return 0
}
}
}
if n == 0 || strings.Trim(s[n:], " \t") != "" {
return 0
}
return 7
}
// htmlBlockEnds reports whether a line ends an HTML block of type t.
func htmlBlockEnds(t int, s string) bool {
switch t {
case 1:
l := strings.ToLower(s)
return strings.Contains(l, "</script>") || strings.Contains(l, "</pre>") || strings.Contains(l, "</style>") || strings.Contains(l, "</textarea>")
case 2:
return strings.Contains(s, "-->")
case 3:
return strings.Contains(s, "?>")
case 4:
return strings.Contains(s, ">")
case 5:
return strings.Contains(s, "]]>")
}
return false
}
// The scanners of inline HTML (CommonMark's raw HTML) return the length
// of what they find at i, or 0.
func scanTagName(s string, i int) int {
if i >= len(s) || !isASCIILetter(s[i]) {
return 0
}
j := i + 1
for j < len(s) && (isASCIILetter(s[j]) || isASCIIDigit(s[j]) || s[j] == '-') {
j++
}
return j - i
}
// skipTagSpace skips whitespace within a tag, at most one line ending.
func skipTagSpace(s string, i int) int {
for i < len(s) && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r') {
i++
}
return i
}
func scanOpenTag(s string, i int) int {
if i >= len(s) || s[i] != '<' {
return 0
}
n := scanTagName(s, i+1)
if n == 0 {
return 0
}
j := i + 1 + n
for {
k := skipTagSpace(s, j)
if k < len(s) && s[k] == '>' {
return k + 1 - i
}
if k+1 < len(s) && s[k] == '/' && s[k+1] == '>' {
return k + 2 - i
}
if k == j {
return 0 // attributes need whitespace before them
}
// An attribute name.
if k >= len(s) || !(isASCIILetter(s[k]) || s[k] == '_' || s[k] == ':') {
return 0
}
k++
for k < len(s) && (isASCIILetter(s[k]) || isASCIIDigit(s[k]) || strings.IndexByte("_.:-", s[k]) >= 0) {
k++
}
// An optional value.
v := skipTagSpace(s, k)
if v < len(s) && s[v] == '=' {
v = skipTagSpace(s, v+1)
if v >= len(s) {
return 0
}
switch s[v] {
case '"', '\'':
e := strings.IndexByte(s[v+1:], s[v])
if e < 0 {
return 0
}
k = v + 1 + e + 1
default:
e := v
for e < len(s) && strings.IndexByte(" \t\n\r\"'=<>`", s[e]) < 0 {
e++
}
if e == v {
return 0
}
k = e
}
}
j = k
}
}
func scanClosingTag(s string, i int) int {
if !strings.HasPrefix(s[i:], "</") {
return 0
}
n := scanTagName(s, i+2)
if n == 0 {
return 0
}
k := skipTagSpace(s, i+2+n)
if k < len(s) && s[k] == '>' {
return k + 1 - i
}
return 0
}
// scanHTMLTag returns the length of the raw HTML at i: a tag, a comment,
// a processing instruction, a declaration or a CDATA section, or 0. The
// scanners noted in no remember that a kind found no end after a point,
// so that unclosed comments repeated do not take quadratic time.
func scanHTMLTag(s string, i int, no *htmlMemo) int {
r := s[i:]
if len(r) < 2 {
return 0
}
switch {
case r[1] == '/':
return scanClosingTag(s, i)
case r[1] == '?':
return no.until(s, i, 2, "?>", &no.pi)
case strings.HasPrefix(r, "<!--"):
if strings.HasPrefix(r, "<!-->") {
return 5
}
if strings.HasPrefix(r, "<!--->") {
return 6
}
return no.until(s, i, 4, "-->", &no.comment)
case strings.HasPrefix(r, "<![CDATA["):
return no.until(s, i, 9, "]]>", &no.cdata)
case r[1] == '!':
if len(r) > 2 && isASCIILetter(r[2]) {
return no.until(s, i, 3, ">", &no.decl)
}
return 0
}
return scanOpenTag(s, i)
}
type htmlMemo struct {
pi, comment, cdata, decl int
steps int // the bytes searched, as Document.steps
}
func (m *htmlMemo) reset() { *m = htmlMemo{-1, -1, -1, -1, 0} }
// until returns the length up to and including end, searched from
// i+skip, or 0; *none notes the offset after which none is.
func (m *htmlMemo) until(s string, i, skip int, end string, none *int) int {
if *none >= 0 && i+skip >= *none {
return 0
}
k := strings.Index(s[i+skip:], end)
if k < 0 {
m.steps += len(s) - i - skip
*none = i + skip
return 0
}
m.steps += k
return skip + k + len(end)
}
// scanDelimiterRow reads a table's delimiter row: cells of dashes, with
// a colon at either end for alignment, between pipes.
func scanDelimiterRow(line string) ([]Align, bool) {
line = strings.TrimRight(line, " \t")
if line == "" {
return nil, false
}
pipes := strings.Count(line, "|")
s := line
if s[0] == '|' {
s = s[1:]
}
if s != "" && s[len(s)-1] == '|' && pipes > 0 && (len(line) > 1 || line[0] != '|') {
if len(s) > 0 {
s = s[:len(s)-1]
}
}
var aligns []Align
for part := range strings.SplitSeq(s, "|") {
part = strings.Trim(part, " \t")
left := strings.HasPrefix(part, ":")
right := strings.HasSuffix(part, ":") && len(part) > 1
if left {
part = part[1:]
}
if right {
part = part[:len(part)-1]
}
if part == "" || strings.Trim(part, "-") != "" {
return nil, false
}
a := AlignNone
switch {
case left && right:
a = AlignCenter
case left:
a = AlignLeft
case right:
a = AlignRight
}
aligns = append(aligns, a)
}
if len(aligns) == 0 {
return nil, false
}
return aligns, true
}
// splitRow splits a table row into its cells' byte ranges, trimmed: an
// optional pipe, then cells between pipes, whose \| do not split.
func splitRow(line string) [][2]int {
var cells [][2]int
i := 0
if i < len(line) && line[i] == '|' {
i++
for i < len(line) && isSpaceOrTab(line[i]) {
i++
}
}
for i < len(line) {
j := i
for j < len(line) && line[j] != '|' {
if line[j] == '\\' && j+1 < len(line) && isEscapable(line[j+1]) {
j++
}
j++
}
j = min(j, len(line))
pipe := j < len(line)
a, b := i, j
for a < b && isSpaceOrTab(line[a]) {
a++
}
for b > a && isSpaceOrTab(line[b-1]) {
b--
}
if j > i || pipe {
cells = append(cells, [2]int{a, b})
}
if !pipe {
break
}
i = j + 1
for i < len(line) && isSpaceOrTab(line[i]) {
i++
}
}
return cells
}
// rowHasCells reports whether a line makes a table row of cells.
func rowHasCells(line string) bool {
return len(splitRow(line)) > 0
}
// isEscapable reports whether a backslash escapes c: ASCII punctuation.
func isEscapable(c byte) bool {
return c >= '!' && c <= '/' || c >= ':' && c <= '@' || c >= '[' && c <= '`' || c >= '{' && c <= '~'
}
// unescapeString resolves backslash escapes and entities.
func unescapeString(s string) string {
if strings.IndexByte(s, '\\') < 0 && strings.IndexByte(s, '&') < 0 {
return s
}
var b strings.Builder
for i := 0; i < len(s); i++ {
c := s[i]
switch {
case c == '\\' && i+1 < len(s) && isEscapable(s[i+1]):
b.WriteByte(s[i+1])
i++
case c == '&':
if n, text := scanEntity(s, i); n > 0 {
b.WriteString(text)
i += n - 1
} else {
b.WriteByte(c)
}
default:
b.WriteByte(c)
}
}
return b.String()
}
// Entity reads the entity or numeric character reference s starts with,
// as &amp; or &#35;, returning its length and the text it stands for, or
// 0 when s starts with none that Markdown reads.
func Entity(s string) (n int, text string) { return scanEntity(s, 0) }
// scanEntity reads an entity or a numeric character reference at i,
// returning its length and its text, or 0.
func scanEntity(s string, i int) (int, string) {
j := i + 1
if j < len(s) && s[j] == '#' {
j++
hex := j < len(s) && (s[j] == 'x' || s[j] == 'X')
if hex {
j++
}
start, v := j, 0
for j < len(s) {
c := s[j]
var d int
switch {
case isASCIIDigit(c):
d = int(c - '0')
case hex && c|0x20 >= 'a' && c|0x20 <= 'f':
d = int(c|0x20-'a') + 10
default:
goto end
}
if v < 0x110000 {
if hex {
v = v*16 + d
} else {
v = v*10 + d
}
}
j++
}
end:
n := j - start
if n == 0 || hex && n > 6 || !hex && n > 7 || j >= len(s) || s[j] != ';' {
return 0, ""
}
r := rune(v)
if v == 0 || v > utf8.MaxRune || v >= 0xD800 && v <= 0xDFFF {
r = utf8.RuneError
}
return j + 1 - i, string(r)
}
start := j
for j < len(s) && j-start <= 32 && (isASCIILetter(s[j]) || isASCIIDigit(s[j])) {
j++
}
if j == start || j >= len(s) || s[j] != ';' || !isASCIILetter(s[start]) {
return 0, ""
}
ent := s[i : j+1]
text := html.UnescapeString(ent)
// A legacy name's prefix decodes, leaving the rest: &notit; is ¬it;.
if text == ent || strings.HasSuffix(text, ";") && ent != "&semi;" {
return 0, ""
}
return j + 1 - i, text
}
// literalToSource returns the offset in source of byte j of text, the
// literal it reads as: escapes and entities decoded, the rest as it is.
func literalToSource(source, text string, j int) int {
if source == text {
return min(j, len(source))
}
i, k := 0, 0
for i < len(source) && k < j {
switch c := source[i]; {
case c == '\\' && i+1 < len(source) && isEscapable(source[i+1]) && k < len(text) && text[k] == source[i+1]:
i, k = i+2, k+1
case c == '&':
if n, lit := scanEntity(source, i); n > 0 && strings.HasPrefix(text[k:], lit) {
i, k = i+n, k+len(lit)
continue
}
i, k = i+1, k+1
default:
i, k = i+1, k+1
}
}
return i
}
+59
View File
@@ -0,0 +1,59 @@
package parser
import (
"encoding/json"
"os"
"strings"
"testing"
)
type specExample struct {
Markdown string `json:"markdown"`
HTML string `json:"html"`
Example int `json:"example"`
Section string `json:"section"`
}
func loadSpec(t testing.TB, name string) []specExample {
data, err := os.ReadFile("testdata/" + name)
if err != nil {
t.Fatal(err)
}
var ex []specExample
if err := json.Unmarshal(data, &ex); err != nil {
t.Fatal(err)
}
return ex
}
func render(src string, ext Extensions) string {
d := New(ext)
d.Set(src)
return d.HTML()
}
// TestCommonMark runs the examples of the CommonMark spec, 0.31.2.
func TestCommonMark(t *testing.T) {
failed := 0
for _, ex := range loadSpec(t, "commonmark.json") {
if got := render(ex.Markdown, 0); got != ex.HTML {
failed++
t.Errorf("example %d (%s):\n%q\ngot %q\nwant %q", ex.Example, ex.Section, ex.Markdown, got, ex.HTML)
}
}
if failed > 0 {
t.Logf("%d failed", failed)
}
}
// TestGFM runs the examples of GitHub's extensions in the GFM spec.
func TestGFM(t *testing.T) {
for _, ex := range loadSpec(t, "gfm.json") {
if !strings.Contains(ex.Section, "(extension)") || ex.Section == "Disallowed Raw HTML (extension)" {
continue
}
if got := render(ex.Markdown, GFM); got != ex.HTML {
t.Errorf("example %d (%s):\n%q\ngot %q\nwant %q", ex.Example, ex.Section, ex.Markdown, got, ex.HTML)
}
}
}
+173
View File
@@ -0,0 +1,173 @@
package parser
import (
"math/rand/v2"
"os"
"strings"
"testing"
"unicode/utf8"
)
// corpus returns the documents streamed in tests: an answer of a
// language model, and extras.md, which exercises what the spec examples
// do not (footnotes, math, definitions after their links, task lists,
// tables streaming).
func corpus(t testing.TB) []string {
var docs []string
for _, name := range []string{"testdata/llm.md", "testdata/extras.md"} {
b, err := os.ReadFile(name)
if err != nil {
t.Fatal(err)
}
docs = append(docs, string(b))
}
return docs
}
// TestAppendMatchesWhole appends documents a character at a time and
// checks each prefix parses as when parsed whole.
func TestAppendMatchesWhole(t *testing.T) {
examples := loadSpec(t, "commonmark.json")
for _, ex := range loadSpec(t, "gfm.json") {
if strings.Contains(ex.Section, "(extension)") {
examples = append(examples, ex)
}
}
for _, ex := range examples {
for _, ext := range []Extensions{0, Default} {
d := New(ext)
src := ex.Markdown
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
if want := render(src[:i], ext); d.HTML() != want {
t.Fatalf("example %d, ext %b, after %q:\ngot %q\nwant %q", ex.Example, ext, src[:i], d.HTML(), want)
}
}
}
}
}
func TestAppendCorpus(t *testing.T) {
for _, src := range corpus(t) {
d := New(Default)
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
if i%997 == 0 || i == len(src) {
if want := render(src[:i], Default); d.HTML() != want {
t.Fatalf("after %d bytes (%q):\ngot %q\nwant %q", i, src[max(0, i-40):i], d.HTML(), want)
}
}
}
}
}
// TestAppendChunks appends in random chunks, a stream's tokens.
func TestAppendChunks(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
for _, src := range corpus(t) {
for range 20 {
d := New(Default)
for i := 0; i < len(src); {
n := min(1+r.IntN(12), len(src)-i)
d.Append(src[i : i+n])
i += n
}
if want := render(src, Default); d.HTML() != want {
t.Fatalf("got %q\nwant %q", d.HTML(), want)
}
}
}
}
// TestStreamingEnds checks that a document streamed with healing parses
// exactly once streaming is turned off.
func TestStreamingEnds(t *testing.T) {
for _, src := range corpus(t) {
d := New(Default)
d.SetStreaming(true)
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
d.Append(src[i : i+n])
i += n
d.HTML() // inlines of the tail, healed
}
d.SetStreaming(false)
if want := render(src, Default); d.HTML() != want {
t.Fatalf("got %q\nwant %q", d.HTML(), want)
}
}
}
// TestEditsMatchWhole edits documents at random places and checks they
// parse as when parsed whole.
func TestEditsMatchWhole(t *testing.T) {
r := rand.New(rand.NewPCG(3, 4))
pieces := []string{"", "\n", "\n\n", "- ", "> ", "# ", "```", "**", "*", "_", "[a]", "[a]: /u\n", "|", "| a | b |\n|---|---|\n", " ", "1. ", "---\n", "text", "`", "<div>", "$$", "[^1]"}
for _, src := range corpus(t) {
d := New(Default)
d.Set(src)
for range 400 {
cur := d.Source()
from := r.IntN(len(cur) + 1)
to := min(len(cur), from+r.IntN(30))
if r.IntN(3) == 0 {
to = from
}
text := pieces[r.IntN(len(pieces))]
next := cur[:from] + text + cur[to:]
if !utf8.ValidString(next) {
continue
}
d.Edit(from, to, text)
if d.Source() != next {
t.Fatalf("source %q, want %q", d.Source(), next)
}
if want := render(next, Default); d.HTML() != want {
t.Fatalf("edit [%d, %d) to %q:\ngot %q\nwant %q", from, to, text, d.HTML(), want)
}
}
}
}
// TestEditJoinsTableParagraph edits the first line of a paragraph whose
// last line is a table's header into an item of the list above it, which
// the paragraph then joins.
func TestEditJoinsTableParagraph(t *testing.T) {
for _, c := range []struct{ src, text string }{
{"- one\n\ntwo\n| a | b |\n|---|---|\n| 1 | 2 |\n", "- "},
{"1. one\n\ntwo\n| a |\n|---|\n", "2. "},
} {
at := strings.Index(c.src, "\n\n") + 2
d := New(Default)
d.Set(c.src)
d.Edit(at, at, c.text)
if want := render(d.Source(), Default); d.HTML() != want {
t.Errorf("%q:\ngot %q\nwant %q", d.Source(), d.HTML(), want)
}
}
}
// TestDefinitionLater checks that a definition appended after its link
// makes the link a link, and that removing it unmakes it.
func TestDefinitionLater(t *testing.T) {
d := New(Default)
d.Append("See [docs].\n\nMore text.\n\n")
if got := d.HTML(); strings.Contains(got, "<a ") {
t.Fatalf("link before its definition: %q", got)
}
d.Append("[docs]: https://example.com\n")
if got := d.HTML(); !strings.Contains(got, `<a href="https://example.com">docs</a>`) {
t.Fatalf("no link after the definition: %q", got)
}
if d.Block(1).Revision() == 0 {
t.Error("the paragraph's revision did not change")
}
d.Set("See [docs].\n\nMore text.\n\n")
if got := d.HTML(); strings.Contains(got, "<a ") {
t.Fatalf("link after its definition went: %q", got)
}
}
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
# Notes on streaming
Text with a footnote[^1] and another[^note], math $$e^{i\pi}+1=0$$ and \(a^2\),
and a [link defined later][later] with *emphasis*, **strong**, ~~struck~~ and `code`.
$$
\int_0^1 x^2\,dx = \frac{1}{3}
$$
\[
a + b
\]
- [ ] a task
- [x] a done task
continued lazily
| a | b |
|---|:-:|
| 1 | 2 |
| 3 | 4 |
> A quote
with a lazy line
> - and a list
> inside
1. one
2. two
still two
3) three
10. ten
```go
func main() {
fmt.Println("hi")
}
```
indented code
<div>
raw <b>HTML</b>
</div>
Setext heading
--------------
Visit www.example.com, https://example.com/a_(b) or mail someone@example.com.
[later]: https://example.com/later "Later"
[^1]: The footnote.
[^note]: A footnote
of two lines.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+265
View File
@@ -0,0 +1,265 @@
package markdown
import (
"strings"
"time"
"unicode/utf8"
"github.com/egoist/mygo/internal/text"
"github.com/egoist/mygo/ui"
)
// Reveal is how Stream shows text as it comes: rather than in the bursts
// a network delivers, at an even pace that catches up with what came
// within CatchUp, a unit at a time, each fading in, as the chat apps show
// replies.
type Reveal struct {
// Unit is what shows at a time: a word by default.
Unit RevealUnit
// CatchUp is how long text that came waits at most before it shows:
// 250 ms when zero. Text comes in faster the more there is waiting.
CatchUp time.Duration
// Fade is how long text takes to fade in: 300 ms when zero, none when
// negative, nor when the desktop asks for less motion.
Fade time.Duration
}
// RevealUnit is what Reveal shows at a time.
type RevealUnit uint8
const (
// ByWord shows a word and the spaces after it at a time. In Chinese
// and Japanese, written without spaces, each ideograph and kana is a
// word.
ByWord RevealUnit = iota
// ByCharacter shows a character at a time.
ByCharacter
// BySentence shows a sentence at a time, once it is complete: up to
// a period, a question or exclamation mark followed by a space, an
// ideographic full stop, or the end of a line.
BySentence
// ByLine shows a line at a time, once it is complete.
ByLine
// ByParagraph shows a paragraph, a block between blank lines, at a
// time, once it is complete.
ByParagraph
// AtOnce shows text as it comes, without pacing.
AtOnce
)
// DefaultReveal is the Reveal of Stream without Options.Reveal.
var DefaultReveal = Reveal{}
// revealState is how much of the source a view shows, and since when
// what it shows came in.
type revealState struct {
// revealing tells a stream being revealed, or done with text left to
// reveal.
revealing bool
src string
shown int
carry float64
last time.Time
marks []revealMark
fade time.Duration
}
// revealMark notes that the source from at on showed at time t.
type revealMark struct {
at int
t time.Time
}
// step returns how much of src shows this frame, and whether more is to
// come in.
func (rs *revealState) step(c *ui.Context, src string, streaming bool, r *Reveal) (int, bool) {
if r == nil {
r = &DefaultReveal
}
now := c.Now()
// Text a stream left to reveal still comes in once it is done; other
// text a finished view is given shows at once, as does an edit.
edited := rs.shown > len(src) || !strings.HasPrefix(src, rs.src[:rs.shown])
pending := rs.revealing && rs.shown < len(rs.src) && !edited
rs.src = src
if !streaming && !pending || r.Unit == AtOnce || edited {
rs.shown, rs.last, rs.revealing = len(src), now, streaming
return rs.shown, false
}
rs.revealing = true
target := len(src)
if streaming && r.Unit != ByWord && r.Unit != ByCharacter {
// Only complete sentences, lines or paragraphs, while more is
// coming.
target = rs.shown
for i := rs.shown; ; {
e := unitEnd(src, i, len(src), r.Unit)
if e < 0 {
break
}
target, i = e, e
}
}
if rs.shown >= target {
// Nothing to show until more text comes, which builds a frame.
rs.last = now
return rs.shown, false
}
dt := now.Sub(rs.last)
if rs.last.IsZero() || dt > 100*time.Millisecond {
dt = 16 * time.Millisecond
}
rs.last = now
catchUp := r.CatchUp
if catchUp <= 0 {
catchUp = 250 * time.Millisecond
}
backlog := target - rs.shown
// As many bytes a second as show the backlog within catchUp, and at
// least a few hundred, so that a trickle does not crawl.
rate := max(float64(backlog)/catchUp.Seconds(), 240)
rs.carry += rate * dt.Seconds()
n := int(rs.carry)
if n == 0 {
return rs.shown, true
}
rs.carry -= float64(n)
next := min(rs.shown+n, target)
next = snap(src, next, target, r.Unit)
if next > rs.shown {
rs.marks = append(rs.marks, revealMark{rs.shown, now})
rs.shown = next
}
return rs.shown, rs.shown < len(src)
}
// snap moves offset i of src forward to the end of the unit it is in.
func snap(src string, i, target int, u RevealUnit) int {
switch u {
case ByWord:
// Up to a space, or to an ideograph or a kana, each a word: past
// the one i is at or inside, else up to the next.
at := i
for i > 0 && i < len(src) && !utf8.RuneStart(src[i]) {
i--
}
for i < target && src[i] != ' ' && src[i] != '\n' {
r, n := utf8.DecodeRuneInString(src[i:])
if text.StandsAlone(r) {
if i <= at {
i += n
}
break
}
i += n
}
i = min(i, target)
for i < target && (src[i] == ' ' || src[i] == '\n') {
i++
}
case BySentence, ByLine, ByParagraph:
if e := unitEnd(src, i, target, u); e >= 0 {
i = e
} else {
i = target
}
}
for i < target && !utf8.RuneStart(src[i]) {
i++
}
return i
}
// unitEnd returns where the first sentence, line or paragraph of src
// ending after i and by limit ends, or -1.
func unitEnd(src string, i, limit int, u RevealUnit) int {
switch u {
case ByLine:
if k := strings.IndexByte(src[i:limit], '\n'); k >= 0 {
return i + k + 1
}
case ByParagraph:
if k := strings.Index(src[i:limit], "\n\n"); k >= 0 {
return i + k + 2
}
case BySentence:
for j := i; j < limit; {
r, n := utf8.DecodeRuneInString(src[j:limit])
j += n
switch r {
case '\n':
return j
case '.', '!', '?', '…':
// Closing quotes and brackets go with it, then a space.
for j < limit && strings.IndexByte(`"')]*_`, src[j]) >= 0 {
j++
}
if j < limit && (src[j] == ' ' || src[j] == '\n') {
return j + 1
}
case '。', '!', '?':
return j
}
}
}
return -1
}
// fader returns the opacity of text at a source offset as it fades in,
// or nil when nothing fades.
func (rs *revealState) fader(c *ui.Context, r *Reveal) func(src int) float32 {
return rs.fadeAt(c.Now(), c.Preferences().ReduceMotion, r)
}
func (rs *revealState) fadeAt(now time.Time, reduceMotion bool, r *Reveal) func(src int) float32 {
if r == nil {
r = &DefaultReveal
}
fade := r.Fade
if fade == 0 {
fade = 300 * time.Millisecond
}
// Marks done fading are gone.
k := 0
for k < len(rs.marks) && (fade < 0 || now.Sub(rs.marks[k].t) >= fade) {
k++
}
rs.marks = append(rs.marks[:0], rs.marks[k:]...)
if len(rs.marks) == 0 || fade < 0 || reduceMotion {
rs.marks = rs.marks[:0]
return nil
}
rs.fade = fade
marks := rs.marks
return func(src int) float32 {
if src < marks[0].at {
return 1
}
// The last mark at or before src.
lo, hi := 0, len(marks)
for lo < hi {
m := (lo + hi) / 2
if marks[m].at <= src {
lo = m + 1
} else {
hi = m
}
}
age := now.Sub(marks[lo-1].t)
a := float32(age) / float32(fade)
// Quantized, so that the spans of text alike stay one.
return min(1, float32(int(easeOut(a)*16))/16)
}
}
func easeOut(t float32) float32 {
t = min(max(t, 0), 1)
u := 1 - t
return 1 - u*u*u
}
// fading reports whether text still fades in.
func (rs *revealState) fading() bool { return len(rs.marks) > 0 }
// revealed reports whether all of the source shows, done fading in.
func (rs *revealState) revealed() bool { return rs.shown >= len(rs.src) && !rs.fading() }
+231
View File
@@ -0,0 +1,231 @@
package markdown
import (
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
// revealChat is a chat's reply as the issue shows it (#1380): streamed,
// then shown with View once done, its time stamp built below it once it
// is done and Revealed.
type revealChat struct {
text string
done bool
o *Options
revealed bool // what Revealed said in the last frame
st *viewState // the view's state, to check it against
}
func (m *revealChat) view(c *ui.Context) {
ui.Column(c).Children(func() {
var md ui.Element
if m.done {
md = View(c, m.text, m.o)
} else {
md = Stream(c, m.text, m.o)
}
m.revealed = Revealed(md)
m.st = *ui.Local(md, stateKey{}, newState)
if m.done && m.revealed {
ui.Text(c, "12:04")
}
})
}
// shows returns the text of the reply the view shows, without the time.
func shows(tt *ui.Tester) string {
return strings.TrimSuffix(strings.Join(tt.Texts(), ""), "12:04")
}
// TestRevealedChat streams a reply in bursts, as a model's come, and
// checks that its time shows only once all of the reply shows and has
// faded in, after the stream is done, on frames the view asks for.
func TestRevealedChat(t *testing.T) {
const fade = 300 * time.Millisecond
src := strings.Repeat("Some words of a reply, and **more** of them. ", 12) + "\n\n- an item\n- another"
m := &revealChat{o: &Options{}}
tt := ui.NewTester(m.view, 600, 800)
for i := 0; i < len(src); {
i = min(i+40, len(src))
m.text = src[:i]
tt.Frame()
if tt.HasText("12:04") {
t.Fatal("the time shows while the reply streams")
}
tt.Advance(16 * time.Millisecond)
}
// The last bytes came: the stream is done, with most of it still to
// show.
m.done = true
tt.Frame()
if m.revealed || tt.HasText("12:04") {
t.Fatalf("revealed as the stream completes, showing %d of %d bytes", len(shows(tt)), len(src))
}
whole := ui.NewTester(func(c *ui.Context) { View(c, src, nil) }, 600, 800)
want := strings.Join(whole.Texts(), "")
var allAt time.Time
for range 300 {
// Only the clock moves: the view asks for the frames.
tt.Advance(10 * time.Millisecond)
all := shows(tt) == want
if all && allAt.IsZero() {
allAt = tt.Now()
}
if m.revealed != (all && !m.st.reveal.fading()) {
t.Fatalf("Revealed is %v, with all shown %v and fading %v", m.revealed, all, m.st.reveal.fading())
}
if m.revealed {
break
}
}
if !tt.HasText("12:04") {
t.Fatalf("the time never showed: %d of %d bytes show", len(shows(tt)), len(want))
}
// The last unit faded in before the time showed.
if d := tt.Now().Sub(allAt); d < fade-20*time.Millisecond || d > fade+50*time.Millisecond {
t.Errorf("the time showed %v after the whole reply did, want about the fade's %v", d, fade)
}
if tt.FramePending() {
t.Error("the view still asks for frames once revealed")
}
}
// TestRevealedGrows checks that a Stream revealed turns unrevealed as
// more text comes, and revealed again once that shows.
func TestRevealedGrows(t *testing.T) {
m := &revealChat{o: &Options{}, text: "First words. "}
tt := ui.NewTester(m.view, 600, 400)
settle := func(what string) {
t.Helper()
for range 100 {
if m.revealed {
return
}
tt.Advance(16 * time.Millisecond)
}
t.Fatalf("%s: never revealed", what)
}
settle("the first words")
m.text += strings.Repeat("and more words ", 20)
tt.Frame()
if m.revealed {
t.Fatal("still revealed as more text came")
}
settle("more text")
if got, want := shows(tt), strings.TrimSpace(m.text); got != want {
t.Errorf("revealed, showing %q, want %q", got, want)
}
m.done = true
tt.Frame()
if !m.revealed || !tt.HasText("12:04") {
t.Error("done with all shown, not revealed")
}
}
// TestRevealedAtOnce checks text that shows at once: revealed in the
// frame it comes, as is no text.
func TestRevealedAtOnce(t *testing.T) {
for _, c := range []struct {
name string
text string
stream bool
o *Options
}{
{"empty view", "", false, nil},
{"empty stream", "", true, nil},
{"view", sample, false, nil},
{"view, revealed by word", sample, false, &Options{Reveal: &Reveal{}}},
{"stream at once", sample, true, &Options{Reveal: &Reveal{Unit: AtOnce}}},
} {
m := &revealChat{text: c.text, done: !c.stream, o: c.o}
ui.NewTester(m.view, 600, 800)
if !m.revealed {
t.Errorf("%s: not revealed", c.name)
}
}
// Nor is an edit, which shows at once.
m := &revealChat{o: &Options{}, text: "Some words that come in."}
tt := ui.NewTester(m.view, 600, 400)
for range 100 {
tt.Advance(16 * time.Millisecond)
}
m.text = "Other words."
tt.Frame()
if !m.revealed {
t.Error("an edit: not revealed")
}
}
// TestRevealedWithoutFade checks that without a fade, by Reveal.Fade or
// the desktop's Reduce Motion, text is revealed once its last word shows.
func TestRevealedWithoutFade(t *testing.T) {
text := strings.Repeat("word ", 100)
for _, c := range []struct {
name string
o *Options
reduce bool
}{
{"negative fade", &Options{Reveal: &Reveal{Fade: -1}}, false},
{"reduce motion", &Options{}, true},
} {
m := &revealChat{o: c.o}
tt := ui.NewTester(m.view, 600, 800)
if c.reduce {
tt.SetPreferences(ui.Preferences{ReduceMotion: true, TextScale: 1})
}
m.text = text
tt.Frame()
for range 200 {
all := shows(tt) == strings.TrimSpace(text)
if m.revealed != all {
t.Fatalf("%s: Revealed is %v with all shown %v", c.name, m.revealed, all)
}
if all {
break
}
tt.Advance(16 * time.Millisecond)
}
if !m.revealed {
t.Errorf("%s: never revealed", c.name)
}
if tt.FramePending() {
t.Errorf("%s: the view still asks for frames once revealed", c.name)
}
}
}
// TestRevealedBySentence checks that a sentence Stream holds back keeps
// the view unrevealed, without frames, until View shows it.
func TestRevealedBySentence(t *testing.T) {
m := &revealChat{o: &Options{Reveal: &Reveal{Unit: BySentence, Fade: -1}}, text: "A whole sentence. And half of"}
tt := ui.NewTester(m.view, 600, 400)
tt.Advance(time.Second)
if m.revealed {
t.Error("revealed with a sentence held back")
}
if tt.FramePending() {
t.Error("the view asks for frames while a sentence waits for its end")
}
m.done = true
tt.Frame()
tt.Advance(time.Second)
if !m.revealed || !tt.HasText("12:04") {
t.Errorf("done: not revealed, showing %q", shows(tt))
}
}
// TestRevealedOtherElement checks Revealed of an element no view
// returned.
func TestRevealedOtherElement(t *testing.T) {
var box, zero bool
ui.NewTester(func(c *ui.Context) {
box = Revealed(ui.Box(c))
zero = Revealed(ui.Element{})
}, 100, 100)
if box || zero {
t.Errorf("Revealed of a box %v, of no element %v", box, zero)
}
}
+258
View File
@@ -0,0 +1,258 @@
package markdown
import (
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// rvView builds a View of *src and returns its tester and a getter of its
// state.
func rvView(src *string, o *Options) (*ui.Tester, func() *viewState) {
var st *viewState
tt := ui.NewTester(func(c *ui.Context) {
root := View(c, *src, o)
st = *ui.Local(root, stateKey{}, newState)
}, 700, 3000)
return tt, func() *viewState { return st }
}
// rvText returns the text of the element of block i noted for copying.
func rvParaText(st *viewState, i int) string {
var b strings.Builder
for _, pc := range st.paras[i].p.pieces {
for _, s := range pc.spans {
b.WriteString(s.Text)
}
}
return b.String()
}
// rvPart returns a selected part of the k-th noted element.
func rvPart(st *viewState, k int, text string, from, to int) ui.SelectedText {
return ui.SelectedText{ID: st.elems[k].id, Text: text, Start: from, End: to}
}
func rvElemOf(t *testing.T, st *viewState, block int) int {
for k, e := range st.elems {
if e.block == block {
return k
}
}
t.Fatalf("no element of block %d in %+v", block, st.elems)
return -1
}
// A selection ending right before emphasis copies a stray closer.
func TestReviewCopyMarkdownEndBeforeEmphasis(t *testing.T) {
src := "foo *bar* baz"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
if text != "foo bar baz" {
t.Fatalf("text %q", text)
}
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 0, 4)}) // "foo "
if got != "foo " {
t.Errorf("copied %q, want %q", got, "foo ")
}
}
// The same, through a real drag.
func TestReviewCopyMarkdownEndBeforeEmphasisDrag(t *testing.T) {
src := "foo *bar* baz"
for dx := float32(10); dx < 40; dx += 0.5 {
tt, _ := rvView(&src, nil)
r, _ := tt.Find("foo bar baz")
y := r.Y + r.H/2
tt.Press(r.X+0.5, y)
tt.Move(r.X+dx, y)
tt.Release(r.X+dx, y)
tt.Command("copy")
if tt.Clipboard() != "foo " {
continue
}
tt.Key(ui.Cmd|ui.Shift, ui.KeyC)
if got := tt.Clipboard(); got != "foo " {
t.Errorf("dragged over %q, copied as Markdown %q", "foo ", got)
}
return
}
t.Fatal("never selected \"foo \"")
}
func measure(t *testing.T, s string) (float32, float32) {
var w, h float32
ui.NewTester(func(c *ui.Context) {
w, h = c.MeasureText(0, ui.Span{Text: s, Size: 14})
}, 100, 100)
return w, h
}
// A selection inside text with an entity maps to the wrong source.
func TestReviewCopyMarkdownEntity(t *testing.T) {
src := "Tom &amp; Jerry *ran* home"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
if text != "Tom & Jerry ran home" {
t.Fatalf("text %q", text)
}
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 6, 11)}) // "Jerry"
if got != "Jerry" {
t.Errorf("copied %q, want %q", got, "Jerry")
}
}
// A paragraph selected to its end copies the next line too, when a block
// follows without a blank line.
func TestReviewCopyMarkdownParagraphEnd(t *testing.T) {
src := "para\n- item\n"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 0, len(text))})
if got != "para" {
t.Errorf("copied %q, want %q", got, "para")
}
}
// Lines 1-32 of a 40-line code block selected copy all 40.
func TestReviewCopyMarkdownCodeChunk(t *testing.T) {
var lines []string
for i := range 40 {
lines = append(lines, "line"+itoa(i))
}
src := "```\n" + strings.Join(lines, "\n") + "\n```\n"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
chunk := strings.Join(lines[:32], "\n")
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, chunk, 6, len([]rune(chunk)))}) // from line 1
want := strings.Join(lines[1:32], "\n")
if got != want {
t.Errorf("copied %d lines, want 31: %q", strings.Count(got, "\n")+1, got)
}
}
// A paragraph that turns into a link once its reference is defined,
// while the source only grows.
func TestReviewStaleParaAfterRefDefined(t *testing.T) {
src := "[foo]\n"
tt, _ := rvView(&src, nil)
if !tt.HasText("[foo]") {
t.Fatalf("shows %q", tt.Texts())
}
src = "[foo]\n\n[foo]: https://go.dev\n"
tt.Frame()
whole, _ := rvView(&src, nil)
if got, want := strings.Join(tt.Texts(), "|"), strings.Join(whole.Texts(), "|"); got != want {
t.Errorf("grown shows %q, whole shows %q", got, want)
}
}
// Stream by line asks for frames forever while waiting for a line end.
func TestReviewByLineFramesForever(t *testing.T) {
text := "Hello world, no newline yet"
o := &Options{Reveal: &Reveal{Unit: ByLine}}
frames := 0
tt := ui.NewTester(func(c *ui.Context) { frames++; Stream(c, text, o) }, 600, 400)
tt.Advance(400 * time.Millisecond)
frames = 0
tt.Frame()
if frames >= 20 || tt.FramePending() {
t.Errorf("one Frame ran %d frames, one pending %v: the view keeps asking for them with nothing to show", frames, tt.FramePending())
}
}
// Links without a scheme open outside a router: on Windows, ShellExecute
// runs programs ("calc", \\host\share\x.exe).
func TestReviewSchemelessLinkOpens(t *testing.T) {
src := "[a](calc) [b](\\\\\\\\evil\\\\share\\\\x.exe)"
tt, _ := rvView(&src, nil)
tt.Click("a")
tt.Click("b")
if got := tt.OpenedURLs(); len(got) > 0 {
t.Errorf("opened %q", got)
}
}
// A heading's color, zero, takes the window theme's text color rather
// than Theme.Text, as HeadingStyle.Color documents.
func TestReviewHeadingColorFollowsText(t *testing.T) {
def := DefaultTheme(ui.LightTheme())
th := resolve(&Theme{Text: ui.RGB(200, 0, 0)}, def)
if th.Headings[0].Color != th.Text {
t.Errorf("heading color %v, text %v", th.Headings[0].Color, th.Text)
}
}
// Part of a code span: its start maps past the span.
func TestReviewCopyMarkdownInsideCodeSpan(t *testing.T) {
src := "x `hello world` y"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 8, 13)}) // "world"
if got != "`world`" {
t.Errorf("copied %q from %q, want %q", got, text, "`world`")
}
}
// A backslash escape makes its text inexact.
func TestReviewCopyMarkdownEscape(t *testing.T) {
src := "1\\. first thing *here*"
_, get := rvView(&src, nil)
st := get()
k := rvElemOf(t, st, 1)
text := rvParaText(st, 1)
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, text, 3, 8)}) // "first"
if got != "first" {
t.Errorf("copied %q from %q, want %q", got, text, "first")
}
}
// One cell selected whole copies its row.
func TestReviewCopyMarkdownTableCell(t *testing.T) {
src := "| a | b |\n|---|---|\n| 1 | 2 |\n"
_, get := rvView(&src, nil)
st := get()
var cell int
for i := 1; i < st.doc.Len(); i++ {
if st.doc.Block(i).Kind == parser.TableCell && st.doc.Source()[st.doc.Block(i).Start:st.doc.Block(i).End] == "1" {
cell = i
}
}
k := rvElemOf(t, st, cell)
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, "1", 0, 1)})
if got != "1" {
t.Errorf("copied %q, want %q", got, "1")
}
}
// A code line with a tab partly taken by the list item's indentation.
func TestReviewCopyMarkdownCodeTab(t *testing.T) {
src := "- foo\n\n\t\tbar\n"
_, get := rvView(&src, nil)
st := get()
var code int
for i := 1; i < st.doc.Len(); i++ {
if st.doc.Block(i).Kind == parser.CodeBlock {
code = i
}
}
line, _ := st.doc.Line(code, 0)
k := rvElemOf(t, st, code)
n := len([]rune(line))
got := st.copyMarkdown([]ui.SelectedText{rvPart(st, k, line, n-3, n-1)}) // "ba"
if got != "ba" {
t.Errorf("line %q: copied %q, want %q", line, got, "ba")
}
}
+93
View File
@@ -0,0 +1,93 @@
package markdown
import (
"testing"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// sharedView builds the issue's document, whose quote a view sharing the
// selection shows through Options.Block, and returns its tester and the
// states of the views, the outer's and the inner's.
func sharedView(t *testing.T) (*ui.Tester, func() (outer, inner *viewState)) {
const src = "Intro\n\n> Read [the guide](https://example.test/guide)\n\nOutro"
var outerO, innerO Options
innerO.ShareSelection = true
var outer, inner *viewState
outerO.Block = func(c *ui.Context, d *parser.Document, i int) bool {
if d.Block(i).Kind != parser.Quote {
return false
}
el := View(c, "Read [the guide](https://example.test/guide)", &innerO)
inner = *ui.Local(el, stateKey{}, newState)
return true
}
tt := ui.NewTester(func(c *ui.Context) {
el := View(c, src, &outerO)
outer = *ui.Local(el, stateKey{}, newState)
}, 400, 300)
tt.Frame()
return tt, func() (*viewState, *viewState) { return outer, inner }
}
// A selection from a view sharing the selection into the view around it
// copies the inner view's part as its own Markdown.
func TestSharedViewCopyMarkdown(t *testing.T) {
tt, _ := sharedView(t)
from, ok := tt.Find("Read the guide")
if !ok {
t.Fatal("no inner text")
}
to, ok := tt.Find("Outro")
if !ok {
t.Fatal("no outer text")
}
tt.Press(from.X+1, from.Y+from.H/2)
tt.Move(to.X+to.W-1, to.Y+to.H/2)
tt.Release(to.X+to.W-1, to.Y+to.H/2)
tt.Key(ui.Cmd|ui.Shift, ui.KeyC)
if got, want := tt.Clipboard(), "Read [the guide](https://example.test/guide)\n\nOutro"; got != want {
t.Errorf("copied as Markdown %q, want %q", got, want)
}
tt.Command("copy")
if got, want := tt.Clipboard(), "Read the guide\n\nOutro"; got != want {
t.Errorf("copied %q, want %q", got, want)
}
}
// A selection containing the inner view whole, and one from the outer
// view's text into the middle of the inner's, whose link it completes.
func TestSharedViewCopyMarkdownParts(t *testing.T) {
_, get := sharedView(t)
outer, inner := get()
if outer == nil || inner == nil || len(outer.nested) != 1 || outer.nested[0].st != inner {
t.Fatalf("inner view not noted in the outer one")
}
part := func(st *viewState, block int, text string, from, to int) ui.SelectedText {
return rvPart(st, rvElemOf(t, st, block), text, from, to)
}
intro := part(outer, 1, "Intro", 0, 5)
outro := part(outer, outer.doc.Block(outer.nested[0].block).Next, "Outro", 0, 5)
const read = "Read the guide"
for _, c := range []struct {
name string
parts []ui.SelectedText
want string
}{
{"whole", []ui.SelectedText{intro, part(inner, 1, read, 0, len(read)), outro},
"Intro\n\nRead [the guide](https://example.test/guide)\n\nOutro"},
{"into the inner view", []ui.SelectedText{intro, part(inner, 1, read, 0, 11)},
"Intro\n\nRead [the gu](https://example.test/guide)"},
{"from the inner view", []ui.SelectedText{part(inner, 1, read, 9, len(read)), outro},
"[guide](https://example.test/guide)\n\nOutro"},
{"within the inner view", []ui.SelectedText{part(inner, 1, read, 5, 8)},
"[the](https://example.test/guide)"},
{"the outer view's alone", []ui.SelectedText{intro, outro},
"Intro\n\n> Read [the guide](https://example.test/guide)\n\nOutro"},
} {
if got := outer.copyMarkdown(c.parts); got != c.want {
t.Errorf("%s: copied %q, want %q", c.name, got, c.want)
}
}
}
+612
View File
@@ -0,0 +1,612 @@
package markdown
import (
"strings"
"unicode/utf8"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// A paragraph is the spans of its text, cut into pieces at its links,
// which are elements of their own inside it (ui.Link), with where each
// span's text is in the source, for copying.
// piece is a run of spans: a link's, when link >= 0 (an index into the
// block's inlines), else plain text.
type piece struct {
link int
spans []ui.Span
// dest is where a mention, a reference (Options.Resolve) or code
// (Options.CodeLink) goes.
dest string
}
// runMark notes that the text of a paragraph from rune comes from the
// source's bytes [src, end): exact when it is those bytes, else written
// otherwise there, as an entity or an escape.
type runMark struct {
rune, src, end int
exact bool
}
// mathObject is math within a paragraph that Options.InlineMath made an
// object of: its rune, the source of the math, delimiters included, and
// how it draws. A link's icon (Options.LinkIcon) is one with no source.
type mathObject struct {
rune, src, end int
draw func(p *ui.Painter, r ui.Rect)
}
// para is what a paragraph, heading or cell shows.
type para struct {
pieces []piece
marks []runMark
// objects are its math drawn by the app, in order: a slice of each
// build's own, which the view's drawing keeps.
objects []mathObject
runes int
fading bool // its spans fade in: build them anew next frame
// refs are the inlines of its mentions, references and code, and
// resolved where each went, "" for those left text, as Options.Resolve
// and CodeLink, which resolvers says were set, answered: it builds anew
// when they answer otherwise.
refs []int
resolved []string
resolvers uint8
// width is the width of its text on one line, once measured.
width float32
measured bool
}
// spanStyle is the style inlines set as the builder descends.
type spanStyle struct {
weight int
italic, strike bool
underline bool
code bool
sub bool
mark bool
color Color
size float32
font string
inLink, pendingLink bool
}
type spanBuilder struct {
d *parser.Document
th *Theme
block int
in []parser.Inline
p *para
cur *piece
fade func(src int) float32 // the opacity of text at a source offset, while revealing
style spanStyle
// html is the stack of inline HTML tags open, as <b>.
html []string
// notes numbers footnotes by their definitions' order.
notes func(label string) int
// linkIndex is the inline of the link being built.
linkIndex int
// math makes math within text objects (Options.InlineMath).
math func(tex string, size float32) (InlineObject, bool)
// linkIcon makes the objects at the start of links (Options.LinkIcon).
linkIcon func(dest string, size float32) (InlineObject, bool)
// resolve makes mentions, references and code links (Options.Resolve
// and CodeLink), and resolvers says which of those are set.
resolve func(in parser.Inline) (string, bool)
resolvers uint8
}
// build makes the paragraph of block i, of base style s.
func (sb *spanBuilder) build(p *para, base spanStyle) {
*p = para{pieces: p.pieces[:0], marks: p.marks[:0], refs: p.refs[:0], resolved: p.resolved[:0], resolvers: sb.resolvers}
sb.p = p
sb.in = sb.d.Inlines(sb.block)
sb.html = sb.html[:0]
sb.style = base
sb.cur = nil
sb.inlines(0, len(sb.in), base)
// A paragraph's pieces keep their own slices: they outlive the build.
for i := range p.pieces {
p.pieces[i].spans = append([]ui.Span(nil), p.pieces[i].spans...)
}
}
func (sb *spanBuilder) piece(link int) *piece {
if sb.cur == nil || sb.cur.link != link {
sb.p.pieces = append(sb.p.pieces, piece{link: link})
sb.cur = &sb.p.pieces[len(sb.p.pieces)-1]
}
return sb.cur
}
// add adds text, which comes from the source's [src, end) (exact when it
// is those bytes), in style s.
func (sb *spanBuilder) add(text string, src, end int, exact bool, s spanStyle, link int) {
if text == "" {
return
}
if sb.fade != nil && exact {
// Text revealed at different times fades in on its own: cut it
// where its opacity changes.
for len(text) > 0 {
a := sb.fade(src)
n := len(text)
for k := 1; k < len(text); k++ {
if sb.fade(src+k) != a {
n = k
break
}
}
for n < len(text) && !utf8.RuneStart(text[n]) {
n++
}
sb.addSpan(text[:n], src, src+n, exact, s, link, a)
text, src = text[n:], src+n
}
return
}
a := float32(1)
if sb.fade != nil {
a = sb.fade(src)
}
sb.addSpan(text, src, end, exact, s, link, a)
}
// addAligned adds text that comes from the source's [src, end) written
// with escapes or entities: as many runs as are its bytes, and the rest,
// each escape or entity, of its own, so that copying maps its runes to
// the source's.
func (sb *spanBuilder) addAligned(text string, src, end int, s spanStyle, link int) {
source := sb.d.Source()[src:end]
i, j := 0, 0 // in source and in text
run := 0 // where the run of the same bytes started, in text
flush := func() {
if j > run {
sb.add(text[run:j], src+i-(j-run), src+i, true, s, link)
}
}
for i < len(source) && j < len(text) {
switch {
case source[i] == '\\' && i+1 < len(source) && isEscapable(source[i+1]) && source[i+1] == text[j]:
flush()
sb.add(text[j:j+1], src+i, src+i+2, false, s, link)
i, j = i+2, j+1
case source[i] == '&' && entityAt(source, i, text[j:]) > 0:
n, lit := parser.Entity(source[i:])
flush()
sb.add(lit, src+i, src+i+n, false, s, link)
i, j = i+n, j+len(lit)
case source[i] == text[j]:
i++
j++
continue
default:
goto rest
}
run = j
}
flush()
run = j
rest:
if j < len(text) {
if j > run {
flush()
}
sb.add(text[j:], src+i, end, false, s, link)
}
}
// entityAt returns the length of the entity at i of source that text
// starts with, decoded, or 0.
func entityAt(source string, i int, text string) int {
n, lit := parser.Entity(source[i:])
if n == 0 || !strings.HasPrefix(text, lit) {
return 0
}
return n
}
func (sb *spanBuilder) addSpan(text string, src, end int, exact bool, s spanStyle, link int, alpha float32) {
th := sb.th
sp := ui.Span{Text: text, Font: th.Font, Size: th.FontSize, Weight: s.weight, Italic: s.italic, Strikethrough: s.strike, Underline: s.underline}
if s.size != 0 {
sp.Size = s.size
}
if s.font != "" {
sp.Font = s.font
}
if s.code {
sp.Font = th.CodeFont
sp.Size = th.em(th.CodeSize)
if s.size != 0 {
sp.Size = s.size * th.CodeSize
}
sp.Background = th.CodeBackground
sp.Radius = max(3, sp.Size/4)
if !s.inLink {
sp.Color = th.Code
}
}
if s.inLink && th.LinkWeight > s.weight {
sp.Weight = th.LinkWeight
}
if s.sub {
sp.Size *= 0.75
}
if s.mark {
sp.Background = th.Mark
}
if s.color.A > 0 {
sp.Color = s.color
}
if alpha < 1 {
// Not quite transparent: a color of alpha 0 is none, the text's.
alpha = max(alpha, 0.02)
if sp.Color.A == 0 {
sp.Color = th.Text
if s.inLink {
sp.Color = th.Link
}
}
sp.Color = sp.Color.Alpha(alpha)
sp.Background = sp.Background.Alpha(alpha)
}
if sb.fade != nil {
sb.p.fading = sb.p.fading || alpha < 1
}
pc := sb.piece(link)
pc.spans = append(pc.spans, sp)
sb.p.marks = append(sb.p.marks, runMark{rune: sb.p.runes, src: src, end: end, exact: exact})
sb.p.runes += utf8.RuneCountInString(text)
}
// addText adds the text of inline n, exact when it is its source's
// bytes, else aligned with them, as an escape or an entity is.
func (sb *spanBuilder) addText(n *parser.Inline, exact bool, s spanStyle, link int) {
if exact {
sb.add(n.Text, n.Start, n.End, true, s, link)
} else {
sb.addAligned(n.Text, n.Start, n.End, s, link)
}
}
func (sb *spanBuilder) inlines(from, to int, s spanStyle) {
in := sb.in
link := -1
if s.inLink {
link = sb.linkIndex
}
for k := from; k < to; k = in[k].Next {
n := &in[k]
switch n.Kind {
case parser.Text:
exact := n.End-n.Start == len(n.Text) && sb.d.Source()[n.Start:n.End] == n.Text
sb.addText(n, exact, sb.htmlStyle(s), link)
case parser.SoftBreak:
sb.add(" ", n.Start, n.End, false, s, link)
case parser.LineBreak:
sb.add("\n", n.Start, n.End, false, s, link)
case parser.Mention, parser.Reference:
exact := n.End-n.Start == len(n.Text) && sb.d.Source()[n.Start:n.End] == n.Text
dest, ok := "", false
if sb.resolve != nil {
dest, ok = sb.resolve(*n)
if !ok {
dest = ""
}
}
sb.p.refs = append(sb.p.refs, k)
sb.p.resolved = append(sb.p.resolved, dest)
if dest == "" || s.inLink {
sb.addText(n, exact, sb.htmlStyle(s), link)
continue
}
cs := sb.htmlStyle(s)
cs.inLink, cs.color = true, Color{}
if n.Kind == parser.Mention {
// As GitHub shows them.
cs.weight = sb.th.StrongWeight
}
sb.addText(n, exact, cs, k)
sb.cur.dest = dest
case parser.Code:
cs := sb.htmlStyle(s)
cs.code = true
// The code's text is its source's bytes but for the spaces
// stripped at its ends and line endings as spaces.
a, z := codeStart(sb.d.Source(), n), n.End-(codeStart(sb.d.Source(), n)-n.Start)
if z-a == len(n.Text)+2 && sb.d.Source()[a] == ' ' {
a++
}
dest := ""
if sb.resolve != nil && sb.resolvers&2 != 0 {
if d, ok := sb.resolve(*n); ok {
dest = d
}
sb.p.refs = append(sb.p.refs, k)
sb.p.resolved = append(sb.p.resolved, dest)
}
if dest == "" || s.inLink {
sb.add(n.Text, a, min(a+len(n.Text), z), z-a == len(n.Text), cs, link)
continue
}
// A link of its own that keeps the code's look.
cs.inLink = true
sb.add(n.Text, a, min(a+len(n.Text), z), z-a == len(n.Text), cs, k)
sb.cur.dest = dest
case parser.Emphasis:
cs := s
cs.italic = true
sb.inlines(k+1, n.Next, cs)
case parser.Strong:
cs := s
cs.weight = sb.th.StrongWeight
if cs.color.A == 0 && !cs.inLink && sb.th.Strong != sb.th.Text {
cs.color = sb.th.Strong
}
sb.inlines(k+1, n.Next, cs)
case parser.Strikethrough:
cs := s
cs.strike = true
sb.inlines(k+1, n.Next, cs)
case parser.Link:
if s.inLink {
sb.inlines(k+1, n.Next, s)
continue
}
cs := s
cs.inLink, cs.pendingLink = true, n.Pending
cs.color = Color{} // the link's
save := sb.linkIndex
sb.linkIndex = k
sb.addLinkIcon(n, cs, k)
sb.inlines(k+1, n.Next, cs)
sb.linkIndex = save
case parser.Image:
// Images within text show their description; a paragraph of
// images alone shows the images (see imagesOnly).
cs := s
cs.color = sb.th.Muted
alt := parser.PlainText(in[k+1 : n.Next])
if alt == "" {
alt = "image"
}
sb.add("["+alt+"]", n.Start, n.End, false, cs, link)
case parser.HTML:
if !sb.inlineHTML(n.Text) {
sb.add(n.Text, n.Start, n.End, true, s, link)
}
case parser.Math:
if sb.mathObject(n, sb.htmlStyle(s), link) {
continue
}
cs := s
cs.font = sb.th.CodeFont
cs.color = sb.th.Muted
if !cs.italic {
cs.size = sb.th.em(sb.th.CodeSize)
}
sb.add(n.Text, mathStart(sb.d.Source(), n), n.End, false, cs, link)
case parser.FootnoteRef:
cs := s
cs.sub = true
cs.color = sb.th.Link
num := 0
if sb.notes != nil {
num = sb.notes(n.Text)
}
label := n.Text
if num > 0 {
label = itoa(num)
}
sb.add("["+label+"]", n.Start, n.End, false, cs, -2-k)
}
}
}
// linkIconJoiner, a word joiner, keeps a link's icon on the line of its
// first word: lines break around an object. It copies as nothing, as the
// icon does.
const linkIconJoiner = '\u2060'
// addLinkIcon adds the object Options.LinkIcon makes for link n, the
// inline k of its block, in style s. It comes from no source, so that it
// copies as nothing.
func (sb *spanBuilder) addLinkIcon(n *parser.Inline, s spanStyle, k int) {
if sb.linkIcon == nil || n.Pending {
return
}
size := sb.th.FontSize
if s.size != 0 {
size = s.size
}
if s.sub {
size *= 0.75
}
o, ok := sb.linkIcon(n.Dest, size)
if !ok || !(o.Width > 0) {
return
}
p := sb.p
p.objects = append(p.objects, mathObject{rune: p.runes, src: n.Start, end: n.Start, draw: o.Draw})
sp := ui.Span{Text: "\uFFFC", Size: size, ObjectWidth: o.Width, ObjectHeight: max(o.Height, 0), ObjectDescent: max(o.Depth, 0)}
if sb.fade != nil {
p.fading = p.fading || sb.fade(n.Start) < 1
}
pc := sb.piece(k)
pc.spans = append(pc.spans, sp)
p.marks = append(p.marks, runMark{rune: p.runes, src: n.Start, end: n.Start})
p.runes++
sb.addSpan(string(linkIconJoiner), n.Start, n.Start, false, s, k, 1)
}
// mathObject adds math n, within text of style s, as the object
// Options.InlineMath makes of it, and reports whether it made one.
func (sb *spanBuilder) mathObject(n *parser.Inline, s spanStyle, link int) bool {
if sb.math == nil {
return false
}
size := sb.th.FontSize
if s.size != 0 {
size = s.size
}
if s.sub {
size *= 0.75
}
o, ok := sb.math(n.Text, size)
if !ok || !(o.Width > 0) {
return false
}
p := sb.p
p.objects = append(p.objects, mathObject{rune: p.runes, src: n.Start, end: n.End, draw: o.Draw})
sp := ui.Span{Text: "\uFFFC", Size: size, ObjectWidth: o.Width, ObjectHeight: max(o.Height, 0), ObjectDescent: max(o.Depth, 0)}
if sb.fade != nil {
sb.p.fading = sb.p.fading || sb.fade(n.Start) < 1
}
pc := sb.piece(link)
pc.spans = append(pc.spans, sp)
p.marks = append(p.marks, runMark{rune: p.runes, src: n.Start, end: n.End})
p.runes++
return true
}
// codeStart returns where a code span's text starts in the source.
func codeStart(src string, n *parser.Inline) int {
i := n.Start
for i < n.End && src[i] == '`' {
i++
}
return i
}
func mathStart(src string, n *parser.Inline) int {
i := n.Start
for i < n.End && (src[i] == '$' || src[i] == '\\' || src[i] == '(' || src[i] == '[') && i-n.Start < 2 {
i++
}
return i
}
func itoa(n int) string {
if n < 10 {
return string(rune('0' + n))
}
var b [20]byte
i := len(b)
for n > 0 {
i--
b[i] = byte('0' + n%10)
n /= 10
}
return string(b[i:])
}
// inlineHTML applies the inline HTML tags of formatting language models
// write, <b>, <i>, <code>, <br> and the like, and reports whether tag was
// one: others show as text.
func (sb *spanBuilder) inlineHTML(tag string) bool {
t := strings.ToLower(strings.Trim(tag, "<>/ \t\n"))
if i := strings.IndexAny(t, " \t\n"); i >= 0 {
t = t[:i]
}
closing := strings.HasPrefix(tag, "</")
switch t {
case "br":
sb.add("\n", 0, 0, false, sb.style, -1)
return true
case "b", "strong", "i", "em", "u", "ins", "s", "del", "strike", "code", "kbd", "samp", "mark", "sub", "sup", "small":
default:
return false
}
if closing {
for i := len(sb.html) - 1; i >= 0; i-- {
if sb.html[i] == t {
sb.html = append(sb.html[:i], sb.html[i+1:]...)
break
}
}
} else if !strings.HasSuffix(tag, "/>") {
sb.html = append(sb.html, t)
}
return true
}
// htmlStyle returns s with the inline HTML tags open applied.
func (sb *spanBuilder) htmlStyle(s spanStyle) spanStyle {
for _, t := range sb.html {
switch t {
case "b", "strong":
s.weight = sb.th.StrongWeight
case "i", "em":
s.italic = true
case "u", "ins":
s.underline = true
case "s", "del", "strike":
s.strike = true
case "code", "kbd", "samp":
s.code = true
case "mark":
s.mark = true
case "sub", "sup", "small":
s.sub = true
}
}
return s
}
// imagesOnly reports whether the inlines are images, and the spaces
// between them, alone: a paragraph showing them as images.
func imagesOnly(in []parser.Inline) bool {
n := 0
for k := 0; k < len(in); k = in[k].Next {
switch in[k].Kind {
case parser.Image:
n++
case parser.SoftBreak, parser.LineBreak:
case parser.Text:
if strings.TrimSpace(in[k].Text) != "" {
return false
}
default:
return false
}
}
return n > 0
}
// sourceAt returns the source offset of rune r of the paragraph's text:
// for the end of a selection (end), that of the text before it, so that
// what follows, as an emphasis's opening *, stays out.
func (p *para) sourceAt(src string, r int, end bool) int {
if len(p.marks) == 0 {
return 0
}
lo, hi := 0, len(p.marks)
for lo < hi {
m := (lo + hi) / 2
if p.marks[m].rune <= r {
lo = m + 1
} else {
hi = m
}
}
k := max(lo-1, 0)
m := p.marks[k]
if r <= m.rune {
if end && k > 0 {
return p.marks[k-1].end
}
return m.src
}
if !m.exact {
return m.end
}
off := m.src
for n := m.rune; n < r && off < m.end; n++ {
_, w := utf8.DecodeRuneInString(src[off:])
off += w
}
return off
}
+117
View File
@@ -0,0 +1,117 @@
package markdown
import (
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// tableState keeps a table's column widths, which only grow while the
// table is being written, so that its columns do not jump as its cells
// fill.
type tableState struct {
widths []float32
seen bool
}
// table builds a table: rows of cells as wide as their column's widest,
// up to Theme.TableMaxColumn, which wrap beyond, scrolling sideways when
// wider than the view.
func (st *viewState) table(c *ui.Context, i int, base spanStyle) ui.Element {
d := st.doc
th := &st.th
b := d.Block(i)
if st.tables == nil {
st.tables = map[int]*tableState{}
}
ts := st.tables[b.Start]
if ts == nil {
ts = &tableState{}
st.tables[b.Start] = ts
}
ts.seen = true
cols := len(b.Align)
padX, padY := th.em(th.TableCellPadding[0]), th.em(th.TableCellPadding[1])
maxW := th.em(th.TableMaxColumn)
// The widths of the columns, from their cells' text.
widths := make([]float32, cols)
if b.Open {
copy(widths, ts.widths)
}
for r := i + 1; r < d.Block(i).Next; r = d.Block(r).Next {
row := d.Block(r)
k := 0
for cell := r + 1; cell < d.Block(r).Next; cell = d.Block(cell).Next {
if k >= cols {
break
}
s := base
if row.Header {
s.weight = th.StrongWeight
}
p := st.para(cell, s)
if !p.measured {
p.width, p.measured = 0, true
for _, pc := range p.pieces {
pw, _ := c.MeasureText(0, pc.spans...)
p.width += pw
}
}
widths[k] = max(widths[k], min(p.width, maxW)+2*padX+1)
k++
}
}
ts.widths = append(ts.widths[:0], widths...)
scroll := ui.ScrollHorizontal(c).AlignSelf(ui.Stretch)
return scroll.Children(func() {
grid := ui.Column(c).Border(1, th.TableBorder).Radius(th.em(0.3)).Clip().Shrink(0).Role(ui.RoleTable)
grid.Children(func() {
n := 0
for r := i + 1; r < d.Block(i).Next; r = d.Block(r).Next {
row := d.Block(r)
rowEl := ui.Row(c).Role(ui.RoleRow).AlignItems(ui.Stretch)
if row.Header {
rowEl.Background(th.TableHeader)
} else if n%2 == 1 && th.TableStripe.A > 0 {
rowEl.Background(th.TableStripe)
}
if n > 0 {
rowEl.BorderWidth(1, 0, 0, 0).BorderColor(th.TableBorder)
}
if st.fade != nil && b.Open {
if a := st.fade(row.Start); a < 1 {
rowEl.Opacity(a)
}
}
header := row.Header
rowEl.Children(func() {
k := 0
for cell := r + 1; cell < d.Block(r).Next; cell = d.Block(cell).Next {
if k >= cols {
break
}
s := base
role := ui.RoleCell
if header {
s.weight = th.StrongWeight
role = ui.RoleColumnHeader
}
box := ui.Column(c).Width(widths[k]).Padding(padY, padX).Role(role)
if k > 0 {
box.BorderWidth(0, 0, 0, 1).BorderColor(th.TableBorder)
}
align := ui.Start
switch b.Align[k] {
case parser.AlignCenter:
align = ui.Center
case parser.AlignRight:
align = ui.End
}
box.Children(func() { st.paragraph(c, cell, s).TextAlign(align) })
k++
}
})
n++
}
})
})
}
+292
View File
@@ -0,0 +1,292 @@
package markdown
import (
"slices"
"strings"
"testing"
"github.com/egoist/mygo/ui"
)
// taskCall is a call of Options.OnTask.
type taskCall struct {
line int
checked bool
}
// checkBoxes returns what assistive technology sees of the check boxes of
// the last frame, in reading order.
func checkBoxes(tt *ui.Tester) []ui.AccessInfo {
var boxes []ui.AccessInfo
for _, a := range tt.AccessAll() {
if a.Role == ui.RoleCheckBox {
boxes = append(boxes, a)
}
}
return boxes
}
// clickBox clicks the center of a check box.
func clickBox(tt *ui.Tester, a ui.AccessInfo) {
tt.ClickAt(a.Bounds.X+a.Bounds.W/2, a.Bounds.Y+a.Bounds.H/2)
}
// lines joins ls with sep, ending the last one too: line k of the
// result, from 1, is ls[k-1].
func lines(sep string, ls ...string) string { return strings.Join(ls, sep) + sep }
// toggleTask checks or unchecks the task on line of src, from 1, as an
// app's OnTask writes the change into its Markdown.
func toggleTask(src string, line int, checked bool) string {
ls := strings.SplitAfter(src, "\n")
if checked {
ls[line-1] = strings.Replace(ls[line-1], "[ ]", "[x]", 1)
} else {
ls[line-1] = strings.Replace(ls[line-1], "[x]", "[ ]", 1)
}
return strings.Join(ls, "")
}
// TestTaskClickReportsLineAndState clicks every check box of a note whose
// tasks come after front matter and a code block holding what looks like
// a task, in nested lists, in an ordered list and in a quote: each reports
// its item's line in the source and the other state, whatever the line
// endings.
func TestTaskClickReportsLineAndState(t *testing.T) {
note := []string{
"---", // 1, front matter: a rule, then a heading
"title: Groceries", // 2
"tags: [home]", // 3
"---", // 4
"", // 5
"```md", // 6
"- [ ] in code, no task", // 7
"```", // 8
"", // 9
"- [ ] milk", // 10
"- [x] eggs", // 11
" - [ ] free range", // 12
" 1. [X] a dozen", // 13
"- bread", // 14, no task
"", // 15
"> - [ ] quoted", // 16
}
want := []taskCall{{10, true}, {11, false}, {12, true}, {13, false}, {16, true}}
names := []string{"milk", "eggs", "free range", "a dozen", "quoted"}
for _, sep := range []string{"\n", "\r\n", "\r"} {
var got []taskCall
o := Options{OnTask: func(line int, checked bool) { got = append(got, taskCall{line, checked}) }}
src := lines(sep, note...)
tt := ui.NewTester(func(c *ui.Context) { View(c, src, &o) }, 500, 700)
boxes := checkBoxes(tt)
if len(boxes) != len(want) {
t.Fatalf("%q: %d check boxes, want %d", sep, len(boxes), len(want))
}
for k, a := range boxes {
if a.Name != names[k] || a.Checked == want[k].checked || !a.Focusable || a.ReadOnly {
t.Errorf("%q: box %d is %+v, want %q, checked %v, focusable and not read-only", sep, k, a, names[k], !want[k].checked)
}
clickBox(tt, a)
}
if !slices.Equal(got, want) {
t.Errorf("%q: OnTask got %v, want %v", sep, got, want)
}
}
}
// TestTaskKeysToggle moves the focus to the check boxes with Tab and
// toggles them with Space and Enter, the app writing each change into the
// source, which the boxes then show.
func TestTaskKeysToggle(t *testing.T) {
src := lines("\n", "Intro.", "", "- [ ] one", " - [x] two")
var got []taskCall
o := Options{OnTask: func(line int, checked bool) {
got = append(got, taskCall{line, checked})
src = toggleTask(src, line, checked)
}}
tt := ui.NewTester(func(c *ui.Context) { View(c, src, &o) }, 400, 300)
focus := func(k int) {
t.Helper()
for range 5 {
if checkBoxes(tt)[k].Focused {
return
}
tt.Key(0, ui.KeyTab)
}
t.Fatalf("Tab never reached box %d: %+v", k, checkBoxes(tt))
}
focus(0)
tt.TypeKey(0, ui.KeySpace, " ")
if b := checkBoxes(tt); !b[0].Checked || !b[0].Focused {
t.Fatalf("after Space, the first box is %+v, want checked and focused", b[0])
}
tt.Key(0, ui.KeyEnter)
if b := checkBoxes(tt); b[0].Checked {
t.Fatalf("after Enter, the first box is %+v, want unchecked", b[0])
}
focus(1)
tt.Key(0, ui.KeyEnter)
want := []taskCall{{3, true}, {3, false}, {4, false}}
if !slices.Equal(got, want) {
t.Errorf("OnTask got %v, want %v", got, want)
}
if wantSrc := lines("\n", "Intro.", "", "- [ ] one", " - [ ] two"); src != wantSrc {
t.Errorf("source %q, want %q", src, wantSrc)
}
if b := checkBoxes(tt); b[0].Checked || b[1].Checked {
t.Errorf("the boxes show %+v, not the source", b)
}
}
// TestTaskNameFollowsItsText checks that a check box is named by its
// task's text as it is now: after an edit, after a definition appended
// below makes its text a link, and of formatted text, its text alone.
func TestTaskNameFollowsItsText(t *testing.T) {
src := "- [ ] milk\n- [ ] **oat** `milk`\n"
o := Options{OnTask: func(int, bool) {}}
tt := ui.NewTester(func(c *ui.Context) { View(c, src, &o) }, 400, 200)
for _, edit := range []struct{ src, second string }{
{src, "oat milk"},
{"- [ ] milk\n- [ ] [silk][s]\n", "[silk][s]"},
{"- [ ] milk\n- [ ] [silk][s]\n\n[s]: https://example.com\n", "silk"},
{"- [ ] milk\n- [ ] [wool][s]\n\n[s]: https://example.com\n", "wool"},
} {
src = edit.src
tt.Frame()
if b := checkBoxes(tt); len(b) != 2 || b[0].Name != "milk" || b[1].Name != edit.second {
t.Errorf("after %q, the boxes are named %+v, want %q and %q", edit.src, b, "milk", edit.second)
}
}
}
// TestTasksWithoutOnTaskAreReadOnly checks that check boxes without
// Options.OnTask show their state, read-only, and take neither the focus
// nor clicks.
func TestTasksWithoutOnTaskAreReadOnly(t *testing.T) {
src := "- [ ] milk\n- [x] eggs\n"
for _, o := range []*Options{nil, {OnLink: func(string) {}}} {
tt := ui.NewTester(func(c *ui.Context) { View(c, src, o) }, 400, 200)
boxes := checkBoxes(tt)
if len(boxes) != 2 || boxes[0].Checked || !boxes[1].Checked {
t.Fatalf("boxes %+v, want milk unchecked and eggs checked", boxes)
}
for _, a := range boxes {
if !a.ReadOnly || a.Focusable {
t.Errorf("box %+v: want read-only and not focusable", a)
}
clickBox(tt, a)
}
tt.Key(0, ui.KeyTab)
for _, a := range checkBoxes(tt) {
if a.Focused {
t.Errorf("Tab focused the read-only box %+v", a)
}
}
if b := checkBoxes(tt); b[0].Checked || !b[1].Checked {
t.Errorf("clicks changed the boxes: %+v", b)
}
}
}
// TestCodeBlockSourceLine checks the line each code block starts on:
// fences at the start, after a paragraph, of tildes, in a list item and
// in a quote, indented code, and a fence still open, with each line ending.
// The lines of their code follow it.
func TestCodeBlockSourceLine(t *testing.T) {
doc := []string{
"```a", // 1
"first", // 2
"```", // 3
"", // 4
"Text.", // 5
"```b", // 6
"second", // 7
"```", // 8
"~~~c", // 9
"third", // 10
"~~~", // 11
"", // 12
"- item", // 13
"", // 14
" ```d", // 15
" in a list", // 16
" ```", // 17
"", // 18
"> ```e", // 19
"> quoted", // 20
"> ```", // 21
"", // 22
" indented", // 23
"", // 24
"```f", // 25
"open", // 26
}
want := map[string]int{"a": 1, "b": 6, "c": 9, "d": 15, "e": 19, "": 23, "f": 25}
for _, sep := range []string{"\n", "\r\n", "\r"} {
got := map[string]int{}
o := Options{CodeBlock: func(c *ui.Context, b *CodeBlockView) {
line := b.SourceLine()
got[b.Info] = line
// The code's first line is on the line after a fence, and on
// the block's own for indented code.
first := line
if b.Info != "" {
first++
}
if code := strings.SplitN(b.Code(), "\n", 2)[0]; !strings.HasSuffix(doc[first-1], code) {
t.Errorf("%q: the code of %q starts with %q, not line %d, %q", sep, b.Info, code, first, doc[first-1])
}
DefaultCodeBlock(c, b)
}}
src := strings.Join(doc, sep)
ui.NewTester(func(c *ui.Context) { View(c, src, &o) }, 500, 900)
for info, line := range want {
if got[info] != line {
t.Errorf("%q: block %q starts on line %d, want %d", sep, info, got[info], line)
}
}
}
}
// TestNestedViewTasksMapToTheSource builds a code block as a view of the
// Markdown in it, whose OnTask adds the block's SourceLine to its lines.
func TestNestedViewTasksMapToTheSource(t *testing.T) {
src := lines("\n", "# Plan", "", "```tasks", "- [ ] write", "- [x] test", "```", "", "- [ ] ship")
var got []taskCall
var inner Options
o := Options{
OnTask: func(line int, checked bool) { got = append(got, taskCall{line, checked}) },
Code: map[string]func(*ui.Context, *CodeBlockView){"tasks": func(c *ui.Context, b *CodeBlockView) {
start := b.SourceLine()
inner.OnTask = func(line int, checked bool) { got = append(got, taskCall{start + line, checked}) }
View(c, b.Code(), &inner)
}},
}
tt := ui.NewTester(func(c *ui.Context) { View(c, src, &o) }, 400, 400)
for _, a := range checkBoxes(tt) {
clickBox(tt, a)
}
if want := []taskCall{{4, true}, {5, false}, {8, true}}; !slices.Equal(got, want) {
t.Errorf("OnTask got %v, want %v", got, want)
}
}
func TestLineAt(t *testing.T) {
for _, tc := range []struct {
src string
off int
want int
}{
{"", 0, 1},
{"abc", 2, 1},
{"a\nb", 2, 2},
{"a\r\nb", 3, 2},
{"a\r\nb", 2, 1}, // within the line's end
{"a\rb", 2, 2},
{"a\r\r\nb\nc", 6, 4},
} {
if got := lineAt(tc.src, tc.off); got != tc.want {
t.Errorf("lineAt(%q, %d) = %d, want %d", tc.src, tc.off, got, tc.want)
}
}
}
+241
View File
@@ -0,0 +1,241 @@
package markdown
import (
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/editor"
)
// Theme is how Markdown looks: fonts, colors and spacing for each kind
// of block and inline. What it leaves zero takes the value of
// DefaultTheme for the window's theme, so that a theme sets only what it
// changes:
//
// app.md.Theme = &markdown.Theme{Link: ui.Hex("#7c3aed"), CodeFont: "JetBrains Mono"}
//
// Lengths in ems are times the FontSize.
type Theme struct {
// FontSize is the size of body text in DIPs: the window theme's
// FontSize when zero.
FontSize float32
// Font is the family of text, the window theme's when empty, and
// CodeFont that of code, the system's monospaced font when empty.
Font, CodeFont string
// LineHeight is how many times its font's line height a line of text
// is: 1.5 by default, and CodeLineHeight that of code, 1.4.
LineHeight, CodeLineHeight float32
// Text colors text, Muted what is secondary (list markers, quotes,
// a code block's language, footnotes), Link links, and Strong strong
// text, the Text color when zero by default.
Text, Muted, Link, Strong Color
// StrongWeight is the weight of strong text: 600.
StrongWeight int
// LinkWeight is the smallest weight of link text, so links stand out
// among prose without lifting strong text down to it: 0 for no floor.
LinkWeight int
// Code colors code spans, with CodeBackground behind them; CodeSize is
// their size in ems: 0.875.
Code, CodeBackground Color
CodeSize float32
// BlockSpacing is the space between blocks, in ems: 0.75. ItemSpacing
// is that between the items of a tight list: 0.25.
BlockSpacing, ItemSpacing float32
// Headings are the styles of headings of levels 1 to 6.
Headings [6]HeadingStyle
// ListIndent is how far list items are from their list's edge, their
// markers in that room, in ems: 1.6.
ListIndent float32
// QuoteBar colors the bar along block quotes, QuoteBarWidth DIPs
// wide (3), and QuoteText their text.
QuoteBar, QuoteText Color
QuoteBarWidth float32
// Alerts color the bar, icon and title of GitHub's alerts, by kind:
// Note, Tip, Important, Warning and Caution, GitHub's colors by
// default, in light or dark as the window theme is.
Alerts [5]Color
// Rule colors thematic breaks and the rules of headings.
Rule Color
// CodeBlockBackground and CodeBlockBorder color code blocks, with
// corners of CodeBlockRadius DIPs (the window theme's Radius plus 2)
// and CodeBlockPadding ems of room inside (0.85). CodeColors colors
// their code's tokens: editor.DefaultTheme's colors when nil.
CodeBlockBackground, CodeBlockBorder Color
CodeBlockRadius, CodeBlockPadding float32
CodeColors *editor.Theme
// TableBorder colors a table's lines, TableHeader the background of
// its header row, and TableStripe that of every other row (none by
// default). TableCellPadding is the room in cells, in ems: 0.6 across
// and 0.4 down. TableMaxColumn is how wide a column grows before its
// cells wrap, in ems: 24.
TableBorder, TableHeader, TableStripe Color
TableCellPadding [2]float32
TableMaxColumn float32
// Mark is the background of text marked with <mark>.
Mark Color
// Checkbox colors the check boxes of task lists that are checked.
Checkbox Color
}
// Color is a color of ui.
type Color = ui.Color
// HeadingStyle is how headings of one level look.
type HeadingStyle struct {
// Size is their size in ems, and Weight their weight.
Size float32
Weight int
// Color colors them: Theme.Text when zero.
Color Color
// Top and Bottom are the room above and below them in ems, which
// replaces Theme.BlockSpacing around them.
Top, Bottom float32
// Rule draws a line below them, as GitHub does below headings of
// levels 1 and 2.
Rule bool
}
// DefaultTheme returns the Markdown theme of a window's theme: its font
// and colors, a code span tinted with its text color, code colored as the
// code editor colors it, and the spacing of the chat apps.
func DefaultTheme(t *ui.Theme) *Theme {
th := &Theme{
FontSize: t.FontSize,
Font: t.Font,
CodeFont: "monospace",
LineHeight: 1.5,
CodeLineHeight: 1.4,
Text: t.Text,
Muted: t.TextMuted,
Link: t.Accent,
Strong: t.Text,
StrongWeight: 600,
Code: t.Text,
CodeBackground: t.Text.Alpha(0.07),
CodeSize: 0.875,
BlockSpacing: 0.75,
ItemSpacing: 0.25,
ListIndent: 1.6,
QuoteBar: t.Border,
QuoteText: t.TextMuted,
QuoteBarWidth: 3,
Alerts: alertColors(t.Dark),
Rule: t.Border,
CodeBlockBackground: t.Text.Alpha(0.04),
CodeBlockBorder: t.Border,
CodeBlockRadius: t.Radius + 2,
CodeBlockPadding: 0.85,
CodeColors: editor.DefaultTheme(t),
TableBorder: t.Border,
TableHeader: t.Text.Alpha(0.04),
TableCellPadding: [2]float32{0.6, 0.4},
TableMaxColumn: 24,
Mark: ui.RGBA(250, 204, 21, 0.35),
Checkbox: t.Accent,
}
if t.FontSize == 0 {
th.FontSize = 14
}
sizes := [6]float32{1.6, 1.35, 1.15, 1, 0.95, 0.9}
weights := [6]int{700, 650, 600, 600, 600, 600}
for i := range th.Headings {
th.Headings[i] = HeadingStyle{Size: sizes[i], Weight: weights[i], Color: t.Text, Top: 1.4, Bottom: 0.55}
}
th.Headings[5].Color = t.TextMuted
return th
}
// resolve returns th with what it leaves zero taken from def.
func resolve(th *Theme, def *Theme) Theme {
if th == nil {
return *def
}
out := *th
f := func(v *float32, d float32) {
if *v == 0 {
*v = d
}
}
c := func(v *Color, d Color) {
if *v == (Color{}) {
*v = d
}
}
s := func(v *string, d string) {
if *v == "" {
*v = d
}
}
f(&out.FontSize, def.FontSize)
s(&out.Font, def.Font)
s(&out.CodeFont, def.CodeFont)
f(&out.LineHeight, def.LineHeight)
f(&out.CodeLineHeight, def.CodeLineHeight)
c(&out.Text, def.Text)
c(&out.Muted, def.Muted)
c(&out.Link, def.Link)
c(&out.Strong, out.Text)
if out.StrongWeight == 0 {
out.StrongWeight = def.StrongWeight
}
c(&out.Code, out.Text)
c(&out.CodeBackground, def.CodeBackground)
f(&out.CodeSize, def.CodeSize)
f(&out.BlockSpacing, def.BlockSpacing)
f(&out.ItemSpacing, def.ItemSpacing)
for i := range out.Headings {
h, d := &out.Headings[i], def.Headings[i]
f(&h.Size, d.Size)
if h.Weight == 0 {
h.Weight = d.Weight
}
if i == 5 {
c(&h.Color, out.Muted)
} else {
c(&h.Color, out.Text)
}
f(&h.Top, d.Top)
f(&h.Bottom, d.Bottom)
}
f(&out.ListIndent, def.ListIndent)
c(&out.QuoteBar, def.QuoteBar)
c(&out.QuoteText, out.Muted)
f(&out.QuoteBarWidth, def.QuoteBarWidth)
for k := range out.Alerts {
c(&out.Alerts[k], def.Alerts[k])
}
c(&out.Rule, def.Rule)
c(&out.CodeBlockBackground, def.CodeBlockBackground)
c(&out.CodeBlockBorder, def.CodeBlockBorder)
f(&out.CodeBlockRadius, def.CodeBlockRadius)
f(&out.CodeBlockPadding, def.CodeBlockPadding)
if out.CodeColors == nil {
out.CodeColors = def.CodeColors
}
c(&out.TableBorder, def.TableBorder)
c(&out.TableHeader, def.TableHeader)
f(&out.TableCellPadding[0], def.TableCellPadding[0])
f(&out.TableCellPadding[1], def.TableCellPadding[1])
f(&out.TableMaxColumn, def.TableMaxColumn)
c(&out.Mark, def.Mark)
c(&out.Checkbox, def.Checkbox)
return out
}
// em returns v ems in DIPs.
func (th *Theme) em(v float32) float32 { return v * th.FontSize }
// alertColors are GitHub's colors of alerts (Primer's fg.accent, success,
// done, attention and danger), in light or dark.
func alertColors(dark bool) [5]Color {
if dark {
return [5]Color{ui.Hex("#4493f8"), ui.Hex("#3fb950"), ui.Hex("#ab7df8"), ui.Hex("#d29922"), ui.Hex("#f85149")}
}
return [5]Color{ui.Hex("#0969da"), ui.Hex("#1a7f37"), ui.Hex("#8250df"), ui.Hex("#9a6700"), ui.Hex("#d1242f")}
}
+995
View File
@@ -0,0 +1,995 @@
package markdown
import (
"slices"
"strings"
"sync"
"github.com/egoist/mygo/internal/l10n"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
// Options are how views show Markdown: their theme, what links and images
// do, how blocks render, and how text being written comes in. Keep one in
// the app's state and give it to every view of a kind, as the messages of
// a chat.
type Options struct {
// Theme is the look: DefaultTheme of the window's theme when nil,
// whose values those the theme leaves zero take.
Theme *Theme
// Extensions is the syntax read beyond CommonMark: Default when zero.
Extensions parser.Extensions
// LinkMenu, when set, builds the context menu of a link, given its
// destination, as a chat's Copy Path and Reveal in Finder for a link
// to a file. The link's menu replaces the one around the view, as its
// Selectable container's, since the innermost element with a context
// menu gets the click; m.EditItems adds the text's Copy and Select
// All to it. Links to #a-heading, footnote references and a link
// whose destination is still coming keep the menu around them.
LinkMenu func(m *ui.Menu, url string)
// OnLink, when set, handles a click on a link, given its destination.
// Without it, links to http, https and mailto addresses open as a
// ui.Link opens them, a path without a scheme goes there in the
// router around the view, a link to #a-heading scrolls to that
// heading, and links of other schemes do nothing.
OnLink func(url string)
// LinkIcon, when set, makes an object at the start of a link's text,
// from its destination and the size of the text around it in DIPs:
// one on the baseline, inside the link, which stays on the line of
// the link's first word and copies as nothing. When it returns false,
// the link has none; a link still being written has none yet. It is
// asked again whenever the paragraph changes: keep what it makes.
LinkIcon func(dest string, size float32) (InlineObject, bool)
// Anchor scrolls to the heading of this slug, with or without its "#",
// or to the block AnchorBlock finds for it, when the document first
// shows, when another document replaces it, and when Anchor changes:
// a docs reader opens guide.md#install at its heading. An OnLink that
// takes #a-heading links sets it.
Anchor string
// AnchorVersion scrolls to Anchor again when it changes, for the same
// heading asked for twice.
AnchorVersion uint64
// AnchorBlock, when set, finds the block an anchor names, given the
// view's document and the anchor without its "#", for Anchor and for
// the links to #an-anchor the view follows itself: a notes app finds
// the paragraph that ends in ^block-id. It returns the block's index,
// or -1 to look for the heading of that slug, as without it. A row or
// a cell of a table scrolls the table into view. The document is the
// view's: read it, never change it.
AnchorBlock func(d *parser.Document, name string) int
// OnTask, when set, makes the check boxes of task list items controls
// of the app's: a click on one, or Space or Enter while it has the
// focus, calls it with the item's line in the view's source, from 1,
// and the state asked for, the other one. The box keeps showing what
// the source says, so the app writes the change into its Markdown,
// which the view then shows. Without it, the boxes only show whether
// their tasks are done.
OnTask func(line int, checked bool)
// Resolve, when set, makes mentions (@octocat) and references to
// issues and pull requests (#123) links: it returns where one goes,
// which OnLink, or else the router or a ui.Link, opens, as a path of
// the app's to open it in place, or false to leave it text, as
// GitHub does for a person or an issue it does not know. Without it,
// they show as text. It is asked for each one shown whenever the view
// builds, so it looks up what the app has at hand, as in a map, and
// paragraphs follow when its answers change.
Resolve func(in parser.Inline) (dest string, ok bool)
// CodeLink, when set, makes code within text a link where it returns
// one: a chat links `src/app.go:12` to the file it names. It is asked
// for each piece of code shown whenever the view builds, as Resolve
// is, and paragraphs follow when its answers change. The code keeps
// its look; its source is untouched, so a document streaming in
// parses as it would without.
CodeLink func(code string) (dest string, ok bool)
// Preview, when set, returns what shows while the pointer rests on a
// link to dest, a mention's or a reference's included: a function
// filling the tip, as ui.TooltipBase does, or nil for the address
// alone. It runs as the view builds, so it shows what the app has at
// hand, fetching the rest in the background.
Preview func(c *ui.Context, dest string) func(tip ui.Element)
// LoadImage loads the image at url, on a goroutine of its own, for the
// views to show; until it has, they show its description. Without
// it, images show as their descriptions. FileImages loads files.
LoadImage func(url string) (ui.ImageSource, error)
// CodeBlock, when set, builds code blocks in place of DefaultCodeBlock,
// which it can call to wrap it; Code builds the code blocks of the
// languages it lists, as "mermaid", in place of either.
CodeBlock func(c *ui.Context, b *CodeBlockView)
Code map[string]func(c *ui.Context, b *CodeBlockView)
// WrapCode wraps the lines of code blocks rather than scrolling them
// sideways.
WrapCode bool
// Math, when set, builds blocks of display math from their TeX, which
// show as their TeX without it; math within text shows as its TeX.
Math func(c *ui.Context, tex string)
// InlineMath, when set, makes math within text an object of the
// text, from its TeX and the size of the text around it in DIPs: one
// on the baseline, which wraps with the words and copies as its
// source, as $x_i$. When it returns false, the math shows as its
// TeX. It is asked again whenever the paragraph changes, as every
// frame of a paragraph streaming in: keep what it makes.
InlineMath func(tex string, size float32) (InlineObject, bool)
// HTML, when set, builds HTML blocks from their HTML, which show as
// their HTML without it; within text, the tags of formatting (<b>,
// <i>, <code>, <br>, <mark>, <sub>, …) apply, and other tags show as
// text.
HTML func(c *ui.Context, html string)
// Block, when set, is asked first for each block, and builds it in
// its place when it returns true.
Block func(c *ui.Context, d *parser.Document, i int) bool
// Reveal is how Stream shows text as it comes: DefaultReveal when nil.
Reveal *Reveal
// ShareSelection leaves the selection to a Selectable container around
// the view, as one across a chat's messages, rather than giving the
// view one of its own. Within another view, as a block Block builds,
// it shares that view's, whose Copy as Markdown copies its text as
// the Markdown of its own source.
ShareSelection bool
images sync.Map // url → *imageEntry
}
// InlineObject is math within text, as Options.InlineMath makes it, or a
// link's icon, as Options.LinkIcon does: a box Width wide, Height above the baseline and Depth below it, in DIPs,
// which Draw paints in r, its box in the window. Draw only paints: it
// may run more than once a frame.
type InlineObject struct {
Width, Height, Depth float32
Draw func(p *ui.Painter, r ui.Rect)
}
// View shows src, finished Markdown, as it reads: CommonMark and what
// Options.Extensions add, parsed again only where src changed since the
// last frame. Its text is selectable, copied as text, as HTML, which
// keeps its formatting where it is pasted (a rich text editor, mail, a
// word processor), and as Markdown (transfer.Markdown), or, with the
// context menu's Copy as Markdown (Shift+Cmd+C, Shift+Ctrl+C on Linux and
// Windows), as Markdown's text. o may be nil.
//
// markdown.View(c, app.readme, &app.md)
func View(c *ui.Context, src string, o *Options) ui.Element {
return build(c, src, o, false)
}
// Stream shows src, Markdown still being written, as a language model's
// reply: text appended to src since the last frame is parsed alone, the
// end shows what its half-written syntax will most likely become (see
// Document.SetStreaming), and text comes in as Options.Reveal says,
// smoothly, fading in. Show the message with View once it is complete,
// in the same place, so that its parse carries on; what is still being
// revealed then still comes in.
//
// if msg.done {
// markdown.View(c, msg.text, &app.md)
// } else {
// markdown.Stream(c, msg.text, &app.md)
// }
func Stream(c *ui.Context, src string, o *Options) ui.Element {
return build(c, src, o, true)
}
// Revealed reports whether el, a view View or Stream returned this frame,
// shows all of its source, done fading in. A chat shows a reply's time
// and actions once its reply is complete and Revealed, not as its last
// bytes arrive, while words still come in:
//
// var md ui.Element
// if msg.done {
// md = markdown.View(c, msg.text, &app.md)
// } else {
// md = markdown.Stream(c, msg.text, &app.md)
// }
// if msg.done && markdown.Revealed(md) {
// ui.Text(c, msg.time)
// }
//
// It tells what this frame shows, so call it after View or Stream, and
// build what it decides after them. The view asks for a frame each
// refresh while it reveals or fades, so a caller that reads it every
// frame sees it turn true without other input, once the last unit shows
// and its fade ends. Text that shows at once (AtOnce, a View given text
// no Stream left to reveal, an edit) is revealed in the frame it comes;
// without a fade (Reveal.Fade negative, or the desktop's Reduce Motion),
// text is revealed once its last unit shows. It turns false again when
// more text comes. Of a Stream, it tells only that the text that came so
// far shows: whether more is coming is the caller's to know, and text
// held back for a sentence, a line or a paragraph to end keeps it false
// until View shows it. It is false for an element neither returned.
func Revealed(el ui.Element) bool {
st := ui.Local(el, stateKey{}, func() *viewState { return nil })
return st != nil && *st != nil && (*st).reveal.revealed()
}
// stateKey keys a view's state among its root's.
type stateKey struct{}
// viewState is what a view keeps from frame to frame.
type viewState struct {
o *Options
doc *parser.Document
ext parser.Extensions
uiTh ui.Theme
def *Theme
th Theme
paras []paraCache
// tasks name the check boxes of tasks, by their items' blocks, while
// Options.OnTask makes them controls.
tasks []taskLabel
// elems notes, for copying, the block each paragraph's element shows,
// and, for a code block's, its first line.
elems []elemInfo
reveal revealState
codes map[int]*codeState
tables map[int]*tableState
// scrollTo is a block to scroll into view, -1 for none.
scrollTo int
anchor string
anchorVersion uint64
notes map[string]int
sb spanBuilder
fade func(src int) float32
// nested are the views with ShareSelection built within this one's
// blocks, whose text this one's selection holds, for copying it as
// Markdown; cur is the block being built, which a nested view is
// noted in.
nested []nestedView
cur int
}
// nestedView is a view sharing the selection of the view around it,
// built in its block.
type nestedView struct {
st *viewState
block int
}
// building maps a window's context to the view whose blocks are being
// built in it, for the views within it that share its selection to note
// themselves in it.
// A plain map under a lock rather than a sync.Map, whose stores
// allocate, so a steady frame stays free of allocations.
var building struct {
sync.Mutex
m map[*ui.Context]*viewState
}
// outerView returns the view whose blocks are being built in c.
func outerView(c *ui.Context) *viewState {
building.Lock()
defer building.Unlock()
return building.m[c]
}
// setBuilding notes st as the view whose blocks are being built in c,
// or that none is when st is nil.
func setBuilding(c *ui.Context, st *viewState) {
building.Lock()
defer building.Unlock()
if st == nil {
delete(building.m, c)
return
}
if building.m == nil {
building.m = map[*ui.Context]*viewState{}
}
building.m[c] = st
}
type paraCache struct {
start, end int
kind parser.Kind
rev uint32
base spanStyle
ok bool
p para
}
type elemInfo struct {
id uint64
block int
line int
}
func newState() *viewState { return &viewState{scrollTo: -1} }
func build(c *ui.Context, src string, o *Options, streaming bool) ui.Element {
if o == nil {
o = &defaultOptions
}
root := ui.Column(c)
st := *ui.Local(root, stateKey{}, newState)
st.o = o
ext := o.Extensions
if ext == 0 {
ext = parser.Default
}
documentChanged := st.doc == nil || st.ext != ext
if documentChanged {
st.doc, st.ext = parser.New(ext), ext
st.paras, st.tasks = st.paras[:0], st.tasks[:0]
}
st.theme(c)
th := &st.th
shown, revealing := st.reveal.step(c, src, streaming, o.Reveal)
st.doc.SetStreaming(streaming || revealing)
if !strings.HasPrefix(src[:shown], st.doc.Source()) {
// Another text, not more of it: blocks where blocks were may
// show other text.
st.forget()
documentChanged = true
}
st.doc.Set(src[:shown])
if o.Anchor != "" && (documentChanged || st.anchor != o.Anchor || st.anchorVersion != o.AnchorVersion) {
st.scrollTo = st.anchorNamed(strings.TrimPrefix(o.Anchor, "#"))
}
st.anchor, st.anchorVersion = o.Anchor, o.AnchorVersion
st.fade = st.reveal.fader(c, o.Reveal)
root.FontSize(th.FontSize).LineHeight(th.LineHeight).TextColor(th.Text)
if th.Font != "" {
root.Font(th.Font)
}
if o.ShareSelection {
if outer := outerView(c); outer != nil {
outer.nested = append(outer.nested, nestedView{st, outer.cur})
}
} else {
root.Selectable()
root.CopyData(st.copyData)
root.ContextMenu(func(m *ui.Menu) {
m.EditItems()
if m.Item(l10n.In(c.Locale()).CopyAsMarkdown()).Chosen() {
c.Services().WriteClipboardData(markdownData(st.copyMarkdown(root.SelectedTexts())))
}
})
if root.FocusWithin() && root.Shortcut(ui.Cmd|ui.Shift, ui.KeyC) {
c.Services().WriteClipboardData(markdownData(st.copyMarkdown(root.SelectedTexts())))
}
}
st.elems = st.elems[:0]
clear(st.nested)
st.nested, st.cur = st.nested[:0], 0
st.numberNotes()
root.Children(func() {
prev := outerView(c)
setBuilding(c, st)
defer setBuilding(c, prev)
st.blocks(c, 0, false, spanStyle{})
st.footnotes(c)
})
if revealing || st.reveal.fading() {
c.AnimationFrame()
}
return root
}
var defaultOptions Options
// theme resolves the theme of the frame.
func (st *viewState) theme(c *ui.Context) {
t := c.Theme()
if st.def == nil || st.uiTh != *t {
st.uiTh = *t
st.def = DefaultTheme(t)
}
th := resolve(st.o.Theme, st.def)
if th != st.th {
st.th = th
clear(st.paras)
for _, cs := range st.codes {
cs.chunks = cs.chunks[:0]
}
}
st.sb.d, st.sb.th = st.doc, &st.th
}
// forget drops what the view made of its blocks.
func (st *viewState) forget() {
clear(st.paras)
clear(st.codes)
clear(st.tables)
clear(st.tasks)
}
func (st *viewState) note(id uint64, block, line int) {
st.elems = append(st.elems, elemInfo{id, block, line})
}
// blocks builds the children of block parent, spaced; tight tells the
// items of a tight list.
func (st *viewState) blocks(c *ui.Context, parent int, tight bool, base spanStyle) {
d := st.doc
th := &st.th
first := true
prevHeading := 0
for j := parent + 1; j < d.Block(parent).Next; j = d.Block(j).Next {
b := d.Block(j)
if b.Kind == parser.FootnoteDefinition || b.Kind == parser.Paragraph && d.LineCount(j) == 0 {
// Footnotes show at the end, and an alert's marker not at all.
continue
}
top := float32(0)
if !first {
top = th.em(th.BlockSpacing)
if tight {
top = th.em(th.ItemSpacing)
}
if prevHeading > 0 {
top = th.em(th.Headings[prevHeading-1].Bottom)
}
if b.Kind == parser.Heading {
top = max(top, th.em(th.Headings[b.Level-1].Top))
}
}
el := st.block(c, j, tight, base)
st.fadeIn(el, b)
if top > 0 {
el.Margin(top, 0, 0, 0)
}
if st.scrollTo == j {
el.ScrollIntoView()
st.scrollTo = -1
}
prevHeading = 0
if b.Kind == parser.Heading {
prevHeading = b.Level
}
first = false
}
}
// block builds block i.
func (st *viewState) block(c *ui.Context, i int, tight bool, base spanStyle) ui.Element {
d := st.doc
o := st.o
th := &st.th
b := d.Block(i)
defer func(prev int) { st.cur = prev }(st.cur)
st.cur = i
if o.Block != nil {
box := ui.Column(c)
done := false
box.Children(func() { done = o.Block(c, d, i) })
if done {
return box
}
return box.Children(func() { st.defaultBlock(c, i, tight, base) })
}
_ = b
_ = th
return st.defaultBlock(c, i, tight, base)
}
func (st *viewState) defaultBlock(c *ui.Context, i int, tight bool, base spanStyle) ui.Element {
d := st.doc
th := &st.th
b := d.Block(i)
switch b.Kind {
case parser.Paragraph:
if imagesOnly(d.Inlines(i)) {
return st.images(c, i)
}
return st.paragraph(c, i, base)
case parser.Heading:
h := th.Headings[b.Level-1]
s := base
s.weight, s.size, s.color = h.Weight, th.em(h.Size), h.Color
el := st.paragraph(c, i, s).Role(ui.RoleHeading).Level(b.Level)
if h.Rule {
el.BorderWidth(0, 0, 1, 0).BorderColor(th.Rule).Padding(0, 0, th.em(0.3), 0)
}
return el
case parser.ThematicBreak:
return ui.Box(c).Height(1).Background(th.Rule).AlignSelf(ui.Stretch).Margin(th.em(0.25), 0)
case parser.CodeBlock:
return st.codeBlock(c, i)
case parser.HTMLBlock:
html := strings.TrimRight(d.Lines(i), "\n")
if st.o.HTML != nil {
box := ui.Column(c)
return box.Children(func() { st.o.HTML(c, html) })
}
el := ui.Text(c, html).Font(th.CodeFont).FontSize(th.em(th.CodeSize)).TextColor(th.Muted)
st.note(el.ID(), i, 0)
return el
case parser.MathBlock:
tex := strings.TrimRight(d.Lines(i), "\n")
if st.o.Math != nil {
box := ui.Column(c)
return box.Children(func() { st.o.Math(c, tex) })
}
box := ui.ScrollHorizontal(c).AlignSelf(ui.Stretch)
return box.Children(func() {
el := ui.Text(c, tex).Font(th.CodeFont).FontSize(th.em(th.CodeSize)).TextColor(th.Muted).NoWrap().Margin(0, ui.Auto)
st.note(el.ID(), i, 0)
})
case parser.Quote:
if b.Alert != parser.NoAlert {
return st.alert(c, i, b.Alert, base)
}
s := base
s.color = th.QuoteText
// The bar on the side lines start: the right right to left.
q := ui.Column(c).BorderStartWidth(th.QuoteBarWidth).BorderColor(th.QuoteBar).PaddingStart(th.em(0.85)).TextColor(th.QuoteText)
return q.Children(func() { st.blocks(c, i, false, s) })
case parser.List:
return st.list(c, i, base)
case parser.Table:
return st.table(c, i, base)
}
return ui.Box(c)
}
// alert builds a GitHub alert: a quote whose bar, icon and title take
// its kind's color, its text the color of text.
func (st *viewState) alert(c *ui.Context, i int, a parser.Alert, base spanStyle) ui.Element {
th := &st.th
color := th.Alerts[a-1]
q := ui.Column(c).BorderStartWidth(th.QuoteBarWidth).BorderColor(color).PaddingStart(th.em(0.85))
return q.Children(func() {
title := ui.Row(c).AlignItems(ui.Center).Gap(th.em(0.5)).TextColor(color).Margin(0, 0, th.em(th.ItemSpacing*2), 0)
title.Children(func() {
if icon := alertIcon(a); icon != nil {
ui.Icon(c, icon)
}
ui.Text(c, a.String()).FontWeight(th.StrongWeight)
})
st.blocks(c, i, false, base)
})
}
// fadeIn fades in a block revealed a moment ago: text fades by its
// spans, and the rest of blocks, as a code block's box or a table's
// lines, by their opacity.
func (st *viewState) fadeIn(el ui.Element, b *parser.Block) {
if st.fade == nil {
return
}
switch b.Kind {
case parser.Paragraph, parser.Heading, parser.List:
return
}
if a := st.fade(b.Start); a < 1 {
el.Opacity(a)
}
}
// para returns the paragraph of block i in style base, built anew only
// when it changed.
func (st *viewState) para(i int, base spanStyle) *para {
for len(st.paras) < st.doc.Len() {
st.paras = append(st.paras, paraCache{})
}
b := st.doc.Block(i)
st.doc.Inlines(i) // their revision
pc := &st.paras[i]
fading := st.fade != nil && st.fade(max(b.End-1, b.Start)) < 1
if pc.ok && pc.start == b.Start && pc.end == b.End && pc.kind == b.Kind && pc.rev == b.Revision() && pc.base == base && !pc.p.fading && !fading && !b.Healed() && st.sameResolved(i, &pc.p) {
return &pc.p
}
pc.start, pc.end, pc.kind, pc.rev, pc.base, pc.ok = b.Start, b.End, b.Kind, b.Revision(), base, true
sb := &st.sb
sb.block = i
sb.fade = st.fade
sb.notes = st.noteNumber
sb.math = st.o.InlineMath
sb.linkIcon = st.o.LinkIcon
sb.resolve, sb.resolvers = nil, st.o.resolvers()
if sb.resolvers != 0 {
sb.resolve = st.o.resolveInline
}
sb.build(&pc.p, base)
return &pc.p
}
// resolvers says which of Resolve and CodeLink are set, as bits.
func (o *Options) resolvers() uint8 {
var r uint8
if o.Resolve != nil {
r |= 1
}
if o.CodeLink != nil {
r |= 2
}
return r
}
// resolveInline asks where an inline goes: Resolve for a mention or a
// reference, CodeLink for code.
func (o *Options) resolveInline(in parser.Inline) (string, bool) {
switch in.Kind {
case parser.Mention, parser.Reference:
if o.Resolve != nil {
return o.Resolve(in)
}
case parser.Code:
if o.CodeLink != nil {
return o.CodeLink(in.Text)
}
}
return "", false
}
// sameResolved reports whether the mentions, references and code of block i
// resolve where they did as p was built, Options.Resolve and CodeLink set
// or not alike.
func (st *viewState) sameResolved(i int, p *para) bool {
if len(p.refs) == 0 {
return true
}
if st.o.resolvers() != p.resolvers {
return false
}
if p.resolvers == 0 {
return true
}
in := st.doc.Inlines(i)
for k, x := range p.refs {
dest, ok := st.o.resolveInline(in[x])
if !ok {
dest = ""
}
if dest != p.resolved[k] {
return false
}
}
return true
}
// paragraph builds the text of block i: a paragraph, a heading or a cell.
func (st *viewState) paragraph(c *ui.Context, i int, base spanStyle) ui.Element {
p := st.para(i, base)
ps := p.pieces
var el ui.Element
switch {
case len(ps) == 0:
el = ui.Text(c, "")
case ps[0].link == -1:
el = ui.RichText(c, ps[0].spans...)
ps = ps[1:]
default:
el = ui.RichText(c)
}
if len(ps) > 0 {
el.Children(func() {
for k := range ps {
st.piece(c, i, &ps[k])
}
})
}
if objects := p.objects; len(objects) > 0 {
el.DrawObjects(func(pa *ui.Painter, at int, r ui.Rect) {
if k, ok := slices.BinarySearchFunc(objects, at, func(o mathObject, at int) int { return o.rune - at }); ok && objects[k].draw != nil {
objects[k].draw(pa, r)
}
})
}
st.note(el.ID(), i, -1)
return el
}
// piece builds a link, or text after one, within a paragraph.
func (st *viewState) piece(c *ui.Context, block int, pc *piece) {
switch {
case pc.link == -1:
ui.RichText(c, pc.spans...)
case pc.link < -1:
// A footnote reference: it scrolls to the footnote.
in := st.doc.Inlines(block)[-2-pc.link]
l := ui.Link(c, "", "")
l.Children(func() { ui.RichText(c, pc.spans...) })
if l.Clicked() {
if i, ok := st.doc.Footnote(in.Text); ok {
st.scrollTo = i
}
}
default:
in := st.doc.Inlines(block)[pc.link]
if pc.dest != "" {
// A mention or a reference, which Options.Resolve made a link,
// or code, which Options.CodeLink did.
in.Dest, in.Auto = pc.dest, true
}
st.link(c, &in, func() { ui.RichText(c, pc.spans...) })
}
}
// link builds a link to in.Dest whose text children builds.
func (st *viewState) link(c *ui.Context, in *parser.Inline, children func()) {
dest := in.Dest
var l ui.Element
switch {
case in.Pending:
l = ui.Link(c, "", "")
case st.o.OnLink != nil:
l = ui.Link(c, "", "")
if l.Clicked() {
st.o.OnLink(dest)
}
case strings.HasPrefix(dest, "#"):
l = ui.Link(c, "", "")
if l.Clicked() {
st.scrollTo = st.anchorNamed(dest[1:])
}
case linkAllowed(dest, c.Router() != nil):
l = ui.Link(c, "", dest)
default:
l = ui.Link(c, "", "")
}
if st.o.LinkMenu != nil && !in.Pending && dest != "" && !strings.HasPrefix(dest, "#") {
l.ContextMenu(func(m *ui.Menu) { st.o.LinkMenu(m, dest) })
}
l.TextColor(st.th.Link)
l.Children(children)
// What the tip says, which describes the link to assistive technology.
tip := in.Title
if tip == "" && !in.Auto && !in.Pending && dest != "" && !strings.HasPrefix(dest, "#") {
tip = dest
}
if st.o.Preview != nil && !in.Pending && dest != "" {
if fill := st.o.Preview(c, dest); fill != nil {
if tip != "" {
l.Description(tip)
}
ui.TooltipBase(c, l, fill)
return
}
}
if tip != "" {
l.Tooltip(tip)
}
}
// linkAllowed reports whether a link's destination opens without
// OnLink: one ui.SafeToOpen allows, or, in a router, a path without a
// scheme, which goes there. Outside a router, a path would open as a file
// or a program, so it does nothing.
func linkAllowed(dest string, router bool) bool {
if strings.ContainsAny(dest, "\\\x00") || strings.HasPrefix(dest, "//") {
return false
}
if i := strings.IndexAny(dest, ":/?#"); i < 0 || dest[i] != ':' {
return router
}
return ui.SafeToOpen(dest)
}
// anchorNamed returns the block to scroll to for the anchor name: the one
// Options.AnchorBlock finds, else the heading of that slug, or -1.
func (st *viewState) anchorNamed(name string) int {
if find := st.o.AnchorBlock; find != nil {
d := st.doc
if i := find(d, name); i > 0 && i < d.Len() {
// A table shows its rows and cells itself.
for k := d.Block(i).Kind; k == parser.TableRow || k == parser.TableCell; k = d.Block(i).Kind {
i = d.Block(i).Parent
}
return i
}
}
return st.headingNamed(name)
}
// headingNamed returns the heading whose slug, as GitHub makes it, is
// name, or -1.
func (st *viewState) headingNamed(name string) int {
d := st.doc
for i := 1; i < d.Len(); i++ {
if d.Block(i).Kind == parser.Heading && Slug(parser.PlainText(d.Inlines(i))) == strings.ToLower(name) {
return i
}
}
return -1
}
// Slug returns the anchor of a heading of text, as GitHub makes it: in
// lower case, spaces as hyphens, without punctuation.
func Slug(text string) string {
var b strings.Builder
for _, r := range strings.ToLower(strings.TrimSpace(text)) {
switch {
case r == ' ':
b.WriteByte('-')
case r == '-' || r == '_' || isAlnum(r):
b.WriteRune(r)
}
}
return b.String()
}
// list builds a list.
func (st *viewState) list(c *ui.Context, i int, base spanStyle) ui.Element {
d := st.doc
th := &st.th
b := d.Block(i)
depth := 0
for p := b.Parent; p > 0; p = d.Block(p).Parent {
if d.Block(p).Kind == parser.List {
depth++
}
}
width := th.em(th.ListIndent)
if b.Ordered {
last := b.Number + max(0, st.countChildren(i)-1)
w, _ := c.MeasureText(0, ui.Span{Text: itoa(last) + string(b.Marker), Font: th.Font, Size: th.FontSize})
width = max(width, w+th.em(0.5))
}
col := ui.Column(c).Role(ui.RoleList)
return col.Children(func() {
n := b.Number
first := true
for j := i + 1; j < d.Block(i).Next; j = d.Block(j).Next {
row := ui.Row(c).AlignItems(ui.Start).Role(ui.RoleListItem)
if !first {
gap := th.BlockSpacing
if b.Tight {
gap = th.ItemSpacing
}
row.Margin(th.em(gap), 0, 0, 0)
}
if st.scrollTo == j {
// An item an anchor named (Options.AnchorBlock).
row.ScrollIntoView()
st.scrollTo = -1
}
num := n
row.Children(func() {
st.marker(c, b, j, num, depth, width)
ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Children(func() { st.blocks(c, j, b.Tight, base) })
})
n++
first = false
}
})
}
func (st *viewState) countChildren(i int) int {
n := 0
for j := i + 1; j < st.doc.Block(i).Next; j = st.doc.Block(j).Next {
n++
}
return n
}
// marker builds the marker of item j of list: a bullet, its number, or its
// check box.
func (st *viewState) marker(c *ui.Context, list *parser.Block, j, n, depth int, width float32) {
th := &st.th
item := st.doc.Block(j)
box := ui.Row(c).Width(width).Shrink(0).Unselectable()
if st.fade != nil {
if a := st.fade(item.Start); a < 1 {
box.Opacity(a)
}
}
box.Children(func() {
switch {
case item.Task != parser.NoTask:
size := th.em(0.95)
lineH := th.FontSize * th.LineHeight * 1.2
checked := item.Task == parser.Checked
cb := ui.Box(c).Size(size, size).Radius(max(3, size/5)).Margin(max(0, (lineH-size)/2-1), 0, 0, 0).Role(ui.RoleCheckBox).Checked(checked)
if onTask := st.o.OnTask; onTask != nil {
// A control, named by its task, which asks the app for
// the other state: the source decides what it shows.
cb.Focusable().Label(st.taskName(j))
if cb.Clicked() {
onTask(lineAt(st.doc.Source(), item.Start), !checked)
}
} else {
cb.ReadOnly(true)
}
if checked {
cb.Background(th.Checkbox).Draw(func(p *ui.Painter, r ui.Rect) {
path := &ui.Path{}
path.MoveTo(r.X+r.W*0.25, r.Y+r.H*0.52)
path.LineTo(r.X+r.W*0.43, r.Y+r.H*0.7)
path.LineTo(r.X+r.W*0.76, r.Y+r.H*0.32)
p.StrokePath(path, max(1.5, r.W/9), ui.RGB(255, 255, 255))
})
} else {
cb.Border(1.5, th.Muted)
}
case list.Ordered:
ui.Text(c, itoa(n)+string(list.Marker)).TextColor(th.Muted).Width(width - th.em(0.4)).TextAlign(ui.End).FontFeatures("tnum")
default:
bullets := [...]string{"•", "◦", "▪"}
ui.Text(c, bullets[min(depth, 2)]).TextColor(th.Muted).Width(width - th.em(0.5)).TextAlign(ui.Center)
}
})
}
// taskLabel is the name of a task's check box: the text of its item's
// first paragraph, kept while that paragraph stays as it was, so that a
// steady frame does not make it again.
type taskLabel struct {
start, end int
rev uint32
ok bool
text string
}
// taskName returns the name of the check box of item j.
func (st *viewState) taskName(j int) string {
d := st.doc
k := j + 1
if k >= d.Block(j).Next || d.Block(k).Kind != parser.Paragraph {
return ""
}
for len(st.tasks) < d.Len() {
st.tasks = append(st.tasks, taskLabel{})
}
in := d.Inlines(k) // their revision
b := d.Block(k)
tn := &st.tasks[j]
if !tn.ok || tn.start != b.Start || tn.end != b.End || tn.rev != b.Revision() {
*tn = taskLabel{b.Start, b.End, b.Revision(), true, parser.PlainText(in)}
}
return tn.text
}
// lineAt returns the line of src that byte off is on, from 1. Lines end
// with \n, \r\n or \r, as CommonMark's do.
func lineAt(src string, off int) int {
s := src[:off]
n := 1 + strings.Count(s, "\n")
if strings.IndexByte(s, '\r') >= 0 {
n += strings.Count(s, "\r") - strings.Count(s, "\r\n")
if s[len(s)-1] == '\r' && off < len(src) && src[off] == '\n' {
n-- // off is within the line's end
}
}
return n
}
// numberNotes numbers the footnotes by the order of their definitions.
func (st *viewState) numberNotes() {
clear(st.notes)
n := 0
for i := 1; i < st.doc.Len(); i++ {
if b := st.doc.Block(i); b.Kind == parser.FootnoteDefinition {
if st.notes == nil {
st.notes = map[string]int{}
}
key := parser.NormalizeLabel(b.Label())
if _, ok := st.notes[key]; !ok {
n++
st.notes[key] = n
}
}
}
}
func (st *viewState) noteNumber(label string) int { return st.notes[parser.NormalizeLabel(label)] }
// footnotes builds the footnotes, below a rule, in order.
func (st *viewState) footnotes(c *ui.Context) {
if len(st.notes) == 0 {
return
}
d := st.doc
th := &st.th
ui.Box(c).Height(1).Background(th.Rule).AlignSelf(ui.Stretch).Margin(th.em(1.2), 0, th.em(0.6), 0)
base := spanStyle{color: th.Muted, size: th.em(0.875)}
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if b.Kind != parser.FootnoteDefinition {
continue
}
num := st.notes[parser.NormalizeLabel(b.Label())]
row := ui.Row(c).AlignItems(ui.Start).Margin(th.em(0.25), 0, 0, 0)
if st.scrollTo == i {
row.ScrollIntoView()
st.scrollTo = -1
}
row.Children(func() {
ui.Text(c, itoa(num)+".").TextColor(th.Muted).FontSize(th.em(0.875)).Width(th.em(1.6)).Shrink(0).Unselectable()
ui.Column(c).Grow(1).Shrink(1).MinWidth(0).TextColor(th.Muted).Children(func() { st.blocks(c, i, false, base) })
})
}
}
+195
View File
@@ -0,0 +1,195 @@
package markdown
import (
"strings"
"testing"
"github.com/egoist/mygo/ui"
"github.com/egoist/mygo/ui/markdown/parser"
)
func TestViewAnchorInitialAndRepeated(t *testing.T) {
var scroll ui.ScrollState
o := Options{Anchor: "#target"}
source := "# Intro\n\n" + strings.Repeat("A paragraph before the destination.\n\n", 30) + "# Target\n\nDestination.\n"
tt := ui.NewTester(func(c *ui.Context) {
c.DisableAnimations()
ui.Scroll(c).Fill().TrackScroll(&scroll).Children(func() { View(c, source, &o) })
}, 400, 160)
if scroll.Y <= 0 {
t.Fatal("initial anchor did not reveal the heading")
}
scroll.Y = 0
tt.Frame()
if scroll.Y != 0 {
t.Fatalf("unchanged anchor kept forcing scroll: %g", scroll.Y)
}
o.AnchorVersion++
tt.Frame()
if scroll.Y <= 0 {
t.Fatal("a new version did not repeat the same anchor jump")
}
scroll.Y = 0
source = "# Another document\n\n" + strings.Repeat("Different text before the target.\n\n", 20) + "# Target\n\nNew destination.\n"
tt.Frame()
if scroll.Y <= 0 {
t.Fatal("a replacement document did not apply the same anchor")
}
}
// TestViewOnLinkSetsAnchor checks that OnLink keeps getting #a-heading
// links, and scrolls the view to the heading by setting Anchor.
func TestViewOnLinkSetsAnchor(t *testing.T) {
var scroll ui.ScrollState
var clicked []string
var o Options
o.OnLink = func(dest string) {
clicked = append(clicked, dest)
if strings.HasPrefix(dest, "#") {
o.Anchor = dest
}
}
source := "[Jump](#target) [File](next.md)\n\n" + strings.Repeat("A paragraph before the destination.\n\n", 30) + "# Target\n\nDestination.\n"
tt := ui.NewTester(func(c *ui.Context) {
c.DisableAnimations()
ui.Scroll(c).Fill().TrackScroll(&scroll).Children(func() { View(c, source, &o) })
}, 400, 160)
if err := tt.Click("File"); err != nil {
t.Fatal(err)
}
if err := tt.Click("Jump"); err != nil {
t.Fatal(err)
}
tt.Frame()
if len(clicked) != 2 || clicked[0] != "next.md" || clicked[1] != "#target" {
t.Fatalf("OnLink got %q, want next.md and #target", clicked)
}
if scroll.Y <= 0 {
t.Fatal("the anchor OnLink set did not reveal its heading")
}
if len(tt.OpenedURLs()) != 0 {
t.Fatalf("links escaped to the system opener: %q", tt.OpenedURLs())
}
}
// blockIDs is an Options.AnchorBlock that finds what an anchor of
// Obsidian's names, ^block-id: the paragraph ending in it, or, for one
// ending in "-item", that paragraph's list item, and a table's cell
// ending in it. It notes the names it is asked for, and returns -1 for
// others.
func blockIDs(asked *[]string) func(d *parser.Document, name string) int {
return func(d *parser.Document, name string) int {
*asked = append(*asked, name)
if !strings.HasPrefix(name, "^") {
return -1
}
for i := 1; i < d.Len(); i++ {
b := d.Block(i)
if (b.Kind == parser.Paragraph || b.Kind == parser.TableCell) && strings.HasSuffix(parser.PlainText(d.Inlines(i)), " "+name) {
if strings.HasSuffix(name, "-item") {
return b.Parent
}
return i
}
}
return -1
}
}
// anchorView builds source in a view of 400 by 160 that scrolls, and
// returns the Tester, whether it shows text s whole, and a function that
// scrolls back to the top, where it shows none of the anchors' blocks.
func anchorView(t *testing.T, source *string, o *Options) (*ui.Tester, func(s string) bool, func()) {
var scroll ui.ScrollState
tt := ui.NewTester(func(c *ui.Context) {
c.DisableAnimations()
ui.Scroll(c).Fill().TrackScroll(&scroll).Children(func() { View(c, *source, o) })
}, 400, 160)
shows := func(s string) bool {
r, ok := tt.Find(s)
return ok && r.Y >= 0 && r.Y+r.H <= 160
}
return tt, shows, func() {
t.Helper()
scroll.Y = 0
tt.Frame()
if !shows("Before.") {
t.Fatal("the view did not scroll back to the top")
}
}
}
// TestAnchorBlockScrollsToABlock checks that Anchor scrolls to the
// paragraph AnchorBlock finds, given the anchor without its "#", to the
// list item and to the table of a cell it finds, and to the heading of the
// slug when it finds nothing or answers a block the document does not have.
func TestAnchorBlockScrollsToABlock(t *testing.T) {
var asked []string
o := Options{Anchor: "#^para", AnchorBlock: blockIDs(&asked)}
source := "Before.\n\n" + strings.Repeat("Before.\n\n", 30) + "Destination. ^para\n\n" +
strings.Repeat("Between.\n\n", 30) + "- first\n- far away ^far-item\n\n" +
strings.Repeat("Between.\n\n", 30) + "| a | b |\n|---|---|\n| 1 | cell ^cell |\n\n" +
strings.Repeat("Between.\n\n", 30) + "# Target\n\n" + strings.Repeat("After.\n\n", 30)
tt, shows, top := anchorView(t, &source, &o)
if !shows("Destination. ^para") {
t.Error("Anchor did not scroll to the paragraph AnchorBlock found")
}
if len(asked) != 1 || asked[0] != "^para" {
t.Errorf("AnchorBlock was asked for %q, want ^para", asked)
}
for _, anchor := range []struct{ name, text string }{
{"^far-item", "far away ^far-item"},
{"^cell", "cell ^cell"},
{"#target", "Target"},
{"^para", "Destination. ^para"},
} {
top()
o.Anchor = anchor.name
tt.Frame()
if !shows(anchor.text) {
t.Errorf("Anchor %q did not scroll to %q", anchor.name, anchor.text)
}
}
// Blocks the document does not have, the root among them, leave the
// heading of the slug.
for _, i := range []int{0, -2, 1} {
o.AnchorBlock = func(d *parser.Document, name string) int {
if i > 0 {
return d.Len() + i - 1
}
return i
}
top()
o.Anchor, o.AnchorVersion = "target", o.AnchorVersion+1
tt.Frame()
if !shows("Target") {
t.Errorf("AnchorBlock answering %d did not leave the heading", i)
}
}
}
// TestAnchorBlockFollowsLinks checks that links to #an-anchor the view
// follows itself go where AnchorBlock says, or to a heading.
func TestAnchorBlockFollowsLinks(t *testing.T) {
var asked []string
o := Options{AnchorBlock: blockIDs(&asked)}
source := "[Block](#^para) and [Heading](#target)\n\nBefore.\n\n" + strings.Repeat("Before.\n\n", 30) +
"Destination. ^para\n\n" + strings.Repeat("Between.\n\n", 30) + "# Target\n\n" + strings.Repeat("After.\n\n", 30)
for _, link := range []struct{ text, name, shows string }{
{"Block", "^para", "Destination. ^para"},
{"Heading", "target", "Target"},
} {
asked = nil
tt, shows, _ := anchorView(t, &source, &o)
if err := tt.Click(link.text); err != nil {
t.Fatal(err)
}
tt.Frame()
if !shows(link.shows) || len(asked) != 1 || asked[0] != link.name {
t.Errorf("%s: AnchorBlock asked for %q, shows %q: %v", link.text, asked, link.shows, shows(link.shows))
}
if len(tt.OpenedURLs()) != 0 {
t.Errorf("%s: links escaped to the system opener: %q", link.text, tt.OpenedURLs())
}
}
}
+79
View File
@@ -0,0 +1,79 @@
package markdown
import (
"slices"
"testing"
"github.com/egoist/mygo/ui"
)
// TestViewLinkMenu checks that Options.LinkMenu gives each link with a
// destination a context menu of its own, told which link it is, in View
// and in Stream, while the text around it, links to #a-heading, footnote
// references and a link still being written keep the menu of the
// Selectable container around the view.
func TestViewLinkMenu(t *testing.T) {
const src = "# Top\n\nIntro text.\n\nSee [plan.md](file:///proj/plan.md), [notes](notes.md) and [up](#top).[^1]\n\n[^1]: A note.\n\nNow [half](file:///pr"
linkMenu := []string{"Copy Path", "Reveal in Finder", "-", "Copy", "-", "Select All"}
outer := []string{"Quote", "-", "Copy", "-", "Select All"}
for _, stream := range []bool{false, true} {
var asked, copied []string
o := &Options{
ShareSelection: true,
Reveal: &Reveal{Unit: AtOnce},
LinkMenu: func(m *ui.Menu, url string) {
asked = append(asked, url)
if m.Item("Copy Path").Chosen() {
copied = append(copied, url)
}
m.Item("Reveal in Finder")
m.Separator()
m.EditItems()
},
}
tt := ui.NewTester(func(c *ui.Context) {
ui.Column(c).Fill().Padding(10).Selectable().ContextMenu(func(m *ui.Menu) {
m.Item("Quote")
m.Separator()
m.EditItems()
}).Children(func() {
if stream {
Stream(c, src, o)
} else {
View(c, src, o)
}
})
}, 600, 400)
for _, s := range []string{"plan.md", "notes"} {
if err := tt.RightClick(s); err != nil {
t.Fatal(err)
}
if !slices.Equal(tt.Menu(), linkMenu) {
t.Errorf("stream %v: menu of %q %q, want %q", stream, s, tt.Menu(), linkMenu)
}
if err := tt.ChooseMenuItem("Copy Path"); err != nil {
t.Fatal(err)
}
}
if want := []string{"file:///proj/plan.md", "notes.md"}; !slices.Equal(copied, want) {
t.Errorf("stream %v: Copy Path got %q, want %q", stream, copied, want)
}
for _, s := range []string{"Intro text.", "up", "[1]", "half"} {
if s == "half" && !stream {
continue // only Stream has a link still being written
}
if err := tt.RightClick(s); err != nil {
t.Fatal(err)
}
if !slices.Equal(tt.Menu(), outer) {
t.Errorf("stream %v: menu of %q %q, want %q", stream, s, tt.Menu(), outer)
}
tt.CloseMenu()
}
for _, url := range asked {
if url != "file:///proj/plan.md" && url != "notes.md" {
t.Errorf("stream %v: LinkMenu asked for %q", stream, url)
}
}
}
}
+424
View File
@@ -0,0 +1,424 @@
package markdown
import (
"os"
"slices"
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/egoist/mygo/ui"
)
const sample = "# Title\n\nSome **bold** and a [link](https://go.dev), `code`.\n\n" +
"- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n\n```go\nfunc main() {}\n```\n\nLast [bad](javascript:alert(1)) one.\n"
func TestViewShows(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) { View(c, sample, nil) }, 600, 800)
for _, s := range []string{"Title", "Some bold and a link, code.", "one", "two", "a", "b", "1", "2", "func main() {}", "Copy", "go"} {
if !tt.HasText(s) {
t.Errorf("no %q in %q", s, tt.Texts())
}
}
}
func TestViewLinks(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) { View(c, sample, nil) }, 600, 800)
if err := tt.Click("link"); err != nil {
t.Fatal(err)
}
if err := tt.Click("bad"); err != nil {
t.Fatal(err)
}
if got := tt.OpenedURLs(); !slices.Equal(got, []string{"https://go.dev"}) {
t.Errorf("opened %q", got)
}
var clicked []string
o := &Options{OnLink: func(url string) { clicked = append(clicked, url) }}
tt = ui.NewTester(func(c *ui.Context) { View(c, sample, o) }, 600, 800)
tt.Click("bad")
if !slices.Equal(clicked, []string{"javascript:alert(1)"}) || len(tt.OpenedURLs()) > 0 {
t.Errorf("OnLink got %q, opened %q", clicked, tt.OpenedURLs())
}
}
// TestViewTableHeaderLinks reaches a link in a table's header, which
// shows what is inside it as a cell does, still named by its text.
func TestViewTableHeaderLinks(t *testing.T) {
src := "| [Name](https://go.dev) | Size |\n|---|---|\n| a.txt | 1 KB |\n"
tt := ui.NewTester(func(c *ui.Context) { View(c, src, nil) }, 600, 400)
for _, name := range []string{"Name", "Size"} {
if _, ok := tt.AccessByRole(ui.RoleColumnHeader, name); !ok {
t.Errorf("no column header named %q", name)
}
}
if _, ok := tt.AccessByRole(ui.RoleLink, "Name"); !ok {
t.Error("the header's link is not in the tree")
}
}
func TestViewCopyButton(t *testing.T) {
tt := ui.NewTester(func(c *ui.Context) { View(c, sample, nil) }, 600, 800)
if err := tt.Click("Copy"); err != nil {
t.Fatal(err)
}
if got := tt.Clipboard(); got != "func main() {}\n" {
t.Errorf("copied %q", got)
}
if !tt.HasText("Copied") {
t.Errorf("no Copied in %q", tt.Texts())
}
}
func TestViewCopySelection(t *testing.T) {
src := "# Title\n\nFirst **para**.\n\n- one\n- two\n\n| a | b |\n|---|---|\n| 1 | 2 |\n"
tt := ui.NewTester(func(c *ui.Context) { View(c, src, nil) }, 600, 800)
r, _ := tt.Find("First para.")
tt.ClickAt(r.X+2, r.Y+r.H/2)
tt.Command("selectAll")
tt.Command("copy")
want := "Title\n\nFirst para.\n\none\ntwo\n\na\tb\n1\t2"
if got := tt.Clipboard(); got != want {
t.Errorf("copied %q, want %q", got, want)
}
tt.Key(ui.Cmd|ui.Shift, ui.KeyC)
if got := tt.Clipboard(); got != strings.TrimSuffix(src, "\n") {
t.Errorf("copied as Markdown %q, want %q", got, src)
}
}
func TestViewCopyMarkdownPartial(t *testing.T) {
src := "Some **bold text**"
tt := ui.NewTester(func(c *ui.Context) { View(c, src, nil) }, 600, 400)
r, _ := tt.Find("Some bold text")
w := float32(50) // within "bold", in the system font of 14 DIPs
// Drag from inside "bold" past the end.
y := r.Y + r.H/2
tt.Press(r.X+w, y)
tt.Move(r.X+r.W-2, y)
tt.Release(r.X+r.W-2, y)
tt.Key(ui.Cmd|ui.Shift, ui.KeyC)
got := tt.Clipboard()
if !strings.HasPrefix(got, "**") || !strings.HasSuffix(got, "text**") || strings.Contains(got, "Some") {
t.Errorf("copied as Markdown %q, want the end of the strong text, completed", got)
}
}
// testdata returns a document of the parser's tests.
func testdata(t testing.TB, name string) string {
b, err := os.ReadFile("parser/testdata/" + name)
if err != nil {
t.Fatal(err)
}
return string(b)
}
// TestStreamMatchesView streams a document a character at a time into
// Stream and checks it shows as View shows it whole.
func TestStreamMatchesView(t *testing.T) {
src := testdata(t, "extras.md")
o := &Options{Reveal: &Reveal{Unit: AtOnce}}
var text string
done := false
tt := ui.NewTester(func(c *ui.Context) {
if done {
View(c, text, o)
} else {
Stream(c, text, o)
}
}, 700, 3000)
for i := 0; i < len(src); {
_, n := utf8.DecodeRuneInString(src[i:])
i += n
text = src[:i]
if i%7 == 0 {
tt.Frame()
}
}
done = true
tt.Frame()
whole := ui.NewTester(func(c *ui.Context) { View(c, src, o) }, 700, 3000)
if got, want := tt.Texts(), whole.Texts(); !slices.Equal(got, want) {
t.Errorf("streamed shows\n%q\nwhole shows\n%q", got, want)
}
}
// TestRevealPaces checks that text streamed in a burst comes in over
// frames, and all of it once the stream is done.
func TestRevealPaces(t *testing.T) {
text := ""
done := false
o := &Options{}
tt := ui.NewTester(func(c *ui.Context) {
if done {
View(c, text, o)
} else {
Stream(c, text, o)
}
}, 600, 400)
text = strings.Repeat("word ", 200)
tt.Frame()
first := strings.Join(tt.Texts(), "")
if len(first) >= len(text)-1 {
t.Fatalf("a burst showed at once: %d of %d bytes", len(first), len(text))
}
tt.Advance(60 * time.Millisecond)
if second := strings.Join(tt.Texts(), ""); len(second) <= len(first) {
t.Fatalf("no more text after a while: %d then %d bytes", len(first), len(second))
}
done = true
// Within two seconds of the clock.
for range 100 {
tt.Advance(20 * time.Millisecond)
if strings.Join(tt.Texts(), "") == strings.TrimSpace(text) {
return
}
}
t.Errorf("not all text showed: %d of %d bytes", len(strings.Join(tt.Texts(), "")), len(text))
}
// TestSelectionSurvivesStreaming selects text of a reply as more of it
// streams in.
func TestSelectionSurvivesStreaming(t *testing.T) {
text := "First paragraph here.\n\nSecond one is being"
o := &Options{Reveal: &Reveal{Unit: AtOnce}}
tt := ui.NewTester(func(c *ui.Context) { Stream(c, text, o) }, 600, 400)
r, _ := tt.Find("First paragraph here.")
tt.ClickAt(r.X+2, r.Y+r.H/2)
tt.Command("selectAll")
text += " written, word by word."
tt.Frame()
tt.Command("copy")
if got := tt.Clipboard(); !strings.HasPrefix(got, "First paragraph here.\n\nSecond one is being") {
t.Errorf("copied %q after streaming", got)
}
}
func TestThemeOverrides(t *testing.T) {
th := &Theme{Link: ui.RGB(255, 0, 0), FontSize: 20}
def := DefaultTheme(ui.LightTheme())
got := resolve(th, def)
if got.Link != th.Link || got.FontSize != 20 || got.Text != def.Text || got.Headings[0].Size != def.Headings[0].Size {
t.Errorf("resolved %+v", got)
}
}
// TestThemeLinkSpans checks that Theme.LinkWeight lifts link text, code
// in a link too, which keeps the code face and wash, and leaves text
// outside links alone.
func TestThemeLinkSpans(t *testing.T) {
o := &Options{Theme: &Theme{LinkWeight: 500}}
th := resolve(o.Theme, DefaultTheme(ui.LightTheme()))
var st *viewState
ui.NewTester(func(c *ui.Context) {
st = *ui.Local(View(c, "Read [the `x.go` docs](https://example.com) and `y.go`.", o), stateKey{}, newState)
}, 400, 100)
var link, linkCode, code *ui.Span
for i := range st.paras {
for _, pc := range st.paras[i].p.pieces {
for k := range pc.spans {
switch s := &pc.spans[k]; s.Text {
case "the ":
link = s
case "x.go":
linkCode = s
case "y.go":
code = s
}
}
}
}
if link == nil || linkCode == nil || code == nil {
t.Fatalf("link or code span missing in %+v", st.paras)
}
if link.Weight != th.LinkWeight {
t.Errorf("link text weighs %d, want %d", link.Weight, th.LinkWeight)
}
if linkCode.Font != th.CodeFont || linkCode.Background != th.CodeBackground || linkCode.Weight != th.LinkWeight {
t.Errorf("code in a link shows %+v, want the code face and wash at %d", *linkCode, th.LinkWeight)
}
if code.Font != th.CodeFont || code.Background != th.CodeBackground || code.Weight == th.LinkWeight {
t.Errorf("code outside a link shows %+v, want the code face and wash at its own weight", *code)
}
}
// TestThemeLink checks that links draw in Theme.Link, not the window
// theme's accent.
func TestThemeLink(t *testing.T) {
o := &Options{Theme: &Theme{Link: ui.RGB(255, 0, 0)}}
tt := ui.NewTester(func(c *ui.Context) { View(c, "plain [a link](https://example.com)", o) }, 300, 80)
img := tt.Image()
acc := ui.LightTheme().Accent
reds, accent := 0, 0
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
r, g, b, _ := img.At(x, y).RGBA()
r, g, b = r>>8, g>>8, b>>8
if r > 200 && g < 60 && b < 60 {
reds++
}
if r == uint32(acc.R) && g == uint32(acc.G) && b == uint32(acc.B) {
accent++
}
}
}
if reds == 0 || accent > 0 {
t.Errorf("%d pixels in Theme.Link, %d in the window theme's accent", reds, accent)
}
}
func TestSlug(t *testing.T) {
for in, want := range map[string]string{"Hello, World!": "hello-world", "API v2 — notes": "api-v2--notes", "foo_bar-baz": "foo_bar-baz"} {
if got := Slug(in); got != want {
t.Errorf("Slug(%q) = %q, want %q", in, got, want)
}
}
}
// TestFadeOrder checks that text revealed later is more transparent.
func TestFadeOrder(t *testing.T) {
now := time.Now()
rs := revealState{marks: []revealMark{{0, now.Add(-250 * time.Millisecond)}, {5, now.Add(-150 * time.Millisecond)}, {8, now.Add(-20 * time.Millisecond)}}}
f := rs.fadeAt(now, false, nil)
a, b, c := f(1), f(6), f(9)
if !(a > b && b > c) {
t.Errorf("opacities %v %v %v, want decreasing", a, b, c)
}
if f(100) != c {
t.Errorf("text after the last mark: %v", f(100))
}
}
// TestFadeReplayed streams anew, a paragraph at a time, text the view
// showed whole, and checks that the text fades in all the same.
func TestFadeReplayed(t *testing.T) {
const src = "First paragraph here.\n\n1. An item\n2. Another\n\nLast one.\n"
text, done := src, true
o := &Options{Reveal: &Reveal{Unit: ByParagraph}}
var st *viewState
tt := ui.NewTester(func(c *ui.Context) {
var root ui.Element
if done {
root = View(c, text, o)
} else {
root = Stream(c, text, o)
}
st = *ui.Local(root, stateKey{}, newState)
}, 600, 400)
text, done = "", false
tt.Frame()
text = src
tt.Frame()
faded := false
for range 20 {
tt.Advance(10 * time.Millisecond)
for i := range st.paras {
for _, pc := range st.paras[i].p.pieces {
for _, s := range pc.spans {
faded = faded || s.Color.A > 0 && s.Color.A < 200
}
}
}
}
if !faded {
t.Error("text streamed again did not fade in")
}
}
func TestSentenceEnds(t *testing.T) {
for _, c := range []struct {
src string
want int
}{
{"Pi is 3.14 today. Next", len("Pi is 3.14 today. ")},
{`He said "go." Then`, len(`He said "go." `)},
{"Really? Yes", len("Really? ")},
{"一句话。下一句", len("一句话。")},
{"- an item\n- next", len("- an item\n")},
{"Not done yet", -1},
{"Ends here.", -1}, // the space after it has not come
} {
if got := unitEnd(c.src, 0, len(c.src), BySentence); got != c.want {
t.Errorf("%q: sentence ends at %d, want %d", c.src, got, c.want)
}
}
}
// TestRevealBySentence checks that Stream by sentence shows only the
// sentences complete while more is coming, and all once done.
func TestSnapByWordCJK(t *testing.T) {
src := "Go语言 is 今日は。"
for _, c := range []struct{ i, want int }{
{0, 2}, // "Go", up to 语
{1, 2}, // in "Go"
{2, 5}, // 语
{3, 5}, // inside 语
{5, 9}, // 言 and the space after it
{9, 12}, // "is "
{12, 15},
{15, 18},
{18, 21},
{21, 24}, // 。
} {
if got := snap(src, c.i, len(src), ByWord); got != c.want {
t.Errorf("snap(%d) = %d, want %d", c.i, got, c.want)
}
}
}
// TestRevealCJKByWord streams Chinese in bursts, as a model's replies
// come over a network: ByWord shows it a character or two at a time, not
// each burst at once, as it shows English a word at a time (#668).
func TestRevealCJKByWord(t *testing.T) {
zh := []rune(strings.Repeat("今天天气很好,我们去公园散步,看到了很多鸟在树上唱歌。", 4))
const burst = 30
text := ""
tt := ui.NewTester(func(c *ui.Context) {
ui.Column(c).Fill().Padding(10).Children(func() { Stream(c, text, &Options{}) })
}, 600, 400)
tt.Frame()
shown, steps, biggest := 0, 0, 0
for fed, frame := 0, 0; shown < len(zh) && frame < 600; frame++ {
if frame%12 == 0 && fed < len(zh) { // a burst every 12 frames
fed = min(fed+burst, len(zh))
text = string(zh[:fed])
tt.Frame()
}
tt.Advance(16 * time.Millisecond)
if n := utf8.RuneCountInString(strings.Join(tt.Texts(), "")); n != shown {
steps, biggest, shown = steps+1, max(biggest, n-shown), n
}
}
if shown != len(zh) {
t.Fatalf("showed %d of %d runes", shown, len(zh))
}
t.Logf("%d visible changes, the largest %d runes", steps, biggest)
if biggest > 4 || steps < len(zh)/4 {
t.Errorf("%d visible changes, the largest %d runes: CJK came in bursts", steps, biggest)
}
}
func TestRevealBySentence(t *testing.T) {
text, done := "", false
o := &Options{Reveal: &Reveal{Unit: BySentence, CatchUp: time.Millisecond}}
tt := ui.NewTester(func(c *ui.Context) {
if done {
View(c, text, o)
} else {
Stream(c, text, o)
}
}, 600, 400)
text = "First sentence here. Second one is still"
tt.Frame()
tt.Advance(100 * time.Millisecond)
if got := strings.Join(tt.Texts(), ""); got != "First sentence here." {
t.Errorf("streaming shows %q", got)
}
done = true
tt.Frame()
tt.Advance(100 * time.Millisecond)
if got := strings.Join(tt.Texts(), ""); got != text {
t.Errorf("done, shows %q", got)
}
}