| 🛟 Updated. 28d5985 k33g 18h ago | 1 | package theme |
| 2 | |
| 3 | import ( |
| 4 | "sort" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/gdamore/tcell/v2" |
| 8 | ) |
| 9 | |
| 10 | // Theme maps style keys to the styles the editor draws with. |
| 11 | // |
| 12 | // Use Style to read a key: it falls back along the dots, so asking for |
| 13 | // "syntax.keyword" in a theme that only defines "syntax" gets the latter, and |
| 14 | // a theme that defines neither gets KeyDefault. |
| 15 | type Theme struct { |
| 16 | name string |
| 17 | description string |
| 18 | styles map[string]tcell.Style |
| 19 | } |
| 20 | |
| 21 | // Name returns the theme's display name, which is what the Options menu lists. |
| 22 | func (t *Theme) Name() string { return t.name } |
| 23 | |
| 24 | // Description returns the one-line description from the theme file, or the |
| 25 | // empty string when it has none. |
| 26 | func (t *Theme) Description() string { return t.description } |
| 27 | |
| 28 | // Style returns the style for a key, falling back along the dots and finally |
| 29 | // onto KeyDefault. |
| 30 | // |
| 31 | // s := th.Style(theme.KeySyntaxKeyword) |
| 32 | // // a theme defining only "syntax" answers that; one defining neither |
| 33 | // // answers "default". |
| 34 | func (t *Theme) Style(key string) tcell.Style { |
| 35 | for { |
| 36 | if style, ok := t.styles[key]; ok { |
| 37 | return style |
| 38 | } |
| 39 | dot := strings.LastIndexByte(key, '.') |
| 40 | if dot < 0 { |
| 41 | break |
| 42 | } |
| 43 | key = key[:dot] |
| 44 | } |
| 45 | return t.styles[KeyDefault] |
| 46 | } |
| 47 | |
| 48 | // Keys returns every key the theme defines, sorted. It exists for tooling and |
| 49 | // for tests that check a theme file is complete. |
| 50 | func (t *Theme) Keys() []string { |
| 51 | keys := make([]string, 0, len(t.styles)) |
| 52 | for key := range t.styles { |
| 53 | keys = append(keys, key) |
| 54 | } |
| 55 | sort.Strings(keys) |
| 56 | return keys |
| 57 | } |
| 58 | |
| 59 | // Defines reports whether the theme sets this exact key, without any fallback. |
| 60 | func (t *Theme) Defines(key string) bool { |
| 61 | _, ok := t.styles[key] |
| 62 | return ok |
| 63 | } |
| 64 | |
| 65 | // fallbackStyle is what a theme resolves to before any file is read: white on |
| 66 | // black, which stays legible on every terminal. |
| 67 | func fallbackStyle() tcell.Style { |
| 68 | return tcell.StyleDefault. |
| 69 | Foreground(tcell.ColorWhite). |
| 70 | Background(tcell.ColorBlack) |
| 71 | } |