| 1 | package markup |
| 2 | |
| 3 | import ( |
| 4 | "net/url" |
| 5 | "regexp" |
| 6 | "strings" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // Kinds of span. |
| 11 | const ( |
| 12 | Text = "text" |
| 13 | InCode = "code" |
| 14 | WikiLink = "wiki" |
| 15 | WebLink = "web" |
| 16 | // Embed is `![[app:item]]`. Slice 1 has no embeds (Paul, |
| 17 | // 2026-11-12), so it renders as the text that was typed; slice 2 |
| 18 | // resolves it through S10. |
| 19 | Embed = "embed" |
| 20 | // Image is , Mapa's own address and no other |
| 21 | // (images spec §2.1): Text is the alt text, Target the public id and |
| 22 | // URL the address. Every other  is what it always was. |
| 23 | Image = "image" |
| 24 | ) |
| 25 | |
| 26 | // Span is one run of a block's inline text. |
| 27 | type Span struct { |
| 28 | Kind string |
| 29 | // Text is what is shown: the run itself, a link's shown text, or |
| 30 | // the source of an embed. |
| 31 | Text string |
| 32 | // Target is a wiki link's target text exactly as typed, and Anchor |
| 33 | // its ^id when it names a block. URL is a web link's address. |
| 34 | Target, Anchor, URL string |
| 35 | // Source is the span exactly as typed. |
| 36 | Source string |
| 37 | } |
| 38 | |
| 39 | // Link is one [[link]] in a body, with the block it sits in. |
| 40 | type Link struct { |
| 41 | Target, Anchor, Shown string |
| 42 | Block int |
| 43 | } |
| 44 | |
| 45 | var ( |
| 46 | autoLink = regexp.MustCompile( |
| 47 | `^https?://[^\s<>()\[\]]+[^\s<>()\[\].,;:!?'"]`) |
| 48 | isoDate = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}$`) |
| 49 | ) |
| 50 | |
| 51 | // Links is every [[link]] in body, outside code, in order. |
| 52 | func Links(body string) []Link { |
| 53 | return LinksIn(Parse(body)) |
| 54 | } |
| 55 | |
| 56 | // LinksIn is Links over blocks already parsed. |
| 57 | func LinksIn(blocks []Block) []Link { |
| 58 | var links []Link |
| 59 | for index, block := range blocks { |
| 60 | if block.Kind == Code { |
| 61 | continue |
| 62 | } |
| 63 | for _, span := range Spans(block.Source) { |
| 64 | if span.Kind == WikiLink { |
| 65 | links = append(links, Link{Target: span.Target, |
| 66 | Anchor: span.Anchor, Shown: span.Text, Block: index}) |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | return links |
| 71 | } |
| 72 | |
| 73 | // Spans splits inline text into runs. Emphasis stays inside Text runs: |
| 74 | // the renderer marks it up, and nothing else needs it. |
| 75 | func Spans(text string) []Span { |
| 76 | var spans []Span |
| 77 | var plain strings.Builder |
| 78 | flush := func() { |
| 79 | if plain.Len() > 0 { |
| 80 | spans = append(spans, Span{Kind: Text, Text: plain.String(), |
| 81 | Source: plain.String()}) |
| 82 | plain.Reset() |
| 83 | } |
| 84 | } |
| 85 | scanned := newScan(text) |
| 86 | for index := 0; index < len(text); { |
| 87 | span, width := spanAt(scanned, index) |
| 88 | if width == 0 { |
| 89 | plain.WriteByte(text[index]) |
| 90 | index++ |
| 91 | continue |
| 92 | } |
| 93 | flush() |
| 94 | span.Source = text[index : index+width] |
| 95 | spans = append(spans, span) |
| 96 | index += width |
| 97 | } |
| 98 | flush() |
| 99 | return spans |
| 100 | } |
| 101 | |
| 102 | // spanAt reads a span starting at text[index], or reports width 0. |
| 103 | func spanAt(scanned *scan, index int) (Span, int) { |
| 104 | text := scanned.text |
| 105 | rest := text[index:] |
| 106 | switch { |
| 107 | case rest[0] == '`': |
| 108 | return codeSpan(rest) |
| 109 | case strings.HasPrefix(rest, "![["): |
| 110 | if end := scanned.closing(index + 3); end >= 0 { |
| 111 | return Span{Kind: Embed, Text: rest[:end+5]}, end + 5 |
| 112 | } |
| 113 | case strings.HasPrefix(rest, "!["): |
| 114 | return imageSpan(scanned, index) |
| 115 | case strings.HasPrefix(rest, "[["): |
| 116 | return wikiSpan(scanned, index) |
| 117 | case rest[0] == '[': |
| 118 | if label, address, ok := scanned.webLink(index); ok && |
| 119 | LinkAddress(address) { |
| 120 | return Span{Kind: WebLink, Text: label, URL: address}, |
| 121 | len(label) + len(address) + 4 |
| 122 | } |
| 123 | case rest[0] == 'h' && wordStart(text, index): |
| 124 | if match := autoLink.FindString(rest); match != "" { |
| 125 | return Span{Kind: WebLink, Text: match, URL: match}, len(match) |
| 126 | } |
| 127 | } |
| 128 | return Span{}, 0 |
| 129 | } |
| 130 | |
| 131 | func codeSpan(rest string) (Span, int) { |
| 132 | end := strings.IndexByte(rest[1:], '`') |
| 133 | if end <= 0 { |
| 134 | return Span{}, 0 |
| 135 | } |
| 136 | return Span{Kind: InCode, Text: rest[1 : end+1]}, end + 2 |
| 137 | } |
| 138 | |
| 139 | func wikiSpan(scanned *scan, index int) (Span, int) { |
| 140 | end := scanned.closing(index + 2) |
| 141 | if end < 0 { |
| 142 | return Span{}, 0 |
| 143 | } |
| 144 | inner := scanned.text[index+2 : index+end+2] |
| 145 | target, shown, _ := strings.Cut(inner, "|") |
| 146 | target, anchor, _ := strings.Cut(target, "#") |
| 147 | target = strings.TrimSpace(target) |
| 148 | if target == "" { |
| 149 | return Span{}, 0 |
| 150 | } |
| 151 | span := Span{Kind: WikiLink, Target: target, Text: strings.TrimSpace( |
| 152 | shown)} |
| 153 | if strings.HasPrefix(anchor, "^") { |
| 154 | span.Anchor = strings.TrimSpace(anchor[1:]) |
| 155 | } |
| 156 | return span, end + 4 |
| 157 | } |
| 158 | |
| 159 | func wordStart(text string, index int) bool { |
| 160 | return index == 0 || strings.ContainsRune(" \t\n(", rune(text[index-1])) |
| 161 | } |
| 162 | |
| 163 | // MaxAddress is the longest address a [label](address) link may have: |
| 164 | // longer is text. Without a bound, a line of "[x](" repeated, closed |
| 165 | // once at its end, parsed one shared address per [, the whole rest of |
| 166 | // the line each time: quadratic (Fable's round-2 M1). The editor's port |
| 167 | // holds the same bound (editor/safeurl.mjs), and the golden corpus a |
| 168 | // case either side of it. |
| 169 | const MaxAddress = 2048 |
| 170 | |
| 171 | // LinkAddress is a [label](address) link's address test: at most |
| 172 | // MaxAddress bytes, an http, https or mailto scheme by its first bytes, |
| 173 | // then SafeURL. The cheap tests come first, so testing every candidate |
| 174 | // in a line costs no more than the line. |
| 175 | func LinkAddress(address string) bool { |
| 176 | if len(address) > MaxAddress { |
| 177 | return false |
| 178 | } |
| 179 | head := strings.ToLower(address[:min(len(address), 8)]) |
| 180 | if !strings.HasPrefix(head, "http://") && |
| 181 | !strings.HasPrefix(head, "https://") && |
| 182 | !strings.HasPrefix(head, "mailto:") { |
| 183 | return false |
| 184 | } |
| 185 | return SafeURL(address) |
| 186 | } |
| 187 | |
| 188 | // SafeURL is an author link Mapa will make clickable: http, https or |
| 189 | // mailto, with a host for the web ones. Everything else (javascript:, |
| 190 | // data: and the rest) stays text. So does a bracketed IP literal |
| 191 | // (http://[::1]/): editor/markup.mjs ports this rule, and that is the one |
| 192 | // part of net/url it would have to reimplement whole (netip's parser). |
| 193 | func SafeURL(raw string) bool { |
| 194 | parsed, err := url.Parse(raw) |
| 195 | if err != nil { |
| 196 | return false |
| 197 | } |
| 198 | switch strings.ToLower(parsed.Scheme) { |
| 199 | case "http", "https": |
| 200 | return parsed.Host != "" && !strings.HasPrefix(parsed.Host, "[") |
| 201 | case "mailto": |
| 202 | return parsed.Opaque != "" |
| 203 | } |
| 204 | return false |
| 205 | } |
| 206 | |
| 207 | // IsDateShaped is link text reserved for daily notes (§3.4): an ISO date |
| 208 | // shape and nothing else. A title or alias of this shape is refused, even |
| 209 | // when it is not a real date. |
| 210 | func IsDateShaped(text string) bool { return isoDate.MatchString(text) } |
| 211 | |
| 212 | // IsDate is a date-shaped text that is a real calendar date. |
| 213 | func IsDate(text string) bool { |
| 214 | if !IsDateShaped(text) { |
| 215 | return false |
| 216 | } |
| 217 | _, err := time.Parse(time.DateOnly, text) |
| 218 | return err == nil |
| 219 | } |
| 220 | |
| 221 | // Retarget rewrites every [[link]] whose target matches to point at |
| 222 | // target instead, keeping its ^id and shown text, and touching nothing |
| 223 | // else in body. It returns the new body and how many links changed. |
| 224 | // "Update links to the new title" (§3.4) is this, run by the person. |
| 225 | func Retarget(body string, matches func(string) bool, |
| 226 | target string) (string, int) { |
| 227 | blocks := Parse(body) |
| 228 | change := map[int]string{} |
| 229 | changed := 0 |
| 230 | for index, block := range blocks { |
| 231 | if block.Kind == Code { |
| 232 | continue |
| 233 | } |
| 234 | var out strings.Builder |
| 235 | count := 0 |
| 236 | for _, span := range Spans(block.Source) { |
| 237 | if span.Kind == WikiLink && matches(span.Target) { |
| 238 | out.WriteString(wikiSource(target, span)) |
| 239 | count++ |
| 240 | continue |
| 241 | } |
| 242 | out.WriteString(span.Source) |
| 243 | } |
| 244 | if count > 0 { |
| 245 | change[index] = out.String() |
| 246 | changed += count |
| 247 | } |
| 248 | } |
| 249 | return Replace(body, blocks, change), changed |
| 250 | } |
| 251 | |
| 252 | func wikiSource(target string, span Span) string { |
| 253 | link := "[[" + target |
| 254 | if span.Anchor != "" { |
| 255 | link += "#^" + span.Anchor |
| 256 | } |
| 257 | if span.Text != "" { |
| 258 | link += "|" + span.Text |
| 259 | } |
| 260 | return link + "]]" |
| 261 | } |
| 262 | |
| 263 | // OpensAt answers, for an index of text holding a [, whether a span |
| 264 | // other than plain text starts there when text is read from that index: |
| 265 | // a web link, a wiki link or an embed. One scan's tables serve every |
| 266 | // index, so asking at each [ of a line is linear. Spans(text[at:]) at |
| 267 | // each [ was quadratic, and a line of 32,000 [ took half a minute to |
| 268 | // neutralise (the Notion mapper's §11.4 table; Fable M2). |
| 269 | func OpensAt(text string) func(int) bool { |
| 270 | scanned := newScan(text) |
| 271 | return func(index int) bool { |
| 272 | if index < 0 || index >= len(text) { |
| 273 | return false |
| 274 | } |
| 275 | _, width := spanAt(scanned, index) |
| 276 | return width > 0 |
| 277 | } |
| 278 | } |
| 279 | |