initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-22 13:21:28 +02:00
commit 156bb18c91
50 files changed
+13466

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
// Package colors parses colors the way Ghostty does: hex values (with or
// without a leading '#', 3 or 6 digits) and X11 color names.
package colors
import (
"bufio"
_ "embed"
"fmt"
"strconv"
"strings"
"sync"
)
// rgb.txt is copied from Ghostty's src/terminal/res/rgb.txt.
//
//go:embed rgb.txt
var rgbTxt string
var (
namesOnce sync.Once
names map[string]string // lowercase name -> "#rrggbb"
)
func loadNames() {
names = make(map[string]string, 800)
sc := bufio.NewScanner(strings.NewReader(rgbTxt))
for sc.Scan() {
line := sc.Text()
if strings.HasPrefix(line, "!") || strings.TrimSpace(line) == "" {
continue
}
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
r, err1 := strconv.Atoi(fields[0])
g, err2 := strconv.Atoi(fields[1])
b, err3 := strconv.Atoi(fields[2])
if err1 != nil || err2 != nil || err3 != nil {
continue
}
name := strings.ToLower(strings.Join(fields[3:], " "))
names[name] = fmt.Sprintf("#%02x%02x%02x", r, g, b)
}
}
// Hex converts a Ghostty color value to "#rrggbb". It reports false if the
// value is not a valid color.
func Hex(value string) (string, bool) {
v := strings.TrimSpace(unquote(value))
if v == "" {
return "", false
}
namesOnce.Do(loadNames)
if h, ok := names[strings.ToLower(v)]; ok {
return h, true
}
h := strings.TrimPrefix(v, "#")
if !isHex(h) {
return "", false
}
switch len(h) {
case 3:
return strings.ToLower("#" + string([]byte{h[0], h[0], h[1], h[1], h[2], h[2]})), true
case 6:
return strings.ToLower("#" + h), true
}
return "", false
}
// Valid reports whether value is a color Ghostty accepts.
func Valid(value string) bool {
_, ok := Hex(value)
return ok
}
// RGB returns the components of a color value.
func RGB(value string) (r, g, b uint8, ok bool) {
h, ok := Hex(value)
if !ok {
return 0, 0, 0, false
}
n, err := strconv.ParseUint(h[1:], 16, 32)
if err != nil {
return 0, 0, 0, false
}
return uint8(n >> 16), uint8(n >> 8), uint8(n), true
}
// Luminance returns the relative brightness in the range 0..1, used to pick
// a readable text color on top of a swatch.
func Luminance(value string) float64 {
r, g, b, ok := RGB(value)
if !ok {
return 0
}
return (0.299*float64(r) + 0.587*float64(g) + 0.114*float64(b)) / 255
}
func isHex(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return false
}
}
return true
}
func unquote(s string) string {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}
+782
View File
@@ -0,0 +1,782 @@
255 250 250 snow
248 248 255 ghost white
248 248 255 GhostWhite
245 245 245 white smoke
245 245 245 WhiteSmoke
220 220 220 gainsboro
255 250 240 floral white
255 250 240 FloralWhite
253 245 230 old lace
253 245 230 OldLace
250 240 230 linen
250 235 215 antique white
250 235 215 AntiqueWhite
255 239 213 papaya whip
255 239 213 PapayaWhip
255 235 205 blanched almond
255 235 205 BlanchedAlmond
255 228 196 bisque
255 218 185 peach puff
255 218 185 PeachPuff
255 222 173 navajo white
255 222 173 NavajoWhite
255 228 181 moccasin
255 248 220 cornsilk
255 255 240 ivory
255 250 205 lemon chiffon
255 250 205 LemonChiffon
255 245 238 seashell
240 255 240 honeydew
245 255 250 mint cream
245 255 250 MintCream
240 255 255 azure
240 248 255 alice blue
240 248 255 AliceBlue
230 230 250 lavender
255 240 245 lavender blush
255 240 245 LavenderBlush
255 228 225 misty rose
255 228 225 MistyRose
255 255 255 white
0 0 0 black
47 79 79 dark slate gray
47 79 79 DarkSlateGray
47 79 79 dark slate grey
47 79 79 DarkSlateGrey
105 105 105 dim gray
105 105 105 DimGray
105 105 105 dim grey
105 105 105 DimGrey
112 128 144 slate gray
112 128 144 SlateGray
112 128 144 slate grey
112 128 144 SlateGrey
119 136 153 light slate gray
119 136 153 LightSlateGray
119 136 153 light slate grey
119 136 153 LightSlateGrey
190 190 190 gray
190 190 190 grey
190 190 190 x11 gray
190 190 190 X11Gray
190 190 190 x11 grey
190 190 190 X11Grey
128 128 128 web gray
128 128 128 WebGray
128 128 128 web grey
128 128 128 WebGrey
211 211 211 light grey
211 211 211 LightGrey
211 211 211 light gray
211 211 211 LightGray
25 25 112 midnight blue
25 25 112 MidnightBlue
0 0 128 navy
0 0 128 navy blue
0 0 128 NavyBlue
100 149 237 cornflower blue
100 149 237 CornflowerBlue
72 61 139 dark slate blue
72 61 139 DarkSlateBlue
106 90 205 slate blue
106 90 205 SlateBlue
123 104 238 medium slate blue
123 104 238 MediumSlateBlue
132 112 255 light slate blue
132 112 255 LightSlateBlue
0 0 205 medium blue
0 0 205 MediumBlue
65 105 225 royal blue
65 105 225 RoyalBlue
0 0 255 blue
30 144 255 dodger blue
30 144 255 DodgerBlue
0 191 255 deep sky blue
0 191 255 DeepSkyBlue
135 206 235 sky blue
135 206 235 SkyBlue
135 206 250 light sky blue
135 206 250 LightSkyBlue
70 130 180 steel blue
70 130 180 SteelBlue
176 196 222 light steel blue
176 196 222 LightSteelBlue
173 216 230 light blue
173 216 230 LightBlue
176 224 230 powder blue
176 224 230 PowderBlue
175 238 238 pale turquoise
175 238 238 PaleTurquoise
0 206 209 dark turquoise
0 206 209 DarkTurquoise
72 209 204 medium turquoise
72 209 204 MediumTurquoise
64 224 208 turquoise
0 255 255 cyan
0 255 255 aqua
224 255 255 light cyan
224 255 255 LightCyan
95 158 160 cadet blue
95 158 160 CadetBlue
102 205 170 medium aquamarine
102 205 170 MediumAquamarine
127 255 212 aquamarine
0 100 0 dark green
0 100 0 DarkGreen
85 107 47 dark olive green
85 107 47 DarkOliveGreen
143 188 143 dark sea green
143 188 143 DarkSeaGreen
46 139 87 sea green
46 139 87 SeaGreen
60 179 113 medium sea green
60 179 113 MediumSeaGreen
32 178 170 light sea green
32 178 170 LightSeaGreen
152 251 152 pale green
152 251 152 PaleGreen
0 255 127 spring green
0 255 127 SpringGreen
124 252 0 lawn green
124 252 0 LawnGreen
0 255 0 green
0 255 0 lime
0 255 0 x11 green
0 255 0 X11Green
0 128 0 web green
0 128 0 WebGreen
127 255 0 chartreuse
0 250 154 medium spring green
0 250 154 MediumSpringGreen
173 255 47 green yellow
173 255 47 GreenYellow
50 205 50 lime green
50 205 50 LimeGreen
154 205 50 yellow green
154 205 50 YellowGreen
34 139 34 forest green
34 139 34 ForestGreen
107 142 35 olive drab
107 142 35 OliveDrab
189 183 107 dark khaki
189 183 107 DarkKhaki
240 230 140 khaki
238 232 170 pale goldenrod
238 232 170 PaleGoldenrod
250 250 210 light goldenrod yellow
250 250 210 LightGoldenrodYellow
255 255 224 light yellow
255 255 224 LightYellow
255 255 0 yellow
255 215 0 gold
238 221 130 light goldenrod
238 221 130 LightGoldenrod
218 165 32 goldenrod
184 134 11 dark goldenrod
184 134 11 DarkGoldenrod
188 143 143 rosy brown
188 143 143 RosyBrown
205 92 92 indian red
205 92 92 IndianRed
139 69 19 saddle brown
139 69 19 SaddleBrown
160 82 45 sienna
205 133 63 peru
222 184 135 burlywood
245 245 220 beige
245 222 179 wheat
244 164 96 sandy brown
244 164 96 SandyBrown
210 180 140 tan
210 105 30 chocolate
178 34 34 firebrick
165 42 42 brown
233 150 122 dark salmon
233 150 122 DarkSalmon
250 128 114 salmon
255 160 122 light salmon
255 160 122 LightSalmon
255 165 0 orange
255 140 0 dark orange
255 140 0 DarkOrange
255 127 80 coral
240 128 128 light coral
240 128 128 LightCoral
255 99 71 tomato
255 69 0 orange red
255 69 0 OrangeRed
255 0 0 red
255 105 180 hot pink
255 105 180 HotPink
255 20 147 deep pink
255 20 147 DeepPink
255 192 203 pink
255 182 193 light pink
255 182 193 LightPink
219 112 147 pale violet red
219 112 147 PaleVioletRed
176 48 96 maroon
176 48 96 x11 maroon
176 48 96 X11Maroon
128 0 0 web maroon
128 0 0 WebMaroon
199 21 133 medium violet red
199 21 133 MediumVioletRed
208 32 144 violet red
208 32 144 VioletRed
255 0 255 magenta
255 0 255 fuchsia
238 130 238 violet
221 160 221 plum
218 112 214 orchid
186 85 211 medium orchid
186 85 211 MediumOrchid
153 50 204 dark orchid
153 50 204 DarkOrchid
148 0 211 dark violet
148 0 211 DarkViolet
138 43 226 blue violet
138 43 226 BlueViolet
160 32 240 purple
160 32 240 x11 purple
160 32 240 X11Purple
128 0 128 web purple
128 0 128 WebPurple
147 112 219 medium purple
147 112 219 MediumPurple
216 191 216 thistle
255 250 250 snow1
238 233 233 snow2
205 201 201 snow3
139 137 137 snow4
255 245 238 seashell1
238 229 222 seashell2
205 197 191 seashell3
139 134 130 seashell4
255 239 219 AntiqueWhite1
238 223 204 AntiqueWhite2
205 192 176 AntiqueWhite3
139 131 120 AntiqueWhite4
255 228 196 bisque1
238 213 183 bisque2
205 183 158 bisque3
139 125 107 bisque4
255 218 185 PeachPuff1
238 203 173 PeachPuff2
205 175 149 PeachPuff3
139 119 101 PeachPuff4
255 222 173 NavajoWhite1
238 207 161 NavajoWhite2
205 179 139 NavajoWhite3
139 121 94 NavajoWhite4
255 250 205 LemonChiffon1
238 233 191 LemonChiffon2
205 201 165 LemonChiffon3
139 137 112 LemonChiffon4
255 248 220 cornsilk1
238 232 205 cornsilk2
205 200 177 cornsilk3
139 136 120 cornsilk4
255 255 240 ivory1
238 238 224 ivory2
205 205 193 ivory3
139 139 131 ivory4
240 255 240 honeydew1
224 238 224 honeydew2
193 205 193 honeydew3
131 139 131 honeydew4
255 240 245 LavenderBlush1
238 224 229 LavenderBlush2
205 193 197 LavenderBlush3
139 131 134 LavenderBlush4
255 228 225 MistyRose1
238 213 210 MistyRose2
205 183 181 MistyRose3
139 125 123 MistyRose4
240 255 255 azure1
224 238 238 azure2
193 205 205 azure3
131 139 139 azure4
131 111 255 SlateBlue1
122 103 238 SlateBlue2
105 89 205 SlateBlue3
71 60 139 SlateBlue4
72 118 255 RoyalBlue1
67 110 238 RoyalBlue2
58 95 205 RoyalBlue3
39 64 139 RoyalBlue4
0 0 255 blue1
0 0 238 blue2
0 0 205 blue3
0 0 139 blue4
30 144 255 DodgerBlue1
28 134 238 DodgerBlue2
24 116 205 DodgerBlue3
16 78 139 DodgerBlue4
99 184 255 SteelBlue1
92 172 238 SteelBlue2
79 148 205 SteelBlue3
54 100 139 SteelBlue4
0 191 255 DeepSkyBlue1
0 178 238 DeepSkyBlue2
0 154 205 DeepSkyBlue3
0 104 139 DeepSkyBlue4
135 206 255 SkyBlue1
126 192 238 SkyBlue2
108 166 205 SkyBlue3
74 112 139 SkyBlue4
176 226 255 LightSkyBlue1
164 211 238 LightSkyBlue2
141 182 205 LightSkyBlue3
96 123 139 LightSkyBlue4
198 226 255 SlateGray1
185 211 238 SlateGray2
159 182 205 SlateGray3
108 123 139 SlateGray4
202 225 255 LightSteelBlue1
188 210 238 LightSteelBlue2
162 181 205 LightSteelBlue3
110 123 139 LightSteelBlue4
191 239 255 LightBlue1
178 223 238 LightBlue2
154 192 205 LightBlue3
104 131 139 LightBlue4
224 255 255 LightCyan1
209 238 238 LightCyan2
180 205 205 LightCyan3
122 139 139 LightCyan4
187 255 255 PaleTurquoise1
174 238 238 PaleTurquoise2
150 205 205 PaleTurquoise3
102 139 139 PaleTurquoise4
152 245 255 CadetBlue1
142 229 238 CadetBlue2
122 197 205 CadetBlue3
83 134 139 CadetBlue4
0 245 255 turquoise1
0 229 238 turquoise2
0 197 205 turquoise3
0 134 139 turquoise4
0 255 255 cyan1
0 238 238 cyan2
0 205 205 cyan3
0 139 139 cyan4
151 255 255 DarkSlateGray1
141 238 238 DarkSlateGray2
121 205 205 DarkSlateGray3
82 139 139 DarkSlateGray4
127 255 212 aquamarine1
118 238 198 aquamarine2
102 205 170 aquamarine3
69 139 116 aquamarine4
193 255 193 DarkSeaGreen1
180 238 180 DarkSeaGreen2
155 205 155 DarkSeaGreen3
105 139 105 DarkSeaGreen4
84 255 159 SeaGreen1
78 238 148 SeaGreen2
67 205 128 SeaGreen3
46 139 87 SeaGreen4
154 255 154 PaleGreen1
144 238 144 PaleGreen2
124 205 124 PaleGreen3
84 139 84 PaleGreen4
0 255 127 SpringGreen1
0 238 118 SpringGreen2
0 205 102 SpringGreen3
0 139 69 SpringGreen4
0 255 0 green1
0 238 0 green2
0 205 0 green3
0 139 0 green4
127 255 0 chartreuse1
118 238 0 chartreuse2
102 205 0 chartreuse3
69 139 0 chartreuse4
192 255 62 OliveDrab1
179 238 58 OliveDrab2
154 205 50 OliveDrab3
105 139 34 OliveDrab4
202 255 112 DarkOliveGreen1
188 238 104 DarkOliveGreen2
162 205 90 DarkOliveGreen3
110 139 61 DarkOliveGreen4
255 246 143 khaki1
238 230 133 khaki2
205 198 115 khaki3
139 134 78 khaki4
255 236 139 LightGoldenrod1
238 220 130 LightGoldenrod2
205 190 112 LightGoldenrod3
139 129 76 LightGoldenrod4
255 255 224 LightYellow1
238 238 209 LightYellow2
205 205 180 LightYellow3
139 139 122 LightYellow4
255 255 0 yellow1
238 238 0 yellow2
205 205 0 yellow3
139 139 0 yellow4
255 215 0 gold1
238 201 0 gold2
205 173 0 gold3
139 117 0 gold4
255 193 37 goldenrod1
238 180 34 goldenrod2
205 155 29 goldenrod3
139 105 20 goldenrod4
255 185 15 DarkGoldenrod1
238 173 14 DarkGoldenrod2
205 149 12 DarkGoldenrod3
139 101 8 DarkGoldenrod4
255 193 193 RosyBrown1
238 180 180 RosyBrown2
205 155 155 RosyBrown3
139 105 105 RosyBrown4
255 106 106 IndianRed1
238 99 99 IndianRed2
205 85 85 IndianRed3
139 58 58 IndianRed4
255 130 71 sienna1
238 121 66 sienna2
205 104 57 sienna3
139 71 38 sienna4
255 211 155 burlywood1
238 197 145 burlywood2
205 170 125 burlywood3
139 115 85 burlywood4
255 231 186 wheat1
238 216 174 wheat2
205 186 150 wheat3
139 126 102 wheat4
255 165 79 tan1
238 154 73 tan2
205 133 63 tan3
139 90 43 tan4
255 127 36 chocolate1
238 118 33 chocolate2
205 102 29 chocolate3
139 69 19 chocolate4
255 48 48 firebrick1
238 44 44 firebrick2
205 38 38 firebrick3
139 26 26 firebrick4
255 64 64 brown1
238 59 59 brown2
205 51 51 brown3
139 35 35 brown4
255 140 105 salmon1
238 130 98 salmon2
205 112 84 salmon3
139 76 57 salmon4
255 160 122 LightSalmon1
238 149 114 LightSalmon2
205 129 98 LightSalmon3
139 87 66 LightSalmon4
255 165 0 orange1
238 154 0 orange2
205 133 0 orange3
139 90 0 orange4
255 127 0 DarkOrange1
238 118 0 DarkOrange2
205 102 0 DarkOrange3
139 69 0 DarkOrange4
255 114 86 coral1
238 106 80 coral2
205 91 69 coral3
139 62 47 coral4
255 99 71 tomato1
238 92 66 tomato2
205 79 57 tomato3
139 54 38 tomato4
255 69 0 OrangeRed1
238 64 0 OrangeRed2
205 55 0 OrangeRed3
139 37 0 OrangeRed4
255 0 0 red1
238 0 0 red2
205 0 0 red3
139 0 0 red4
255 20 147 DeepPink1
238 18 137 DeepPink2
205 16 118 DeepPink3
139 10 80 DeepPink4
255 110 180 HotPink1
238 106 167 HotPink2
205 96 144 HotPink3
139 58 98 HotPink4
255 181 197 pink1
238 169 184 pink2
205 145 158 pink3
139 99 108 pink4
255 174 185 LightPink1
238 162 173 LightPink2
205 140 149 LightPink3
139 95 101 LightPink4
255 130 171 PaleVioletRed1
238 121 159 PaleVioletRed2
205 104 137 PaleVioletRed3
139 71 93 PaleVioletRed4
255 52 179 maroon1
238 48 167 maroon2
205 41 144 maroon3
139 28 98 maroon4
255 62 150 VioletRed1
238 58 140 VioletRed2
205 50 120 VioletRed3
139 34 82 VioletRed4
255 0 255 magenta1
238 0 238 magenta2
205 0 205 magenta3
139 0 139 magenta4
255 131 250 orchid1
238 122 233 orchid2
205 105 201 orchid3
139 71 137 orchid4
255 187 255 plum1
238 174 238 plum2
205 150 205 plum3
139 102 139 plum4
224 102 255 MediumOrchid1
209 95 238 MediumOrchid2
180 82 205 MediumOrchid3
122 55 139 MediumOrchid4
191 62 255 DarkOrchid1
178 58 238 DarkOrchid2
154 50 205 DarkOrchid3
104 34 139 DarkOrchid4
155 48 255 purple1
145 44 238 purple2
125 38 205 purple3
85 26 139 purple4
171 130 255 MediumPurple1
159 121 238 MediumPurple2
137 104 205 MediumPurple3
93 71 139 MediumPurple4
255 225 255 thistle1
238 210 238 thistle2
205 181 205 thistle3
139 123 139 thistle4
0 0 0 gray0
0 0 0 grey0
3 3 3 gray1
3 3 3 grey1
5 5 5 gray2
5 5 5 grey2
8 8 8 gray3
8 8 8 grey3
10 10 10 gray4
10 10 10 grey4
13 13 13 gray5
13 13 13 grey5
15 15 15 gray6
15 15 15 grey6
18 18 18 gray7
18 18 18 grey7
20 20 20 gray8
20 20 20 grey8
23 23 23 gray9
23 23 23 grey9
26 26 26 gray10
26 26 26 grey10
28 28 28 gray11
28 28 28 grey11
31 31 31 gray12
31 31 31 grey12
33 33 33 gray13
33 33 33 grey13
36 36 36 gray14
36 36 36 grey14
38 38 38 gray15
38 38 38 grey15
41 41 41 gray16
41 41 41 grey16
43 43 43 gray17
43 43 43 grey17
46 46 46 gray18
46 46 46 grey18
48 48 48 gray19
48 48 48 grey19
51 51 51 gray20
51 51 51 grey20
54 54 54 gray21
54 54 54 grey21
56 56 56 gray22
56 56 56 grey22
59 59 59 gray23
59 59 59 grey23
61 61 61 gray24
61 61 61 grey24
64 64 64 gray25
64 64 64 grey25
66 66 66 gray26
66 66 66 grey26
69 69 69 gray27
69 69 69 grey27
71 71 71 gray28
71 71 71 grey28
74 74 74 gray29
74 74 74 grey29
77 77 77 gray30
77 77 77 grey30
79 79 79 gray31
79 79 79 grey31
82 82 82 gray32
82 82 82 grey32
84 84 84 gray33
84 84 84 grey33
87 87 87 gray34
87 87 87 grey34
89 89 89 gray35
89 89 89 grey35
92 92 92 gray36
92 92 92 grey36
94 94 94 gray37
94 94 94 grey37
97 97 97 gray38
97 97 97 grey38
99 99 99 gray39
99 99 99 grey39
102 102 102 gray40
102 102 102 grey40
105 105 105 gray41
105 105 105 grey41
107 107 107 gray42
107 107 107 grey42
110 110 110 gray43
110 110 110 grey43
112 112 112 gray44
112 112 112 grey44
115 115 115 gray45
115 115 115 grey45
117 117 117 gray46
117 117 117 grey46
120 120 120 gray47
120 120 120 grey47
122 122 122 gray48
122 122 122 grey48
125 125 125 gray49
125 125 125 grey49
127 127 127 gray50
127 127 127 grey50
130 130 130 gray51
130 130 130 grey51
133 133 133 gray52
133 133 133 grey52
135 135 135 gray53
135 135 135 grey53
138 138 138 gray54
138 138 138 grey54
140 140 140 gray55
140 140 140 grey55
143 143 143 gray56
143 143 143 grey56
145 145 145 gray57
145 145 145 grey57
148 148 148 gray58
148 148 148 grey58
150 150 150 gray59
150 150 150 grey59
153 153 153 gray60
153 153 153 grey60
156 156 156 gray61
156 156 156 grey61
158 158 158 gray62
158 158 158 grey62
161 161 161 gray63
161 161 161 grey63
163 163 163 gray64
163 163 163 grey64
166 166 166 gray65
166 166 166 grey65
168 168 168 gray66
168 168 168 grey66
171 171 171 gray67
171 171 171 grey67
173 173 173 gray68
173 173 173 grey68
176 176 176 gray69
176 176 176 grey69
179 179 179 gray70
179 179 179 grey70
181 181 181 gray71
181 181 181 grey71
184 184 184 gray72
184 184 184 grey72
186 186 186 gray73
186 186 186 grey73
189 189 189 gray74
189 189 189 grey74
191 191 191 gray75
191 191 191 grey75
194 194 194 gray76
194 194 194 grey76
196 196 196 gray77
196 196 196 grey77
199 199 199 gray78
199 199 199 grey78
201 201 201 gray79
201 201 201 grey79
204 204 204 gray80
204 204 204 grey80
207 207 207 gray81
207 207 207 grey81
209 209 209 gray82
209 209 209 grey82
212 212 212 gray83
212 212 212 grey83
214 214 214 gray84
214 214 214 grey84
217 217 217 gray85
217 217 217 grey85
219 219 219 gray86
219 219 219 grey86
222 222 222 gray87
222 222 222 grey87
224 224 224 gray88
224 224 224 grey88
227 227 227 gray89
227 227 227 grey89
229 229 229 gray90
229 229 229 grey90
232 232 232 gray91
232 232 232 grey91
235 235 235 gray92
235 235 235 grey92
237 237 237 gray93
237 237 237 grey93
240 240 240 gray94
240 240 240 grey94
242 242 242 gray95
242 242 242 grey95
245 245 245 gray96
245 245 245 grey96
247 247 247 gray97
247 247 247 grey97
250 250 250 gray98
250 250 250 grey98
252 252 252 gray99
252 252 252 grey99
255 255 255 gray100
255 255 255 grey100
169 169 169 dark grey
169 169 169 DarkGrey
169 169 169 dark gray
169 169 169 DarkGray
0 0 139 dark blue
0 0 139 DarkBlue
0 139 139 dark cyan
0 139 139 DarkCyan
139 0 139 dark magenta
139 0 139 DarkMagenta
139 0 0 dark red
139 0 0 DarkRed
144 238 144 light green
144 238 144 LightGreen
220 20 60 crimson
75 0 130 indigo
128 128 0 olive
102 51 153 rebecca purple
102 51 153 RebeccaPurple
192 192 192 silver
0 128 128 teal
+435
View File
@@ -0,0 +1,435 @@
// Package config reads and writes Ghostty config files while preserving
// everything the editor does not touch: comments, blank lines, ordering and
// formatting of untouched entries.
package config
import (
"bytes"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
)
// Line is one line of a config file.
type Line struct {
Raw string // original text; regenerated when the entry changes
Key string // empty for comments, blank lines and unparsable lines
Value string // raw value text after '=', trimmed (quotes are kept)
}
// IsEntry reports whether the line is a key/value entry.
func (l Line) IsEntry() bool { return l.Key != "" }
// File is a parsed config file.
type File struct {
Path string
Exists bool
ModTime time.Time
Lines []Line
}
// Load reads path. A missing file yields an empty File that will be created
// on save.
func Load(path string) (*File, error) {
f := &File{Path: path}
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return f, nil
}
if err != nil {
return nil, err
}
if fi, err := os.Stat(path); err == nil {
f.ModTime = fi.ModTime()
}
f.Exists = true
f.Lines = Parse(data)
return f, nil
}
// Parse splits config data into lines.
func Parse(data []byte) []Line {
text := strings.ReplaceAll(string(data), "\r\n", "\n")
text = strings.TrimSuffix(text, "\n")
if text == "" {
return nil
}
parts := strings.Split(text, "\n")
lines := make([]Line, len(parts))
for i, raw := range parts {
lines[i] = parseLine(raw)
}
return lines
}
func parseLine(raw string) Line {
l := Line{Raw: raw}
t := strings.TrimSpace(raw)
if t == "" || strings.HasPrefix(t, "#") {
return l
}
key, value, found := strings.Cut(t, "=")
key = strings.TrimSpace(key)
if key == "" || strings.ContainsAny(key, " \t") {
return l
}
l.Key = key
if found {
l.Value = strings.TrimSpace(value)
}
return l
}
// FormatLine renders a key/value entry.
func FormatLine(key, value string) string {
if value == "" {
value = `""`
} else if strings.TrimSpace(value) != value && !isQuoted(value) {
value = `"` + value + `"`
}
return key + " = " + value
}
func isQuoted(v string) bool {
return len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"'
}
func newEntry(key, value string) Line {
return Line{Raw: FormatLine(key, value), Key: key, Value: value}
}
// Clone returns a deep copy (used for undo snapshots).
func (f *File) Clone() *File {
c := *f
c.Lines = append([]Line(nil), f.Lines...)
return &c
}
// Has reports whether key is set in the file.
func (f *File) Has(key string) bool {
for _, l := range f.Lines {
if l.Key == key {
return true
}
}
return false
}
// Get returns the effective (last) value of key.
func (f *File) Get(key string) (string, bool) {
for i := len(f.Lines) - 1; i >= 0; i-- {
if f.Lines[i].Key == key {
return f.Lines[i].Value, true
}
}
return "", false
}
// GetAll returns every value of key in file order.
func (f *File) GetAll(key string) []string {
var out []string
for _, l := range f.Lines {
if l.Key == key {
out = append(out, l.Value)
}
}
return out
}
// Keys returns the distinct keys set in the file, in order of appearance.
func (f *File) Keys() []string {
var out []string
seen := map[string]bool{}
for _, l := range f.Lines {
if l.Key != "" && !seen[l.Key] {
seen[l.Key] = true
out = append(out, l.Key)
}
}
return out
}
// Set assigns a single value. The first existing entry is updated in place
// and any further entries for the key are removed; otherwise a new entry is
// appended.
func (f *File) Set(key, value string) {
f.SetAll(key, []string{value})
}
// SetAll replaces all entries of key with values while disturbing the file
// as little as possible: entries whose value is unchanged stay where they
// are (with their original formatting), changed entries are rewritten in
// place, removed ones are dropped and additional ones are inserted after
// the preceding entry of the same key. An empty slice removes the key.
func (f *File) SetAll(key string, values []string) {
if len(values) == 0 {
f.Unset(key)
return
}
var pos []int // line indexes of the existing entries
var old []string
for i, l := range f.Lines {
if l.Key == key {
pos = append(pos, i)
old = append(old, l.Value)
}
}
if len(pos) == 0 {
at := f.insertPos()
entries := make([]Line, len(values))
for i, v := range values {
entries[i] = newEntry(key, v)
}
f.Lines = append(f.Lines[:at:at], append(entries, f.Lines[at:]...)...)
return
}
replace := map[int]Line{} // line index -> new content
remove := map[int]bool{} // line indexes to drop
after := map[int][]Line{} // new entries to insert after a line index
before := map[int][]Line{} // new entries to insert before a line index
last := -1 // line index of the last kept/replaced entry
var dels []int // pending deleted entries in the current gap
var ins []string // pending inserted values in the current gap
flushGap := func() {
// Pair deletions with insertions as in-place edits.
n := min(len(dels), len(ins))
for k := 0; k < n; k++ {
replace[pos[dels[k]]] = newEntry(key, ins[k])
last = pos[dels[k]]
}
for _, d := range dels[n:] {
remove[pos[d]] = true
}
for _, v := range ins[n:] {
if last >= 0 {
after[last] = append(after[last], newEntry(key, v))
} else {
before[pos[0]] = append(before[pos[0]], newEntry(key, v))
}
}
dels, ins = nil, nil
}
for _, op := range diff(old, values) {
switch op.kind {
case opKeep:
flushGap()
last = pos[op.i]
case opDel:
dels = append(dels, op.i)
case opIns:
ins = append(ins, values[op.j])
}
}
flushGap()
lines := make([]Line, 0, len(f.Lines)+len(values))
for i, l := range f.Lines {
lines = append(lines, before[i]...)
switch {
case remove[i]:
case replace[i].Key != "":
lines = append(lines, replace[i])
default:
lines = append(lines, l)
}
lines = append(lines, after[i]...)
}
f.Lines = lines
}
// insertPos is where new keys are appended: after the last entry, so that
// trailing comments stay at the end of the file.
func (f *File) insertPos() int {
for i := len(f.Lines) - 1; i >= 0; i-- {
if f.Lines[i].IsEntry() {
return i + 1
}
}
return len(f.Lines)
}
type opKind int
const (
opKeep opKind = iota
opDel
opIns
)
type diffOp struct {
kind opKind
i, j int // index into old (keep, del) and new (keep, ins)
}
// diff computes a minimal edit script from a to b using the longest common
// subsequence. Lists are short (at most a few hundred entries).
func diff(a, b []string) []diffOp {
m, n := len(a), len(b)
lcs := make([][]int, m+1)
for i := range lcs {
lcs[i] = make([]int, n+1)
}
for i := m - 1; i >= 0; i-- {
for j := n - 1; j >= 0; j-- {
if a[i] == b[j] {
lcs[i][j] = lcs[i+1][j+1] + 1
} else {
lcs[i][j] = max(lcs[i+1][j], lcs[i][j+1])
}
}
}
var ops []diffOp
i, j := 0, 0
for i < m && j < n {
switch {
case a[i] == b[j]:
ops = append(ops, diffOp{opKeep, i, j})
i++
j++
case lcs[i+1][j] >= lcs[i][j+1]:
ops = append(ops, diffOp{opDel, i, j})
i++
default:
ops = append(ops, diffOp{opIns, i, j})
j++
}
}
for ; i < m; i++ {
ops = append(ops, diffOp{opDel, i, j})
}
for ; j < n; j++ {
ops = append(ops, diffOp{opIns, i, j})
}
return ops
}
// Change is one entry of a diff between two value lists.
type Change struct {
Removed bool // the value was removed, otherwise added
Value string
}
// Diff lists the values removed from and added to a repeatable option, in
// file order. Values present in both lists are left out.
func Diff(old, new []string) []Change {
var out []Change
for _, op := range diff(old, new) {
switch op.kind {
case opDel:
out = append(out, Change{true, old[op.i]})
case opIns:
out = append(out, Change{false, new[op.j]})
}
}
return out
}
// Unset removes every entry of key.
func (f *File) Unset(key string) {
kept := f.Lines[:0:0]
for _, l := range f.Lines {
if l.Key != key {
kept = append(kept, l)
}
}
f.Lines = kept
}
// Bytes renders the file.
func (f *File) Bytes() []byte {
var b bytes.Buffer
for _, l := range f.Lines {
b.WriteString(l.Raw)
b.WriteByte('\n')
}
return b.Bytes()
}
// Equal reports whether two files render identically.
func (f *File) Equal(o *File) bool {
return bytes.Equal(f.Bytes(), o.Bytes())
}
// ChangedOnDisk reports whether the file was modified by someone else since
// it was loaded or last saved.
func (f *File) ChangedOnDisk() bool {
fi, err := os.Stat(f.Path)
if err != nil {
return f.Exists
}
return !f.Exists || !fi.ModTime().Equal(f.ModTime)
}
// target returns the real file behind Path, so that saving a symlinked
// config (e.g. from a dotfiles repository) keeps the symlink intact.
func (f *File) target() string {
if t, err := filepath.EvalSymlinks(f.Path); err == nil {
return t
}
return f.Path
}
// WriteTemp writes the file's content to a temporary file next to the
// target, so that relative config-file includes resolve the same way.
func (f *File) WriteTemp() (string, error) {
target := f.target()
dir := filepath.Dir(target)
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
tmp, err := os.CreateTemp(dir, "."+filepath.Base(target)+".ghosttyconf-*")
if err != nil {
return "", err
}
if _, err := tmp.Write(f.Bytes()); err != nil {
tmp.Close()
os.Remove(tmp.Name())
return "", err
}
if err := tmp.Close(); err != nil {
os.Remove(tmp.Name())
return "", err
}
return tmp.Name(), nil
}
// Save atomically replaces the file on disk. When backup is true and the
// file exists, the previous version is kept as <path>.bak.
func (f *File) Save(backup bool) error {
target := f.target()
mode := fs.FileMode(0o644)
if fi, err := os.Stat(target); err == nil {
mode = fi.Mode().Perm()
if backup {
old, err := os.ReadFile(target)
if err != nil {
return fmt.Errorf("read for backup: %w", err)
}
if err := os.WriteFile(target+".bak", old, mode); err != nil {
return fmt.Errorf("write backup: %w", err)
}
}
}
tmp, err := f.WriteTemp()
if err != nil {
return err
}
if err := os.Chmod(tmp, mode); err != nil {
os.Remove(tmp)
return err
}
if err := os.Rename(tmp, target); err != nil {
os.Remove(tmp)
return err
}
f.Exists = true
if fi, err := os.Stat(f.Path); err == nil {
f.ModTime = fi.ModTime()
}
return nil
}
+202
View File
@@ -0,0 +1,202 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
)
const sample = `# My Ghostty config
font-family = Hack Nerd Font Mono
font-size=15
keybind = a=new_tab
# split navigation
keybind = b=goto_split:next
theme = "Dracula"
# trailing comment
`
func parse(t *testing.T, s string) *File {
t.Helper()
return &File{Lines: Parse([]byte(s))}
}
func TestRoundTripPreservesEverything(t *testing.T) {
f := parse(t, sample)
if got := string(f.Bytes()); got != sample {
t.Fatalf("round trip changed the file:\n%s", got)
}
if v, _ := f.Get("font-size"); v != "15" {
t.Errorf("font-size = %q", v)
}
if v, _ := f.Get("theme"); v != `"Dracula"` {
t.Errorf("theme should keep its quotes, got %q", v)
}
if got := f.Keys(); strings.Join(got, ",") != "font-family,font-size,keybind,theme" {
t.Errorf("keys = %v", got)
}
}
func TestSetUpdatesInPlace(t *testing.T) {
f := parse(t, sample)
f.Set("font-size", "16")
want := strings.Replace(sample, "font-size=15", "font-size = 16", 1)
if got := string(f.Bytes()); got != want {
t.Fatalf("got:\n%s\nwant:\n%s", got, want)
}
}
func TestSetAppendsAfterLastEntry(t *testing.T) {
f := parse(t, sample)
f.Set("cursor-style", "bar")
want := strings.Replace(sample, "theme = \"Dracula\"\n", "theme = \"Dracula\"\ncursor-style = bar\n", 1)
if got := string(f.Bytes()); got != want {
t.Fatalf("got:\n%s", got)
}
}
func TestSetRemovesDuplicates(t *testing.T) {
f := parse(t, "a = 1\nb = 2\na = 3\n")
f.Set("a", "4")
if got := string(f.Bytes()); got != "a = 4\nb = 2\n" {
t.Fatalf("got:\n%s", got)
}
}
func TestSetAllKeepsPositions(t *testing.T) {
tests := []struct {
name string
values []string
want string
}{
{
name: "append",
values: []string{"a=new_tab", "b=goto_split:next", "c=close_surface"},
want: "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\nkeybind = c=close_surface\n",
},
{
name: "edit second",
values: []string{"a=new_tab", "b=goto_split:previous"},
want: "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:previous\n",
},
{
name: "delete first",
values: []string{"b=goto_split:next"},
want: "# split navigation\nkeybind = b=goto_split:next\n",
},
{
name: "insert at front",
values: []string{"z=reset", "a=new_tab", "b=goto_split:next"},
want: "keybind = z=reset\nkeybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\n",
},
{
name: "swap",
values: []string{"b=goto_split:next", "a=new_tab"},
// The comment stays attached to the entry it describes.
want: "# split navigation\nkeybind = b=goto_split:next\nkeybind = a=new_tab\n",
},
}
const base = "keybind = a=new_tab\n# split navigation\nkeybind = b=goto_split:next\n"
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := parse(t, base)
f.SetAll("keybind", tt.values)
if got := string(f.Bytes()); got != tt.want {
t.Fatalf("got:\n%s\nwant:\n%s", got, tt.want)
}
if got := f.GetAll("keybind"); strings.Join(got, "|") != strings.Join(tt.values, "|") {
t.Fatalf("values = %v", got)
}
})
}
}
func TestUnset(t *testing.T) {
f := parse(t, sample)
f.Unset("keybind")
if f.Has("keybind") {
t.Fatal("keybind still present")
}
if !strings.Contains(string(f.Bytes()), "# split navigation") {
t.Fatal("comments must be kept")
}
}
func TestFormatLineQuoting(t *testing.T) {
cases := map[string]string{
"bar": "k = bar",
"": `k = ""`,
" x": `k = " x"`,
`"quoted"`: `k = "quoted"`,
}
for in, want := range cases {
if got := FormatLine("k", in); got != want {
t.Errorf("FormatLine(%q) = %q, want %q", in, got, want)
}
}
}
func TestSaveBackupAndSymlink(t *testing.T) {
dir := t.TempDir()
real := filepath.Join(dir, "real.ghostty")
link := filepath.Join(dir, "config.ghostty")
if err := os.WriteFile(real, []byte("font-size = 12\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(real, link); err != nil {
t.Fatal(err)
}
f, err := Load(link)
if err != nil {
t.Fatal(err)
}
f.Set("font-size", "14")
if err := f.Save(true); err != nil {
t.Fatal(err)
}
if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Fatal("symlink was replaced")
}
got, _ := os.ReadFile(real)
if string(got) != "font-size = 14\n" {
t.Fatalf("saved content = %q", got)
}
bak, _ := os.ReadFile(real + ".bak")
if string(bak) != "font-size = 12\n" {
t.Fatalf("backup content = %q", bak)
}
if fi, _ := os.Stat(real); fi.Mode().Perm() != 0o600 {
t.Fatalf("permissions changed to %v", fi.Mode().Perm())
}
if f.ChangedOnDisk() {
t.Fatal("file should not be reported as changed after our own save")
}
}
func TestLoadMissingFile(t *testing.T) {
f, err := Load(filepath.Join(t.TempDir(), "nope"))
if err != nil {
t.Fatal(err)
}
if f.Exists || len(f.Lines) != 0 {
t.Fatal("expected empty, non-existing file")
}
}
func TestDiffListsOnlyChanges(t *testing.T) {
old := []string{"super+d=new_split:right", "super+shift+d=new_split:down", "super+k=unbind"}
new := []string{"super+shift+d=new_split:down", "super+k=unbind", "super+d=unbind", `super+\=new_split:right`}
got := Diff(old, new)
want := []Change{{true, "super+d=new_split:right"}, {false, "super+d=unbind"}, {false, `super+\=new_split:right`}}
if len(got) != len(want) {
t.Fatalf("Diff = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("Diff = %v, want %v", got, want)
}
}
}
+264
View File
@@ -0,0 +1,264 @@
// Package ghostty talks to the installed Ghostty binary: it locates it,
// reads documentation, defaults, themes, fonts and actions from it, and
// validates config files with `ghostty +validate-config`.
package ghostty
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
// Ghostty is an installed Ghostty binary.
type Ghostty struct {
Bin string
Version string
}
var (
reVersion = regexp.MustCompile(`Ghostty (\d+\.\d+\.\d+\S*)`)
reValidation = regexp.MustCompile(`^.+?:(\d+):(.*)$`)
)
// Find locates the ghostty binary. An explicit path takes precedence, then
// $PATH, then the usual macOS application locations.
func Find(explicit string) (*Ghostty, error) {
var candidates []string
if explicit != "" {
candidates = append(candidates, explicit)
} else {
if p, err := exec.LookPath("ghostty"); err == nil {
candidates = append(candidates, p)
}
if runtime.GOOS == "darwin" {
candidates = append(candidates,
"/Applications/Ghostty.app/Contents/MacOS/ghostty",
filepath.Join(os.Getenv("HOME"), "Applications/Ghostty.app/Contents/MacOS/ghostty"),
)
}
}
for _, c := range candidates {
if fi, err := os.Stat(c); err != nil || fi.IsDir() {
continue
}
g := &Ghostty{Bin: c}
out, err := g.run(5*time.Second, "+version")
if err != nil {
continue
}
if m := reVersion.FindStringSubmatch(out); m != nil {
g.Version = m[1]
}
return g, nil
}
if explicit != "" {
return nil, fmt.Errorf("%s is not a usable ghostty binary", explicit)
}
return nil, errors.New("ghostty binary not found")
}
func (g *Ghostty) run(timeout time.Duration, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, g.Bin, args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// Keep Ghostty from treating our pipe as an interactive terminal.
cmd.Stdin = nil
err := cmd.Run()
if err != nil && stdout.Len() == 0 {
msg := strings.TrimSpace(stderr.String())
if msg == "" {
msg = err.Error()
}
return "", fmt.Errorf("ghostty %s: %s", strings.Join(args, " "), msg)
}
return stdout.String(), err
}
// DefaultsWithDocs returns `ghostty +show-config --default --docs`.
func (g *Ghostty) DefaultsWithDocs() (string, error) {
out, err := g.run(10*time.Second, "+show-config", "--default", "--docs")
if err != nil && out == "" {
return "", err
}
return out, nil
}
// Themes lists all available theme names.
func (g *Ghostty) Themes() ([]string, error) {
out, err := g.run(10*time.Second, "+list-themes", "--plain")
if out == "" && err != nil {
return nil, err
}
var names []string
seen := map[string]bool{}
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Lines look like "Dracula (resources)" or "Mine (user)".
if i := strings.LastIndex(line, " ("); i > 0 && strings.HasSuffix(line, ")") {
line = line[:i]
}
if !seen[line] {
seen[line] = true
names = append(names, line)
}
}
return names, nil
}
// Fonts lists the font families Ghostty can find.
func (g *Ghostty) Fonts() ([]string, error) {
out, err := g.run(20*time.Second, "+list-fonts")
if out == "" && err != nil {
return nil, err
}
var families []string
seen := map[string]bool{}
for _, line := range strings.Split(out, "\n") {
if line == "" || line[0] == ' ' || line[0] == '\t' {
continue
}
line = strings.TrimSpace(line)
if !seen[line] {
seen[line] = true
families = append(families, line)
}
}
sort.Slice(families, func(i, j int) bool {
return strings.ToLower(families[i]) < strings.ToLower(families[j])
})
return families, nil
}
// Action is a keybinding action.
type Action struct {
Name string
Summary string // first line of the documentation
Doc string
}
// Actions lists all keybinding actions with their documentation.
func (g *Ghostty) Actions() ([]Action, error) {
out, err := g.run(10*time.Second, "+list-actions", "--docs")
if out == "" && err != nil {
return nil, err
}
return parseActions(out), nil
}
func parseActions(out string) []Action {
var actions []Action
var cur *Action
var doc []string
flush := func() {
if cur == nil {
return
}
cur.Doc = strings.TrimSpace(strings.Join(doc, "\n"))
if i := strings.Index(cur.Doc, "\n\n"); i >= 0 {
cur.Summary = strings.ReplaceAll(cur.Doc[:i], "\n", " ")
} else {
cur.Summary = strings.ReplaceAll(cur.Doc, "\n", " ")
}
actions = append(actions, *cur)
}
for _, line := range strings.Split(out, "\n") {
if line != "" && line[0] != ' ' && strings.HasSuffix(line, ":") {
flush()
cur = &Action{Name: strings.TrimSuffix(line, ":")}
doc = nil
continue
}
if cur != nil {
doc = append(doc, strings.TrimPrefix(line, " "))
}
}
flush()
return actions
}
// ValidationError is one problem reported by `ghostty +validate-config`.
type ValidationError struct {
Line int // 0 if unknown
Message string
}
func (e ValidationError) String() string {
if e.Line > 0 {
return fmt.Sprintf("line %d: %s", e.Line, e.Message)
}
return e.Message
}
// Validate runs `ghostty +validate-config` on path.
func (g *Ghostty) Validate(path string) ([]ValidationError, error) {
abs, err := filepath.Abs(path)
if err != nil {
return nil, err
}
out, runErr := g.run(15*time.Second, "+validate-config", "--config-file="+abs)
var errs []ValidationError
sc := bufio.NewScanner(strings.NewReader(out))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" {
continue
}
// Lines look like "/path/to/config:3:font-size: invalid value".
e := ValidationError{Message: line}
if m := reValidation.FindStringSubmatch(line); m != nil {
e.Line, _ = strconv.Atoi(m[1])
e.Message = m[2]
}
errs = append(errs, e)
}
if runErr != nil && len(errs) == 0 {
var exitErr *exec.ExitError
if !errors.As(runErr, &exitErr) {
return nil, runErr
}
errs = append(errs, ValidationError{Message: "ghostty reported an invalid configuration"})
}
return errs, nil
}
// ResourcesDir returns Ghostty's resources directory (where the bundled
// themes live), or "".
func (g *Ghostty) ResourcesDir() string {
if d := os.Getenv("GHOSTTY_RESOURCES_DIR"); d != "" {
return d
}
if g == nil {
return ""
}
bin, err := filepath.EvalSymlinks(g.Bin)
if err != nil {
bin = g.Bin
}
dir := filepath.Dir(bin)
for _, c := range []string{
filepath.Join(dir, "../Resources/ghostty"), // macOS app bundle
filepath.Join(dir, "../share/ghostty"), // Linux prefix install
} {
if fi, err := os.Stat(filepath.Join(c, "themes")); err == nil && fi.IsDir() {
return filepath.Clean(c)
}
}
return ""
}
+140
View File
@@ -0,0 +1,140 @@
package ghostty
import (
"bufio"
"os"
"path/filepath"
"runtime"
"strings"
)
func xdgConfigDir() string {
if d := os.Getenv("XDG_CONFIG_HOME"); d != "" {
return filepath.Join(d, "ghostty")
}
return filepath.Join(os.Getenv("HOME"), ".config", "ghostty")
}
func macConfigDir() string {
return filepath.Join(os.Getenv("HOME"), "Library", "Application Support", "com.mitchellh.ghostty")
}
// ConfigCandidates lists the files Ghostty loads by default, in load order.
func ConfigCandidates() []string {
xdg := xdgConfigDir()
c := []string{filepath.Join(xdg, "config"), filepath.Join(xdg, "config.ghostty")}
if runtime.GOOS == "darwin" {
mac := macConfigDir()
c = append(c, filepath.Join(mac, "config"), filepath.Join(mac, "config.ghostty"))
}
return c
}
// DefaultConfigPath picks the config file to edit: the last existing file
// in Ghostty's load order (it has the final say), or the preferred location
// for a new file.
func DefaultConfigPath() string {
c := ConfigCandidates()
for i := len(c) - 1; i >= 0; i-- {
if fi, err := os.Stat(c[i]); err == nil && !fi.IsDir() {
return c[i]
}
}
if runtime.GOOS == "darwin" {
return filepath.Join(macConfigDir(), "config.ghostty")
}
return filepath.Join(xdgConfigDir(), "config.ghostty")
}
// ExistingConfigFiles returns all default config files that exist.
func ExistingConfigFiles() []string {
var out []string
for _, c := range ConfigCandidates() {
if fi, err := os.Stat(c); err == nil && !fi.IsDir() {
out = append(out, c)
}
}
return out
}
// Theme holds the colors of a theme file, used for previews.
type Theme struct {
Name string
Background string
Foreground string
Cursor string
Selection string
Palette [16]string
}
// ThemeDirs returns the directories searched for themes, user dirs first.
func (g *Ghostty) ThemeDirs() []string {
dirs := []string{filepath.Join(xdgConfigDir(), "themes")}
if runtime.GOOS == "darwin" {
dirs = append(dirs, filepath.Join(macConfigDir(), "themes"))
}
if r := g.ResourcesDir(); r != "" {
dirs = append(dirs, filepath.Join(r, "themes"))
}
return dirs
}
// LoadTheme reads a theme by name (or absolute path) for previewing.
func (g *Ghostty) LoadTheme(name string) (*Theme, error) {
var path string
if filepath.IsAbs(name) {
path = name
} else {
for _, d := range g.ThemeDirs() {
p := filepath.Join(d, name)
if _, err := os.Stat(p); err == nil {
path = p
break
}
}
}
if path == "" {
return nil, os.ErrNotExist
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
t := &Theme{Name: name}
sc := bufio.NewScanner(f)
for sc.Scan() {
key, value, ok := strings.Cut(sc.Text(), "=")
if !ok {
continue
}
key, value = strings.TrimSpace(key), strings.TrimSpace(value)
switch key {
case "background":
t.Background = value
case "foreground":
t.Foreground = value
case "cursor-color":
t.Cursor = value
case "selection-background":
t.Selection = value
case "palette":
idx, color, ok := strings.Cut(value, "=")
if !ok {
continue
}
var n int
for _, c := range strings.TrimSpace(idx) {
if c < '0' || c > '9' {
n = -1
break
}
n = n*10 + int(c-'0')
}
if n >= 0 && n < 16 {
t.Palette[n] = strings.TrimSpace(color)
}
}
}
return t, sc.Err()
}
+38
View File
@@ -0,0 +1,38 @@
package ghostty
import (
"bytes"
"errors"
)
// ErrNotRunning is returned by Reload when no Ghostty instance was found.
var ErrNotRunning = errors.New("Ghostty is not running")
// ErrReloadUnsupported is returned by Reload on platforms where Ghostty
// cannot be asked to reload from outside.
var ErrReloadUnsupported = errors.New("automatic reload is not supported on this platform")
// Reload asks every running Ghostty instance to reload its configuration,
// as if the reload_config action (⌘⇧, / ctrl+shift+,) had been triggered.
//
// On macOS this uses Ghostty's AppleScript "perform action" command, on
// Linux the SIGUSR2 handler of the GTK app.
func Reload() error {
return reload()
}
// isCLIAction reports whether a NUL-separated command line runs a Ghostty
// CLI action ("ghostty +validate-config", …) rather than the app. Like
// Ghostty, it only looks at arguments before "-e".
func isCLIAction(cmdline []byte) bool {
args := bytes.Split(bytes.TrimRight(cmdline, "\x00"), []byte{0})
for _, a := range args[1:] {
if string(a) == "-e" {
break
}
if bytes.HasPrefix(a, []byte("+")) {
return true
}
}
return false
}
+58
View File
@@ -0,0 +1,58 @@
package ghostty
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"strings"
"time"
)
// The bundle id is used instead of the name so that the script never
// launches a different app, and the "is running" check keeps it from
// starting Ghostty when it is closed.
const reloadScript = `
if application id "com.mitchellh.ghostty" is running then
tell application id "com.mitchellh.ghostty"
if (count of terminals) is 0 then return "no terminals"
return perform action "reload_config" on first terminal
end tell
else
return "not running"
end if`
func reload() error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "osascript", "-e", reloadScript)
var stdout, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
out := strings.TrimSpace(stdout.String())
if err != nil {
msg := strings.TrimSpace(stderr.String())
switch {
case errors.Is(ctx.Err(), context.DeadlineExceeded):
return errors.New("osascript timed out (is a permission dialog open?)")
case strings.Contains(msg, "-1743"):
return errors.New("not allowed to control Ghostty; allow it in System Settings → Privacy & Security → Automation")
case strings.Contains(msg, "-1708"), strings.Contains(msg, "-10000"):
return errors.New("Ghostty refused the AppleScript command (is macos-applescript = false set?)")
case msg != "":
return fmt.Errorf("osascript: %s", msg)
}
return fmt.Errorf("osascript: %w", err)
}
switch out {
case "true":
return nil
case "not running":
return ErrNotRunning
case "no terminals":
return errors.New("Ghostty has no open terminal to send the reload to")
default:
return fmt.Errorf("Ghostty did not perform reload_config (%s)", out)
}
}
+61
View File
@@ -0,0 +1,61 @@
package ghostty
import (
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
)
// reload sends SIGUSR2 to the user's running Ghostty apps, which makes the
// GTK app reload its configuration.
func reload() error {
pids := ghosttyApps("/proc", os.Getuid())
if len(pids) == 0 {
return ErrNotRunning
}
var errs []error
for _, pid := range pids {
if err := syscall.Kill(pid, syscall.SIGUSR2); err != nil {
errs = append(errs, err)
}
}
if len(errs) == len(pids) {
return errors.Join(errs...)
}
return nil
}
// ghosttyApps finds Ghostty GUI processes owned by uid. CLI invocations
// such as "ghostty +list-themes" are skipped: they do not handle SIGUSR2 and
// would be terminated by it.
func ghosttyApps(proc string, uid int) []int {
entries, err := os.ReadDir(proc)
if err != nil {
return nil
}
var pids []int
for _, e := range entries {
pid, err := strconv.Atoi(e.Name())
if err != nil || pid == os.Getpid() {
continue
}
dir := filepath.Join(proc, e.Name())
comm, err := os.ReadFile(filepath.Join(dir, "comm"))
if err != nil || strings.TrimSpace(string(comm)) != "ghostty" {
continue
}
var st syscall.Stat_t
if err := syscall.Stat(dir, &st); err != nil || int(st.Uid) != uid {
continue
}
cmdline, err := os.ReadFile(filepath.Join(dir, "cmdline"))
if err != nil || isCLIAction(cmdline) {
continue
}
pids = append(pids, pid)
}
return pids
}
+7
View File
@@ -0,0 +1,7 @@
//go:build !darwin && !linux
package ghostty
func reload() error {
return ErrReloadUnsupported
}
+18
View File
@@ -0,0 +1,18 @@
package ghostty
import "testing"
func TestIsCLIAction(t *testing.T) {
cases := map[string]bool{
"/usr/bin/ghostty\x00": false,
"ghostty\x00--gtk-single-instance=true\x00": false,
"ghostty\x00+list-themes\x00": true,
"ghostty\x00--config-file=x\x00+show-config\x00": true,
"ghostty\x00-e\x00vim\x00+10\x00file\x00": false,
}
for cmdline, want := range cases {
if got := isCLIAction([]byte(cmdline)); got != want {
t.Errorf("isCLIAction(%q) = %v, want %v", cmdline, got, want)
}
}
}
+288
View File
@@ -0,0 +1,288 @@
// Package keybind understands Ghostty key bindings: it splits and
// normalizes triggers the same way Ghostty's src/input/Binding.zig does,
// computes the effective set of bindings from Ghostty's defaults plus the
// user's `keybind` entries, and translates edits of that set back into
// config entries.
package keybind
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// Split splits "trigger=action". It mirrors Ghostty's parser: an '=' that is
// directly followed by '+' or '=' belongs to the trigger, so "ctrl+==reset"
// and "=+ctrl=reset" both bind the '=' key.
func Split(v string) (trigger, action string) {
for i := 0; i < len(v); i++ {
if v[i] != '=' {
continue
}
if i < len(v)-1 && (v[i+1] == '+' || v[i+1] == '=') {
continue
}
return strings.TrimSpace(v[:i]), strings.TrimSpace(v[i+1:])
}
return strings.TrimSpace(v), ""
}
// Flag prefixes that may precede a trigger, e.g. "global:ctrl+grave".
var flagPrefixes = []string{"all:", "global:", "unconsumed:", "performable:"}
// StripFlags separates leading flag prefixes from a trigger.
func StripFlags(trigger string) (flags, rest string) {
rest = trigger
for {
found := false
for _, p := range flagPrefixes {
if strings.HasPrefix(rest, p) {
flags += p
rest = rest[len(p):]
found = true
}
}
if !found {
return flags, rest
}
}
}
// Modifier names in the order Ghostty prints them.
var modOrder = []string{"super", "ctrl", "alt", "shift", "caps_lock", "num_lock"}
var modAliases = map[string]string{
"super": "super", "cmd": "super", "command": "super",
"ctrl": "ctrl", "control": "ctrl",
"alt": "alt", "opt": "alt", "option": "alt",
"shift": "shift",
"caps_lock": "caps_lock",
"num_lock": "num_lock",
}
// keyNames are Ghostty's physical key names (src/input/key.zig, 1.3).
var keyNames = map[string]bool{}
func init() {
for _, k := range strings.Fields(`backquote backslash bracket_left bracket_right comma
digit_0 digit_1 digit_2 digit_3 digit_4 digit_5 digit_6 digit_7 digit_8 digit_9 equal
intl_backslash intl_ro intl_yen key_a key_b key_c key_d key_e key_f key_g key_h key_i
key_j key_k key_l key_m key_n key_o key_p key_q key_r key_s key_t key_u key_v key_w key_x
key_y key_z minus period quote semicolon slash alt_left alt_right backspace caps_lock
context_menu control_left control_right enter meta_left meta_right shift_left shift_right
space tab convert kana_mode non_convert delete end help home insert page_down page_up
arrow_down arrow_left arrow_right arrow_up num_lock numpad_0 numpad_1 numpad_2 numpad_3
numpad_4 numpad_5 numpad_6 numpad_7 numpad_8 numpad_9 numpad_add numpad_backspace
numpad_clear numpad_clear_entry numpad_comma numpad_decimal numpad_divide numpad_enter
numpad_equal numpad_memory_add numpad_memory_clear numpad_memory_recall
numpad_memory_store numpad_memory_subtract numpad_multiply numpad_paren_left
numpad_paren_right numpad_subtract numpad_separator numpad_up numpad_down numpad_right
numpad_left numpad_begin numpad_home numpad_end numpad_insert numpad_delete
numpad_page_up numpad_page_down escape f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14
f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 f25 fn_lock print_screen scroll_lock pause
browser_back browser_favorites browser_forward browser_home browser_refresh
browser_search browser_stop eject launch_app_1 launch_app_2 launch_mail media_play_pause
media_select media_stop media_track_next media_track_previous power sleep
audio_volume_down audio_volume_mute audio_volume_up wake_up copy cut paste catch_all`) {
keyNames[k] = true
}
}
// compatKeys are the Ghostty 1.1 key names that 1.2+ still accepts.
var compatKeys = map[string]string{
"zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5",
"six": "6", "seven": "7", "eight": "8", "nine": "9", "plus": "+", "apostrophe": "'",
"grave_accent": "backquote", "left_bracket": "bracket_left", "right_bracket": "bracket_right",
"up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right",
"kp_add": "numpad_add", "kp_subtract": "numpad_subtract", "kp_multiply": "numpad_multiply",
"kp_divide": "numpad_divide", "kp_decimal": "numpad_decimal", "kp_enter": "numpad_enter",
"kp_equal": "numpad_equal", "kp_separator": "numpad_separator", "kp_left": "numpad_left",
"kp_right": "numpad_right", "kp_up": "numpad_up", "kp_down": "numpad_down",
"kp_page_up": "numpad_page_up", "kp_page_down": "numpad_page_down", "kp_home": "numpad_home",
"kp_end": "numpad_end", "kp_insert": "numpad_insert", "kp_delete": "numpad_delete",
"kp_begin": "numpad_begin", "left_shift": "shift_left", "right_shift": "shift_right",
"left_control": "control_left", "right_control": "control_right", "left_alt": "alt_left",
"right_alt": "alt_right", "left_super": "meta_left", "right_super": "meta_right",
}
func init() {
for i := 0; i <= 9; i++ {
compatKeys[fmt.Sprintf("kp_%d", i)] = fmt.Sprintf("numpad_%d", i)
}
// "physical:" variants of the compatibility names.
for k, v := range map[string]string{
"zero": "digit_0", "one": "digit_1", "two": "digit_2", "three": "digit_3", "four": "digit_4",
"five": "digit_5", "six": "digit_6", "seven": "digit_7", "eight": "digit_8", "nine": "digit_9",
"apostrophe": "quote", "grave_accent": "backquote", "left_bracket": "bracket_left",
"right_bracket": "bracket_right", "up": "arrow_up", "down": "arrow_down",
"left": "arrow_left", "right": "arrow_right",
} {
compatKeys["physical:"+k] = v
}
for i := 0; i <= 9; i++ {
compatKeys[fmt.Sprintf("physical:kp_%d", i)] = fmt.Sprintf("numpad_%d", i)
}
}
// Trigger is one key combination of a (possibly multi-key) trigger.
type Trigger struct {
Mods []string // canonical modifier names in modOrder
Key string // canonical key: a physical key name or a single character
}
func (t Trigger) String() string {
parts := append(append([]string(nil), t.Mods...), t.Key)
return strings.Join(parts, "+")
}
// ParseTrigger parses a single key combination such as "cmd+shift+t" the
// way Ghostty does. Unknown multi-character key names are an error.
func ParseTrigger(s string) (Trigger, error) {
var t Trigger
if s == "" {
return t, fmt.Errorf("empty trigger")
}
mods := map[string]bool{}
keySet := false
// Same loop as Ghostty: an empty part is a literal '+' key.
for rem := s; len(rem) > 0; {
idx := strings.IndexByte(rem, '+')
if idx < 0 {
idx = len(rem)
}
part := rem[:idx]
if idx >= len(rem) {
rem = ""
} else {
rem = rem[idx+1:]
}
if m, ok := modAliases[part]; ok {
if mods[m] {
return t, fmt.Errorf("modifier %q is repeated", part)
}
mods[m] = true
continue
}
if keySet {
return t, fmt.Errorf("only one key per combination is allowed (use > for sequences)")
}
keySet = true
key, err := canonicalKey(part)
if err != nil {
return t, err
}
t.Key = key
}
if !keySet {
return t, fmt.Errorf("the trigger has modifiers but no key")
}
for _, m := range modOrder {
if mods[m] {
t.Mods = append(t.Mods, m)
}
}
return t, nil
}
func canonicalKey(part string) (string, error) {
if part == "" {
return "+", nil // "ctrl++" binds the plus key
}
if keyNames[part] {
return part, nil
}
if utf8.RuneCountInString(part) == 1 {
r, _ := utf8.DecodeRuneInString(part)
// Unicode keys match case-insensitively.
return string(unicode.ToLower(r)), nil
}
if k := fromW3C(part); k != "" {
return k, nil
}
if k, ok := compatKeys[part]; ok {
return k, nil
}
return "", fmt.Errorf("unknown key %q", part)
}
// fromW3C converts W3C key codes such as "KeyA", "ArrowUp" or "Numpad0" to
// Ghostty's names.
func fromW3C(s string) string {
if s == "" || !unicode.IsUpper(rune(s[0])) {
return ""
}
var b strings.Builder
for i, r := range s {
if i > 0 && (unicode.IsUpper(r) || (unicode.IsDigit(r) && !unicode.IsDigit(rune(s[i-1])) && s[:i] != "F")) {
b.WriteByte('_')
}
b.WriteRune(unicode.ToLower(r))
}
if keyNames[b.String()] {
return b.String()
}
return ""
}
// Normalize returns a canonical identity for a trigger (including flag
// prefixes and sequences), so that "cmd+shift+t", "shift+super+T" and
// "global:super+shift+t" compare equal. Ghostty stores bindings by trigger;
// flags are attributes of a binding, not part of its identity.
func Normalize(trigger string) (string, error) {
_, rest := StripFlags(strings.TrimSpace(trigger))
if rest == "" {
return "", fmt.Errorf("empty trigger")
}
var parts []string
for _, p := range splitSequence(rest) {
t, err := ParseTrigger(p)
if err != nil {
return "", err
}
parts = append(parts, t.String())
}
return strings.Join(parts, ">"), nil
}
// NormalizeLoose is Normalize that falls back to the trimmed input for
// triggers it cannot parse, so that unknown syntax still gets an identity.
func NormalizeLoose(trigger string) string {
if n, err := Normalize(trigger); err == nil {
return n
}
_, rest := StripFlags(strings.TrimSpace(trigger))
return strings.ToLower(rest)
}
// splitSequence splits "ctrl+a>n" at '>' separators. A '>' that is itself
// the key (e.g. "shift+>") is kept.
func splitSequence(s string) []string {
var parts []string
start := 0
for i := 0; i < len(s); i++ {
if s[i] != '>' || i == start || s[i-1] == '+' {
continue
}
parts = append(parts, s[start:i])
start = i + 1
}
return append(parts, s[start:])
}
// Action names are lowercase with underscores; the parameter follows ':'.
func ActionName(action string) string {
name, _, _ := strings.Cut(action, ":")
return strings.TrimSpace(name)
}
// FormatMods renders modifiers in Ghostty's order.
func FormatMods(mods map[string]bool) []string {
var out []string
for _, m := range modOrder {
if mods[m] {
out = append(out, m)
}
}
return out
}
+250
View File
@@ -0,0 +1,250 @@
package keybind
import (
"strings"
"testing"
)
func TestSplit(t *testing.T) {
cases := map[string][2]string{
"ctrl+a=new_tab": {"ctrl+a", "new_tab"},
"==text:=": {"=", "text:="},
"ctrl+==text:=hello": {"ctrl+=", "text:=hello"},
"=+ctrl=text:=hello": {"=+ctrl", "text:=hello"},
"super+shift+,=reload": {"super+shift+,", "reload"},
"ctrl+a>n=new_window": {"ctrl+a>n", "new_window"},
"§=goto_split:next": {"§", "goto_split:next"},
"super++=increase": {"super++", "increase"},
}
for in, want := range cases {
tr, ac := Split(in)
if tr != want[0] || ac != want[1] {
t.Errorf("Split(%q) = %q, %q", in, tr, ac)
}
}
}
func TestNormalize(t *testing.T) {
same := [][]string{
{"cmd+shift+t", "shift+super+T", "command+shift+t", "global:super+shift+t"},
{"ctrl+up", "control+arrow_up", "ctrl+ArrowUp"},
{"super++", "super+plus"},
{"opt+grave_accent", "alt+backquote"},
{"ctrl+a>n", "control+a>N"},
{"super+=", "cmd+="},
}
for _, group := range same {
want, err := Normalize(group[0])
if err != nil {
t.Fatalf("%s: %v", group[0], err)
}
for _, g := range group[1:] {
got, err := Normalize(g)
if err != nil || got != want {
t.Errorf("Normalize(%q) = %q, %v; want %q", g, got, err, want)
}
}
}
for _, bad := range []string{"ctrl+ctrl+a", "ctrl+", "ctrl+a+b", "ctrl+bogus"} {
if _, err := Normalize(bad); err == nil && bad != "ctrl+" {
t.Errorf("Normalize(%q) should fail", bad)
}
}
}
var defaults = []string{
"super+t=new_tab",
"super+w=close_surface",
"super+d=new_split:right",
"super+arrow_right=text:\\x05",
}
func values(s *Set) string { return strings.Join(s.Values(), " | ") }
func find(t *testing.T, s *Set, trigger string) Binding {
t.Helper()
n, _ := Normalize(trigger)
for _, b := range s.Bindings() {
if b.Norm == n {
return b
}
}
t.Fatalf("no binding for %s", trigger)
return Binding{}
}
func TestEffective(t *testing.T) {
s := NewSet(defaults, []string{
"super+w=unbind",
"cmd+t=new_window",
"ctrl+a>n=new_tab",
"chain=toggle_fullscreen",
})
if b := find(t, s, "super+t"); b.Source != Changed || b.Action != "new_window" || b.Default != "new_tab" {
t.Errorf("super+t = %+v", b)
}
if b := find(t, s, "super+w"); b.Source != Unbound {
t.Errorf("super+w = %+v", b)
}
if b := find(t, s, "ctrl+a>n"); b.Source != Custom || len(b.Chain) != 1 || b.Chain[0] != "toggle_fullscreen" {
t.Errorf("ctrl+a>n = %+v", b)
}
if b := find(t, s, "super+d"); b.Source != Default || b.InConfig {
t.Errorf("super+d = %+v", b)
}
}
func TestClear(t *testing.T) {
s := NewSet(defaults, []string{"clear", "super+t=new_tab"})
if b := find(t, s, "super+t"); b.Source != Default || !b.InConfig {
t.Errorf("super+t = %+v", b)
}
if b := find(t, s, "super+d"); b.Source != Unbound {
t.Errorf("super+d should be unbound after clear: %+v", b)
}
s.Restore(find(t, s, "super+d"))
if got := values(s); got != "clear | super+t=new_tab | super+d=new_split:right" {
t.Errorf("restore after clear: %s", got)
}
}
func TestChangeDefaultAction(t *testing.T) {
s := NewSet(defaults, nil)
b := find(t, s, "super+d")
if err := s.Change(&b, "super+d=new_split:down"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "super+d=new_split:down" {
t.Errorf("got %s", got)
}
}
func TestMoveDefaultBinding(t *testing.T) {
s := NewSet(defaults, nil)
b := find(t, s, "super+d")
if err := s.Change(&b, "super+shift+d=new_split:right"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "super+d=unbind | super+shift+d=new_split:right" {
t.Errorf("got %s", got)
}
}
func TestMoveUserBindingRevertsToDefault(t *testing.T) {
s := NewSet(defaults, []string{"super+arrow_right=goto_window:next"})
b := find(t, s, "super+arrow_right")
if err := s.Change(&b, "super+alt+arrow_right=goto_window:next"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "super+alt+arrow_right=goto_window:next" {
t.Errorf("got %s", got)
}
if b := find(t, s, "super+arrow_right"); b.Source != Default {
t.Errorf("old trigger should fall back to the default: %+v", b)
}
}
func TestMoveUserBindingKeepsPosition(t *testing.T) {
s := NewSet(defaults, []string{"a=new_tab", "super+arrow_right=goto_window:next", "b=new_window"})
b := find(t, s, "super+arrow_right")
if err := s.Change(&b, "super+shift+k=goto_window:next"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "a=new_tab | super+shift+k=goto_window:next | b=new_window" {
t.Errorf("got %s", got)
}
}
func TestChangeReplacesConflictInPlace(t *testing.T) {
s := NewSet(defaults, []string{"ctrl+x=copy_to_clipboard", "ctrl+y=paste_from_clipboard"})
b := find(t, s, "ctrl+y")
if err := s.Change(&b, "ctrl+x=paste_from_clipboard"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "ctrl+x=paste_from_clipboard" {
t.Errorf("got %s", got)
}
}
func TestChangeBackToDefaultRemovesEntry(t *testing.T) {
s := NewSet(defaults, []string{"# not a keybind", "super+t=new_window"})
b := find(t, s, "super+t")
if err := s.Change(&b, "super+t=new_tab"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "# not a keybind" {
t.Errorf("got %s", got)
}
}
func TestUnbindAndRestore(t *testing.T) {
s := NewSet(defaults, []string{"super+t=new_window", "ctrl+q=quit"})
s.Unbind(find(t, s, "super+t"))
s.Unbind(find(t, s, "ctrl+q"))
if got := values(s); got != "super+t=unbind" {
t.Errorf("after unbind: %s", got)
}
s.Restore(find(t, s, "super+t"))
if got := values(s); got != "" {
t.Errorf("after restore: %s", got)
}
}
func TestChainMovesWithBinding(t *testing.T) {
s := NewSet(nil, []string{"ctrl+a=new_tab", "chain=toggle_fullscreen"})
b := find(t, s, "ctrl+a")
if err := s.Change(&b, "ctrl+b=new_tab"); err != nil {
t.Fatal(err)
}
if got := values(s); got != "ctrl+b=new_tab | chain=toggle_fullscreen" {
t.Errorf("got %s", got)
}
}
func TestDecodeCSI(t *testing.T) {
cases := map[string]string{
"\x1b[116;9u": "super+t",
"\x1b[116;10u": "super+shift+t",
"\x1b[44;10u": "super+shift+,",
"\x1b[97;5u": "ctrl+a",
"\x1b[167;9u": "super+§",
"\x1b[1;9C": "super+arrow_right",
"\x1b[5;3~": "alt+page_up",
"\x1b[13;2u": "shift+enter",
"\x1b[57399;5u": "ctrl+numpad_0",
"\x1b[57376u": "f13",
"\x1b[97:65;2u": "shift+a",
}
for seq, want := range cases {
c, ok := DecodeCSI([]byte(seq))
if !ok || c.String() != want {
t.Errorf("DecodeCSI(%q) = %q, %v; want %q", seq, c.String(), ok, want)
}
}
if c, ok := DecodeCSI([]byte("\x1b[57441;2u")); !ok || !c.Modifier {
t.Error("left shift should be reported as a modifier key")
}
if _, ok := DecodeCSI([]byte("\x1b[?9u")); ok {
t.Error("kitty reply is not a key")
}
}
func TestDecodeKeyName(t *testing.T) {
cases := map[string]string{
"ctrl+a": "ctrl+a",
"alt+shift+up": "alt+shift+arrow_up",
"ctrl+shift+up": "ctrl+shift+arrow_up",
"f5": "f5",
"A": "shift+a",
"pgdown": "page_down",
"shift+tab": "shift+tab",
"alt+x": "alt+x",
"+": "+",
}
for in, want := range cases {
c, ok := DecodeKeyName(in)
if !ok || c.String() != want {
t.Errorf("DecodeKeyName(%q) = %q, %v; want %q", in, c.String(), ok, want)
}
}
}
+223
View File
@@ -0,0 +1,223 @@
package keybind
import (
"strconv"
"strings"
"unicode/utf8"
)
// Key recording.
//
// While recording, the editor asks the terminal for the kitty keyboard
// protocol (flags 1|8: disambiguate escape codes, report all keys as escape
// codes). Ghostty then reports every key press, including ones with the
// super/cmd modifier, as "CSI code ; modifiers u" (or the legacy
// "CSI 1 ; modifiers A" forms for arrows and function keys). Terminals
// without the protocol send classic sequences, which are decoded from the
// key names Bubble Tea produces.
// PushKitty and PopKitty enable and restore the kitty keyboard protocol.
// QueryKitty asks the terminal for the current flags; a terminal that
// supports the protocol answers with "CSI ? flags u".
const (
PushKitty = "\x1b[>9u"
PopKitty = "\x1b[<u"
QueryKitty = "\x1b[?u"
)
// Combo is one recorded key combination.
type Combo struct {
Mods map[string]bool
Key string
Modifier bool // a lone modifier key press (ignored by the recorder)
}
func (c Combo) String() string {
return strings.Join(append(FormatMods(c.Mods), c.Key), "+")
}
// Plain reports whether the combination has no modifiers.
func (c Combo) Plain() bool {
for _, on := range c.Mods {
if on {
return false
}
}
return true
}
// IsKittyReply reports whether seq is the answer to QueryKitty.
func IsKittyReply(seq []byte) bool {
s := string(seq)
return strings.HasPrefix(s, "\x1b[?") && strings.HasSuffix(s, "u")
}
var kittyFunctional = map[int]string{
9: "tab", 13: "enter", 27: "escape", 32: "space", 127: "backspace",
57358: "caps_lock", 57359: "scroll_lock", 57360: "num_lock", 57361: "print_screen",
57362: "pause", 57363: "context_menu",
57409: "numpad_decimal", 57410: "numpad_divide", 57411: "numpad_multiply",
57412: "numpad_subtract", 57413: "numpad_add", 57414: "numpad_enter", 57415: "numpad_equal",
57416: "numpad_separator", 57417: "numpad_left", 57418: "numpad_right", 57419: "numpad_up",
57420: "numpad_down", 57421: "numpad_page_up", 57422: "numpad_page_down",
57423: "numpad_home", 57424: "numpad_end", 57425: "numpad_insert", 57426: "numpad_delete",
57427: "numpad_begin",
57430: "media_play_pause", 57432: "media_stop", 57435: "media_track_next",
57436: "media_track_previous", 57438: "audio_volume_down", 57439: "audio_volume_up",
57440: "audio_volume_mute",
}
var legacyFinal = map[byte]string{
'A': "arrow_up", 'B': "arrow_down", 'C': "arrow_right", 'D': "arrow_left",
'H': "home", 'F': "end", 'E': "numpad_begin", 'P': "f1", 'Q': "f2", 'R': "f3", 'S': "f4",
}
var tildeKeys = map[int]string{
2: "insert", 3: "delete", 5: "page_up", 6: "page_down", 7: "home", 8: "end",
11: "f1", 12: "f2", 13: "f3", 14: "f4", 15: "f5", 17: "f6", 18: "f7", 19: "f8",
20: "f9", 21: "f10", 23: "f11", 24: "f12", 29: "context_menu", 57427: "numpad_begin",
}
func init() {
for i := 0; i <= 9; i++ {
kittyFunctional[57399+i] = "numpad_" + strconv.Itoa(i)
}
for i := 13; i <= 25; i++ {
kittyFunctional[57376+i-13] = "f" + strconv.Itoa(i)
}
}
func decodeMods(field string) map[string]bool {
mods := map[string]bool{}
v, _, _ := strings.Cut(field, ":") // drop the event type
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return mods
}
n--
mods["shift"] = n&1 != 0
mods["alt"] = n&2 != 0
mods["ctrl"] = n&4 != 0
mods["super"] = n&8 != 0
return mods
}
// DecodeCSI decodes a key event escape sequence ("\x1b[...u", "\x1b[1;9A",
// "\x1b[5;3~", …). ok is false for anything that is not a key event.
func DecodeCSI(seq []byte) (Combo, bool) {
s := string(seq)
if !strings.HasPrefix(s, "\x1b[") || len(s) < 3 || IsKittyReply(seq) {
return Combo{}, false
}
final := s[len(s)-1]
params := strings.Split(s[2:len(s)-1], ";")
modField := ""
if len(params) > 1 {
modField = params[1]
}
c := Combo{Mods: decodeMods(modField)}
switch {
case final == 'u':
codeStr, _, _ := strings.Cut(params[0], ":") // drop shifted/base-layout keys
code, err := strconv.Atoi(codeStr)
if err != nil {
return Combo{}, false
}
if code >= 57441 && code <= 57452 {
c.Modifier = true // shift, ctrl, alt, super, hyper, meta, … keys
return c, true
}
if name, ok := kittyFunctional[code]; ok {
c.Key = name
if code == 57358 || code == 57360 {
c.Modifier = true // lock keys
}
return c, true
}
if code < 32 || !utf8.ValidRune(rune(code)) {
return Combo{}, false
}
c.Key = string(rune(code))
return c, true
case final == '~':
code, err := strconv.Atoi(params[0])
if err != nil {
return Combo{}, false
}
name, ok := tildeKeys[code]
if !ok {
return Combo{}, false
}
c.Key = name
return c, true
default:
name, ok := legacyFinal[final]
if !ok {
return Combo{}, false
}
c.Key = name
return c, true
}
}
var legacyNames = map[string]string{
"up": "arrow_up", "down": "arrow_down", "left": "arrow_left", "right": "arrow_right",
"pgup": "page_up", "pgdown": "page_down", "home": "home", "end": "end",
"insert": "insert", "delete": "delete", "tab": "tab", "enter": "enter",
"esc": "escape", "backspace": "backspace", " ": "space", "space": "space",
}
// DecodeKeyName converts a Bubble Tea key name ("ctrl+a", "alt+shift+up",
// "f5", "A") into a combination. Classic terminal input cannot represent
// super/cmd, and shifted symbols arrive as the symbol itself.
func DecodeKeyName(name string) (Combo, bool) {
c := Combo{Mods: map[string]bool{}}
if name == "" {
return c, false
}
switch name {
case "shift+tab":
c.Mods["shift"] = true
c.Key = "tab"
return c, true
case "ctrl+@", "ctrl+ ":
c.Mods["ctrl"] = true
c.Key = "space"
return c, true
}
rest := name
for {
found := false
for _, m := range []string{"ctrl+", "alt+", "shift+"} {
if strings.HasPrefix(rest, m) && len(rest) > len(m) {
c.Mods[strings.TrimSuffix(m, "+")] = true
rest = rest[len(m):]
found = true
}
}
if !found {
break
}
}
if k, ok := legacyNames[rest]; ok {
c.Key = k
return c, true
}
if len(rest) >= 2 && rest[0] == 'f' {
if n, err := strconv.Atoi(rest[1:]); err == nil && n >= 1 && n <= 25 {
c.Key = rest
return c, true
}
}
if utf8.RuneCountInString(rest) == 1 {
r, _ := utf8.DecodeRuneInString(rest)
if r >= 'A' && r <= 'Z' {
c.Mods["shift"] = true
r += 'a' - 'A'
}
c.Key = string(r)
return c, true
}
return c, false
}
+326
View File
@@ -0,0 +1,326 @@
package keybind
import (
"fmt"
"strings"
)
// Source tells where an effective binding comes from.
type Source int
const (
Default Source = iota // Ghostty's built-in binding
Changed // a built-in trigger the user bound to another action
Custom // a user binding on a trigger without built-in binding
Unbound // a built-in binding the user removed
)
func (s Source) String() string {
switch s {
case Changed:
return "changed"
case Custom:
return "custom"
case Unbound:
return "unbound"
}
return "default"
}
// Entry is one parsed `keybind` value.
type Entry struct {
Value string
Flags string // e.g. "global:"
Trigger string // without flags, as written
Norm string // canonical identity of the trigger
Action string
Clear bool // "keybind = clear"
Chain bool // "keybind = chain=ACTION"
}
// ParseEntry parses a raw `keybind` config value.
func ParseEntry(v string) Entry {
v = strings.TrimSpace(v)
if len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' {
v = v[1 : len(v)-1]
}
e := Entry{Value: v}
if v == "clear" {
e.Clear = true
return e
}
t, a := Split(v)
e.Action = a
if t == "chain" {
e.Chain = true
return e
}
e.Flags, e.Trigger = StripFlags(t)
e.Norm = NormalizeLoose(t)
return e
}
// Binding is one row of the effective key binding table.
type Binding struct {
Norm string
Trigger string // as written, including flag prefixes
Action string
Chain []string // actions chained with "chain="
Source Source
Default string // Ghostty's built-in action for this trigger, if any
InConfig bool // the user's config has an entry for this trigger
}
// group is a binding entry together with the "chain=" entries after it.
type group struct {
entries []string
e Entry
}
func (g group) chain() []string { return g.entries[1:] }
// Set is the user's keybind entries on top of Ghostty's defaults.
type Set struct {
defaults []Entry
defByNorm map[string]Entry
groups []group
}
// NewSet builds a set from Ghostty's default values and the user's values.
func NewSet(defaults, user []string) *Set {
s := &Set{defByNorm: map[string]Entry{}}
for _, d := range defaults {
e := ParseEntry(d)
if e.Norm == "" || e.Action == "" {
continue
}
if _, dup := s.defByNorm[e.Norm]; !dup {
s.defaults = append(s.defaults, e)
}
s.defByNorm[e.Norm] = e
}
for _, v := range user {
e := ParseEntry(v)
if e.Chain && len(s.groups) > 0 && !s.groups[len(s.groups)-1].e.Clear {
last := &s.groups[len(s.groups)-1]
last.entries = append(last.entries, v)
continue
}
s.groups = append(s.groups, group{entries: []string{v}, e: e})
}
return s
}
// Values returns the user's keybind entries.
func (s *Set) Values() []string {
var out []string
for _, g := range s.groups {
out = append(out, g.entries...)
}
return out
}
// HasClear reports whether the user's entries contain "clear".
func (s *Set) HasClear() bool {
for _, g := range s.groups {
if g.e.Clear {
return true
}
}
return false
}
// effective computes the active bindings in insertion order.
func (s *Set) effective() (map[string]*Binding, []string) {
m := map[string]*Binding{}
var order []string
put := func(b *Binding) {
if _, ok := m[b.Norm]; !ok {
order = append(order, b.Norm)
}
m[b.Norm] = b
}
for _, d := range s.defaults {
put(&Binding{Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Default, Default: d.Action})
}
for _, g := range s.groups {
e := g.e
switch {
case e.Clear:
m, order = map[string]*Binding{}, nil
case e.Chain || e.Norm == "":
case e.Action == "unbind":
delete(m, e.Norm)
default:
b := &Binding{Norm: e.Norm, Trigger: e.Flags + e.Trigger, Action: e.Action, InConfig: true, Source: Custom}
for _, c := range g.chain() {
_, a := Split(c)
b.Chain = append(b.Chain, a)
}
if d, ok := s.defByNorm[e.Norm]; ok {
b.Default = d.Action
b.Source = Changed
if d.Action == e.Action && d.Flags == e.Flags && len(b.Chain) == 0 {
b.Source = Default
}
}
put(b)
}
}
return m, order
}
// Bindings returns every effective binding plus the built-in bindings that
// were removed (as Unbound).
func (s *Set) Bindings() []Binding {
m, order := s.effective()
var out []Binding
for _, n := range order {
if b, ok := m[n]; ok {
out = append(out, *b)
}
}
for _, d := range s.defaults {
if _, ok := m[d.Norm]; ok {
continue
}
out = append(out, Binding{
Norm: d.Norm, Trigger: d.Flags + d.Trigger, Action: d.Action, Source: Unbound,
Default: d.Action, InConfig: s.lastGroup(d.Norm) >= 0,
})
}
return out
}
// Lookup returns the effective binding for a trigger identity.
func (s *Set) Lookup(norm string) (Binding, bool) {
m, _ := s.effective()
if b, ok := m[norm]; ok {
return *b, true
}
return Binding{}, false
}
// lastGroup returns the index of the last user group for norm, or -1.
func (s *Set) lastGroup(norm string) int {
for i := len(s.groups) - 1; i >= 0; i-- {
if s.groups[i].e.Norm == norm && !s.groups[i].e.Chain && !s.groups[i].e.Clear {
return i
}
}
return -1
}
// drop removes all user groups for norm except the one at keep (-1 for
// none) and returns the new index of the kept group.
func (s *Set) drop(norm string, keep int) int {
var out []group
newKeep := -1
for i, g := range s.groups {
if g.e.Norm == norm && !g.e.Clear && !g.e.Chain && i != keep {
continue
}
if i == keep {
newKeep = len(out)
}
out = append(out, g)
}
s.groups = out
return newKeep
}
func (s *Set) active(norm string) (Binding, bool) { return s.Lookup(norm) }
func (s *Set) appendValue(v string) {
s.groups = append(s.groups, group{entries: []string{v}, e: ParseEntry(v)})
}
// Change binds value ("trigger=action"). When old is given, that binding is
// being edited: if its trigger changes, a built-in binding is unbound from
// its old trigger, while a user binding simply moves (the old trigger falls
// back to Ghostty's default, if it has one). Any other binding of the new
// trigger is replaced.
func (s *Set) Change(old *Binding, value string) error {
ne := ParseEntry(value)
if ne.Clear || ne.Chain || ne.Norm == "" || ne.Action == "" {
return fmt.Errorf("expected trigger=action")
}
if _, err := Normalize(ne.Flags + ne.Trigger); err != nil {
return err
}
// The user's own entry for the edited binding, if any.
oldIdx := -1
if old != nil && old.Source != Unbound {
if i := s.lastGroup(old.Norm); i >= 0 && s.groups[i].e.Action != "unbind" {
oldIdx = i
}
}
var chain []string
if oldIdx >= 0 {
chain = s.groups[oldIdx].chain()
}
g := group{entries: append([]string{ne.Value}, chain...), e: ne}
var idx int
switch {
case oldIdx >= 0 && old.Source != Default:
// Rewrite the user's entry in place, then remove other entries for
// the old and the new trigger. If the trigger changed, the old one
// falls back to Ghostty's default (if it has one).
s.groups[oldIdx] = g
idx = s.drop(old.Norm, oldIdx)
idx = s.drop(ne.Norm, idx)
default:
if old != nil && old.Norm != ne.Norm && old.Source == Default {
// Moving a built-in binding: the old trigger must stop doing it.
s.drop(old.Norm, -1)
if _, still := s.active(old.Norm); still {
_, trigger := StripFlags(old.Trigger)
s.appendValue(trigger + "=unbind")
}
}
idx = s.drop(ne.Norm, s.lastGroup(ne.Norm))
if idx >= 0 {
s.groups[idx] = g
} else {
s.groups = append(s.groups, g)
idx = len(s.groups) - 1
}
}
// A binding identical to Ghostty's default needs no config entry.
if d, ok := s.defByNorm[ne.Norm]; ok && d.Action == ne.Action && d.Flags == ne.Flags && len(chain) == 0 {
saved := append([]group(nil), s.groups...)
s.groups = append(s.groups[:idx:idx], s.groups[idx+1:]...)
if b, ok := s.active(ne.Norm); !ok || b.Action != ne.Action {
s.groups = saved // needed after all (e.g. after "clear")
}
}
return nil
}
// Unbind removes the binding of b's trigger.
func (s *Set) Unbind(b Binding) {
if b.Source == Unbound {
return
}
s.drop(b.Norm, -1)
if _, still := s.active(b.Norm); still {
_, trigger := StripFlags(b.Trigger)
s.appendValue(trigger + "=unbind")
}
}
// Restore resets b's trigger to Ghostty's built-in behavior: the built-in
// binding if there is one, otherwise no binding.
func (s *Set) Restore(b Binding) {
s.drop(b.Norm, -1)
d, ok := s.defByNorm[b.Norm]
if !ok {
return
}
if cur, active := s.active(b.Norm); !active || cur.Action != d.Action {
s.appendValue(d.Value) // e.g. after "keybind = clear"
}
}
+172
View File
@@ -0,0 +1,172 @@
package schema
import (
"regexp"
"strings"
)
// Ghostty itself has no option categories; these groupings exist only to
// make the editor easier to navigate.
const (
CatFonts = "Fonts"
CatFontMetrics = "Font Metrics"
CatColors = "Colors & Theme"
CatBackground = "Background"
CatCursor = "Cursor"
CatWindow = "Window"
CatTabsSplits = "Tabs & Splits"
CatMouse = "Mouse & Selection"
CatClipboard = "Clipboard"
CatKeyboard = "Keyboard"
CatShell = "Shell & Commands"
CatScrolling = "Scrolling"
CatNotifications = "Notifications & Bell"
CatQuickTerminal = "Quick Terminal"
CatShaders = "Shaders"
CatMacOS = "macOS"
CatLinux = "Linux & GTK"
CatConfigFiles = "Config Files"
CatAdvanced = "Advanced"
)
var categoryOrder = []string{
CatFonts, CatFontMetrics, CatColors, CatBackground, CatCursor, CatWindow,
CatTabsSplits, CatMouse, CatClipboard, CatKeyboard, CatShell, CatScrolling,
CatNotifications, CatQuickTerminal, CatShaders, CatMacOS, CatLinux,
CatConfigFiles, CatAdvanced,
}
// exact key assignments, checked before the prefix rules below.
var categoryByKey = map[string]string{
"keybind": CatKeyboard,
"key-remap": CatKeyboard,
"macos-option-as-alt": CatKeyboard,
"vt-kam-allowed": CatKeyboard,
"config-file": CatConfigFiles,
"config-default-files": CatConfigFiles,
"cursor-click-to-move": CatMouse,
"theme": CatColors,
"background": CatColors,
"foreground": CatColors,
"bold-color": CatColors,
"minimum-contrast": CatColors,
"faint-opacity": CatColors,
"alpha-blending": CatColors,
"osc-color-report-format": CatColors,
"window-colorspace": CatColors,
"selection-foreground": CatColors,
"selection-background": CatColors,
"window-title-font-family": CatWindow,
"freetype-load-flags": CatFonts,
"grapheme-width-method": CatFonts,
"window-new-tab-position": CatTabsSplits,
"window-show-tab-bar": CatTabsSplits,
"window-inherit-working-directory": CatShell,
"tab-inherit-working-directory": CatShell,
"split-inherit-working-directory": CatShell,
"scrollback-limit": CatScrolling,
"scrollbar": CatScrolling,
"scroll-to-bottom": CatScrolling,
"mouse-scroll-multiplier": CatScrolling,
"focus-follows-mouse": CatMouse,
"click-repeat-interval": CatMouse,
"right-click-action": CatMouse,
"copy-on-select": CatClipboard,
"command": CatShell,
"initial-command": CatShell,
"env": CatShell,
"input": CatShell,
"working-directory": CatShell,
"wait-after-command": CatShell,
"abnormal-command-exit-runtime": CatShell,
"term": CatShell,
"enquiry-response": CatShell,
"command-palette-entry": CatShell,
"app-notifications": CatNotifications,
"desktop-notifications": CatNotifications,
"progress-style": CatNotifications,
"auto-update": CatMacOS,
"auto-update-channel": CatMacOS,
"class": CatLinux,
"async-backend": CatLinux,
"language": CatLinux,
"maximize": CatWindow,
"fullscreen": CatWindow,
"title": CatWindow,
"initial-window": CatWindow,
"confirm-close-surface": CatWindow,
"undo-timeout": CatWindow,
}
var categoryPrefixes = []struct {
prefix, cat string
}{
{"quick-terminal-", CatQuickTerminal},
{"gtk-quick-terminal-", CatQuickTerminal},
{"custom-shader", CatShaders},
{"adjust-cursor-", CatCursor},
{"adjust-", CatFontMetrics},
{"font-", CatFonts},
{"cursor-", CatCursor},
{"background-", CatBackground},
{"palette", CatColors},
{"search-", CatColors},
{"split-", CatTabsSplits},
{"unfocused-split-", CatTabsSplits},
{"mouse-", CatMouse},
{"selection-", CatMouse},
{"link", CatMouse},
{"clipboard-", CatClipboard},
{"shell-integration", CatShell},
{"bell-", CatNotifications},
{"notify-on-", CatNotifications},
{"macos-", CatMacOS},
{"gtk-", CatLinux},
{"linux-", CatLinux},
{"x11-", CatLinux},
{"window-", CatWindow},
{"resize-overlay", CatWindow},
{"quit-after-", CatWindow},
}
func categorize(key string) string {
if c, ok := categoryByKey[key]; ok {
return c
}
for _, p := range categoryPrefixes {
if strings.HasPrefix(key, p.prefix) {
return p.cat
}
}
return CatAdvanced
}
// platform reports which OS an option is limited to, based on its key
// prefix and on sentences like "This is only supported on macOS." in its
// documentation. Notes about individual values (e.g. "(macOS only)" in a
// list item) or about several platforms are ignored.
func platform(o *Option) string {
switch {
case strings.HasPrefix(o.Key, "macos-"):
return "macOS"
case strings.HasPrefix(o.Key, "gtk-"), strings.HasPrefix(o.Key, "linux-"),
strings.HasPrefix(o.Key, "x11-"):
return "Linux"
}
text := strings.Join(strings.Fields(o.Doc), " ")
for _, sentence := range strings.SplitAfter(text, ". ") {
m := rePlatformNote.FindStringSubmatch(strings.ToLower(strings.TrimSpace(sentence)))
if m == nil {
continue
}
if m[1] == "macos" || m[2] == "macos" {
return "macOS"
}
return "Linux"
}
return ""
}
var rePlatformNote = regexp.MustCompile(
`^(?:note: )?(?:(?:this|it)(?: \w+)? (?:is )?)?(?:currently )?only (?:supported|implemented|available) on (macos|linux|gtk)\b(?: \(gtk\))?[.,;]?$` +
`|^(macos|gtk|linux) only\.?$`)
+334
View File
@@ -0,0 +1,334 @@
// Package schema describes every Ghostty configuration option: its value
// kind, allowed values, documentation and default values.
//
// The type information is generated from Ghostty's Config.zig (see
// tools/genschema) and embedded into the binary. Documentation and defaults
// are refreshed at runtime from the installed Ghostty binary when available,
// so they always match the version the user actually runs.
package schema
import (
_ "embed"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)
// Kind describes how the value of an option is edited and validated.
type Kind string
const (
KindBool Kind = "bool"
KindEnum Kind = "enum" // one of Values
KindChoice Kind = "choice" // one of Values or a custom value
KindFlags Kind = "flags" // comma separated set of Flags, "no-" prefix disables
KindInt Kind = "int" // integer within Min/Max
KindFloat Kind = "float" // floating point number
KindColor Kind = "color" // hex or X11 color name, plus optional Values
KindColorList Kind = "colorlist" // comma separated colors
KindMetric Kind = "metric" // integer or percentage, e.g. "2" or "-10%"
KindDuration Kind = "duration" // e.g. "750ms", "1h30m"
KindPadding Kind = "padding" // "2" or "2,4"
KindText Kind = "text"
KindPath Kind = "path"
KindTheme Kind = "theme"
KindFont Kind = "font"
KindKeybind Kind = "keybind"
KindPalette Kind = "palette"
)
// Option is a single configuration key.
type Option struct {
Key string `json:"key"`
ZigType string `json:"zigType,omitempty"`
Kind Kind `json:"kind"`
Repeatable bool `json:"repeatable,omitempty"`
Values []string `json:"values,omitempty"`
Flags []string `json:"flags,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Hint string `json:"hint,omitempty"`
Doc string `json:"doc,omitempty"`
Defaults []string `json:"defaults,omitempty"`
// NotListed marks options that Ghostty accepts but does not print
// with `+show-config`. They are kept even when refreshing from a live
// Ghostty binary.
NotListed bool `json:"notListed,omitempty"`
Category string `json:"-"`
Platform string `json:"-"` // "", "macOS" or "Linux"
}
// Default returns the default value for scalar options ("" when unset).
func (o *Option) Default() string {
if len(o.Defaults) == 0 {
return ""
}
return o.Defaults[len(o.Defaults)-1]
}
// DefaultList returns the default entries of a repeatable option, ignoring
// the empty placeholder entry Ghostty prints for empty lists.
func (o *Option) DefaultList() []string {
var out []string
for _, d := range o.Defaults {
if d != "" {
out = append(out, d)
}
}
return out
}
// TypeLabel is a short human readable description of the value type.
func (o *Option) TypeLabel() string {
var s string
switch o.Kind {
case KindBool:
s = "boolean"
case KindEnum:
s = "one of " + strings.Join(o.Values, ", ")
case KindChoice:
s = strings.Join(o.Values, ", ") + " or custom value"
case KindFlags:
s = "flags: " + strings.Join(o.Flags, ", ")
case KindInt:
s = "integer"
if o.Min != nil && o.Max != nil {
s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max))
} else if o.Min != nil {
s += fmt.Sprintf(" (%s or more)", num(*o.Min))
}
case KindFloat:
s = "number"
if o.Min != nil && o.Max != nil {
s += fmt.Sprintf(" (%s to %s)", num(*o.Min), num(*o.Max))
} else if o.Min != nil {
s += fmt.Sprintf(" (%s or more)", num(*o.Min))
}
case KindColor:
s = "color (#rrggbb or X11 name)"
if len(o.Values) > 0 {
s += " or " + strings.Join(o.Values, ", ")
}
case KindColorList:
s = "comma separated colors"
case KindMetric:
s = "integer or percentage (e.g. 2, -10%)"
case KindDuration:
s = "duration (e.g. 500ms, 5s, 1h30m)"
case KindPadding:
s = "pixels, optionally two values (e.g. 2 or 2,4)"
case KindPath:
s = "file path"
case KindTheme:
s = "theme name (or light:NAME,dark:NAME)"
case KindFont:
s = "font family"
case KindKeybind:
s = "key binding (trigger=action)"
case KindPalette:
s = "palette entries (N=color)"
default:
s = "text"
}
if o.Repeatable && o.Kind != KindKeybind && o.Kind != KindPalette {
s = "list of " + s
}
return s
}
// Schema is the full set of known options.
type Schema struct {
GhosttyVersion string `json:"ghosttyVersion"`
Options []*Option `json:"options"`
// Source describes where docs and defaults came from.
Source string `json:"-"`
byKey map[string]*Option
}
//go:embed schema.json
var embedded []byte
// Embedded returns the schema compiled into the binary.
func Embedded() (*Schema, error) {
var s Schema
if err := json.Unmarshal(embedded, &s); err != nil {
return nil, fmt.Errorf("decode embedded schema: %w", err)
}
s.Source = "built-in (Ghostty " + s.GhosttyVersion + ")"
s.finish()
return &s, nil
}
// Lookup returns the option for key, or nil.
func (s *Schema) Lookup(key string) *Option {
return s.byKey[key]
}
func (s *Schema) finish() {
s.byKey = make(map[string]*Option, len(s.Options))
for _, o := range s.Options {
o.Category = categorize(o.Key)
o.Platform = platform(o)
s.byKey[o.Key] = o
}
}
// Refresh replaces docs and defaults with the output of
// `ghostty +show-config --default --docs` from the installed Ghostty.
// Options unknown to the installed version are dropped; options unknown to
// the embedded schema are added with an inferred kind.
func (s *Schema) Refresh(docsOutput, version string) {
parsed := ParseDocs(docsOutput)
if len(parsed) == 0 {
return
}
var opts []*Option
seen := make(map[string]bool)
for _, p := range parsed {
seen[p.Key] = true
o := s.byKey[p.Key]
if o == nil {
o = inferOption(p)
}
o.Doc = p.Doc
o.Defaults = p.Defaults
opts = append(opts, o)
}
for _, o := range s.Options {
if !seen[o.Key] && o.NotListed {
opts = append(opts, o)
}
}
s.Options = opts
if version != "" {
s.GhosttyVersion = version
}
s.Source = "Ghostty " + s.GhosttyVersion
s.finish()
}
// inferOption guesses the kind of an option the embedded schema does not
// know about (e.g. one added in a newer Ghostty release).
func inferOption(p DocEntry) *Option {
o := &Option{Key: p.Key, Kind: KindText, Repeatable: len(p.Defaults) > 1}
d := ""
if len(p.Defaults) > 0 {
d = p.Defaults[0]
}
switch {
case d == "true" || d == "false":
o.Kind = KindBool
case isNumber(d):
o.Kind = KindFloat
}
return o
}
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
func isNumber(s string) bool {
if s == "" {
return false
}
var f float64
_, err := fmt.Sscanf(s, "%g", &f)
return err == nil && strings.TrimLeft(s, "-+0123456789.") == ""
}
// DocEntry is one key parsed from `+show-config --default --docs`.
type DocEntry struct {
Key string
Doc string
Defaults []string
}
// ParseDocs parses the output of `ghostty +show-config --default --docs`.
// Keys that directly follow another key without their own comment block
// share the previous documentation (e.g. font-family-bold).
func ParseDocs(out string) []DocEntry {
var (
entries []DocEntry
index = map[string]int{}
pending []string
lastDoc string
)
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSuffix(line, "\r")
switch {
case strings.HasPrefix(line, "#"):
text := strings.TrimPrefix(line, "#")
text = strings.TrimPrefix(text, " ")
pending = append(pending, text)
case strings.TrimSpace(line) == "":
continue
default:
key, value, ok := splitShowConfigLine(line)
if !ok {
continue
}
if len(pending) > 0 {
lastDoc = strings.TrimRight(strings.Join(pending, "\n"), "\n ")
pending = nil
}
if i, ok := index[key]; ok {
entries[i].Defaults = append(entries[i].Defaults, value)
continue
}
index[key] = len(entries)
entries = append(entries, DocEntry{Key: key, Doc: lastDoc, Defaults: []string{value}})
}
}
return entries
}
// splitShowConfigLine splits "key = value". The value is kept verbatim
// because leading whitespace can be significant (selection-word-chars).
func splitShowConfigLine(line string) (key, value string, ok bool) {
i := strings.Index(line, " =")
if i <= 0 {
return "", "", false
}
key = line[:i]
if strings.ContainsAny(key, " \t") {
return "", "", false
}
value = strings.TrimPrefix(line[i+2:], " ")
return key, value, true
}
// Categories returns category names in display order, restricted to those
// that contain at least one option.
func (s *Schema) Categories() []string {
present := map[string]bool{}
for _, o := range s.Options {
present[o.Category] = true
}
var out []string
for _, c := range categoryOrder {
if present[c] {
out = append(out, c)
delete(present, c)
}
}
var rest []string
for c := range present {
rest = append(rest, c)
}
sort.Strings(rest)
return append(out, rest...)
}
// InCategory returns the options of a category in schema order.
func (s *Schema) InCategory(cat string) []*Option {
var out []*Option
for _, o := range s.Options {
if o.Category == cat {
out = append(out, o)
}
}
return out
}
File diff suppressed because it is too large. Load diff
+176
View File
@@ -0,0 +1,176 @@
package schema
import (
"strings"
"testing"
)
func TestEmbeddedSchema(t *testing.T) {
s, err := Embedded()
if err != nil {
t.Fatal(err)
}
if len(s.Options) < 150 {
t.Fatalf("only %d options in embedded schema", len(s.Options))
}
for _, o := range s.Options {
if o.Kind == "" {
t.Errorf("%s has no kind", o.Key)
}
if o.Category == "" {
t.Errorf("%s has no category", o.Key)
}
if (o.Kind == KindEnum || o.Kind == KindChoice) && len(o.Values) == 0 {
t.Errorf("%s has no values", o.Key)
}
if o.Kind == KindEnum && o.Default() != "" && !contains(o.Values, o.Default()) {
t.Errorf("%s: default %q is not a valid value", o.Key, o.Default())
}
if !o.Repeatable && o.Default() != "" {
if err := o.Validate(o.Default()); err != nil {
t.Errorf("%s: default %q does not validate: %v", o.Key, o.Default(), err)
}
}
}
for _, key := range []string{"font-family", "keybind", "palette", "theme", "cursor-style", "shell-integration-features"} {
if s.Lookup(key) == nil {
t.Errorf("missing %s", key)
}
}
}
func TestParseDocs(t *testing.T) {
out := `# Font families.
#
# Can be repeated.
font-family =
font-family-bold =
# The palette.
palette = 0=#000000
palette = 1=#ff0000
selection-word-chars = '"
`
got := ParseDocs(out)
if len(got) != 4 {
t.Fatalf("got %d entries", len(got))
}
if got[0].Doc != "Font families.\n\nCan be repeated." {
t.Errorf("doc = %q", got[0].Doc)
}
if got[1].Doc != got[0].Doc {
t.Errorf("font-family-bold should share the font-family docs")
}
if len(got[2].Defaults) != 2 {
t.Errorf("palette defaults = %v", got[2].Defaults)
}
if got[3].Defaults[0] != " \t'\"" {
t.Errorf("leading whitespace must be kept, got %q", got[3].Defaults[0])
}
}
func TestValidate(t *testing.T) {
opt := func(k Kind) *Option {
return &Option{Kind: k, Values: []string{"cell-foreground"}, Flags: []string{"cursor", "sudo"}}
}
cases := []struct {
kind Kind
value string
ok bool
}{
{KindBool, "true", true},
{KindBool, "yes", false},
{KindColor, "#1e1e2e", true},
{KindColor, "fff", true},
{KindColor, "dark slate gray", true},
{KindColor, "cell-foreground", true},
{KindColor, "#12345", false},
{KindMetric, "-10%", true},
{KindMetric, "2", true},
{KindMetric, "1.5", false},
{KindDuration, "750ms", true},
{KindDuration, "1h 30m", true},
{KindDuration, "0", true},
{KindDuration, "5", false},
{KindPadding, "2,4", true},
{KindPadding, "a", false},
{KindFlags, "no-cursor,sudo", true},
{KindFlags, "false", true},
{KindFlags, "bogus", false},
{KindKeybind, "ctrl+==reset_font_size", true},
{KindKeybind, "clear", true},
{KindKeybind, "ctrl+a", false},
{KindPalette, "4=#89b4fa", true},
{KindPalette, "256=#000000", false},
{KindFloat, "0.5", true},
{KindFloat, "x", false},
}
for _, c := range cases {
err := opt(c.kind).Validate(c.value)
if (err == nil) != c.ok {
t.Errorf("%s %q: err = %v, want ok=%v", c.kind, c.value, err, c.ok)
}
}
}
func TestFlags(t *testing.T) {
o := &Option{Kind: KindFlags, Flags: []string{"cursor", "sudo", "title"}, Defaults: []string{"cursor,no-sudo,title"}}
st := o.ParseFlags("no-cursor")
if st["cursor"] || st["sudo"] || !st["title"] {
t.Fatalf("state = %v", st)
}
if got := o.FormatFlags(st); got != "no-cursor,no-sudo,title" {
t.Fatalf("format = %q", got)
}
}
func TestSplitKeybind(t *testing.T) {
cases := map[string][2]string{
"ctrl+a=new_tab": {"ctrl+a", "new_tab"},
"==text:=": {"=", "text:="},
"ctrl+==text:=hello": {"ctrl+=", "text:=hello"},
"super+shift+,=reload": {"super+shift+,", "reload"},
"ctrl+a>n=new_window": {"ctrl+a>n", "new_window"},
"§=goto_split:next": {"§", "goto_split:next"},
}
for in, want := range cases {
tr, ac := SplitKeybind(in)
if tr != want[0] || ac != want[1] {
t.Errorf("SplitKeybind(%q) = %q, %q", in, tr, ac)
}
}
}
func TestCategoriesCoverEverything(t *testing.T) {
s, _ := Embedded()
cats := s.Categories()
total := 0
for _, c := range cats {
total += len(s.InCategory(c))
}
if total != len(s.Options) {
t.Fatalf("categories hold %d of %d options", total, len(s.Options))
}
if !strings.Contains(strings.Join(cats, ","), CatFonts) {
t.Fatal("missing Fonts category")
}
}
func TestPlatformDetection(t *testing.T) {
s, _ := Embedded()
want := map[string]string{
"keybind": "",
"fullscreen": "",
"window-theme": "",
"window-step-resize": "macOS",
"undo-timeout": "macOS",
"window-subtitle": "Linux",
"macos-icon": "macOS",
"gtk-wide-tabs": "Linux",
}
for key, p := range want {
if o := s.Lookup(key); o == nil || o.Platform != p {
t.Errorf("%s: platform = %q, want %q", key, o.Platform, p)
}
}
}
+197
View File
@@ -0,0 +1,197 @@
package schema
import (
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"ghosttyconf/internal/colors"
"ghosttyconf/internal/keybind"
)
var (
reMetric = regexp.MustCompile(`^[+-]?\d+$|^[+-]?\d+(\.\d+)?%$`)
reDuration = regexp.MustCompile(`^(\s*\d+\s*(y|w|d|h|m|s|ms|µs|us|ns)\s*)+$`)
rePadding = regexp.MustCompile(`^\d+(\s*,\s*\d+)?$`)
rePalette = regexp.MustCompile(`^\s*(\d{1,3})\s*=\s*(.+?)\s*$`)
)
// Unquote strips one pair of surrounding double quotes, as Ghostty does
// when reading a config file.
func Unquote(s string) string {
if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
return s[1 : len(s)-1]
}
return s
}
// Validate checks a single (raw, possibly quoted) value for the option. For
// repeatable options it validates one list entry.
func (o *Option) Validate(raw string) error {
v := strings.TrimSpace(Unquote(raw))
if v == "" {
// An empty value resets the option to its default; always allowed.
return nil
}
switch o.Kind {
case KindBool:
if v != "true" && v != "false" {
return errors.New(`expected "true" or "false"`)
}
case KindEnum:
if !contains(o.Values, v) {
return fmt.Errorf("expected one of: %s", strings.Join(o.Values, ", "))
}
case KindFlags:
return o.validateFlags(v)
case KindInt:
n, err := strconv.ParseInt(v, 10, 64)
if err != nil {
return errors.New("expected a whole number")
}
return o.checkRange(float64(n))
case KindFloat:
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return errors.New("expected a number")
}
return o.checkRange(f)
case KindColor:
if contains(o.Values, v) || colors.Valid(v) {
return nil
}
return errors.New("expected a color like #1e1e2e, 1e1e2e, #fff or an X11 name like \"dark slate gray\"")
case KindColorList:
for _, part := range strings.Split(v, ",") {
if !colors.Valid(part) {
return fmt.Errorf("%q is not a valid color", strings.TrimSpace(part))
}
}
case KindMetric:
if !reMetric.MatchString(v) {
return errors.New("expected an integer (e.g. 2, -1) or a percentage (e.g. 10%, -5%)")
}
case KindDuration:
if v != "0" && !reDuration.MatchString(v) {
return errors.New("expected a duration such as 750ms, 5s, 2m or 1h30m")
}
case KindPadding:
if !rePadding.MatchString(v) {
return errors.New("expected one or two non-negative integers, e.g. 4 or 4,8")
}
case KindKeybind:
if v == "clear" {
return nil
}
trigger, action := SplitKeybind(v)
if trigger == "" || action == "" {
return errors.New("expected trigger=action, e.g. ctrl+shift+t=new_tab (or \"clear\")")
}
case KindPalette:
m := rePalette.FindStringSubmatch(v)
if m == nil {
return errors.New("expected N=COLOR, e.g. 4=#89b4fa")
}
if n, _ := strconv.Atoi(m[1]); n > 255 {
return errors.New("palette index must be between 0 and 255")
}
if !colors.Valid(m[2]) {
return fmt.Errorf("%q is not a valid color", m[2])
}
}
return nil
}
func (o *Option) validateFlags(v string) error {
if v == "true" || v == "false" {
return nil
}
for _, part := range strings.Split(v, ",") {
name := strings.TrimPrefix(strings.TrimSpace(part), "no-")
if !contains(o.Flags, name) {
return fmt.Errorf("unknown flag %q (valid: %s)", name, strings.Join(o.Flags, ", "))
}
}
return nil
}
func (o *Option) checkRange(f float64) error {
if o.Min != nil && f < *o.Min {
return fmt.Errorf("must be at least %s", num(*o.Min))
}
if o.Max != nil && f > *o.Max {
return fmt.Errorf("must be at most %s", num(*o.Max))
}
return nil
}
// ParseFlags returns the state of every flag for a flags value, starting
// from the option's default the same way Ghostty does.
func (o *Option) ParseFlags(value string) map[string]bool {
state := make(map[string]bool, len(o.Flags))
apply := func(v string) {
v = strings.TrimSpace(Unquote(v))
if v == "true" || v == "false" {
for _, f := range o.Flags {
state[f] = v == "true"
}
return
}
for _, part := range strings.Split(v, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
on := !strings.HasPrefix(part, "no-")
state[strings.TrimPrefix(part, "no-")] = on
}
}
apply(o.Default())
if value != "" {
apply(value)
}
return state
}
// FormatFlags renders flag states in Ghostty's explicit form,
// e.g. "cursor,no-sudo,title".
func (o *Option) FormatFlags(state map[string]bool) string {
parts := make([]string, len(o.Flags))
for i, f := range o.Flags {
if state[f] {
parts[i] = f
} else {
parts[i] = "no-" + f
}
}
return strings.Join(parts, ",")
}
// SplitKeybind splits "trigger=action" exactly like Ghostty does.
func SplitKeybind(v string) (trigger, action string) {
return keybind.Split(v)
}
// SplitPalette splits a palette entry into its index and color.
func SplitPalette(v string) (index int, color string, ok bool) {
m := rePalette.FindStringSubmatch(Unquote(v))
if m == nil {
return 0, "", false
}
n, err := strconv.Atoi(m[1])
if err != nil || n > 255 {
return 0, "", false
}
return n, m[2], true
}
func contains(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
+966
View File
@@ -0,0 +1,966 @@
// Package ui implements the terminal user interface.
package ui
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"ghosttyconf/internal/config"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
const (
catSet = "Set in Config"
catAll = "All Options"
)
type pane int
const (
paneCats pane = iota
paneOpts
)
// Messages delivering data loaded in the background.
type itemsMsg struct {
source string // "themes" or "fonts"
items []string
err error
}
type actionsMsg struct {
items []ghostty.Action
err error
}
// reloadMsg reports the result of asking Ghostty to reload its config.
type reloadMsg struct {
saved string // status text describing the save
err error
}
type undoEntry struct {
file *config.File
key string
}
type rect struct{ x, y, w, h int }
func (r rect) contains(x, y int) bool {
return x >= r.x && x < r.x+r.w && y >= r.y && y < r.y+r.h
}
// App is the Bubble Tea model of the editor.
type App struct {
sch *schema.Schema
gh *ghostty.Ghostty
file *config.File
saved *config.File
undo []undoEntry
rev int // incremented on every change to file
backup bool // a .bak copy was written this session
unknown map[string]*schema.Option
osName string
width, height int
focus pane
cats []string
catIdx int
catTop int
opts []*schema.Option
optIdx int
optTop int
search textinput.Model
searching bool
query string
hideForeign bool
doc viewport.Model
docFor string
editor editor
editOpt *schema.Option
dlg *dialog
status string
statusStyle lipgloss.Style
quitAfterSave bool
autoReload bool
// Screen regions from the last render, for mouse handling.
catRect, optRect, docRect rect
optListY int
themes []string
themesErr error
themesLoaded bool
fonts []string
fontsErr error
fontsLoaded bool
actions []ghostty.Action
actionsLoaded bool
themeCache map[string]*ghostty.Theme
}
// New creates the editor for file. gh may be nil when Ghostty is not
// installed; validation, themes, fonts and actions are then unavailable.
func New(sch *schema.Schema, gh *ghostty.Ghostty, file *config.File) *App {
a := &App{
sch: sch,
gh: gh,
file: file,
saved: file.Clone(),
unknown: map[string]*schema.Option{},
themeCache: map[string]*ghostty.Theme{},
doc: viewport.New(0, 0),
focus: paneOpts,
autoReload: true,
}
switch runtime.GOOS {
case "darwin":
a.osName = "macOS"
case "linux", "freebsd":
a.osName = "Linux"
}
a.search = textinput.New()
a.search.Prompt = "/ "
a.search.PromptStyle = stAccent
a.search.Placeholder = "search options and documentation"
a.search.PlaceholderStyle = stDim
a.cats = append([]string{catSet, catAll}, sch.Categories()...)
if len(file.Keys()) == 0 {
a.catIdx = 2 // nothing set yet: start with the first real category
}
a.rebuild()
if gh == nil {
a.setStatus("Running without the ghostty binary: built-in docs only; validation, themes, fonts and actions are unavailable.", stChanged)
}
return a
}
// SetAutoReload controls whether Ghostty is asked to reload its config
// after every save (on by default).
func (a *App) SetAutoReload(on bool) { a.autoReload = on }
func (a *App) Init() tea.Cmd {
if a.gh == nil {
return nil
}
gh := a.gh
return tea.Batch(
func() tea.Msg { t, err := gh.Themes(); return itemsMsg{"themes", t, err} },
func() tea.Msg { f, err := gh.Fonts(); return itemsMsg{"fonts", f, err} },
func() tea.Msg { ac, err := gh.Actions(); return actionsMsg{ac, err} },
)
}
func (a *App) setStatus(s string, st lipgloss.Style) {
a.status, a.statusStyle = s, st
}
func (a *App) dirty() bool { return !a.file.Equal(a.saved) }
// option returns the schema entry for key, synthesizing one for keys in the
// config file that Ghostty does not know.
func (a *App) option(key string) *schema.Option {
if o := a.sch.Lookup(key); o != nil {
return o
}
if o := a.unknown[key]; o != nil {
return o
}
o := &schema.Option{
Key: key,
Kind: schema.KindText,
Repeatable: len(a.file.GetAll(key)) > 1,
Category: catSet,
Doc: "This key is not a known Ghostty " + a.sch.GhosttyVersion + " option. " +
"It may be misspelled or belong to a different Ghostty version. " +
"Ghostty will report it as an error; press r to remove it.",
}
a.unknown[key] = o
return o
}
func (a *App) selected() *schema.Option {
if a.optIdx >= 0 && a.optIdx < len(a.opts) {
return a.opts[a.optIdx]
}
return nil
}
func (a *App) visible(o *schema.Option) bool {
return !a.hideForeign || o.Platform == "" || a.osName == "" || o.Platform == a.osName
}
// categoryOptions returns the options listed under a category.
func (a *App) categoryOptions(cat string) []*schema.Option {
var list []*schema.Option
switch cat {
case catSet:
for _, k := range a.file.Keys() {
list = append(list, a.option(k))
}
return list // always show everything that is set
case catAll:
list = append(list, a.sch.Options...)
sort.Slice(list, func(i, j int) bool { return list[i].Key < list[j].Key })
default:
list = a.sch.InCategory(cat)
}
var out []*schema.Option
for _, o := range list {
if a.visible(o) {
out = append(out, o)
}
}
return out
}
// searchOptions ranks options by how well they match the query: key
// matches first, then documentation matches.
func (a *App) searchOptions(q string) []*schema.Option {
terms := strings.Fields(strings.ToLower(q))
var byKey, byDoc []*schema.Option
for _, o := range a.sch.Options {
if !a.visible(o) {
continue
}
key, doc := o.Key, strings.ToLower(o.Doc)
inKey, inAny := true, true
for _, t := range terms {
if !strings.Contains(key, t) {
inKey = false
if !strings.Contains(doc, t) {
inAny = false
}
}
}
switch {
case inKey:
byKey = append(byKey, o)
case inAny:
byDoc = append(byDoc, o)
}
}
return append(byKey, byDoc...)
}
// rebuild recomputes the visible option list, keeping the selection.
func (a *App) rebuild() {
var keep string
if o := a.selected(); o != nil {
keep = o.Key
}
if a.query != "" {
a.opts = a.searchOptions(a.query)
} else {
a.opts = a.categoryOptions(a.cats[a.catIdx])
}
a.optIdx = min(a.optIdx, max(0, len(a.opts)-1))
for i, o := range a.opts {
if o.Key == keep {
a.optIdx = i
break
}
}
}
func (a *App) selectCategory(i int) {
if i == a.catIdx && a.query == "" {
return
}
a.catIdx = i
a.clearSearch()
a.optIdx, a.optTop = 0, 0
a.opts = nil
a.rebuild()
}
func (a *App) clearSearch() {
a.query = ""
a.searching = false
a.search.SetValue("")
a.search.Blur()
}
// ---------------------------------------------------------------------------
// Update
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
a.width, a.height = msg.Width, msg.Height
return a, nil
case itemsMsg:
switch msg.source {
case "themes":
a.themes, a.themesErr, a.themesLoaded = msg.items, msg.err, true
case "fonts":
a.fonts, a.fontsErr, a.fontsLoaded = msg.items, msg.err, true
}
case actionsMsg:
a.actions, a.actionsLoaded = msg.items, true
case reloadMsg:
switch {
case msg.err == nil:
a.setStatus(msg.saved+" Ghostty reloaded the configuration.", stOK)
case errors.Is(msg.err, ghostty.ErrNotRunning):
a.setStatus(msg.saved+" Ghostty is not running; it will use the new config on its next start.", stOK)
default:
a.setStatus(msg.saved+" Automatic reload failed: "+msg.err.Error()+". Reload with "+reloadShortcut()+".", stChanged)
}
return a, nil
case tea.MouseMsg:
return a, a.handleMouse(msg)
case tea.KeyMsg:
if msg.String() == "ctrl+c" && !a.capturing() {
if a.dlg != nil && a.dlg.quit {
return a, tea.Quit
}
return a, a.quit()
}
if a.dlg != nil {
return a, a.dlg.update(a, msg)
}
if a.editor != nil {
return a, a.updateEditor(msg)
}
return a, a.updateBrowse(msg)
}
if a.editor != nil {
return a, a.updateEditor(msg)
}
return a, nil
}
// capturing reports whether the editor records raw key presses, in which
// case no key may be interpreted by the application.
func (a *App) capturing() bool {
c, ok := a.editor.(interface{ capturing() bool })
return ok && c.capturing()
}
func (a *App) updateEditor(msg tea.Msg) tea.Cmd {
if km, ok := msg.(tea.KeyMsg); ok && !a.capturing() {
switch km.String() {
case "shift+down":
a.doc.ScrollDown(3)
return nil
case "shift+up":
a.doc.ScrollUp(3)
return nil
}
}
cmd, res := a.editor.Update(msg)
if res != nil {
o := a.editOpt
a.editor, a.editOpt = nil, nil
a.apply(o, res)
}
return cmd
}
func (a *App) updateBrowse(km tea.KeyMsg) tea.Cmd {
key := km.String()
if a.searching {
switch key {
case "esc":
a.clearSearch()
a.rebuild()
case "enter", "down", "tab":
a.searching = false
a.search.Blur()
a.focus = paneOpts
default:
var cmd tea.Cmd
a.search, cmd = a.search.Update(km)
if v := a.search.Value(); v != a.query {
a.query = v
a.optIdx, a.optTop = 0, 0
a.rebuild()
}
return cmd
}
return nil
}
a.status = ""
switch key {
case "q":
return a.quit()
case "?", "f1":
a.dlg = helpDialog()
return nil
case "/", "ctrl+f":
// Every search starts fresh, like "/" in less or vim.
a.search.SetValue("")
if a.query != "" {
a.query = ""
a.rebuild()
}
a.searching = true
a.focus = paneOpts
return a.search.Focus()
case "ctrl+s":
return a.save(false, false)
case "u", "ctrl+z":
a.undoLast()
return nil
case "c":
a.dlg = a.changesDialog()
return nil
case "b":
if o := a.sch.Lookup("keybind"); o != nil {
return a.edit(o)
}
return nil
case "p":
a.hideForeign = !a.hideForeign
if a.hideForeign {
a.setStatus("Hiding options that do not apply to "+a.osName+".", stDim)
} else {
a.setStatus("Showing options for all platforms.", stDim)
}
a.rebuild()
return nil
case "tab":
if a.focus == paneCats {
a.focus = paneOpts
} else {
a.focus = paneCats
}
return nil
case "esc":
if a.query != "" {
a.clearSearch()
a.rebuild()
}
return nil
case "ctrl+d", "shift+down":
a.doc.ScrollDown(max(3, a.doc.Height/2))
return nil
case "ctrl+u", "shift+up":
a.doc.ScrollUp(max(3, a.doc.Height/2))
return nil
}
if a.focus == paneCats {
if c, moved := moveCursor(key, a.catIdx, len(a.cats), 5); moved {
a.selectCategory(c)
return nil
}
switch key {
case "right", "l", "enter":
a.focus = paneOpts
}
return nil
}
if c, moved := moveCursor(key, a.optIdx, len(a.opts), max(1, a.optRect.h-3)); moved {
a.optIdx = c
return nil
}
o := a.selected()
switch key {
case "left", "h":
a.focus = paneCats
case "enter", "e", "right", "l":
if o != nil {
if key == "right" || key == "l" {
// Only open editors that are not instant toggles.
if o.Kind == schema.KindBool && !o.Repeatable {
return nil
}
}
return a.edit(o)
}
case " ":
if o != nil {
a.quickToggle(o)
}
case "+", "=", "-", "_":
if o != nil && !o.Repeatable {
delta := 1
if key == "-" || key == "_" {
delta = -1
}
a.step(o, delta)
}
case "r", "delete", "backspace", "d":
if o != nil {
a.apply(o, &result{})
}
}
return nil
}
// edit opens the editor for o. Booleans are toggled directly.
func (a *App) edit(o *schema.Option) tea.Cmd {
if o.Kind == schema.KindBool && !o.Repeatable {
a.quickToggle(o)
return nil
}
values := a.file.GetAll(o.Key)
current, _ := a.file.Get(o.Key)
switch {
case o.Kind == schema.KindKeybind:
a.editor = newKeybindManager(o, values, a.actions, func(v string) editor {
return a.valueEditor(o, v)
})
case o.Kind == schema.KindPalette:
pe := newPaletteEditor(o, values)
if th := a.currentTheme(); th != nil {
pe.useTheme(th)
}
a.editor = pe
case o.Repeatable:
a.editor = newListEditor(o, values, func(v string) editor {
e := a.valueEditor(o, v)
if t, ok := e.(*textEditor); ok {
t.item = true
}
return e
})
default:
a.editor = a.valueEditor(o, current)
}
a.editOpt = o
a.docFor = "" // force docs to re-render for the editor layout
return nil
}
func (a *App) valueEditor(o *schema.Option, current string) editor {
switch o.Kind {
case schema.KindBool, schema.KindEnum, schema.KindChoice:
return newChoiceEditor(o, current)
case schema.KindFlags:
return newFlagsEditor(o, current)
case schema.KindTheme:
p := newPickerEditor(o, "themes", current)
p.preview = a.loadTheme
var overrides []string
for _, k := range []string{"background", "foreground", "cursor-color", "cursor-text", "selection-background", "selection-foreground", "palette"} {
if a.file.Has(k) {
overrides = append(overrides, k)
}
}
if len(overrides) > 0 {
p.note = "Your config also sets " + strings.Join(overrides, ", ") + ", which take precedence over the theme."
}
if a.themesLoaded {
p.setItems(a.themes, a.themesErr)
} else if a.gh == nil {
p.setItems(nil, fmt.Errorf("ghostty not found"))
}
return p
case schema.KindFont:
p := newPickerEditor(o, "fonts", current)
if a.fontsLoaded {
p.setItems(a.fonts, a.fontsErr)
} else if a.gh == nil {
p.setItems(nil, fmt.Errorf("ghostty not found"))
}
return p
case schema.KindKeybind:
return newKeybindEditor(current, a.actions)
default:
return newTextEditor(o, current)
}
}
func (a *App) loadTheme(name string) *ghostty.Theme {
if a.gh == nil {
return nil
}
if t, ok := a.themeCache[name]; ok {
return t
}
t, err := a.gh.LoadTheme(name)
if err != nil {
t = nil
}
a.themeCache[name] = t
return t
}
// currentTheme loads the theme set in the config (the dark variant for
// "light:A,dark:B"), or nil.
func (a *App) currentTheme() *ghostty.Theme {
v, ok := a.file.Get("theme")
if !ok {
return nil
}
v = schema.Unquote(v)
name := v
if strings.Contains(v, ":") && !strings.HasPrefix(v, "/") {
for _, part := range strings.Split(v, ",") {
mode, n, found := strings.Cut(strings.TrimSpace(part), ":")
if found && (mode == "dark" || name == v) {
name = strings.TrimSpace(n)
}
}
}
return a.loadTheme(name)
}
// quickToggle flips booleans and cycles through enum values in place.
func (a *App) quickToggle(o *schema.Option) {
if o.Repeatable {
return
}
cur, ok := a.file.Get(o.Key)
if !ok {
cur = o.Default()
}
cur = schema.Unquote(cur)
var values []string
switch o.Kind {
case schema.KindBool:
values = []string{"false", "true"}
if cur == "" {
cur = "false"
}
case schema.KindEnum:
values = o.Values
default:
a.setStatus("Space toggles booleans and cycles choices; press enter to edit "+o.Key+".", stDim)
return
}
next := values[0]
for i, v := range values {
if v == cur {
next = values[(i+1)%len(values)]
break
}
}
a.apply(o, valuesResult(next))
}
func (a *App) step(o *schema.Option, delta int) {
switch o.Kind {
case schema.KindInt, schema.KindFloat, schema.KindMetric:
default:
return
}
cur, _ := a.file.Get(o.Key)
v, ok := stepValue(o, cur, delta)
if !ok {
return
}
if err := o.Validate(v); err != nil {
a.setStatus(err.Error(), stError)
return
}
a.apply(o, valuesResult(v))
}
// apply writes an editor result into the in-memory config.
func (a *App) apply(o *schema.Option, res *result) {
if res == nil || res.cancel {
return
}
before := a.file.Clone()
switch {
case res.values == nil:
a.file.Unset(o.Key)
case o.Repeatable:
a.file.SetAll(o.Key, res.values)
default:
a.file.Set(o.Key, res.values[0])
}
if a.file.Equal(before) {
return
}
a.rev++
a.undo = append(a.undo, undoEntry{file: before, key: o.Key})
if len(a.undo) > 500 {
a.undo = a.undo[1:]
}
switch {
case res.values == nil:
a.setStatus("Reset "+o.Key+" to its default.", stChanged)
case o.Repeatable:
a.setStatus(fmt.Sprintf("Updated %s (%d entr%s).", o.Key, len(res.values), plural(len(res.values), "y", "ies")), stChanged)
default:
a.setStatus("Set "+o.Key+" = "+res.values[0], stChanged)
}
a.rebuild()
}
func (a *App) undoLast() {
if len(a.undo) == 0 {
a.setStatus("Nothing to undo.", stDim)
return
}
last := a.undo[len(a.undo)-1]
a.undo = a.undo[:len(a.undo)-1]
a.file = last.file
a.rev++
a.setStatus("Undid change to "+last.key+".", stChanged)
a.rebuild()
}
// ---------------------------------------------------------------------------
// Saving and quitting
func (a *App) save(skipDiskCheck, skipValidation bool) tea.Cmd {
if !a.dirty() {
a.setStatus("No changes to save.", stDim)
if a.quitAfterSave {
return tea.Quit
}
return nil
}
if !skipDiskCheck && a.file.ChangedOnDisk() {
a.dlg = &dialog{
title: "File changed on disk",
lines: []string{
"The config file was modified outside the editor since it was loaded:",
"",
a.file.Path,
"",
"Saving will overwrite those changes.",
},
keys: []dialogKey{{"o", "Overwrite"}, {"esc", "Cancel"}},
onKey: func(k string) tea.Cmd {
if k == "o" {
return a.save(true, skipValidation)
}
a.quitAfterSave = false
return nil
},
warn: true,
}
return nil
}
if !skipValidation && a.gh != nil {
if errs := a.validate(); len(errs) > 0 {
lines := []string{"Ghostty reported problems with the new configuration:", ""}
for _, e := range errs {
lines = append(lines, stError.Render("• ")+e)
}
lines = append(lines, "", "Ghostty ignores invalid lines and uses defaults instead.")
a.dlg = &dialog{
title: "Validation failed",
lines: lines,
keys: []dialogKey{{"s", "Save anyway"}, {"esc", "Back to editing"}},
onKey: func(k string) tea.Cmd {
if k == "s" {
return a.save(true, true)
}
a.quitAfterSave = false
return nil
},
warn: true,
}
return nil
}
}
makeBackup := !a.backup && a.file.Exists
if err := a.file.Save(makeBackup); err != nil {
a.setStatus("Save failed: "+err.Error(), stError)
a.quitAfterSave = false
return nil
}
a.backup = a.backup || makeBackup
a.saved = a.file.Clone()
msg := "Saved."
if makeBackup {
msg += " Backup: " + filepath.Base(a.file.Path) + ".bak."
}
if a.autoReload {
a.setStatus(msg+" Reloading Ghostty…", stOK)
reload := func() tea.Msg { return reloadMsg{saved: msg, err: ghostty.Reload()} }
if a.quitAfterSave {
return tea.Sequence(reload, tea.Quit)
}
return reload
}
a.setStatus(msg+" Reload Ghostty's config with "+reloadShortcut()+" to apply.", stOK)
if a.quitAfterSave {
return tea.Quit
}
return nil
}
// validate checks the pending config with `ghostty +validate-config`.
func (a *App) validate() []string {
tmp, err := a.file.WriteTemp()
if err != nil {
return []string{"could not write temporary file: " + err.Error()}
}
defer os.Remove(tmp)
errs, err := a.gh.Validate(tmp)
if err != nil {
return nil // validation unavailable; do not block saving
}
var out []string
for _, e := range errs {
out = append(out, e.String())
}
return out
}
func (a *App) quit() tea.Cmd {
if !a.dirty() {
return tea.Quit
}
n := len(a.changedKeys())
a.dlg = &dialog{
title: "Unsaved changes",
lines: []string{fmt.Sprintf("You have unsaved changes to %d option(s).", n)},
keys: []dialogKey{{"s", "Save and quit"}, {"d", "Discard and quit"}, {"esc", "Cancel"}},
onKey: func(k string) tea.Cmd {
switch k {
case "s":
a.quitAfterSave = true
return a.save(false, false)
case "d":
return tea.Quit
}
return nil
},
quit: true,
}
return nil
}
// changedKeys lists keys whose values differ from the saved file.
func (a *App) changedKeys() []string {
seen := map[string]bool{}
var keys []string
for _, k := range append(a.saved.Keys(), a.file.Keys()...) {
if seen[k] {
continue
}
seen[k] = true
if !equalStrings(a.saved.GetAll(k), a.file.GetAll(k)) {
keys = append(keys, k)
}
}
return keys
}
func (a *App) changesDialog() *dialog {
keys := a.changedKeys()
var lines []string
if len(keys) == 0 {
lines = append(lines, "No unsaved changes.")
}
for _, k := range keys {
lines = append(lines, stBold.Render(k))
for _, c := range config.Diff(a.saved.GetAll(k), a.file.GetAll(k)) {
if c.Removed {
lines = append(lines, stError.Render(" - "+config.FormatLine(k, c.Value)))
} else {
lines = append(lines, stOK.Render(" + "+config.FormatLine(k, c.Value)))
}
}
}
return &dialog{
title: fmt.Sprintf("Unsaved changes (%d)", len(keys)),
lines: lines,
keys: []dialogKey{{"esc", "Close"}},
}
}
func equalStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func reloadShortcut() string {
if runtime.GOOS == "darwin" {
return "⌘⇧,"
}
return "ctrl+shift+,"
}
func shortPath(p string) string {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home+string(os.PathSeparator)) {
return "~" + p[len(home):]
}
return p
}
// ---------------------------------------------------------------------------
// Mouse
func (a *App) handleMouse(m tea.MouseMsg) tea.Cmd {
if a.dlg != nil || a.capturing() {
return nil
}
wheel := 0
switch m.Button {
case tea.MouseButtonWheelUp:
wheel = -1
case tea.MouseButtonWheelDown:
wheel = 1
}
if wheel != 0 {
switch {
case a.docRect.contains(m.X, m.Y):
if wheel > 0 {
a.doc.ScrollDown(3)
} else {
a.doc.ScrollUp(3)
}
case a.editor != nil:
if _, isText := a.editor.(*textEditor); isText {
return nil // up/down would change numeric values
}
key := tea.KeyMsg{Type: tea.KeyDown}
if wheel < 0 {
key = tea.KeyMsg{Type: tea.KeyUp}
}
return a.updateEditor(key)
case a.optRect.contains(m.X, m.Y):
a.optIdx = min(max(0, a.optIdx+wheel), max(0, len(a.opts)-1))
case a.catRect.contains(m.X, m.Y):
a.selectCategory(min(max(0, a.catIdx+wheel), len(a.cats)-1))
}
return nil
}
if a.editor != nil || m.Action != tea.MouseActionPress || m.Button != tea.MouseButtonLeft {
return nil
}
switch {
case a.catRect.contains(m.X, m.Y):
a.focus = paneCats
row := m.Y - a.catRect.y - 1 + a.catTop
if i := a.catRowIndex(row); i >= 0 {
a.selectCategory(i)
}
case a.optRect.contains(m.X, m.Y):
a.focus = paneOpts
i := m.Y - a.optListY + a.optTop
if m.Y >= a.optListY && i >= 0 && i < len(a.opts) {
if i == a.optIdx {
return a.edit(a.opts[i])
}
a.optIdx = i
}
}
return nil
}
+220
View File
@@ -0,0 +1,220 @@
package ui
import (
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/config"
"ghosttyconf/internal/schema"
)
func newTestApp(t *testing.T, content string) *App {
t.Helper()
sch, err := schema.Embedded()
if err != nil {
t.Fatal(err)
}
f := &config.File{Path: "/tmp/ghosttyconf-test/config.ghostty", Lines: config.Parse([]byte(content))}
a := New(sch, nil, f)
a.Update(tea.WindowSizeMsg{Width: 160, Height: 45})
return a
}
func press(a *App, keys ...string) {
for _, k := range keys {
var msg tea.KeyMsg
switch k {
case "enter":
msg = tea.KeyMsg{Type: tea.KeyEnter}
case "esc":
msg = tea.KeyMsg{Type: tea.KeyEsc}
case "down":
msg = tea.KeyMsg{Type: tea.KeyDown}
case "up":
msg = tea.KeyMsg{Type: tea.KeyUp}
case "tab":
msg = tea.KeyMsg{Type: tea.KeyTab}
case "shift+tab":
msg = tea.KeyMsg{Type: tea.KeyShiftTab}
case "space":
msg = tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}}
default:
msg = tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(k)}
}
a.Update(msg)
}
}
// TestEveryEditorRenders opens the editor of every option at several
// terminal sizes to catch panics and layout bugs.
func TestEveryEditorRenders(t *testing.T) {
a := newTestApp(t, "font-family = Hack\nkeybind = ctrl+a=new_tab\npalette = 1=#ff0000\n")
sizes := [][2]int{{160, 45}, {100, 30}, {60, 16}, {40, 12}}
for _, o := range a.sch.Options {
for _, sz := range sizes {
a.Update(tea.WindowSizeMsg{Width: sz[0], Height: sz[1]})
a.edit(o)
if a.editor == nil && o.Kind != schema.KindBool {
t.Fatalf("%s: no editor opened", o.Key)
}
_ = a.View()
press(a, "down", "down")
_ = a.View()
for i := 0; i < 3 && a.editor != nil; i++ {
press(a, "esc")
}
if a.editor != nil {
t.Fatalf("%s: editor did not close on esc", o.Key)
}
_ = a.View()
}
}
}
func TestEditEnumAndUndo(t *testing.T) {
a := newTestApp(t, "# keep me\ncursor-style = block\n")
press(a, "/")
for _, r := range "cursor-style" {
press(a, string(r))
}
press(a, "enter")
if o := a.selected(); o == nil || o.Key != "cursor-style" {
t.Fatalf("selected = %v", o)
}
press(a, "enter", "down", "enter") // block -> bar
if v, _ := a.file.Get("cursor-style"); v != "bar" {
t.Fatalf("cursor-style = %q", v)
}
if !a.dirty() {
t.Fatal("expected unsaved changes")
}
press(a, "u")
if v, _ := a.file.Get("cursor-style"); v != "block" {
t.Fatalf("after undo cursor-style = %q", v)
}
if a.dirty() {
t.Fatal("undo should restore the saved state")
}
if !strings.HasPrefix(string(a.file.Bytes()), "# keep me\n") {
t.Fatal("comment lost")
}
}
func TestToggleStepAndReset(t *testing.T) {
a := newTestApp(t, "font-size = 13\n")
a.selectCategory(0) // Set in Config
press(a, "+", "+")
if v, _ := a.file.Get("font-size"); v != "14" {
t.Fatalf("font-size = %q", v)
}
press(a, "r")
if a.file.Has("font-size") {
t.Fatal("font-size should have been removed")
}
}
func TestKeybindListAdd(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
press(a, "a")
for _, r := range "ctrl+shift+t" {
press(a, string(r))
}
press(a, "tab")
for _, r := range "new_tab" {
press(a, string(r))
}
press(a, "enter", "esc")
if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+shift+t=new_tab" {
t.Fatalf("keybind = %v", got)
}
}
func TestKeybindManagerChangeDefault(t *testing.T) {
a := newTestApp(t, "")
o := a.sch.Lookup("keybind")
a.edit(o)
m, ok := a.editor.(*keybindManager)
if !ok {
t.Fatalf("editor is %T", a.editor)
}
// Find the built-in super+d binding and move it to super+shift+d.
press(a, "/")
for _, r := range "super+d" {
press(a, string(r))
}
press(a, "enter")
b := m.selected()
if b == nil || b.Trigger != "super+d" {
t.Fatalf("selected = %+v", b)
}
press(a, "enter") // change
press(a, "shift+tab") // trigger field
a.Update(tea.KeyMsg{Type: tea.KeyCtrlU}) // clear it
for _, r := range "super+shift+d" {
press(a, string(r))
}
press(a, "enter", "esc")
got := strings.Join(a.file.GetAll("keybind"), " | ")
if got != "super+d=unbind | super+shift+d="+b.Action {
t.Fatalf("keybind = %s", got)
}
}
func TestKeybindManagerUnbindRestore(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
m := a.editor.(*keybindManager)
b := *m.selected()
press(a, "d")
if v := m.set.Values(); len(v) != 1 || !strings.HasSuffix(v[0], "=unbind") {
t.Fatalf("after unbind: %v", v)
}
press(a, "r")
if v := m.set.Values(); len(v) != 0 {
t.Fatalf("after restore: %v", v)
}
press(a, "esc")
if a.file.Has("keybind") {
t.Fatalf("no change expected, got %v (binding %s)", a.file.GetAll("keybind"), b.Trigger)
}
}
func TestKeybindRecording(t *testing.T) {
a := newTestApp(t, "")
a.edit(a.sch.Lookup("keybind"))
press(a, "a")
a.Update(tea.KeyMsg{Type: tea.KeyCtrlR})
if !a.capturing() {
t.Fatal("not recording")
}
// ctrl+c must be recorded, not quit the program.
_, cmd := a.Update(tea.KeyMsg{Type: tea.KeyCtrlC})
if a.dlg != nil || cmd != nil && a.capturing() == false {
t.Fatal("ctrl+c was not captured")
}
press(a, "enter")
if a.capturing() {
t.Fatal("still recording")
}
for _, r := range "copy_to_clipboard" {
press(a, string(r))
}
press(a, "enter", "esc")
if got := a.file.GetAll("keybind"); len(got) != 1 || got[0] != "ctrl+c=copy_to_clipboard" {
t.Fatalf("keybind = %v", got)
}
}
func TestUnknownKeyIsListed(t *testing.T) {
a := newTestApp(t, "bogus-key = 1\n")
a.selectCategory(0)
if len(a.opts) != 1 || a.opts[0].Key != "bogus-key" {
t.Fatalf("opts = %v", a.opts)
}
if !strings.Contains(a.View(), "bogus-key") {
t.Fatal("unknown key not rendered")
}
}
+154
View File
@@ -0,0 +1,154 @@
package ui
import (
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/x/ansi"
)
type dialogKey struct{ key, label string }
// dialog is a modal box drawn over the main view.
type dialog struct {
title string
lines []string
keys []dialogKey
onKey func(key string) tea.Cmd
scroll int
warn bool
quit bool // the unsaved-changes prompt: a second ctrl+c quits
height int // visible body lines in the last render
}
func (d *dialog) update(a *App, km tea.KeyMsg) tea.Cmd {
key := km.String()
switch key {
case "up", "k":
d.scroll = max(0, d.scroll-1)
return nil
case "down", "j":
d.scroll = min(d.scroll+1, max(0, len(d.lines)-d.height))
return nil
case "pgup":
d.scroll = max(0, d.scroll-d.height)
return nil
case "pgdown", " ":
d.scroll = min(d.scroll+d.height, max(0, len(d.lines)-d.height))
return nil
}
for _, k := range d.keys {
if k.key == key {
a.dlg = nil
if d.onKey != nil {
return d.onKey(key)
}
return nil
}
}
if key == "esc" || key == "q" || key == "enter" {
a.dlg = nil
if d.onKey != nil {
return d.onKey("esc")
}
}
return nil
}
func (d *dialog) view(width, height int) string {
var keys []string
for _, k := range d.keys {
keys = append(keys, stKey.Render(k.key)+" "+k.label)
}
hint := strings.Join(keys, " ")
// Size the box to its content, within the screen.
want := max(40, ansi.StringWidth(hint)+18, ansi.StringWidth(d.title)+8)
for _, l := range d.lines {
want = max(want, ansi.StringWidth(l)+4)
}
w := min(width-4, 84, want)
inner := w - 4
var body []string
for _, l := range d.lines {
if l == "" {
body = append(body, "")
continue
}
body = append(body, strings.Split(ansi.Wrap(l, inner, ""), "\n")...)
}
maxBody := max(3, height-8)
d.height = min(len(body), maxBody)
d.scroll = min(d.scroll, max(0, len(body)-d.height))
visible := body[d.scroll : d.scroll+d.height]
if len(body) > d.height {
hint += stDim.Render(" ↑↓ scroll")
}
lines := []string{""}
for _, l := range visible {
lines = append(lines, " "+l)
}
lines = append(lines, "", " "+hint)
content := strings.Join(lines, "\n")
color := colAccent
if d.warn {
color = colChanged
}
return framed(d.title, content, w, len(lines)+2, color)
}
func helpDialog() *dialog {
k := func(key, desc string) string { return stKey.Render(fit(key, 16)) + desc }
return &dialog{
title: "Help",
lines: []string{
stBold.Render("Browsing"),
k("↑↓ / j k", "move"),
k("← → / tab", "switch between categories and options"),
k("enter", "edit the selected option (booleans toggle)"),
k("space", "toggle a boolean / cycle through choices"),
k("+ / -", "increase / decrease numbers"),
k("r / del", "reset to the default (removes the line from the file)"),
k("/", "search option names and documentation"),
k("b", "open the key binding editor"),
k("shift+↑↓", "scroll the documentation (also ctrl+u / ctrl+d)"),
k("p", "hide options for other platforms"),
k("u / ctrl+z", "undo the last change"),
k("c", "show unsaved changes"),
k("ctrl+s", "validate with Ghostty, save and reload Ghostty's config"),
k("q / ctrl+c", "quit"),
"",
stBold.Render("Editors"),
k("enter", "apply the value"),
k("esc", "cancel (in list editors: done)"),
k("↑↓", "choose; in number fields: increase / decrease"),
k("tab", "complete the highlighted theme, font or action"),
"",
stBold.Render("Key bindings") + stDim.Render(" (b, or enter on keybind)"),
k("enter", "change the selected binding (also built-in ones)"),
k("a", "add a binding"),
k("d", "unbind: the key no longer does anything in Ghostty"),
k("r", "restore Ghostty's default for this key"),
k("ctrl+r", "in the binding form: record the key combination"),
k("/ c s", "filter · show changes only · sort by action or key"),
k("R", "edit the raw keybind entries"),
"",
stBold.Render("List editors") + stDim.Render(" (font-family, env, config-file, …)"),
k("a", "add an entry"),
k("enter / e", "edit the entry; on a built-in default: copy it"),
k("r", "edit the entry as raw text"),
k("d", "delete the entry"),
k("J / K", "move the entry down / up"),
k("v", "show or hide Ghostty's built-in defaults"),
"",
stBold.Render("Markers"),
stSet.Render("●") + " set in your config " + stChanged.Render("●") + " changed, not saved " + stChanged.Render("○") + " removed, not saved",
"",
"Comments, blank lines and the order of untouched lines in your config file are kept. " +
"Before the first save a backup is written to <config>.bak.",
},
keys: []dialogKey{{"esc", "Close"}},
}
}
+117
View File
@@ -0,0 +1,117 @@
package ui
import (
"strings"
"github.com/charmbracelet/x/ansi"
)
// renderDoc reflows Ghostty's option documentation (lightly formatted
// Markdown) to width: paragraphs are re-wrapped, list items get a hanging
// indent, indented code examples are kept verbatim and `code` spans are
// highlighted.
func renderDoc(doc string, width int) string {
if width < 10 {
width = 10
}
var out []string
var para []string
prefix, hang := "", ""
flush := func() {
if len(para) == 0 {
return
}
text := strings.Join(para, " ")
wrapped := strings.Split(ansi.Wrap(text, width-ansi.StringWidth(prefix), ""), "\n")
inCode := false
for i, l := range wrapped {
p := hang
if i == 0 {
p = prefix
}
var styled string
styled, inCode = styleInline(l, inCode)
out = append(out, p+styled)
}
para, prefix, hang = nil, "", ""
}
inBullet := false
bulletIndent := 0
for _, line := range strings.Split(doc, "\n") {
trimmed := strings.TrimSpace(line)
indent := len(line) - len(strings.TrimLeft(line, " "))
switch {
case trimmed == "":
flush()
inBullet = false
out = append(out, "")
case isBullet(trimmed):
flush()
inBullet = true
bulletIndent = indent + 2
lead := strings.Repeat(" ", min(indent, 4))
prefix = lead + "• "
hang = lead + " "
para = append(para, strings.TrimSpace(trimmed[2:]))
case inBullet && indent >= bulletIndent:
para = append(para, trimmed)
case indent >= 4 || strings.HasPrefix(line, "\t"):
flush()
inBullet = false
out = append(out, stCode.Render(ansi.Truncate(" "+trimmed, width, "…")))
default:
if inBullet {
flush()
inBullet = false
}
para = append(para, trimmed)
}
}
flush()
// Collapse repeated blank lines.
var res []string
for i, l := range out {
if l == "" && (i == 0 || out[i-1] == "") {
continue
}
res = append(res, l)
}
return strings.TrimRight(strings.Join(res, "\n"), "\n")
}
func isBullet(s string) bool {
return strings.HasPrefix(s, "* ") || strings.HasPrefix(s, "- ")
}
// styleInline highlights `code` spans. inCode carries an open span across
// wrapped lines.
func styleInline(line string, inCode bool) (string, bool) {
if !strings.Contains(line, "`") && !inCode {
return line, false
}
var b, seg strings.Builder
emit := func() {
if seg.Len() == 0 {
return
}
if inCode {
b.WriteString(stCode.Render(seg.String()))
} else {
b.WriteString(seg.String())
}
seg.Reset()
}
for _, r := range line {
if r == '`' {
emit()
inCode = !inCode
continue
}
seg.WriteRune(r)
}
emit()
return b.String(), inCode
}
+435
View File
@@ -0,0 +1,435 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/cursor"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"ghosttyconf/internal/schema"
)
// result is what an editor produces when it closes.
type result struct {
cancel bool
// values are the new raw values. nil (without cancel) removes the
// option from the config file, restoring the default.
values []string
}
func cancelled() *result { return &result{cancel: true} }
func valuesResult(v ...string) *result { return &result{values: v} }
// editor edits the value of one option (or one entry of a list option).
type editor interface {
Update(msg tea.Msg) (tea.Cmd, *result)
View(width, height int) string
Help() string
}
func newInput(value, placeholder string) textinput.Model {
ti := textinput.New()
ti.Prompt = "› "
ti.PromptStyle = stAccent
ti.Placeholder = placeholder
ti.PlaceholderStyle = stDim
ti.Cursor.SetMode(cursor.CursorStatic)
ti.SetValue(value)
ti.CursorEnd()
ti.Focus()
return ti
}
// scrollWindow returns the first visible row so that cursor stays visible.
func scrollWindow(cursor, top, height, n int) int {
if height <= 0 {
return 0
}
if cursor < top {
top = cursor
}
if cursor >= top+height {
top = cursor - height + 1
}
if top > n-height {
top = max(0, n-height)
}
return max(0, top)
}
// moveCursor applies common list navigation keys.
func moveCursor(key string, cursor, n, page int) (int, bool) {
if n == 0 {
return 0, false
}
switch key {
case "up", "k", "ctrl+p":
cursor--
case "down", "j", "ctrl+n":
cursor++
case "pgup":
cursor -= page
case "pgdown":
cursor += page
case "home", "g":
cursor = 0
case "end", "G":
cursor = n - 1
default:
return cursor, false
}
return min(max(cursor, 0), n-1), true
}
// ---------------------------------------------------------------------------
// Choice editor: booleans, enums and enums with a custom value.
type choiceItem struct {
value string
label string
custom bool
}
type choiceEditor struct {
opt *schema.Option
items []choiceItem
cursor int
top int
height int
current string
text *textEditor // active while typing a custom value
}
func newChoiceEditor(o *schema.Option, current string) *choiceEditor {
e := &choiceEditor{opt: o, current: schema.Unquote(current)}
values := o.Values
if o.Kind == schema.KindBool {
values = []string{"true", "false"}
}
for _, v := range values {
e.items = append(e.items, choiceItem{value: v, label: v})
}
if o.Kind == schema.KindChoice {
label := "Custom value…"
if e.current != "" && !contains(values, e.current) {
label = "Custom value: " + e.current
}
e.items = append(e.items, choiceItem{label: label, custom: true})
}
e.cursor = 0
effective := e.current
if effective == "" {
effective = o.Default()
}
for i, it := range e.items {
if it.value == effective || (it.custom && effective != "" && !contains(values, effective)) {
e.cursor = i
break
}
}
return e
}
func (e *choiceEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.text != nil {
cmd, res := e.text.Update(msg)
if res != nil {
e.text = nil
if res.cancel {
return nil, nil
}
return nil, res
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, len(e.items), max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
return nil, cancelled()
case "enter", " ":
it := e.items[e.cursor]
if it.custom {
v := ""
if !contains(e.opt.Values, e.current) {
v = e.current
}
e.text = newTextEditor(e.opt, v)
return nil, nil
}
return nil, valuesResult(it.value)
}
return nil, nil
}
func (e *choiceEditor) View(width, height int) string {
if e.text != nil {
return e.text.View(width, height)
}
e.height = height
e.top = scrollWindow(e.cursor, e.top, height, len(e.items))
var lines []string
def := e.opt.Default()
for i := e.top; i < len(e.items) && len(lines) < height; i++ {
it := e.items[i]
sel := i == e.cursor
labelSt := lipgloss.NewStyle()
if sel {
labelSt = stBold
}
segs := []seg{cursorSeg(sel), styled(fit(it.label, 28), labelSt), plain(" ")}
if !it.custom && it.value == e.current {
segs = append(segs, styled("● current ", stSet))
}
if !it.custom && it.value == def {
segs = append(segs, styled("default", stDim))
}
lines = append(lines, renderRow(segs, width, sel))
}
return strings.Join(lines, "\n")
}
func (e *choiceEditor) Help() string {
if e.text != nil {
return e.text.Help()
}
return "↑↓ choose · enter select · esc cancel"
}
// ---------------------------------------------------------------------------
// Flags editor: packed structs such as shell-integration-features.
type flagsEditor struct {
opt *schema.Option
state map[string]bool
def map[string]bool
cursor int
}
func newFlagsEditor(o *schema.Option, current string) *flagsEditor {
return &flagsEditor{opt: o, state: o.ParseFlags(current), def: o.ParseFlags("")}
}
func (e *flagsEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, len(e.opt.Flags), 5); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
return nil, cancelled()
case " ", "x":
f := e.opt.Flags[e.cursor]
e.state[f] = !e.state[f]
case "a":
for _, f := range e.opt.Flags {
e.state[f] = true
}
case "n":
for _, f := range e.opt.Flags {
e.state[f] = false
}
case "d":
for _, f := range e.opt.Flags {
e.state[f] = e.def[f]
}
case "enter":
return nil, valuesResult(e.opt.FormatFlags(e.state))
}
return nil, nil
}
func (e *flagsEditor) View(width, height int) string {
var lines []string
for i, f := range e.opt.Flags {
box := styled("[ ]", stDim)
if e.state[f] {
box = styled("[✓]", stSet)
}
segs := []seg{cursorSeg(i == e.cursor), box, plain(" " + fit(f, 22) + " ")}
if e.state[f] != e.def[f] {
segs = append(segs, styled("changed from default", stChanged))
}
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
lines = append(lines, "", stDim.Render("Result: ")+stCode.Render(e.opt.FormatFlags(e.state)))
return strings.Join(lines, "\n")
}
func (e *flagsEditor) Help() string {
return "↑↓ move · space toggle · a all · n none · d defaults · enter apply · esc cancel"
}
// ---------------------------------------------------------------------------
// Text editor with validation, used for numbers, colors, durations, paths
// and free text.
type textEditor struct {
opt *schema.Option
input textinput.Model
err string
// item is set when editing one entry of a list option: an empty value
// then means "remove this entry" rather than "reset to default".
item bool
}
func newTextEditor(o *schema.Option, value string) *textEditor {
placeholder := o.Default()
if placeholder == "" {
placeholder = o.Hint
}
return &textEditor{opt: o, input: newInput(value, placeholder)}
}
func (e *textEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if km, ok := msg.(tea.KeyMsg); ok {
switch km.String() {
case "esc":
return nil, cancelled()
case "enter":
v := strings.TrimSpace(e.input.Value())
if v == "" {
return nil, &result{}
}
if err := e.opt.Validate(v); err != nil {
e.err = err.Error()
return nil, nil
}
return nil, valuesResult(v)
case "up", "down":
if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric {
delta := 1
if km.String() == "down" {
delta = -1
}
if v, ok := stepValue(e.opt, e.input.Value(), delta); ok {
e.input.SetValue(v)
e.input.CursorEnd()
}
return nil, nil
}
}
}
var cmd tea.Cmd
e.input, cmd = e.input.Update(msg)
e.err = ""
return cmd, nil
}
func (e *textEditor) View(width, height int) string {
e.input.Width = max(10, width-4)
var lines []string
lines = append(lines, e.input.View(), "")
v := strings.TrimSpace(e.input.Value())
switch {
case e.err != "":
lines = append(lines, stError.Render("✗ "+e.err))
case v == "" && e.item:
lines = append(lines, stDim.Render("Empty: the entry will be removed."))
case v == "":
lines = append(lines, stDim.Render("Empty: the option will be reset to its default."))
default:
if err := e.opt.Validate(v); err != nil {
lines = append(lines, stError.Render("✗ "+err.Error()))
} else {
lines = append(lines, stOK.Render("✓ valid"))
}
}
if e.opt.Kind == schema.KindColor || e.opt.Kind == schema.KindPalette || e.opt.Kind == schema.KindColorList {
var sw []string
for _, part := range strings.Split(v, ",") {
if s := swatch(part); s != "" {
sw = append(sw, s+s+s)
}
}
if len(sw) > 0 {
lines = append(lines, "", strings.Join(sw, " ")+" "+stDim.Render("preview"))
}
}
if e.opt.Hint != "" {
lines = append(lines, "", stDim.Render("Format: ")+e.opt.Hint)
}
if e.opt.Kind == schema.KindInt || e.opt.Kind == schema.KindFloat || e.opt.Kind == schema.KindMetric {
lines = append(lines, "", stDim.Render("Use ↑/↓ to increase or decrease the value."))
}
return strings.Join(lines, "\n")
}
func (e *textEditor) Help() string {
return "type to edit · enter apply · esc cancel"
}
// stepValue increments or decrements numeric values, keeping a percentage
// suffix for metric modifiers.
func stepValue(o *schema.Option, value string, delta int) (string, bool) {
v := strings.TrimSpace(schema.Unquote(value))
if v == "" {
v = o.Default()
}
pct := strings.HasSuffix(v, "%")
v = strings.TrimSuffix(v, "%")
if v == "" {
v = "0"
}
var f float64
if _, err := fmt.Sscanf(v, "%g", &f); err != nil {
return "", false
}
step := 1.0
if o.Kind == schema.KindFloat {
switch {
case o.Max != nil && *o.Max <= 1:
step = 0.05
case f < 1 && f > -1 && o.Key != "font-size":
step = 0.1
case o.Key == "font-size":
step = 0.5
}
}
f += float64(delta) * step
if o.Min != nil && f < *o.Min {
f = *o.Min
}
if o.Max != nil && f > *o.Max {
f = *o.Max
}
var s string
if o.Kind == schema.KindFloat {
s = strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), ".")
if s == "" || s == "-" {
s = "0"
}
} else {
s = fmt.Sprintf("%d", int64(f))
}
if pct {
s += "%"
}
return s, true
}
func contains(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}
+342
View File
@@ -0,0 +1,342 @@
package ui
import (
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/keybind"
"ghosttyconf/internal/schema"
)
const triggerPlaceholder = "e.g. super+shift+t, ctrl+a>n, global:ctrl+backquote"
// keybindEditor edits a single "trigger=action" binding with a separate
// field for each half, key recording for the trigger and completion for
// action names.
type keybindEditor struct {
trigger textinput.Model
action textinput.Model
focus int // 0 = trigger, 1 = action
actions []ghostty.Action
matches []ghostty.Action
cursor int
top int
err string
// conflict describes an existing binding of a trigger ("" if none).
conflict func(trigger string) string
recording bool
recorded []string
beforeRecord string
kittyReply bool // the terminal confirmed the kitty keyboard protocol
}
func newKeybindEditor(value string, actions []ghostty.Action) *keybindEditor {
t, a := schema.SplitKeybind(schema.Unquote(value))
e := &keybindEditor{
trigger: newInput(t, triggerPlaceholder),
action: newInput(a, "e.g. new_tab, goto_split:right, text:\\x15"),
actions: actions,
}
e.trigger.Prompt = "Trigger › "
e.action.Prompt = "Action › "
if t != "" {
e.focus = 1
e.trigger.Blur()
} else {
e.action.Blur()
}
e.refilter()
return e
}
// capturing reports whether all keys must go to this editor (recording).
func (e *keybindEditor) capturing() bool { return e.recording }
func (e *keybindEditor) refilter() {
name := strings.ToLower(keybind.ActionName(e.action.Value()))
var prefix, rest []ghostty.Action
for _, a := range e.actions {
switch {
case strings.HasPrefix(a.Name, name):
prefix = append(prefix, a)
case strings.Contains(a.Name, name) || (name != "" && strings.Contains(strings.ToLower(a.Summary), name)):
rest = append(rest, a)
}
}
e.matches = append(prefix, rest...)
e.cursor, e.top = 0, 0
for i, a := range e.matches {
if a.Name == name {
e.cursor = i
break
}
}
}
func (e *keybindEditor) setFocus(f int) {
e.focus = f
if f == 0 {
e.trigger.Focus()
e.action.Blur()
} else {
e.action.Focus()
e.trigger.Blur()
}
}
func (e *keybindEditor) startRecording() tea.Cmd {
e.setFocus(0)
e.recording = true
e.recorded = nil
e.beforeRecord = e.trigger.Value()
e.trigger.SetValue("")
e.trigger.Placeholder = "waiting for keys…"
e.err = ""
return enableKeyCapture()
}
func (e *keybindEditor) stopRecording(keep bool) tea.Cmd {
e.recording = false
e.trigger.Placeholder = triggerPlaceholder
if !keep || len(e.recorded) == 0 {
e.trigger.SetValue(e.beforeRecord)
} else {
e.trigger.SetValue(strings.Join(e.recorded, ">"))
e.setFocus(1)
}
e.trigger.CursorEnd()
return disableKeyCapture()
}
// updateRecording handles input while recording: every key combination is
// appended to the trigger; plain Enter finishes, plain Esc cancels and plain
// Backspace removes the last combination.
func (e *keybindEditor) updateRecording(msg tea.Msg) tea.Cmd {
var combo keybind.Combo
var ok bool
if raw, isRaw := rawSequence(msg); isRaw {
if keybind.IsKittyReply(raw) {
e.kittyReply = true
return nil
}
combo, ok = keybind.DecodeCSI(raw)
} else if km, isKey := msg.(tea.KeyMsg); isKey {
combo, ok = keybind.DecodeKeyName(km.String())
} else {
return nil
}
if !ok || combo.Modifier {
return nil
}
if combo.Plain() {
switch combo.Key {
case "enter":
return e.stopRecording(true)
case "escape":
return e.stopRecording(false)
case "backspace":
if len(e.recorded) > 0 {
e.recorded = e.recorded[:len(e.recorded)-1]
}
e.trigger.SetValue(strings.Join(e.recorded, ">"))
return nil
}
}
e.recorded = append(e.recorded, combo.String())
e.trigger.SetValue(strings.Join(e.recorded, ">"))
return nil
}
func (e *keybindEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.recording {
return e.updateRecording(msg), nil
}
if km, ok := msg.(tea.KeyMsg); ok {
key := km.String()
switch key {
case "esc":
return nil, cancelled()
case "ctrl+r":
return e.startRecording(), nil
case "enter":
t := strings.TrimSpace(e.trigger.Value())
a := strings.TrimSpace(e.action.Value())
if t == "" && a == "" {
return nil, &result{}
}
if t == "clear" && a == "" {
return nil, valuesResult("clear")
}
if t == "" {
e.err = "the trigger is empty"
e.setFocus(0)
return nil, nil
}
if a == "" {
e.err = "the action is empty"
e.setFocus(1)
return nil, nil
}
return nil, valuesResult(t + "=" + a)
case "shift+tab":
e.setFocus(0)
return nil, nil
case "tab":
if e.focus == 0 {
e.setFocus(1)
return nil, nil
}
if len(e.matches) > 0 {
name := e.matches[e.cursor].Name
_, param, hasParam := strings.Cut(e.action.Value(), ":")
v := name
if hasParam {
v += ":" + param
}
e.action.SetValue(v)
e.action.CursorEnd()
e.refilter()
}
return nil, nil
case "up", "down", "pgup", "pgdown":
if e.focus == 1 {
if key == "up" && e.cursor == 0 {
e.setFocus(0)
return nil, nil
}
e.cursor, _ = moveCursor(key, e.cursor, len(e.matches), 5)
return nil, nil
}
if key == "down" {
e.setFocus(1)
}
return nil, nil
}
}
var cmd tea.Cmd
if e.focus == 0 {
e.trigger, cmd = e.trigger.Update(msg)
} else {
before := e.action.Value()
e.action, cmd = e.action.Update(msg)
if e.action.Value() != before {
e.refilter()
}
}
e.err = ""
return cmd, nil
}
// triggerStatus validates the trigger and reports conflicts.
func (e *keybindEditor) triggerStatus() []string {
t := strings.TrimSpace(e.trigger.Value())
if t == "" || t == "clear" {
return nil
}
if _, err := keybind.Normalize(t); err != nil {
return []string{stError.Render("✗ " + err.Error())}
}
if e.conflict != nil {
if c := e.conflict(t); c != "" {
return []string{stChanged.Render("⚠ " + c)}
}
}
return []string{stOK.Render("✓ trigger is free")}
}
func (e *keybindEditor) actionStatus() []string {
name := keybind.ActionName(e.action.Value())
if name == "" || len(e.actions) == 0 {
return nil
}
for _, a := range e.actions {
if a.Name == name {
return nil
}
}
return []string{stChanged.Render("⚠ unknown action " + name)}
}
func (e *keybindEditor) View(width, height int) string {
e.trigger.Width = max(10, width-14)
e.action.Width = max(10, width-14)
var lines []string
if e.recording {
lines = append(lines,
stRecording.Render(" ● REC ")+" "+stBold.Render("Press the key combination now."),
"",
e.trigger.View(),
"",
stDim.Render("enter finish · esc cancel · backspace remove last key"),
stDim.Render("Press several combinations in a row to record a sequence (ctrl+a>n)."),
"",
stDim.Render("Keys that Ghostty or macOS already use (e.g. a current Ghostty"),
stDim.Render("shortcut) never reach this program: type those instead."),
)
if !e.kittyReply {
lines = append(lines, "", stChanged.Render("The terminal did not confirm the kitty keyboard protocol;"),
stChanged.Render("super/cmd combinations may not be recorded."))
}
return strings.Join(lines, "\n")
}
lines = append(lines, e.trigger.View())
lines = append(lines, e.triggerStatus()...)
lines = append(lines, e.action.View())
lines = append(lines, e.actionStatus()...)
lines = append(lines, "")
if e.err != "" {
lines = append(lines, stError.Render("✗ "+e.err), "")
}
if e.focus == 0 {
lines = append(lines,
stKey.Render("ctrl+r")+" record the keys instead of typing them",
"",
stDim.Render("Modifiers: ")+"super (cmd), ctrl, alt (opt), shift",
stDim.Render("Keys: ")+"a, 1, ,, arrow_up, page_down, enter, f1, backquote, …",
stDim.Render("Sequences: ")+"ctrl+a>n (press ctrl+a, then n)",
stDim.Render("Prefixes: ")+"global:, all:, unconsumed:, performable:",
)
return strings.Join(lines, "\n")
}
if len(e.actions) == 0 {
lines = append(lines, stDim.Render("Action list unavailable (ghostty binary not found)."))
return strings.Join(lines, "\n")
}
lines = append(lines, stDim.Render("Actions (tab to complete, add :param where needed):"))
listH := min(8, max(3, height-len(lines)-6))
e.top = scrollWindow(e.cursor, e.top, listH, len(e.matches))
for i := e.top; i < len(e.matches) && i < e.top+listH; i++ {
a := e.matches[i]
segs := []seg{cursorSeg(i == e.cursor), plain(fit(a.Name, 30) + " "), styled(a.Summary, stDim)}
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
if len(e.matches) == 0 {
lines = append(lines, stDim.Render(" no matching action"))
}
if len(e.matches) > 0 {
doc := e.matches[e.cursor].Doc
if rest := height - len(lines) - 1; rest > 2 {
lines = append(lines, "")
docLines := strings.Split(renderDoc(doc, width), "\n")
if len(docLines) > rest {
docLines = docLines[:rest]
}
lines = append(lines, docLines...)
}
}
return strings.Join(lines, "\n")
}
func (e *keybindEditor) Help() string {
if e.recording {
return "recording: press keys · enter finish · esc cancel"
}
return "ctrl+r record keys · tab next field / complete · ↑↓ choose action · enter save · esc cancel"
}
+472
View File
@@ -0,0 +1,472 @@
package ui
import (
"fmt"
"sort"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/keybind"
"ghosttyconf/internal/schema"
)
// keybindManager shows the effective key bindings — Ghostty's defaults
// merged with the user's keybind entries — and lets the user change,
// unbind, restore and add bindings. Edits are translated into the minimal
// set of keybind entries.
type keybindManager struct {
opt *schema.Option
set *keybind.Set
original []string
defaults []string
actions []ghostty.Action
summaries map[string]string
rows []keybind.Binding
cursor int
top int
height int
filter textinput.Model
filtering bool
changesOnly bool
byTrigger bool
msg string
msgStyle lipgloss.Style
child editor
childFor *keybind.Binding // binding being edited; nil when adding
childRaw bool // child is the raw entry list
newItem func(string) editor
}
func newKeybindManager(o *schema.Option, values []string, actions []ghostty.Action, newItem func(string) editor) *keybindManager {
m := &keybindManager{
opt: o,
original: append([]string(nil), values...),
defaults: o.DefaultList(),
actions: actions,
summaries: map[string]string{},
newItem: newItem,
filter: newInput("", "filter by key, action or description"),
}
m.filter.Prompt = "/ "
m.filter.Blur()
for _, a := range actions {
m.summaries[a.Name] = a.Summary
}
m.set = keybind.NewSet(m.defaults, values)
m.refresh("")
return m
}
func (m *keybindManager) capturing() bool {
c, ok := m.child.(interface{ capturing() bool })
return ok && c.capturing()
}
// refresh recomputes the visible rows and keeps the cursor on norm (or on
// the current row when norm is empty).
func (m *keybindManager) refresh(norm string) {
if norm == "" && m.cursor < len(m.rows) {
norm = m.rows[m.cursor].Norm
}
query := strings.TrimSpace(m.filter.Value())
terms := strings.Fields(strings.ToLower(query))
// A query that is a valid trigger ("cmd+d") also finds that exact
// binding, whatever spelling it uses.
exact, err := keybind.Normalize(query)
if err != nil || query == "" {
exact = ""
}
var rows []keybind.Binding
for _, b := range m.set.Bindings() {
if m.changesOnly && b.Source == keybind.Default && !b.InConfig {
continue
}
if exact != "" && b.Norm == exact {
rows = append(rows, b)
continue
}
hay := strings.ToLower(b.Trigger + " " + b.Action + " " + b.Source.String() + " " + m.summaries[keybind.ActionName(b.Action)])
ok := true
for _, t := range terms {
if !strings.Contains(hay, t) {
ok = false
break
}
}
if ok {
rows = append(rows, b)
}
}
sort.SliceStable(rows, func(i, j int) bool {
a, b := rows[i], rows[j]
if (a.Norm == exact) != (b.Norm == exact) {
return a.Norm == exact
}
if m.byTrigger {
return a.Norm < b.Norm
}
if a.Action != b.Action {
return a.Action < b.Action
}
return a.Norm < b.Norm
})
m.rows = rows
m.cursor = min(m.cursor, max(0, len(rows)-1))
for i, b := range rows {
if b.Norm == norm {
m.cursor = i
break
}
}
}
func (m *keybindManager) selected() *keybind.Binding {
if m.cursor < len(m.rows) {
b := m.rows[m.cursor]
return &b
}
return nil
}
func (m *keybindManager) changed() bool {
return !equalStrings(m.set.Values(), m.original)
}
func (m *keybindManager) setMsg(s string, st lipgloss.Style) { m.msg, m.msgStyle = s, st }
func (m *keybindManager) openEditor(b *keybind.Binding) {
value := ""
if b != nil {
value = b.Trigger + "=" + b.Action
}
e := newKeybindEditor(value, m.actions)
if b == nil {
e.setFocus(0)
}
e.conflict = func(trigger string) string {
n, err := keybind.Normalize(trigger)
if err != nil || (b != nil && n == b.Norm) {
return ""
}
if cur, ok := m.set.Lookup(n); ok {
return fmt.Sprintf("already bound to %s (%s); saving replaces that binding", cur.Action, cur.Source)
}
return ""
}
m.child, m.childFor, m.childRaw = e, b, false
}
func (m *keybindManager) Update(msg tea.Msg) (tea.Cmd, *result) {
if m.child != nil {
cmd, res := m.child.Update(msg)
if res != nil {
m.finishChild(res)
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if m.filtering {
switch key {
case "esc":
m.filter.SetValue("")
m.filtering = false
m.filter.Blur()
m.refresh("")
case "enter", "down", "tab":
m.filtering = false
m.filter.Blur()
default:
var cmd tea.Cmd
before := m.filter.Value()
m.filter, cmd = m.filter.Update(km)
if m.filter.Value() != before {
m.cursor, m.top = 0, 0
m.refresh("")
}
return cmd, nil
}
return nil, nil
}
if c, moved := moveCursor(key, m.cursor, len(m.rows), max(1, m.height-1)); moved {
m.cursor = c
return nil, nil
}
m.msg = ""
b := m.selected()
switch key {
case "esc", "q":
if m.filter.Value() != "" && key == "esc" {
m.filter.SetValue("")
m.refresh("")
return nil, nil
}
if !m.changed() {
return nil, cancelled()
}
v := m.set.Values()
if len(v) == 0 {
return nil, &result{}
}
return nil, valuesResult(v...)
case "/":
m.filtering = true
return m.filter.Focus(), nil
case "enter", "e":
if b != nil {
m.openEditor(b)
}
case "a", "n", "+", "insert":
m.openEditor(nil)
case "d", "x", "delete", "backspace":
if b == nil {
break
}
if b.Source == keybind.Unbound {
m.setMsg(b.Trigger+" is already unbound. Press r to restore it.", stDim)
break
}
m.set.Unbind(*b)
m.setMsg("Unbound "+b.Trigger+".", stChanged)
m.refresh(b.Norm)
case "r":
if b == nil {
break
}
m.set.Restore(*b)
if b.Default != "" {
m.setMsg("Restored "+b.Trigger+" → "+b.Default+".", stChanged)
} else {
m.setMsg("Removed "+b.Trigger+" (it has no default binding).", stChanged)
}
m.refresh(b.Norm)
case "c":
m.changesOnly = !m.changesOnly
m.refresh("")
case "s":
m.byTrigger = !m.byTrigger
m.refresh("")
case "R":
le := newListEditor(m.opt, m.set.Values(), m.newItem)
m.child, m.childFor, m.childRaw = le, nil, true
}
return nil, nil
}
func (m *keybindManager) finishChild(res *result) {
defer func() { m.child, m.childFor, m.childRaw = nil, nil, false }()
if res.cancel {
return
}
if m.childRaw {
m.set = keybind.NewSet(m.defaults, res.values)
m.refresh("")
m.setMsg("Updated the raw keybind entries.", stChanged)
return
}
if len(res.values) == 0 {
return
}
v := res.values[0]
if v == "clear" {
m.set = keybind.NewSet(m.defaults, append(m.set.Values(), "clear"))
m.refresh("")
m.setMsg("Added keybind = clear: all built-in bindings are removed.", stChanged)
return
}
if err := m.set.Change(m.childFor, v); err != nil {
m.setMsg("Not changed: "+err.Error(), stError)
return
}
trigger, action := keybind.Split(v)
norm := keybind.NormalizeLoose(trigger)
if m.changesOnly || m.filter.Value() != "" {
// Make sure the edited binding stays visible.
m.changesOnly = false
m.filter.SetValue("")
}
m.refresh(norm)
m.setMsg("Bound "+trigger+" → "+action+".", stChanged)
}
func (m *keybindManager) View(width, height int) string {
if m.child != nil {
title := "New binding"
switch {
case m.childRaw:
title = "Raw keybind entries"
case m.childFor != nil:
title = "Change " + m.childFor.Trigger
if m.childFor.Source == keybind.Default {
title += stDim.Render(" (built-in binding)")
}
}
return stBold.Render(title) + "\n\n" + m.child.View(width, height-2)
}
var lines []string
counts := map[keybind.Source]int{}
for _, b := range m.set.Bindings() {
counts[b.Source]++
}
summary := fmt.Sprintf("%d active · %s · %s · %s",
counts[keybind.Default]+counts[keybind.Changed]+counts[keybind.Custom],
stChanged.Render(fmt.Sprintf("%d changed", counts[keybind.Changed])),
stSet.Render(fmt.Sprintf("%d custom", counts[keybind.Custom])),
stError.Render(fmt.Sprintf("%d unbound", counts[keybind.Unbound])))
view := "all"
if m.changesOnly {
view = "changes only"
}
sortBy := "action"
if m.byTrigger {
sortBy = "key"
}
lines = append(lines, summary+stDim.Render(fmt.Sprintf(" showing %s, sorted by %s", view, sortBy)))
if m.set.HasClear() {
lines = append(lines, stChanged.Render("Your config contains keybind = clear: built-in bindings before it are removed."))
}
if m.filtering || m.filter.Value() != "" {
m.filter.Width = max(10, width-4)
lines = append(lines, m.filter.View())
}
lines = append(lines, "")
trigW := 12
for _, b := range m.rows {
trigW = max(trigW, ansi.StringWidth(b.Trigger))
}
trigW = min(trigW+2, width*40/100)
srcW := 9
actW := max(10, width-trigW-srcW-3)
lines = append(lines, stDim.Render(" "+fit("Key", trigW)+fit("Action", actW)+" Source"))
detailH := 3
listH := max(3, height-len(lines)-detailH-1)
m.height = listH
m.top = scrollWindow(m.cursor, m.top, listH, len(m.rows))
if len(m.rows) == 0 {
lines = append(lines, stDim.Render(" No bindings match."))
}
for i := m.top; i < len(m.rows) && i < m.top+listH; i++ {
lines = append(lines, renderRow(m.rowSegs(m.rows[i], i == m.cursor, trigW, actW), width, i == m.cursor))
}
for len(lines) < height-detailH {
lines = append(lines, "")
}
lines = append(lines, m.detail(width)...)
return strings.Join(lines, "\n")
}
func (m *keybindManager) rowSegs(b keybind.Binding, selected bool, trigW, actW int) []seg {
action := b.Action
if len(b.Chain) > 0 {
action += " + " + strings.Join(b.Chain, " + ")
}
actSt := lipgloss.NewStyle()
var src seg
switch b.Source {
case keybind.Default:
src = styled("default", stDim)
actSt = stDim
if b.InConfig {
actSt = lipgloss.NewStyle()
}
case keybind.Changed:
src = styled("changed", stChanged)
case keybind.Custom:
src = styled("custom", stSet)
case keybind.Unbound:
src = styled("unbound", stError)
actSt = stDim.Strikethrough(true)
}
return []seg{
cursorSeg(selected),
styled(fit(b.Trigger, trigW), stKey),
styled(fit(action, actW), actSt),
plain(" "),
src,
}
}
func (m *keybindManager) detail(width int) []string {
b := m.selected()
var lines []string
if m.msg != "" {
lines = append(lines, m.msgStyle.Render(ansi.Truncate(m.msg, width, "…")))
} else {
lines = append(lines, "")
}
if b == nil {
return append(lines, "", "")
}
var info string
switch b.Source {
case keybind.Default:
info = "Ghostty's built-in binding."
case keybind.Changed:
info = "Changed in your config. Ghostty's default: " + b.Default + " (press r to restore)."
case keybind.Custom:
info = "Added in your config."
case keybind.Unbound:
info = "Removed in your config. Press r to restore " + b.Default + "."
}
sum := m.summaries[keybind.ActionName(b.Action)]
lines = append(lines,
stDim.Render(ansi.Truncate(info, width, "…")),
ansi.Truncate(stKey.Render(keybind.ActionName(b.Action))+" "+sum, width, "…"))
return lines
}
// docFor shows the documentation of the selected binding's action and all
// keys bound to it.
func (m *keybindManager) docFor() (id, title, body string, ok bool) {
b := m.selected()
if m.child != nil || b == nil {
return "", "", "", false
}
name := keybind.ActionName(b.Action)
var doc string
for _, a := range m.actions {
if a.Name == name {
doc = a.Doc
break
}
}
if doc == "" {
doc = "No documentation available for this action."
}
var keys []string
for _, other := range m.set.Bindings() {
if keybind.ActionName(other.Action) == name && other.Source != keybind.Unbound {
keys = append(keys, "* `"+other.Trigger+"` → `"+other.Action+"` ("+other.Source.String()+")")
}
}
body = doc
if len(keys) > 0 {
body += "\n\nKeys bound to " + name + ":\n\n" + strings.Join(keys, "\n")
}
return fmt.Sprintf("action:%s#%d", name, len(m.set.Values())) + strings.Join(m.set.Values(), "\x00"), name, body, true
}
func (m *keybindManager) Help() string {
if m.child != nil {
return m.child.Help()
}
if m.filtering {
return "type to filter · enter/↓ results · esc clear"
}
return "enter change · a add · d unbind · r restore · / filter · c changes only · s sort · R raw · esc done"
}
+243
View File
@@ -0,0 +1,243 @@
package ui
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/schema"
)
// listEditor edits repeatable options (font-family, keybind, env, …). The
// entries from the config file can be added, edited, removed and
// reordered; Ghostty's built-in default entries are shown read-only and can
// be copied as a starting point.
type listEditor struct {
opt *schema.Option
items []string
defaults []string
showDefaults bool
cursor int
top int
height int
changed bool
child editor
childIndex int // index being edited, or -1 for a new entry
childTitle string
newItem func(value string) editor
}
func newListEditor(o *schema.Option, items []string, newItem func(string) editor) *listEditor {
return &listEditor{
opt: o,
items: append([]string(nil), items...),
defaults: o.DefaultList(),
newItem: newItem,
}
}
func (e *listEditor) capturing() bool {
c, ok := e.child.(interface{ capturing() bool })
return ok && c.capturing()
}
func (e *listEditor) rows() int {
n := len(e.items)
if e.showDefaults {
n += len(e.defaults)
}
return n
}
func (e *listEditor) onDefault() (string, bool) {
if e.cursor >= len(e.items) {
return e.defaults[e.cursor-len(e.items)], true
}
return "", false
}
func (e *listEditor) startChild(index int, value, title string, raw bool) {
e.childIndex = index
e.childTitle = title
if raw {
t := newTextEditor(e.opt, value)
t.item = true
e.child = t
} else {
e.child = e.newItem(value)
}
}
func (e *listEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.child != nil {
cmd, res := e.child.Update(msg)
if res != nil {
e.finishChild(res)
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, e.rows(), max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
def, isDefault := "", false
if e.rows() > 0 {
def, isDefault = e.onDefault()
}
switch key {
case "esc", "q":
if !e.changed {
return nil, cancelled()
}
if len(e.items) == 0 {
return nil, &result{}
}
return nil, valuesResult(e.items...)
case "a", "n", "insert", "+":
e.startChild(-1, "", "New entry", false)
case "enter", "e":
switch {
case e.rows() == 0:
e.startChild(-1, "", "New entry", false)
case isDefault:
e.startChild(-1, def, "New entry (copied from default)", false)
default:
e.startChild(e.cursor, e.items[e.cursor], "Edit entry", false)
}
case "r":
if e.rows() > 0 && !isDefault {
e.startChild(e.cursor, e.items[e.cursor], "Edit entry (raw text)", true)
}
case "d", "x", "delete", "backspace":
if e.rows() == 0 {
break
}
if isDefault {
if e.opt.Kind == schema.KindKeybind {
trigger, _ := schema.SplitKeybind(def)
e.items = append(e.items, trigger+"=unbind")
e.changed = true
e.cursor = len(e.items) - 1
}
break
}
e.items = append(e.items[:e.cursor], e.items[e.cursor+1:]...)
e.changed = true
e.cursor = min(e.cursor, max(0, e.rows()-1))
case "K", "shift+up":
if !isDefault && e.cursor > 0 && e.cursor < len(e.items) {
e.items[e.cursor-1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor-1]
e.cursor--
e.changed = true
}
case "J", "shift+down":
if !isDefault && e.cursor < len(e.items)-1 {
e.items[e.cursor+1], e.items[e.cursor] = e.items[e.cursor], e.items[e.cursor+1]
e.cursor++
e.changed = true
}
case "v":
if len(e.defaults) > 0 {
e.showDefaults = !e.showDefaults
e.cursor = min(e.cursor, max(0, e.rows()-1))
}
}
return nil, nil
}
func (e *listEditor) finishChild(res *result) {
defer func() { e.child = nil }()
if res.cancel {
return
}
value := ""
if len(res.values) > 0 {
value = res.values[0]
}
switch {
case e.childIndex < 0 && value == "":
return
case e.childIndex < 0:
e.items = append(e.items, value)
e.cursor = len(e.items) - 1
case value == "":
e.items = append(e.items[:e.childIndex], e.items[e.childIndex+1:]...)
e.cursor = min(e.childIndex, max(0, e.rows()-1))
default:
e.items[e.childIndex] = value
}
e.changed = true
}
func (e *listEditor) View(width, height int) string {
if e.child != nil {
title := stBold.Render(e.childTitle)
return title + "\n\n" + e.child.View(width, height-2)
}
var lines []string
if len(e.items) == 0 {
lines = append(lines, stDim.Render("No entries in your config. Press a to add one."))
}
e.height = height - 2
listH := e.height
e.top = scrollWindow(e.cursor, e.top, listH, e.rows())
for i := e.top; i < e.rows() && len(lines) < listH; i++ {
isDefault := i >= len(e.items)
var v string
if isDefault {
if i == len(e.items) {
if len(lines) > 0 {
lines = append(lines, "")
}
lines = append(lines, stDim.Render(fmt.Sprintf("Built-in defaults (%d, read-only):", len(e.defaults))))
}
v = e.defaults[i-len(e.items)]
} else {
v = e.items[i]
}
segs := append([]seg{cursorSeg(i == e.cursor)}, e.itemSegs(v, isDefault)...)
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
if len(e.defaults) > 0 && !e.showDefaults {
lines = append(lines, "", stDim.Render(fmt.Sprintf("Ghostty has %d built-in default entries. Press v to show them.", len(e.defaults))))
}
if e.changed {
lines = append(lines, "", stChanged.Render("Modified. Press esc to keep the changes."))
}
return strings.Join(lines, "\n")
}
func (e *listEditor) itemSegs(v string, isDefault bool) []seg {
if isDefault {
return []seg{styled(v, stDim)}
}
switch e.opt.Kind {
case schema.KindKeybind:
trigger, action := schema.SplitKeybind(v)
if action == "" {
return []seg{plain(v)}
}
return []seg{styled(trigger, stKey), styled(" → ", stDim), plain(action)}
case schema.KindColor:
return []seg{rawSeg(swatch(v)), plain(" " + v)}
}
return []seg{plain(v)}
}
func (e *listEditor) Help() string {
if e.child != nil {
return e.child.Help()
}
h := "a add · enter edit · r raw · d delete · J/K move · esc done"
if len(e.defaults) > 0 {
h += " · v defaults"
}
return h
}
+161
View File
@@ -0,0 +1,161 @@
package ui
import (
"fmt"
"sort"
"strings"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
// paletteEditor shows all 256 palette colors and edits individual
// overrides (written as "palette = N=COLOR").
type paletteEditor struct {
opt *schema.Option
defaults [256]string
overrides map[int]string
extra []string // entries that could not be parsed; kept as is
cursor int
top int
height int
changed bool
child *textEditor
colorOpt *schema.Option
theme string // theme providing the defaults of colors 0-15
}
// useTheme takes the base colors from the configured theme, since those
// are what an override replaces.
func (e *paletteEditor) useTheme(t *ghostty.Theme) {
for i, c := range t.Palette {
if c != "" {
e.defaults[i] = c
e.theme = t.Name
}
}
}
func newPaletteEditor(o *schema.Option, entries []string) *paletteEditor {
e := &paletteEditor{
opt: o,
overrides: map[int]string{},
colorOpt: &schema.Option{Key: "palette", Kind: schema.KindColor},
}
for _, d := range o.DefaultList() {
if i, c, ok := schema.SplitPalette(d); ok {
e.defaults[i] = c
}
}
for _, v := range entries {
if i, c, ok := schema.SplitPalette(v); ok {
e.overrides[i] = c
} else {
e.extra = append(e.extra, v)
}
}
return e
}
func (e *paletteEditor) values() []string {
idx := make([]int, 0, len(e.overrides))
for i := range e.overrides {
idx = append(idx, i)
}
sort.Ints(idx)
var out []string
for _, i := range idx {
out = append(out, fmt.Sprintf("%d=%s", i, e.overrides[i]))
}
return append(out, e.extra...)
}
func (e *paletteEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if e.child != nil {
cmd, res := e.child.Update(msg)
if res != nil {
if !res.cancel {
if len(res.values) == 0 {
delete(e.overrides, e.cursor)
} else {
e.overrides[e.cursor] = res.values[0]
}
e.changed = true
}
e.child = nil
}
return cmd, nil
}
km, ok := msg.(tea.KeyMsg)
if !ok {
return nil, nil
}
key := km.String()
if c, moved := moveCursor(key, e.cursor, 256, max(1, e.height-1)); moved {
e.cursor = c
return nil, nil
}
switch key {
case "esc", "q":
if !e.changed {
return nil, cancelled()
}
v := e.values()
if len(v) == 0 {
return nil, &result{}
}
return nil, valuesResult(v...)
case "enter", "e":
cur := e.overrides[e.cursor]
e.child = newTextEditor(e.colorOpt, cur)
e.child.item = true
e.child.input.Placeholder = e.defaults[e.cursor]
case "d", "x", "delete", "backspace":
if _, ok := e.overrides[e.cursor]; ok {
delete(e.overrides, e.cursor)
e.changed = true
}
}
return nil, nil
}
func (e *paletteEditor) View(width, height int) string {
if e.child != nil {
head := stBold.Render(fmt.Sprintf("Palette color %d", e.cursor))
if d := e.defaults[e.cursor]; d != "" {
head += stDim.Render(" default ") + swatch(d) + " " + d
}
return head + "\n\n" + e.child.View(width, height-2)
}
var lines []string
lines = append(lines, stDim.Render(fmt.Sprintf("%d of 256 colors overridden. 0–7 normal, 8–15 bright, 16–255 extended.", len(e.overrides))))
if e.theme != "" {
lines = append(lines, stDim.Render("Colors 0–15 default to the theme "+e.theme+"."))
}
lines = append(lines, "")
e.height = height - len(lines)
e.top = scrollWindow(e.cursor, e.top, e.height, 256)
for i := e.top; i < 256 && i < e.top+e.height; i++ {
value, set := e.overrides[i]
if !set {
value = e.defaults[i]
}
segs := []seg{cursorSeg(i == e.cursor), plain(fmt.Sprintf("%3d ", i)), rawSeg(swatch(value)), plain(" ")}
if set {
segs = append(segs, styled("● "+value, stSet), styled(" (default "+e.defaults[i]+")", stDim))
} else {
segs = append(segs, styled(" "+value, stDim))
}
lines = append(lines, renderRow(segs, width, i == e.cursor))
}
return strings.Join(lines, "\n")
}
func (e *paletteEditor) Help() string {
if e.child != nil {
return e.child.Help()
}
return "↑↓ move · enter edit · d reset color · esc done"
}
+222
View File
@@ -0,0 +1,222 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/colors"
"ghosttyconf/internal/ghostty"
"ghosttyconf/internal/schema"
)
// pickerEditor selects a value from a long, filterable list (themes, font
// families). Any typed value can be used as well.
type pickerEditor struct {
opt *schema.Option
source string // "themes" or "fonts"
all []string
loading bool
loadErr error
filter textinput.Model
matches []string
cursor int
top int
height int
current string
preview func(name string) *ghostty.Theme
note string
}
func newPickerEditor(o *schema.Option, source, current string) *pickerEditor {
p := &pickerEditor{
opt: o,
source: source,
current: schema.Unquote(current),
loading: true,
filter: newInput("", "type to filter, or enter any value"),
}
p.filter.Prompt = "Search: "
return p
}
// setItems delivers the asynchronously loaded list.
func (p *pickerEditor) setItems(items []string, err error) {
p.all, p.loadErr, p.loading = items, err, false
p.refilter()
for i, m := range p.matches {
if m == p.current {
p.cursor = i
break
}
}
}
func (p *pickerEditor) refilter() {
q := strings.ToLower(strings.TrimSpace(p.filter.Value()))
terms := strings.Fields(q)
var prefix, rest []string
for _, it := range p.all {
l := strings.ToLower(it)
ok := true
for _, t := range terms {
if !strings.Contains(l, t) {
ok = false
break
}
}
if !ok {
continue
}
if q != "" && strings.HasPrefix(l, q) {
prefix = append(prefix, it)
} else {
rest = append(rest, it)
}
}
p.matches = append(prefix, rest...)
p.cursor = 0
p.top = 0
}
func (p *pickerEditor) Update(msg tea.Msg) (tea.Cmd, *result) {
if km, ok := msg.(tea.KeyMsg); ok {
key := km.String()
switch key {
case "esc":
return nil, cancelled()
case "enter":
if len(p.matches) > 0 {
return nil, valuesResult(p.matches[p.cursor])
}
v := strings.TrimSpace(p.filter.Value())
if v == "" {
return nil, &result{}
}
return nil, valuesResult(v)
case "tab":
if len(p.matches) > 0 {
p.filter.SetValue(p.matches[p.cursor])
p.filter.CursorEnd()
p.refilter()
}
return nil, nil
case "up", "down", "pgup", "pgdown", "ctrl+p", "ctrl+n":
p.cursor, _ = moveCursor(key, p.cursor, len(p.matches), max(1, p.height-1))
return nil, nil
}
}
before := p.filter.Value()
var cmd tea.Cmd
p.filter, cmd = p.filter.Update(msg)
if p.filter.Value() != before {
p.refilter()
}
return cmd, nil
}
func (p *pickerEditor) View(width, height int) string {
p.filter.Width = max(10, width-12)
var lines []string
count := ""
if !p.loading {
count = stDim.Render(fmt.Sprintf("%d of %d", len(p.matches), len(p.all)))
}
lines = append(lines, p.filter.View(), count)
if p.note != "" {
var note []string
for _, l := range strings.Split(ansi.Wrap(p.note, width, ""), "\n") {
note = append(note, stChanged.Render(l))
}
lines = append(lines[:1], append(note, lines[1:]...)...)
}
var previewLines []string
if p.preview != nil && len(p.matches) > 0 && height >= 16 {
if t := p.preview(p.matches[p.cursor]); t != nil {
previewLines = strings.Split(renderThemePreview(t, width), "\n")
}
}
listH := height - len(lines) - len(previewLines)
if len(previewLines) > 0 {
listH--
}
p.height = listH
switch {
case p.loading:
lines = append(lines, stDim.Render("Loading "+p.source+"…"))
case p.loadErr != nil:
lines = append(lines, stError.Render("Could not load "+p.source+": "+p.loadErr.Error()),
stDim.Render("Type a value and press enter."))
case len(p.matches) == 0:
lines = append(lines, stDim.Render("No matches. Press enter to use the typed value."))
default:
p.top = scrollWindow(p.cursor, p.top, listH, len(p.matches))
for i := p.top; i < len(p.matches) && i < p.top+listH; i++ {
m := p.matches[i]
segs := []seg{cursorSeg(i == p.cursor), plain(m)}
if m == p.current {
segs = append(segs, styled(" ● current", stSet))
}
lines = append(lines, renderRow(segs, width, i == p.cursor))
}
}
if len(previewLines) > 0 {
for len(lines) < height-len(previewLines) {
lines = append(lines, "")
}
lines = append(lines, previewLines...)
}
return strings.Join(lines, "\n")
}
func (p *pickerEditor) Help() string {
return "type to filter · ↑↓ choose · tab complete · enter select · esc cancel"
}
// renderThemePreview draws a small terminal mock-up using a theme's colors.
func renderThemePreview(t *ghostty.Theme, width int) string {
bg, fg := t.Background, t.Foreground
if !colors.Valid(bg) {
bg = "#000000"
}
if !colors.Valid(fg) {
fg = "#ffffff"
}
hexOf := func(v, fallback string) lipgloss.Color {
if h, ok := colors.Hex(v); ok {
return lipgloss.Color(h)
}
return lipgloss.Color(fallback)
}
base := lipgloss.NewStyle().Background(hexOf(bg, "#000000")).Foreground(hexOf(fg, "#ffffff"))
col := func(i int) lipgloss.Style { return base.Foreground(hexOf(t.Palette[i], fg)) }
w := min(width, 48)
row := func(parts ...string) string {
s := strings.Join(parts, "")
return s + base.Render(strings.Repeat(" ", max(0, w-lipglossWidth(s))))
}
var lines []string
lines = append(lines,
row(base.Render(" ")),
row(base.Render(" "), col(2).Bold(true).Render("user@host"), base.Render(" "), col(4).Render("~/src"), base.Render(" $ "), base.Render("ls --color")),
row(base.Render(" "), col(4).Bold(true).Render("docs"), base.Render(" "), col(2).Render("build.sh"), base.Render(" "), col(1).Render("error.log"), base.Render(" "), col(3).Render("notes.md")),
row(base.Render(" "), col(5).Render("import"), base.Render(" os "), col(6).Render("# comment"), base.Render(" "), col(8).Render("dimmed")),
)
var normal, bright strings.Builder
normal.WriteString(base.Render(" "))
bright.WriteString(base.Render(" "))
for i := 0; i < 8; i++ {
normal.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i], bg)).Render(" ") + base.Render(" "))
bright.WriteString(lipgloss.NewStyle().Background(hexOf(t.Palette[i+8], bg)).Render(" ") + base.Render(" "))
}
lines = append(lines, row(base.Render(" ")), row(normal.String()), row(bright.String()), row(base.Render(" ")))
return strings.Join(lines, "\n")
}
func lipglossWidth(s string) int { return lipgloss.Width(s) }
+184
View File
@@ -0,0 +1,184 @@
package ui
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/colors"
)
// The UI uses the 16 ANSI colors so it follows the user's terminal theme.
var (
colAccent = lipgloss.Color("12")
colBorder = lipgloss.Color("8")
colDim = lipgloss.Color("8")
colSet = lipgloss.Color("2")
colChanged = lipgloss.Color("3")
colError = lipgloss.Color("1")
colCode = lipgloss.Color("6")
colSelected = lipgloss.AdaptiveColor{Light: "254", Dark: "237"}
stTitle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colAccent).Padding(0, 1)
stHeader = lipgloss.NewStyle().Foreground(colDim)
stDim = lipgloss.NewStyle().Foreground(colDim)
stBold = lipgloss.NewStyle().Bold(true)
stAccent = lipgloss.NewStyle().Foreground(colAccent)
stSet = lipgloss.NewStyle().Foreground(colSet)
stChanged = lipgloss.NewStyle().Foreground(colChanged)
stError = lipgloss.NewStyle().Foreground(colError)
stOK = lipgloss.NewStyle().Foreground(colSet)
stCode = lipgloss.NewStyle().Foreground(colCode)
stSelected = lipgloss.NewStyle().Background(colSelected)
stKey = lipgloss.NewStyle().Foreground(colAccent).Bold(true)
stLabel = lipgloss.NewStyle().Foreground(colDim).Width(9)
stRecording = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("0")).Background(colError)
)
// swatch renders a small color sample, or "" if value is not a color.
func swatch(value string) string {
h, ok := colors.Hex(value)
if !ok {
return ""
}
return lipgloss.NewStyle().Background(lipgloss.Color(h)).Render(" ")
}
// fit truncates or pads s to exactly width cells.
func fit(s string, width int) string {
if width <= 0 {
return ""
}
if w := ansi.StringWidth(s); w > width {
return ansi.Truncate(s, width, "…")
} else if w < width {
return s + strings.Repeat(" ", width-w)
}
return s
}
// panel draws a rounded box with a title in the top border. The content is
// clipped to the inner area.
func panel(title, content string, width, height int, focused bool) string {
if focused {
return framed(title, content, width, height, colAccent)
}
return framed(title, content, width, height, colBorder)
}
// framed is panel with an explicit border color.
func framed(title, content string, width, height int, color lipgloss.TerminalColor) string {
if width < 4 || height < 2 {
return ""
}
border := lipgloss.NewStyle().Foreground(color)
titleSt := stDim
if color != colBorder {
titleSt = lipgloss.NewStyle().Foreground(color).Bold(true)
}
inner := width - 2
var b strings.Builder
t := ""
if title != "" {
t = ansi.Truncate(" "+title+" ", inner-2, "… ")
}
dashes := max(0, inner-1-ansi.StringWidth(t))
b.WriteString(border.Render("╭─") + titleSt.Render(t) + border.Render(strings.Repeat("─", dashes)+"╮") + "\n")
lines := strings.Split(content, "\n")
for i := 0; i < height-2; i++ {
line := ""
if i < len(lines) {
line = lines[i]
}
b.WriteString(border.Render("│") + fit(line, inner) + "\x1b[0m" + border.Render("│") + "\n")
}
b.WriteString(border.Render("╰" + strings.Repeat("─", inner) + "╯"))
return b.String()
}
// overlay draws box centered on top of base.
func overlay(base, box string, width, height int) string {
baseLines := strings.Split(base, "\n")
for len(baseLines) < height {
baseLines = append(baseLines, "")
}
boxLines := strings.Split(box, "\n")
bw := 0
for _, l := range boxLines {
if w := ansi.StringWidth(l); w > bw {
bw = w
}
}
x := max(0, (width-bw)/2)
y := max(0, (height-len(boxLines))/2)
for i, l := range boxLines {
row := y + i
if row >= len(baseLines) {
break
}
bl := baseLines[row]
left := fit(ansi.Truncate(bl, x, ""), x)
right := ansi.TruncateLeft(bl, x+bw, "")
baseLines[row] = left + "\x1b[0m" + fit(l, bw) + "\x1b[0m" + right
}
return strings.Join(baseLines, "\n")
}
// seg is a styled piece of a list row.
type seg struct {
text string
st lipgloss.Style
raw bool // pre-rendered (e.g. a swatch); keeps its own background
}
func plain(s string) seg { return seg{text: s, st: lipgloss.NewStyle()} }
func styled(s string, st lipgloss.Style) seg { return seg{text: s, st: st} }
func rawSeg(s string) seg { return seg{text: s, raw: true} }
// renderRow joins segments into a row of exactly width cells. Selected rows
// get a background on every segment, so nested styles do not interrupt the
// highlight.
func renderRow(segs []seg, width int, selected bool) string {
var b strings.Builder
used := 0
for _, s := range segs {
if used >= width {
break
}
w := ansi.StringWidth(s.text)
text := s.text
if used+w > width {
text = ansi.Truncate(text, width-used, "…")
w = ansi.StringWidth(text)
}
switch {
case s.raw:
b.WriteString(text)
case selected:
b.WriteString(s.st.Background(colSelected).Render(text))
default:
b.WriteString(s.st.Render(text))
}
used += w
}
if used < width {
pad := strings.Repeat(" ", width-used)
if selected {
pad = stSelected.Render(pad)
}
b.WriteString(pad)
}
return b.String()
}
// cursorSeg is the "▸ " marker in front of the selected row.
func cursorSeg(selected bool) seg {
if selected {
return styled("▸ ", stAccent)
}
return plain(" ")
}
+68
View File
@@ -0,0 +1,68 @@
package ui
import (
"os"
"reflect"
"sync"
tea "github.com/charmbracelet/bubbletea"
"ghosttyconf/internal/keybind"
)
// rawSequence extracts the bytes of an escape sequence Bubble Tea did not
// recognize. Bubble Tea v1 reports those as an unexported []byte message
// type, which is where kitty keyboard protocol key events end up.
func rawSequence(msg tea.Msg) ([]byte, bool) {
if msg == nil {
return nil, false
}
t := reflect.TypeOf(msg)
if t.Kind() != reflect.Slice || t.Elem().Kind() != reflect.Uint8 ||
t.PkgPath() != "github.com/charmbracelet/bubbletea" {
return nil, false
}
return reflect.ValueOf(msg).Bytes(), true
}
var (
kittyMu sync.Mutex
kittyActive bool
)
func writeTerminal(s string) {
_, _ = os.Stdout.WriteString(s)
}
// enableKeyCapture switches the terminal to the kitty keyboard protocol so
// that every key (including cmd/super combinations) can be recorded.
func enableKeyCapture() tea.Cmd {
return func() tea.Msg {
kittyMu.Lock()
defer kittyMu.Unlock()
if !kittyActive {
writeTerminal(keybind.PushKitty + keybind.QueryKitty)
kittyActive = true
}
return nil
}
}
// disableKeyCapture restores the previous keyboard mode.
func disableKeyCapture() tea.Cmd {
return func() tea.Msg {
RestoreTerminal()
return nil
}
}
// RestoreTerminal undoes enableKeyCapture. It is safe to call at any time
// and is called on exit in case the program stops while recording.
func RestoreTerminal() {
kittyMu.Lock()
defer kittyMu.Unlock()
if kittyActive {
writeTerminal(keybind.PopKitty)
kittyActive = false
}
}
+51
View File
@@ -0,0 +1,51 @@
package ui
import (
"io"
"strings"
"testing"
"time"
tea "github.com/charmbracelet/bubbletea"
)
// rawProbe stops at the first message rawSequence accepts.
type rawProbe struct{ got []byte }
func (p *rawProbe) Init() tea.Cmd { return nil }
func (p *rawProbe) View() string { return "" }
func (p *rawProbe) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if b, ok := rawSequence(msg); ok {
p.got = b
return p, tea.Quit
}
return p, nil
}
// TestRawSequenceFromBubbleTea feeds a kitty keyboard protocol key event
// through Bubble Tea's input parser. It breaks if a Bubble Tea upgrade
// changes how unknown escape sequences are delivered.
func TestRawSequenceFromBubbleTea(t *testing.T) {
const seq = "\x1b[92;9u" // super+\
p := &rawProbe{}
prog := tea.NewProgram(p, tea.WithInput(strings.NewReader(seq)), tea.WithOutput(io.Discard),
tea.WithoutRenderer(), tea.WithoutSignals())
done := make(chan error, 1)
go func() {
_, err := prog.Run()
done <- err
}()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(3 * time.Second):
prog.Kill()
t.Fatal("Bubble Tea did not deliver the sequence")
}
if string(p.got) != seq {
t.Fatalf("rawSequence = %q, want %q", p.got, seq)
}
}
+488
View File
@@ -0,0 +1,488 @@
package ui
import (
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"ghosttyconf/internal/keybind"
"ghosttyconf/internal/schema"
)
func (a *App) View() string {
if a.width < 40 || a.height < 12 {
return "Terminal too small for the Ghostty config editor (min. 40×12)."
}
bodyH := a.height - 3
var body string
if a.editor != nil {
body = a.viewEditor(a.width, bodyH)
} else {
body = a.viewBrowse(a.width, bodyH)
}
out := a.viewHeader() + "\n" + body + "\n" + a.viewFooter()
if a.dlg != nil {
out = overlay(out, a.dlg.view(a.width, a.height), a.width, a.height)
}
return out
}
func (a *App) viewHeader() string {
title := stTitle.Render("Ghostty Config Editor") + " "
right := stHeader.Render(fmt.Sprintf(" %s · %d options ", a.sch.Source, len(a.sch.Options)))
if lipgloss.Width(title)+lipgloss.Width(right)+20 > a.width {
right = ""
}
path := shortPath(a.file.Path)
if !a.file.Exists {
path += " (new file)"
}
pathW := a.width - lipgloss.Width(title) - lipgloss.Width(right)
if ansi.StringWidth(path) > pathW {
// Keep the end of the path, which is the informative part.
path = "…" + ansi.TruncateLeft(path, ansi.StringWidth(path)-pathW+1, "")
}
return title + fit(stHeader.Render(path), pathW) + right
}
func (a *App) viewFooter() string {
right := ""
if n := len(a.changedKeys()); n > 0 {
right = stChanged.Render(fmt.Sprintf("● %d unsaved ", n))
}
status := a.statusStyle.Render(a.status)
statusW := a.width - lipgloss.Width(right) - 1
line1 := " " + fit(status, statusW) + right
var help string
switch {
case a.editor != nil:
help = a.editor.Help() + " · shift+↑↓ scroll docs"
case a.searching:
help = "type to search keys and docs · enter/↓ go to results · esc clear"
case a.focus == paneCats:
help = "↑↓ category · → options · / search · b keybindings · c changes · ctrl+s save · ? help · q quit"
default:
help = "↑↓ move · enter edit · space toggle · +/- adjust · r reset · u undo · / search · ctrl+s save · ? help · q quit"
}
return line1 + "\n" + stDim.Render(fit(" "+help, a.width))
}
// ---------------------------------------------------------------------------
// Browse screen
func (a *App) viewBrowse(w, h int) string {
catW := 26
if w < 90 {
catW = 20
}
rightW := w - catW
a.catRect = rect{0, 1, catW, h}
cats := panel("Categories", a.renderCats(catW-2, h-2), catW, h, a.focus == paneCats && !a.searching)
optTitle := a.cats[a.catIdx]
if a.query != "" || a.searching {
optTitle = fmt.Sprintf("Search (%d)", len(a.opts))
} else {
optTitle = fmt.Sprintf("%s (%d)", optTitle, len(a.opts))
}
if rightW >= 120 {
optW := rightW * 52 / 100
docW := rightW - optW
a.optRect = rect{catW, 1, optW, h}
a.docRect = rect{catW + optW, 1, docW, h}
opts := panel(optTitle, a.renderOpts(optW-2, h-2), optW, h, a.focus == paneOpts)
content := a.renderDocs(a.selected(), docW-4, h-2)
docs := panel(a.docTitle(), content, docW, h, false)
return lipgloss.JoinHorizontal(lipgloss.Top, cats, opts, docs)
}
optH := max(7, h*55/100)
docH := h - optH
a.optRect = rect{catW, 1, rightW, optH}
a.docRect = rect{catW, 1 + optH, rightW, docH}
opts := panel(optTitle, a.renderOpts(rightW-2, optH-2), rightW, optH, a.focus == paneOpts)
content := a.renderDocs(a.selected(), rightW-4, docH-2)
docs := panel(a.docTitle(), content, rightW, docH, false)
return lipgloss.JoinHorizontal(lipgloss.Top, cats, lipgloss.JoinVertical(lipgloss.Left, opts, docs))
}
// catRows returns the rendered category rows; -1 marks the separator.
func (a *App) catRows() []int {
rows := []int{0, 1, -1}
for i := 2; i < len(a.cats); i++ {
rows = append(rows, i)
}
return rows
}
func (a *App) catRowIndex(row int) int {
rows := a.catRows()
if row < 0 || row >= len(rows) {
return -1
}
return rows[row]
}
func (a *App) renderCats(w, h int) string {
rows := a.catRows()
sel := 0
for i, r := range rows {
if r == a.catIdx {
sel = i
}
}
a.catTop = scrollWindow(sel, a.catTop, h, len(rows))
var lines []string
for i := a.catTop; i < len(rows) && len(lines) < h; i++ {
ci := rows[i]
if ci < 0 {
lines = append(lines, stDim.Render(strings.Repeat("─", w)))
continue
}
name := a.cats[ci]
n := len(a.categoryOptions(name))
count := fmt.Sprintf("%d", n)
selected := ci == a.catIdx && a.query == ""
nameSt := lipgloss.NewStyle()
if ci == 0 && n > 0 {
nameSt = stSet
}
if selected && a.focus == paneCats {
nameSt = nameSt.Bold(true)
}
nameW := w - 2 - len(count) - 1
segs := []seg{cursorSeg(selected), styled(fit(name, nameW), nameSt), plain(" "), styled(count, stDim)}
lines = append(lines, renderRow(segs, w, selected && a.focus == paneCats))
}
return strings.Join(lines, "\n")
}
func (a *App) renderOpts(w, h int) string {
var lines []string
listY := a.optRect.y + 1
if a.searching || a.query != "" {
a.search.Width = max(10, w-4)
lines = append(lines, a.search.View(), "")
h -= 2
listY += 2
}
a.optListY = listY
if len(a.opts) == 0 {
msg := "No options."
switch {
case a.query != "":
msg = "No options match your search."
case a.cats[a.catIdx] == catSet:
msg = "Your config file does not set any options yet."
}
lines = append(lines, stDim.Render(" "+msg))
return strings.Join(lines, "\n")
}
keyW := 0
for _, o := range a.opts {
keyW = max(keyW, len(o.Key))
}
keyW = min(keyW+1, w*55/100)
valW := w - keyW - 4
a.optTop = scrollWindow(a.optIdx, a.optTop, h, len(a.opts))
for i := a.optTop; i < len(a.opts) && i < a.optTop+h; i++ {
o := a.opts[i]
selected := i == a.optIdx
keySt := lipgloss.NewStyle()
switch {
case a.unknown[o.Key] == o:
keySt = stError
case o.Platform != "" && a.osName != "" && o.Platform != a.osName:
keySt = stDim
}
if selected && a.focus == paneOpts {
keySt = keySt.Bold(true)
}
segs := []seg{cursorSeg(selected), a.marker(o), styled(fit(o.Key, keyW), keySt), plain(" ")}
segs = append(segs, a.valueSegs(o, valW)...)
lines = append(lines, renderRow(segs, w, selected && a.focus == paneOpts))
}
return strings.Join(lines, "\n")
}
// marker shows whether an option is set in the file and whether it has
// unsaved changes.
func (a *App) marker(o *schema.Option) seg {
now := a.file.GetAll(o.Key)
changed := !equalStrings(now, a.saved.GetAll(o.Key))
switch {
case changed && len(now) == 0:
return styled("○ ", stChanged)
case changed:
return styled("● ", stChanged)
case len(now) > 0:
return styled("● ", stSet)
}
return plain(" ")
}
// valueSegs summarizes the current value for the option list.
func (a *App) valueSegs(o *schema.Option, w int) []seg {
vals := a.file.GetAll(o.Key)
set := len(vals) > 0
switch {
case o.Kind == schema.KindKeybind:
counts := map[keybind.Source]int{}
for _, b := range keybind.NewSet(o.DefaultList(), vals).Bindings() {
counts[b.Source]++
}
var parts []seg
add := func(n int, label string, st lipgloss.Style) {
if n == 0 {
return
}
if len(parts) > 0 {
parts = append(parts, styled(" · ", stDim))
}
parts = append(parts, styled(fmt.Sprintf("%d %s", n, label), st))
}
add(counts[keybind.Changed], "changed", stChanged)
add(counts[keybind.Custom], "custom", stSet)
add(counts[keybind.Unbound], "unbound", stError)
if len(parts) == 0 {
return []seg{styled(fmt.Sprintf("%d built-in bindings", counts[keybind.Default]), stDim)}
}
return parts
case o.Kind == schema.KindPalette:
if set {
return []seg{plain(fmt.Sprintf("%d color(s) overridden", len(vals)))}
}
return []seg{styled("default palette", stDim)}
case o.Repeatable:
if set {
s := vals[0]
if o.Kind == schema.KindKeybind {
s = keybindSummary(vals[0])
}
if len(vals) > 1 {
return []seg{plain(ansi.Truncate(s, max(5, w-10), "…")), styled(fmt.Sprintf(" +%d more", len(vals)-1), stDim)}
}
return []seg{plain(s)}
}
defs := o.DefaultList()
switch len(defs) {
case 0:
return []seg{styled("—", stDim)}
case 1:
return []seg{styled(defs[0], stDim)}
}
return []seg{styled(fmt.Sprintf("%d built-in entries", len(defs)), stDim)}
}
v := o.Default()
st := stDim
if set {
v, st = vals[len(vals)-1], lipgloss.NewStyle()
if o.Validate(v) != nil {
st = stError
}
}
if v == "" {
return []seg{styled("—", stDim)}
}
v = strings.ReplaceAll(v, "\t", "\\t")
if o.Kind == schema.KindColor || o.Kind == schema.KindColorList {
if sw := swatch(strings.Split(v, ",")[0]); sw != "" {
return []seg{rawSeg(sw), plain(" "), styled(v, st)}
}
}
return []seg{styled(v, st)}
}
func keybindSummary(v string) string {
t, act := schema.SplitKeybind(v)
if act == "" {
return v
}
return t + " → " + act
}
// renderDocs renders the documentation panel content for o into a.doc and
// returns the visible part.
func (a *App) renderDocs(o *schema.Option, w, h int) string {
if o == nil {
return ""
}
a.doc.Width, a.doc.Height = w, h
id := o.Key
var content func() string
// Editors can show documentation of their own (e.g. of the selected
// keybind action) instead of the option's.
if dp, ok := a.editor.(interface {
docFor() (id, title, body string, ok bool)
}); ok {
if did, title, body, ok := dp.docFor(); ok {
id = did
content = func() string { return stAccent.Bold(true).Render(title) + "\n\n" + renderDoc(body, w) }
}
}
if content == nil {
content = func() string { return a.docContent(o, w) }
}
key := fmt.Sprintf("%s|%d|%d", id, w, a.rev)
if a.editor != nil {
key += "|edit"
}
if key != a.docFor {
if !strings.HasPrefix(a.docFor, id+"|") {
a.doc.GotoTop()
}
a.docFor = key
a.doc.SetContent(content())
}
lines := strings.Split(a.doc.View(), "\n")
for i := range lines {
lines[i] = " " + lines[i]
}
return strings.Join(lines, "\n")
}
// docTitle is the documentation panel title, with a scroll position when
// the text does not fit. Call it after renderDocs.
func (a *App) docTitle() string {
if a.doc.TotalLineCount() <= a.doc.Height {
return "Documentation"
}
return fmt.Sprintf("Documentation · %d%% · shift+↑↓ scroll", int(a.doc.ScrollPercent()*100))
}
func (a *App) docContent(o *schema.Option, w int) string {
var b strings.Builder
b.WriteString(stAccent.Bold(true).Render(o.Key) + "\n\n")
row := func(label, value string) {
b.WriteString(stLabel.Render(label) + " " + ansi.Wrap(value, max(10, w-10), "") + "\n")
}
if a.editor == nil {
row("Type", o.TypeLabel())
vals := a.file.GetAll(o.Key)
switch {
case o.Repeatable:
defs := o.DefaultList()
if len(defs) > 0 {
row("Default", fmt.Sprintf("%d built-in entries", len(defs)))
} else {
row("Default", "none")
}
if len(vals) == 0 {
row("Value", stDim.Render("not set"))
} else {
row("Value", fmt.Sprintf("%d entr%s in your config", len(vals), plural(len(vals), "y", "ies")))
for i, v := range vals {
if i == 8 {
b.WriteString(stDim.Render(fmt.Sprintf(" … and %d more", len(vals)-8)) + "\n")
break
}
b.WriteString(" " + ansi.Truncate(v, max(10, w-10), "…") + "\n")
}
}
default:
def := o.Default()
if def == "" {
def = stDim.Render("(unset)")
} else if sw := swatch(def); sw != "" && o.Kind == schema.KindColor {
def = sw + " " + def
}
row("Default", strings.ReplaceAll(def, "\t", "\\t"))
if len(vals) == 0 {
row("Value", stDim.Render("not set (uses default)"))
} else {
v := vals[len(vals)-1]
if sw := swatch(v); sw != "" && o.Kind == schema.KindColor {
v = sw + " " + v
}
row("Value", v+" "+stSet.Render("● set in config"))
if err := o.Validate(vals[len(vals)-1]); err != nil {
b.WriteString(stError.Render(" ✗ invalid: "+err.Error()) + "\n")
}
if len(vals) > 1 {
b.WriteString(stChanged.Render(fmt.Sprintf(" set %d times; the last one wins", len(vals))) + "\n")
}
}
}
if o.Platform != "" {
row("Platform", o.Platform+" only")
}
row("Category", o.Category)
b.WriteString("\n")
}
if o.Doc == "" {
b.WriteString(stDim.Render("No documentation available."))
} else {
b.WriteString(renderDoc(o.Doc, w))
}
return b.String()
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// ---------------------------------------------------------------------------
// Editor screen
func (a *App) viewEditor(w, h int) string {
o := a.editOpt
title := "Edit " + o.Key
if w >= 110 {
edW := w * 55 / 100
docW := w - edW
a.optRect = rect{0, 1, edW, h}
a.docRect = rect{edW, 1, docW, h}
left := panel(title, a.renderEditor(edW-4, h-2), edW, h, true)
content := a.renderDocs(o, docW-4, h-2)
right := panel(a.docTitle(), content, docW, h, false)
return lipgloss.JoinHorizontal(lipgloss.Top, left, right)
}
edH := max(10, h*62/100)
switch a.editor.(type) {
case *keybindManager, *listEditor, *paletteEditor:
edH = max(10, h*75/100) // long lists need the room
}
docH := h - edH
a.optRect = rect{0, 1, w, edH}
a.docRect = rect{0, 1 + edH, w, docH}
top := panel(title, a.renderEditor(w-4, edH-2), w, edH, true)
if docH < 3 {
return top
}
content := a.renderDocs(o, w-4, docH-2)
bottom := panel(a.docTitle(), content, w, docH, false)
return lipgloss.JoinVertical(lipgloss.Left, top, bottom)
}
func (a *App) renderEditor(w, h int) string {
o := a.editOpt
var head []string
head = append(head, stLabel.Render("Type")+" "+ansi.Truncate(o.TypeLabel(), max(10, w-10), "…"))
if !o.Repeatable {
def := o.Default()
if def == "" {
def = stDim.Render("(unset)")
}
cur, ok := a.file.Get(o.Key)
if !ok {
cur = stDim.Render("not set")
}
head = append(head,
stLabel.Render("Default")+" "+ansi.Truncate(strings.ReplaceAll(def, "\t", "\\t"), max(10, w-10), "…"),
stLabel.Render("Current")+" "+ansi.Truncate(cur, max(10, w-10), "…"))
}
head = append(head, "")
body := a.editor.View(w, h-len(head))
lines := append(head, strings.Split(body, "\n")...)
for i := range lines {
lines[i] = " " + lines[i]
}
return strings.Join(lines, "\n")
}