| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "unicode" |
| 6 | "unicode/utf8" |
| 7 | |
| 8 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 9 | ) |
| 10 | |
| 11 | // word is one word of a text: folded for comparison, with its byte span |
| 12 | // in the original so a match can be edited in place ("Link it", §6.4). |
| 13 | type word struct { |
| 14 | fold string |
| 15 | start, end int |
| 16 | } |
| 17 | |
| 18 | // wordsOf splits text into words: runs of letters and digits. Search, |
| 19 | // unlinked mentions and title matching all count words this one way. |
| 20 | func wordsOf(text string) []word { |
| 21 | var found []word |
| 22 | start := -1 |
| 23 | for index, char := range text { |
| 24 | inside := unicode.IsLetter(char) || unicode.IsDigit(char) || |
| 25 | unicode.Is(unicode.Mn, char) |
| 26 | switch { |
| 27 | case inside && start < 0: |
| 28 | start = index |
| 29 | case !inside && start >= 0: |
| 30 | found = append(found, word{fold: Fold(text[start:index]), |
| 31 | start: start, end: index}) |
| 32 | start = -1 |
| 33 | } |
| 34 | } |
| 35 | if start >= 0 { |
| 36 | found = append(found, word{fold: Fold(text[start:]), start: start, |
| 37 | end: len(text)}) |
| 38 | } |
| 39 | return found |
| 40 | } |
| 41 | |
| 42 | // folds is the folded words of text. |
| 43 | func folds(text string) []string { |
| 44 | found := wordsOf(text) |
| 45 | out := make([]string, len(found)) |
| 46 | for index, item := range found { |
| 47 | out[index] = item.fold |
| 48 | } |
| 49 | return out |
| 50 | } |
| 51 | |
| 52 | // phraseAt finds phrase, as whole words, in text's words, and returns its |
| 53 | // byte span, or -1. Case, accents and the space between words do not |
| 54 | // matter; word boundaries do. |
| 55 | func phraseAt(text []word, phrase []string) (int, int) { |
| 56 | if len(phrase) == 0 { |
| 57 | return -1, -1 |
| 58 | } |
| 59 | for start := 0; start+len(phrase) <= len(text); start++ { |
| 60 | matched := true |
| 61 | for offset, want := range phrase { |
| 62 | if text[start+offset].fold != want { |
| 63 | matched = false |
| 64 | break |
| 65 | } |
| 66 | } |
| 67 | if matched { |
| 68 | return text[start].start, text[start+len(phrase)-1].end |
| 69 | } |
| 70 | } |
| 71 | return -1, -1 |
| 72 | } |
| 73 | |
| 74 | // firstLine is a scratch page's label: its first non-empty line, cut. |
| 75 | func firstLine(blocks []markup.Block) string { |
| 76 | for _, block := range blocks { |
| 77 | text := strings.TrimSpace(markup.Words(block)) |
| 78 | line, _, _ := strings.Cut(text, "\n") |
| 79 | if line = strings.TrimSpace(line); line != "" { |
| 80 | return cut(line, 80) |
| 81 | } |
| 82 | } |
| 83 | return "" |
| 84 | } |
| 85 | |
| 86 | func cut(text string, limit int) string { |
| 87 | if utf8.RuneCountInString(text) <= limit { |
| 88 | return text |
| 89 | } |
| 90 | runes := []rune(text) |
| 91 | return string(runes[:limit-1]) + "…" |
| 92 | } |
| 93 | |