config.go RawHistoryFolder

1// Package config reads the flat `key = value` config file (ADR 012).
2package config
3
4import (
5	"bufio"
6	"fmt"
7	"io"
8	"math"
9	"os"
10	"path/filepath"
11	"regexp"
12	"slices"
13	"sort"
14	"strconv"
15	"strings"
16	"time"
17	"unicode"
18
19	"github.com/bnema/neferwl/internal/ports"
20)
21
22// maxVRRFlipGap bounds render.vrr-flip-gap below one refresh of a slow
23// VRR panel (48 Hz: 20.8 ms).
24const maxVRRFlipGap = 10 * time.Millisecond
25
26// maxCursorHideAfter bounds cursor.hide-after.
27const maxCursorHideAfter = time.Hour
28
29// defaultBinds use the config syntax and go through the same parser as user binds.
30var defaultBinds = []struct{ combo, action string }{
31	{"cmd+return", "spawn-terminal"},
32	{"cmd+left", "focus-column-left"},
33	{"cmd+right", "focus-column-right"},
34	{"cmd+up", "focus-window-up"},
35	{"cmd+down", "focus-window-down"},
36	{"cmd+shift+left", "move-column-left"},
37	{"cmd+shift+right", "move-column-right"},
38	{"cmd+bracketleft", "consume-or-expel-window-left"},
39	{"cmd+bracketright", "consume-or-expel-window-right"},
40	{"cmd+r", "cycle-column-width"},
41	{"cmd+f", "maximize-column"},
42	{"cmd+shift+f", "toggle-fullscreen"},
43	{"cmd+s", "toggle-stash-visible"},
44	{"cmd+shift+s", "toggle-window-stash"},
45	{"cmd+o", "toggle-overview"},
46	{"cmd+q", "close-window"},
47	{"ctrl+alt+backspace", "quit"},
48	{"ctrl+cmd+space", "spawn fuzzel"},
49	{"cmd+pageup", "focus-workspace-up"},
50	{"cmd+pagedown", "focus-workspace-down"},
51	{"cmd+shift+pageup", "move-column-to-workspace-up"},
52	{"cmd+shift+pagedown", "move-column-to-workspace-down"},
53	{"cmd+ctrl+left", "focus-monitor-left"},
54	{"cmd+ctrl+right", "focus-monitor-right"},
55	{"cmd+ctrl+up", "focus-monitor-up"},
56	{"cmd+ctrl+down", "focus-monitor-down"},
57	{"cmd+ctrl+shift+left", "move-workspace-to-monitor-left"},
58	{"cmd+ctrl+shift+right", "move-workspace-to-monitor-right"},
59	{"cmd+shift+up", "move-window-up"},
60	{"cmd+shift+down", "move-window-down"},
61	{"cmd+alt+left", "set-column-width -10%"},
62	{"cmd+alt+right", "set-column-width +10%"},
63	{"cmd+alt+up", "set-window-height -10%"},
64	{"cmd+alt+down", "set-window-height +10%"},
65	{"cmd+ctrl+shift+up", "move-workspace-up"},
66	{"cmd+ctrl+shift+down", "move-workspace-down"},
67	{"cmd+shift+space", "toggle-floating"},
68}
69var actions = map[string]bool{
70	"focus-monitor-left":              true,
71	"focus-monitor-right":             true,
72	"move-workspace-to-monitor-left":  true,
73	"move-workspace-to-monitor-right": true,
74	"focus-monitor-up":                true,
75	"focus-monitor-down":              true,
76	"move-workspace-to-monitor-up":    true,
77	"move-workspace-to-monitor-down":  true,
78	"scale-up":                        true,
79	"scale-down":                      true,
80	"focus-workspace-up":              true,
81	"focus-workspace-down":            true,
82	"move-column-to-workspace-up":     true,
83	"move-column-to-workspace-down":   true,
84	"move-window-to-workspace-up":     true,
85	"move-window-to-workspace-down":   true,
86	"none":                            true,
87	"consume-or-expel-window-left":    true,
88	"consume-or-expel-window-right":   true,
89	"spawn-terminal":                  true,
90	"focus-column-left":               true,
91	"focus-column-right":              true,
92	"focus-window-up":                 true,
93	"focus-window-down":               true,
94	"move-column-left":                true,
95	"move-column-right":               true,
96	"cycle-column-width":              true,
97	"maximize-column":                 true,
98	"toggle-fullscreen":               true,
99	"toggle-window-stash":             true,
100	"toggle-stash-visible":            true,
101	"toggle-overview":                 true,
102	"close-window":                    true,
103	"quit":                            true,
104	"move-window-up":                  true,
105	"move-window-down":                true,
106	"move-workspace-up":               true,
107	"move-workspace-down":             true,
108	"toggle-floating":                 true,
109}
110var components = map[string]bool{"core": true, "wayland": true, "input": true, "drm": true, "seat": true, "render": true, "sync": true, "config": true, "app": true}
111var color = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
112
113// resizeStep is the +N% or -N% step of set-column-width and
114// set-window-height, N from 1 to 100.
115var resizeStep = regexp.MustCompile(`^[+-]([1-9][0-9]?|100)%$`)
116
117// namedKeys maps lowercase names to xkb keysym names so binds are case-insensitive.
118var namedKeys = map[string]string{
119	"return": "Return", "enter": "Return", "space": "space", "tab": "Tab", "escape": "Escape", "esc": "Escape",
120	"backspace": "BackSpace", "delete": "Delete", "insert": "Insert", "home": "Home", "end": "End",
121	"pageup": "Prior", "prior": "Prior", "pagedown": "Next", "next": "Next", "print": "Print",
122	"left": "Left", "right": "Right", "up": "Up", "down": "Down",
123}
124
125// Warning is a non-fatal problem at one line; the key keeps its default.
126type Warning struct {
127	Line int
128	Msg  string
129}
130
131func (w Warning) String() string { return fmt.Sprintf("line %d: %s", w.Line, w.Msg) }
132
133func DefaultPath() string {
134	base := os.Getenv("XDG_CONFIG_HOME")
135	if base == "" {
136		home, err := os.UserHomeDir()
137		if err == nil {
138			base = filepath.Join(home, ".config")
139		}
140	}
141	return filepath.Join(base, "neferwl", "config")
142}
143
144func Defaults() ports.Config {
145	var c ports.Config
146	c.Keyboard.RepeatRate = 25
147	c.Keyboard.RepeatDelay = 600
148	c.Keyboard.CmdKey = "super"
149	c.Terminal.Command = strings.Fields(os.Getenv("TERMINAL"))
150	if len(c.Terminal.Command) == 0 {
151		c.Terminal.Command = []string{"foot"}
152	}
153	c.Terminal.AutoOpen = "first"
154	c.Xwayland = "xwayland-satellite"
155	c.Background.Color = "#111111"
156	c.Floating.Dim = 0.3
157	c.Stash.Width = 80
158	c.Stash.Gap = 2
159	c.Stash.Dim = 0.5
160	c.Stash.Capture = true
161	c.Border.Width = 2
162	c.Border.Active = "#808080"
163	c.Border.Inactive = "#111111"
164	c.Layout.MaxColumns = 2
165	c.Layout.Presets = []string{"1/3", "1/2", "2/3", "1"}
166	c.Layout.Overflow = "scroll"
167	c.Touchpad.Tap = true
168	c.Touchpad.AccelProfile = ports.AccelAdaptive
169	c.Touchpad.ScrollFactor = 1
170	c.Mouse.AccelProfile = ports.AccelAdaptive
171	c.Cursor.HideAfter = 5 * time.Second
172	c.Focus.Animation = ports.FocusAnimationPulse
173	c.Focus.Effect = ports.FocusEffectScreen
174	c.Focus.Strength = 0.04
175	c.Binds = map[string]string{}
176	for _, b := range defaultBinds {
177		combos := []string{b.combo}
178		// Every arrow bind has a vim twin: h j k l.
179		for arrow, vim := range map[string]string{"left": "h", "down": "j", "up": "k", "right": "l"} {
180			if base, ok := strings.CutSuffix(b.combo, "+"+arrow); ok {
181				combos = append(combos, base+"+"+vim)
182			}
183		}
184		for _, s := range combos {
185			combo, err := parseCombo(s)
186			if err != nil {
187				panic(err)
188			}
189			c.Binds[combo] = b.action
190		}
191	}
192	// Digits and zoom use physical keys (evdev codes 2-10, 12, 13), so they
193	// work the same on AZERTY, QWERTZ or Dvorak.
194	for combo, action := range map[string]string{"cmd+code:13": "scale-up", "cmd+code:12": "scale-down"} {
195		canon, _ := parseCombo(combo)
196		c.Binds[canon] = action
197	}
198	for n := 1; n <= 9; n++ {
199		focus, _ := parseCombo(fmt.Sprintf("cmd+code:%d", n+1))
200		move, _ := parseCombo(fmt.Sprintf("cmd+shift+code:%d", n+1))
201		c.Binds[focus] = fmt.Sprintf("focus-workspace %d", n)
202		c.Binds[move] = fmt.Sprintf("move-column-to-workspace %d", n)
203	}
204	c.Render.DirectScanout = true
205	c.Render.Tearing = true
206	c.Render.VRR = true
207	c.Render.VRRFlipGap = time.Millisecond
208	c.Performance.Realtime = true
209	c.Log.Level = "info"
210	c.Log.Debug = []string{}
211	return c
212}
213
214// LoadDefault loads DefaultPath; a missing file means defaults.
215func LoadDefault() (ports.Config, []Warning, error) {
216	c, w, err := Load(DefaultPath())
217	if os.IsNotExist(err) {
218		return Defaults(), nil, nil
219	}
220	return c, w, err
221}
222
223// Load reads a config file. The error is only for I/O; bad lines become warnings.
224func Load(path string) (ports.Config, []Warning, error) {
225	f, err := os.Open(path)
226	if err != nil {
227		return Defaults(), nil, err
228	}
229	defer f.Close()
230	return Parse(f)
231}
232
233// maxOutputOffset bounds output.<name>.offset (logical px), far beyond any
234// real layout but small enough that placement arithmetic cannot overflow.
235const maxOutputOffset = 65536
236
237// outputRelations lists the relation suffixes, tried in order.
238var outputRelations = [...]struct {
239	suffix string
240	rel    ports.OutputRelation
241}{
242	{".right-of", ports.RelationRightOf},
243	{".left-of", ports.RelationLeftOf},
244	{".above", ports.RelationAbove},
245	{".below", ports.RelationBelow},
246}
247
248// outputRelation splits "<output>.right-of" (left-of, above, below) into the
249// relation and the output name.
250func outputRelation(name string) (ports.OutputRelation, string, bool) {
251	for _, r := range outputRelations {
252		if base, ok := strings.CutSuffix(name, r.suffix); ok {
253			return r.rel, base, true
254		}
255	}
256	return ports.RelationNone, "", false
257}
258
259// checkOutputAnchors warns about an offset without a relation, then drops the
260// relations that form a cycle (every output of the cycle, one warning each),
261// and warns about outputs sharing the same relation, reference and offset.
262// Core places a cycle automatically anyway; runtime overrides never create
263// relations, so this is the only place to detect them.
264func checkOutputAnchors(outputs []ports.OutputConfig, relKeys map[string]string, offsetLines, seen map[string]int) []Warning {
265	var warnings []Warning
266	for _, o := range outputs {
267		if line, ok := offsetLines[o.Name]; ok && o.Anchor.Relation == ports.RelationNone {
268			warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("output.%s.offset: ignored without a relation (right-of, left-of, above, below)", o.Name)})
269		}
270	}
271	byName := make(map[string]*ports.OutputConfig, len(outputs))
272	for i := range outputs {
273		byName[outputs[i].Name] = &outputs[i]
274	}
275	var cycle []*ports.OutputConfig
276	for i := range outputs {
277		for cur, steps := &outputs[i], 0; steps <= len(outputs); steps++ {
278			if cur.Anchor.Relation == ports.RelationNone {
279				break
280			}
281			if cur = byName[cur.Anchor.To]; cur == nil {
282				break
283			}
284			if cur == &outputs[i] {
285				cycle = append(cycle, cur)
286				break
287			}
288		}
289	}
290	for _, o := range cycle {
291		key := relKeys[o.Name]
292		warnings = append(warnings, Warning{Line: seen[key], Msg: fmt.Sprintf("%s: relation cycle, ignored", key)})
293		o.Anchor.Relation, o.Anchor.To = ports.RelationNone, ""
294	}
295	// Two outputs with the same relation, reference and offset overlap.
296	for i, o := range outputs {
297		if o.Anchor.Relation == ports.RelationNone {
298			continue
299		}
300		for _, prev := range outputs[:i] {
301			if prev.Anchor == o.Anchor {
302				warnings = append(warnings, Warning{Line: seen[relKeys[o.Name]], Msg: fmt.Sprintf("output.%s: same relation as output.%s; both get the same position", o.Name, prev.Name)})
303				break
304			}
305		}
306	}
307	return warnings
308}
309
310// Parse reads `key = value` lines on top of the defaults.
311func Parse(r io.Reader) (ports.Config, []Warning, error) {
312	c, _, w, err := parse(r)
313	return c, w, err
314}
315
316// parse also returns the effective key/value pairs, used to log what changed on reload.
317func parse(r io.Reader) (ports.Config, map[string]string, []Warning, error) {
318	c := Defaults()
319	var warnings []Warning
320	raw := map[string]string{}
321	seen := map[string]int{}
322	outputs := map[string]int{}
323	relKeys := map[string]string{}  // output -> key of its relation
324	offsetLines := map[string]int{} // output -> line of its offset
325	workspaces := map[string]int{}
326	scanner := bufio.NewScanner(r)
327	for n := 1; scanner.Scan(); n++ {
328		line := strings.TrimSpace(scanner.Text())
329		if line == "" || strings.HasPrefix(line, "#") {
330			continue
331		}
332		warn := func(format string, a ...any) {
333			warnings = append(warnings, Warning{Line: n, Msg: fmt.Sprintf(format, a...)})
334		}
335		key, value, ok := strings.Cut(line, "=")
336		key, value = strings.TrimSpace(key), stripComment(strings.TrimSpace(value))
337		if !ok || key == "" {
338			warn("expected key = value")
339			continue
340		}
341		if combo, ok := strings.CutPrefix(key, "bind."); ok {
342			if strings.HasSuffix(combo, "+") && strings.HasPrefix(value, "=") {
343				warn("%s: write %sequal instead of %s=", key, combo, combo)
344				continue
345			}
346			canon, err := parseCombo(combo)
347			if err != nil {
348				warn("%s: %v", key, err)
349				continue
350			}
351			if err := checkAction(value); err != nil {
352				warn("%s: %v", key, err)
353				continue
354			}
355			key = "bind." + canon
356			if prev, dup := seen[key]; dup {
357				warn("%s: overrides line %d", key, prev)
358			}
359			seen[key] = n
360			raw[key] = value
361			c.Binds[canon] = value
362			continue
363		}
364		override := func() {
365			if prev, dup := seen[key]; dup {
366				warn("%s: overrides line %d", key, prev)
367			}
368			seen[key] = n
369			raw[key] = value
370		}
371		if name, ok := strings.CutPrefix(key, "output."); ok {
372			entry := func() *ports.OutputConfig {
373				if i, ok := outputs[name]; ok {
374					return &c.Outputs[i]
375				}
376				outputs[name] = len(c.Outputs)
377				c.Outputs = append(c.Outputs, ports.OutputConfig{Name: name, ScaleOnly: true, SDRBrightness: ports.DefaultSDRBrightness})
378				return &c.Outputs[len(c.Outputs)-1]
379			}
380			if base, ok := strings.CutSuffix(name, ".primary"); ok {
381				name = base
382				b, err := onOff(value)
383				if err != nil {
384					warn("%s: %v", key, err)
385					continue
386				}
387				override()
388				entry().Primary = b
389				continue
390			}
391			if base, ok := strings.CutSuffix(name, ".hdr"); ok {
392				name = base
393				b, err := onOff(value)
394				if err != nil {
395					warn("%s: %v", key, err)
396					continue
397				}
398				override()
399				entry().HDR = b
400				continue
401			}
402			if base, ok := strings.CutSuffix(name, ".sdr-brightness"); ok {
403				name = base
404				nits, err := strconv.Atoi(value)
405				if err != nil || nits < 80 || nits > 1000 {
406					warn("%s: must be between 80 and 1000", key)
407					continue
408				}
409				override()
410				entry().SDRBrightness = nits
411				continue
412			}
413			if base, ok := strings.CutSuffix(name, ".offset"); ok {
414				name = base
415				off, err := strconv.Atoi(value)
416				if err != nil || off < -maxOutputOffset || off > maxOutputOffset {
417					warn("%s: must be an integer between -%d and %d", key, maxOutputOffset, maxOutputOffset)
418					continue
419				}
420				override()
421				entry().Anchor.Offset = off
422				offsetLines[name] = n
423				continue
424			}
425			if rel, base, ok := outputRelation(name); ok {
426				name = base
427				if value == "" {
428					warn("%s: expected an output name", key)
429					continue
430				}
431				if value == name {
432					warn("%s: an output cannot be placed relative to itself", key)
433					continue
434				}
435				if prev, ok := relKeys[name]; ok && prev != key {
436					warn("%s: overrides line %d (%s)", key, seen[prev], prev)
437					delete(raw, prev)
438					// Stale lines of the other relation keys must not trigger a
439					// second override warning from override() or a later switch.
440					delete(seen, prev)
441					delete(seen, key)
442				}
443				override()
444				relKeys[name] = key
445				a := &entry().Anchor
446				a.Relation, a.To = rel, value
447				continue
448			}
449			if base, ok := strings.CutSuffix(name, ".scale"); ok {
450				name = base
451				s, err := parseScale(value)
452				if err != nil {
453					warn("%s: %v", key, err)
454					continue
455				}
456				override()
457				entry().Scale = s
458				continue
459			}
460			if base, ok := strings.CutSuffix(name, ".transform"); ok {
461				name = base
462				t, err := parseTransform(value)
463				if err != nil {
464					warn("%s: %v", key, err)
465					continue
466				}
467				override()
468				entry().Transform = t
469				continue
470			}
471			o := ports.OutputConfig{Name: name}
472			if value == "off" {
473				o.Off = true
474			} else if _, _, _, err := ParseMode(value); err != nil {
475				warn("%s: %v", key, err)
476				continue
477			} else if value != "preferred" {
478				o.Mode = value
479			}
480			override()
481			e := entry()
482			o.Scale, o.Transform, o.Primary, o.HDR, o.SDRBrightness, o.Anchor = e.Scale, e.Transform, e.Primary, e.HDR, e.SDRBrightness, e.Anchor
483			*e = o
484			continue
485		}
486		if rest, ok := strings.CutPrefix(key, "workspace."); ok {
487			name, field, _ := strings.Cut(rest, ".")
488			if !workspaceName.MatchString(name) {
489				warn("%s: workspace name must be letters, digits, - or _", key)
490				continue
491			}
492			var ws ports.WorkspaceConfig
493			if i, ok := workspaces[name]; ok {
494				ws = c.Workspaces[i]
495			}
496			if err := setWorkspace(&ws, field, value); err != nil {
497				warn("%s: %v", key, err)
498				continue
499			}
500			override()
501			if i, ok := workspaces[name]; ok {
502				c.Workspaces[i] = ws
503			} else {
504				ws.Name = name
505				workspaces[name] = len(c.Workspaces)
506				c.Workspaces = append(c.Workspaces, ws)
507			}
508			continue
509		}
510		if err := set(&c, key, value); err != nil {
511			warn("%s: %v", key, err)
512			continue
513		}
514		if key == "startup" {
515			// Repeatable: each line adds a command.
516			raw[fmt.Sprintf("startup.%d", len(c.Startup))] = value
517			continue
518		}
519		override()
520	}
521	if err := scanner.Err(); err != nil {
522		return c, raw, warnings, err
523	}
524	warnings = append(warnings, checkOutputAnchors(c.Outputs, relKeys, offsetLines, seen)...)
525	warnings = append(warnings, checkWorkspaceBinds(c, seen)...)
526	sort.SliceStable(warnings, func(i, j int) bool { return warnings[i].Line < warnings[j].Line })
527	// A user bind on a digit (cmd+1, even "none") replaces the default bound
528	// to the same physical key (cmd+code:2), so older configs keep working.
529	for combo := range c.Binds {
530		if seen["bind."+combo] == 0 {
531			continue
532		}
533		parts := strings.Split(combo, "+")
534		key := parts[len(parts)-1]
535		if len(key) != 1 || key[0] < '0' || key[0] > '9' {
536			continue
537		}
538		code := int(key[0]-'0') + 1
539		if key == "0" {
540			code = 11
541		}
542		parts[len(parts)-1] = "code:" + strconv.Itoa(code)
543		if physical := strings.Join(parts, "+"); seen["bind."+physical] == 0 {
544			delete(c.Binds, physical)
545		}
546	}
547	// "none" only removes a default bind.
548	for combo, a := range c.Binds {
549		if a == "none" {
550			delete(c.Binds, combo)
551		}
552	}
553	// Cmd resolves to a real modifier; drop binds that then collide. As for any key,
554	// the later line wins; defaults (no line) lose to every user line.
555	combos := make([]string, 0, len(c.Binds))
556	for combo := range c.Binds {
557		combos = append(combos, combo)
558	}
559	order := func(combo string) int {
560		if n := seen["bind."+combo]; n > 0 {
561			return -n
562		}
563		return math.MaxInt
564	}
565	sort.Slice(combos, func(i, j int) bool {
566		a, b := order(combos[i]), order(combos[j])
567		return a < b || a == b && combos[i] < combos[j]
568	})
569	resolved := map[string]string{}
570	for _, combo := range combos {
571		r, err := expandCmd(combo, c.Keyboard.CmdKey)
572		if prev, dup := resolved[r]; err == nil && dup {
573			err = fmt.Errorf("overridden by bind.%s (same keys with keyboard.cmd = %s)", prev, c.Keyboard.CmdKey)
574		}
575		if err != nil {
576			if n := seen["bind."+combo]; n > 0 {
577				warnings = append(warnings, Warning{Line: n, Msg: fmt.Sprintf("bind.%s: %v", combo, err)})
578			}
579			delete(c.Binds, combo)
580			delete(raw, "bind."+combo)
581			continue
582		}
583		resolved[r] = combo
584	}
585	return c, raw, warnings, nil
586}
587
588// expandCmd replaces Cmd with the configured modifier and re-sorts.
589func expandCmd(combo, cmd string) (string, error) {
590	parts := strings.Split(combo, "+")
591	key := parts[len(parts)-1]
592	// cmd is super, alt or ctrl; its modifier name is the capitalized form.
593	cmdName := strings.ToUpper(cmd[:1]) + cmd[1:]
594	seen := map[string]bool{}
595	for _, m := range parts[:len(parts)-1] {
596		if m == "Cmd" {
597			m = cmdName
598		}
599		if seen[m] {
600			return "", fmt.Errorf("%s is already cmd (keyboard.cmd = %s)", strings.ToLower(m), cmd)
601		}
602		seen[m] = true
603	}
604	mods := make([]string, 0, len(seen))
605	for m := range seen {
606		mods = append(mods, m)
607	}
608	sort.Strings(mods)
609	return strings.Join(append(mods, key), "+"), nil
610}
611
612// set applies one scalar key. Unknown keys and invalid values are errors.
613func set(c *ports.Config, key, v string) error {
614	switch key {
615	case "keyboard.layout":
616		c.Keyboard.Layout = v
617	case "keyboard.variant":
618		c.Keyboard.Variant = v
619	case "keyboard.options":
620		c.Keyboard.Options = v
621	case "keyboard.repeat-rate":
622		return positive(&c.Keyboard.RepeatRate, v, 1000)
623	case "keyboard.repeat-delay":
624		return positive(&c.Keyboard.RepeatDelay, v, 10000)
625	case "keyboard.cmd":
626		if v != "super" && v != "alt" && v != "ctrl" {
627			return fmt.Errorf("must be super, alt or ctrl")
628		}
629		c.Keyboard.CmdKey = v
630	case "startup":
631		argv := strings.Fields(v)
632		if len(argv) == 0 {
633			return fmt.Errorf("must not be empty")
634		}
635		c.Startup = append(c.Startup, argv)
636	case "terminal":
637		argv := strings.Fields(v)
638		if len(argv) == 0 {
639			return fmt.Errorf("must not be empty")
640		}
641		c.Terminal.Command = argv
642	case "terminal.auto-open":
643		if v != "first" && v != "all" && v != "off" {
644			return fmt.Errorf("must be first, all or off")
645		}
646		c.Terminal.AutoOpen = v
647	case "xwayland":
648		switch {
649		case v == "off":
650			c.Xwayland = ""
651		case v == "" || strings.ContainsAny(v, " \t"):
652			return fmt.Errorf("must be off or the xwayland-satellite program")
653		default:
654			c.Xwayland = v
655		}
656	case "background":
657		if !color.MatchString(v) {
658			return fmt.Errorf("must be #rrggbb")
659		}
660		c.Background.Color = v
661	case "floating.dim":
662		dim, err := strconv.ParseFloat(v, 64)
663		if err != nil || !(dim >= 0 && dim <= 1) {
664			return fmt.Errorf("must be between 0 and 1")
665		}
666		c.Floating.Dim = dim
667	case "stash.width":
668		n, err := strconv.Atoi(strings.TrimSuffix(v, "%"))
669		if err != nil || n < 10 || n > 90 {
670			return fmt.Errorf("must be between 10 and 90")
671		}
672		c.Stash.Width = n
673	case "stash.gap":
674		n, err := strconv.Atoi(v)
675		if err != nil || n < 0 || n > 10 {
676			return fmt.Errorf("must be between 0 and 10")
677		}
678		c.Stash.Gap = n
679	case "stash.dim":
680		dim, err := strconv.ParseFloat(v, 64)
681		if err != nil || !(dim >= 0 && dim <= 1) {
682			return fmt.Errorf("must be between 0 and 1")
683		}
684		c.Stash.Dim = dim
685	case "stash.capture":
686		b, err := onOff(v)
687		if err != nil {
688			return err
689		}
690		c.Stash.Capture = b
691	case "border.width":
692		n, err := strconv.Atoi(v)
693		if err != nil || n < 0 || n > 32 {
694			return fmt.Errorf("must be between 0 and 32")
695		}
696		c.Border.Width = n
697	case "border.active":
698		if !color.MatchString(v) {
699			return fmt.Errorf("must be #rrggbb")
700		}
701		c.Border.Active = v
702	case "border.inactive":
703		if v != "" && !color.MatchString(v) {
704			return fmt.Errorf("must be #rrggbb or empty (none)")
705		}
706		c.Border.Inactive = v
707	case "layout.gaps":
708		n, err := strconv.Atoi(v)
709		if err != nil || n < 0 || n > 200 {
710			return fmt.Errorf("must be between 0 and 200")
711		}
712		c.Layout.Gaps = n
713	case "layout.default-width":
714		return fmt.Errorf("replaced by layout.max-columns (columns share the width equally)")
715	case "layout.max-columns":
716		return setLayoutRule(&c.Layout.LayoutRules, "max-columns", v)
717	case "layout.overflow":
718		return setLayoutRule(&c.Layout.LayoutRules, "overflow", v)
719	case "layout.presets":
720		list := splitList(v)
721		if len(list) == 0 {
722			return fmt.Errorf("must not be empty")
723		}
724		for _, s := range list {
725			if !width(s) {
726				return fmt.Errorf("%q: must be a fraction like 1/2, a percentage like 50%%, 1, or pixels like 800px", s)
727			}
728		}
729		c.Layout.Presets = list
730	case "touchpad.tap":
731		b, err := onOff(v)
732		if err != nil {
733			return err
734		}
735		c.Touchpad.Tap = b
736	case "touchpad.scroll-factor":
737		f, err := strconv.ParseFloat(v, 64)
738		if err != nil || !(f > 0 && f <= 10) {
739			return fmt.Errorf("must be above 0 and at most 10")
740		}
741		c.Touchpad.ScrollFactor = f
742	case "cursor.hide-after":
743		if v == "off" {
744			c.Cursor.HideAfter = 0
745			return nil
746		}
747		d, err := time.ParseDuration(v)
748		if err != nil || d < 100*time.Millisecond || d > maxCursorHideAfter {
749			return fmt.Errorf("must be off or a duration between 100ms and %s, e.g. 5s", maxCursorHideAfter)
750		}
751		c.Cursor.HideAfter = d
752	case "focus.follow-move":
753		b, err := onOff(v)
754		if err != nil {
755			return err
756		}
757		c.Focus.FollowMove = b
758	case "focus.animation":
759		if v != ports.FocusAnimationPulse && v != ports.FocusAnimationOff {
760			return fmt.Errorf("must be pulse or off")
761		}
762		c.Focus.Animation = v
763	case "focus.effect":
764		if v != ports.FocusEffectScreen {
765			return fmt.Errorf("must be screen")
766		}
767		c.Focus.Effect = v
768	case "focus.strength":
769		// Capped low: the focus indicator must never flash.
770		f, err := strconv.ParseFloat(v, 64)
771		if err != nil || !(f >= 0.01 && f <= 0.2) {
772			return fmt.Errorf("must be between 0.01 and 0.2")
773		}
774		c.Focus.Strength = f
775	case "render.direct-scanout":
776		b, err := onOff(v)
777		if err != nil {
778			return err
779		}
780		c.Render.DirectScanout = b
781	case "render.tearing":
782		b, err := onOff(v)
783		if err != nil {
784			return err
785		}
786		c.Render.Tearing = b
787	case "render.vrr":
788		b, err := onOff(v)
789		if err != nil {
790			return err
791		}
792		c.Render.VRR = b
793	case "render.vrr-flip-gap":
794		d, err := time.ParseDuration(v)
795		if v == "0" {
796			d, err = 0, nil
797		}
798		if err != nil || d < 0 || d > maxVRRFlipGap {
799			return fmt.Errorf("must be a duration between 0 and %s, e.g. 1ms", maxVRRFlipGap)
800		}
801		c.Render.VRRFlipGap = d
802	case "performance.realtime":
803		b, err := onOff(v)
804		if err != nil {
805			return err
806		}
807		c.Performance.Realtime = b
808	case "log.level":
809		if v != "debug" && v != "info" && v != "warn" && v != "error" {
810			return fmt.Errorf("must be debug, info, warn or error")
811		}
812		c.Log.Level = v
813	case "log.debug":
814		list := splitList(v)
815		for _, s := range list {
816			if !components[s] && s != "all" {
817				return fmt.Errorf("unknown component %q", s)
818			}
819		}
820		c.Log.Debug = list
821	default:
822		if rest, ok := strings.CutPrefix(key, "touchpad."); ok {
823			return parsePointerKey(rest, v, &c.Touchpad.PointerConfig)
824		}
825		if rest, ok := strings.CutPrefix(key, "mouse."); ok {
826			return parsePointerKey(rest, v, &c.Mouse)
827		}
828		if rest, ok := strings.CutPrefix(key, "layout."); ok {
829			if i := strings.LastIndex(rest, "."); i > 0 {
830				return setOutputLayout(c, rest[:i], rest[i+1:], v)
831			}
832		}
833		return fmt.Errorf("unknown key")
834	}
835	return nil
836}
837
838// parsePointerKey applies one pointer key shared by touchpads and mice, with
839// the touchpad. or mouse. prefix already removed. Touchpad-only keys are
840// handled before; anything else is unknown. On an error p is left unchanged.
841func parsePointerKey(key, v string, p *ports.PointerConfig) error {
842	switch key {
843	case "natural-scroll":
844		b, err := onOff(v)
845		if err != nil {
846			return err
847		}
848		p.NaturalScroll = b
849	case "left-handed":
850		b, err := onOff(v)
851		if err != nil {
852			return err
853		}
854		p.LeftHanded = b
855	case "accel-speed":
856		s, err := strconv.ParseFloat(v, 64)
857		if err != nil || !(s >= -1 && s <= 1) {
858			return fmt.Errorf("must be between -1 and 1")
859		}
860		p.AccelSpeed = s
861	case "accel-profile":
862		if v != ports.AccelAdaptive && v != ports.AccelFlat {
863			return fmt.Errorf("must be adaptive or flat")
864		}
865		p.AccelProfile = v
866	default:
867		return fmt.Errorf("unknown key")
868	}
869	return nil
870}
871
872// setOutputLayout applies one layout.<output>.<field> key.
873func setOutputLayout(c *ports.Config, output, field, v string) error {
874	i := slices.IndexFunc(c.Layout.Outputs, func(o ports.OutputLayout) bool { return o.Output == output })
875	o := ports.OutputLayout{Output: output}
876	if i >= 0 {
877		o = c.Layout.Outputs[i]
878	}
879	if err := setLayoutRule(&o.LayoutRules, field, v); err != nil {
880		return err
881	}
882	if i < 0 {
883		c.Layout.Outputs = append(c.Layout.Outputs, o)
884	} else {
885		c.Layout.Outputs[i] = o
886	}
887	return nil
888}
889
890// setLayoutRule applies max-columns or overflow, for layout.*,
891// layout.<output>.* and workspace.<name>.*.
892func setLayoutRule(r *ports.LayoutRules, field, v string) error {
893	switch field {
894	case "max-columns":
895		return positive(&r.MaxColumns, v, 16)
896	case "overflow":
897		if v != "scroll" && v != "fixed" {
898			return fmt.Errorf("must be scroll or fixed")
899		}
900		r.Overflow = v
901		return nil
902	}
903	return fmt.Errorf("unknown key (max-columns, overflow)")
904}
905
906// checkWorkspaceBinds warns about a `workspace <name>` bind to an undeclared
907// workspace (it does nothing) and a named workspace no bind reaches.
908func checkWorkspaceBinds(c ports.Config, seen map[string]int) []Warning {
909	declared := map[string]bool{}
910	for _, w := range c.Workspaces {
911		declared[w.Name] = true
912	}
913	bound := map[string]bool{}
914	var warnings []Warning
915	for combo, a := range c.Binds {
916		name, ok := strings.CutPrefix(a, "workspace ")
917		if !ok {
918			continue
919		}
920		name = strings.TrimSpace(name)
921		bound[name] = true
922		if !declared[name] {
923			warnings = append(warnings, Warning{Line: seen["bind."+combo], Msg: fmt.Sprintf("bind.%s: no workspace.%s.* declared", combo, name)})
924		}
925	}
926	for _, w := range c.Workspaces {
927		// The config only knows the monitor as written: a connector home
928		// does not match a key rule, and the reverse.
929		rules := c.Layout.LayoutRules
930		for _, o := range c.Layout.Outputs {
931			if w.Monitor != "" && o.Output == w.Monitor {
932				rules = o.Over(rules)
933			}
934		}
935		if w.Over(rules).Overflow == "fixed" && len(w.Slots) > 0 {
936			line := seen["workspace."+w.Name+".column."+strconv.Itoa(w.Slots[0].Index)]
937			warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("workspace.%s: column widths are ignored with overflow = fixed (columns share the width)", w.Name)})
938		}
939		if !bound[w.Name] {
940			line := 0
941			for key, n := range seen {
942				if strings.HasPrefix(key, "workspace."+w.Name+".") && (line == 0 || n < line) {
943					line = n
944				}
945			}
946			warnings = append(warnings, Warning{Line: line, Msg: fmt.Sprintf("workspace.%s: no bind shows it (add bind.<keys> = workspace %s)", w.Name, w.Name)})
947		}
948	}
949	sort.Slice(warnings, func(i, j int) bool { return warnings[i].Line < warnings[j].Line })
950	return warnings
951}
952
953var workspaceName = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
954
955// setWorkspace applies one workspace.<name>.<field> key.
956func setWorkspace(w *ports.WorkspaceConfig, field, v string) error {
957	switch field {
958	case "monitor":
959		if v == "" {
960			return fmt.Errorf("needs a connector (DP-2) or a monitor key")
961		}
962		w.Monitor = v
963	case "size":
964		if v == "inherit" {
965			w.Size = [2]int{}
966			return nil
967		}
968		width, height, _, err := ParseMode(v)
969		if err != nil || width == 0 || strings.Contains(v, "@") {
970			return fmt.Errorf("must be inherit or WxH in logical pixels")
971		}
972		w.Size = [2]int{width, height}
973	case "max-columns", "overflow":
974		return setLayoutRule(&w.LayoutRules, field, v)
975	default:
976		n, ok := strings.CutPrefix(field, "column.")
977		if !ok {
978			return fmt.Errorf("unknown key (monitor, size, max-columns, overflow, column.N)")
979		}
980		index, err := strconv.Atoi(n)
981		if err != nil || index < 1 || index > 16 {
982			return fmt.Errorf("column number must be between 1 and 16")
983		}
984		size, cmd, _ := strings.Cut(v, ",")
985		size = strings.TrimSpace(size)
986		argv := strings.Fields(cmd)
987		if !width(size) || len(argv) == 0 {
988			return fmt.Errorf("must be <width>, <command> like 67%%, foot")
989		}
990		slot := ports.SlotConfig{Index: index, Width: size, Argv: argv}
991		i := sort.Search(len(w.Slots), func(i int) bool { return w.Slots[i].Index >= index })
992		if i < len(w.Slots) && w.Slots[i].Index == index {
993			w.Slots[i] = slot
994		} else {
995			w.Slots = slices.Insert(w.Slots, i, slot)
996		}
997	}
998	return nil
999}
1000
1001func positive(dst *int, v string, max int) error {
1002	n, err := strconv.Atoi(v)
1003	if err != nil || n <= 0 || n > max {
1004		return fmt.Errorf("must be between 1 and %d", max)
1005	}
1006	*dst = n
1007	return nil
1008}
1009
1010func onOff(v string) (bool, error) {
1011	switch v {
1012	case "on":
1013		return true, nil
1014	case "off":
1015		return false, nil
1016	}
1017	return false, fmt.Errorf("must be on or off")
1018}
1019
1020func splitList(v string) []string {
1021	list := []string{}
1022	for _, s := range strings.Split(v, ",") {
1023		if s = strings.TrimSpace(s); s != "" {
1024			list = append(list, s)
1025		}
1026	}
1027	return list
1028}
1029
1030// stripComment drops a trailing ` # comment` from a value. A # that starts the
1031// value is kept, so colors like #1e1e2e need no quotes.
1032func stripComment(value string) string {
1033	for i := 1; i < len(value); i++ {
1034		if value[i] == '#' && (value[i-1] == ' ' || value[i-1] == '\t') {
1035			return strings.TrimSpace(value[:i])
1036		}
1037	}
1038	return value
1039}
1040
1041func checkAction(v string) error {
1042	if rest, ok := strings.CutPrefix(v, "spawn "); ok {
1043		if len(strings.Fields(rest)) == 0 {
1044			return fmt.Errorf("spawn needs a command")
1045		}
1046		return nil
1047	}
1048	if rest, ok := strings.CutPrefix(v, "workspace "); ok {
1049		if !workspaceName.MatchString(strings.TrimSpace(rest)) {
1050			return fmt.Errorf("workspace needs a name (letters, digits, - or _)")
1051		}
1052		return nil
1053	}
1054	for _, prefix := range []string{"focus-workspace ", "move-column-to-workspace ", "move-window-to-workspace "} {
1055		if rest, ok := strings.CutPrefix(v, prefix); ok {
1056			if n, err := strconv.Atoi(strings.TrimSpace(rest)); err != nil || n < 1 || n > 99 {
1057				return fmt.Errorf("%snumber must be between 1 and 99", prefix)
1058			}
1059			return nil
1060		}
1061	}
1062	for _, prefix := range []string{"set-column-width ", "set-window-height "} {
1063		if rest, ok := strings.CutPrefix(v, prefix); ok {
1064			if !resizeStep.MatchString(strings.TrimSpace(rest)) {
1065				return fmt.Errorf("%sneeds +N%% or -N%% (1-100)", prefix)
1066			}
1067			return nil
1068		}
1069	}
1070	if !actions[v] {
1071		return fmt.Errorf(`unknown action %q (or "spawn <command>", "workspace <name>")`, v)
1072	}
1073	return nil
1074}
1075
1076// parseCombo turns `ctrl+cmd+é` into the canonical `Cmd+Ctrl+eacute`:
1077// modifiers sorted, the key as an xkb keysym name.
1078func parseCombo(s string) (string, error) {
1079	parts := strings.Split(s, "+")
1080	key := parts[len(parts)-1]
1081	if len(parts) > 1 && key == "" {
1082		// "cmd++" means the + key.
1083		if len(parts) > 2 && parts[len(parts)-2] == "" {
1084			parts, key = parts[:len(parts)-1], "+"
1085		} else {
1086			return "", fmt.Errorf("missing key")
1087		}
1088	}
1089	if key == "" {
1090		return "", fmt.Errorf("missing key")
1091	}
1092	seen := map[string]bool{}
1093	for _, m := range parts[:len(parts)-1] {
1094		var name string
1095		switch strings.ToLower(m) {
1096		case "cmd":
1097			name = "Cmd"
1098		case "shift":
1099			name = "Shift"
1100		case "ctrl":
1101			name = "Ctrl"
1102		case "alt":
1103			name = "Alt"
1104		case "super":
1105			name = "Super"
1106		default:
1107			return "", fmt.Errorf("unknown modifier %q", m)
1108		}
1109		if seen[name] {
1110			return "", fmt.Errorf("duplicate modifier %q", m)
1111		}
1112		seen[name] = true
1113	}
1114	mods := make([]string, 0, len(seen))
1115	for m := range seen {
1116		mods = append(mods, m)
1117	}
1118	sort.Strings(mods)
1119	name, err := keysym(key)
1120	if err != nil {
1121		return "", err
1122	}
1123	return strings.Join(append(mods, name), "+"), nil
1124}
1125
1126// keysym maps a written key to its xkb keysym name.
1127func keysym(k string) (string, error) {
1128	// code:N is the physical key (evdev code), the same on every layout.
1129	if rest, ok := strings.CutPrefix(strings.ToLower(k), "code:"); ok {
1130		if n, err := strconv.Atoi(rest); err == nil && n > 0 && n < 768 {
1131			return "code:" + rest, nil
1132		}
1133		return "", fmt.Errorf("code must be an evdev key code like code:2")
1134	}
1135	if r := []rune(k); len(r) == 1 {
1136		// Binds match the unshifted keysym, so É means é.
1137		if name, ok := runeKeysyms[unicode.ToLower(r[0])]; ok {
1138			return name, nil
1139		}
1140		if r[0] > unicode.MaxASCII {
1141			return "", fmt.Errorf("write %q by its xkb keysym name", k)
1142		}
1143		return strings.ToLower(k), nil
1144	}
1145	if name, ok := namedKeys[strings.ToLower(k)]; ok {
1146		return name, nil
1147	}
1148	if len(k) <= 3 && (k[0] == 'f' || k[0] == 'F') {
1149		if n, err := strconv.Atoi(k[1:]); err == nil && n >= 1 && n <= 24 {
1150			return "F" + k[1:], nil
1151		}
1152	}
1153	return k, nil
1154}
1155
1156// parseTransform accepts the wl_output.transform names.
1157func parseTransform(v string) (ports.BufferTransform, error) {
1158	switch v {
1159	case "normal":
1160		return 0, nil
1161	case "90":
1162		return 1, nil
1163	case "180":
1164		return 2, nil
1165	case "270":
1166		return 3, nil
1167	case "flipped":
1168		return 4, nil
1169	case "flipped-90":
1170		return 5, nil
1171	case "flipped-180":
1172		return 6, nil
1173	case "flipped-270":
1174		return 7, nil
1175	}
1176	return 0, fmt.Errorf("invalid transform %q (normal, 90, 180, 270, flipped, flipped-90, flipped-180, flipped-270)", v)
1177}
1178
1179// parseScale accepts a decimal (1.5) or a fraction (4/3) between 1 and 4.
1180func parseScale(v string) (float64, error) {
1181	var s float64
1182	var err error
1183	if num, den, ok := strings.Cut(v, "/"); ok {
1184		var n, d float64
1185		n, err = strconv.ParseFloat(strings.TrimSpace(num), 64)
1186		if err == nil {
1187			d, err = strconv.ParseFloat(strings.TrimSpace(den), 64)
1188		}
1189		if err == nil && d != 0 {
1190			s = n / d
1191		}
1192	} else {
1193		s, err = strconv.ParseFloat(v, 64)
1194	}
1195	if err != nil || !(s >= 1 && s <= 4) {
1196		return 0, fmt.Errorf("must be between 1 and 4, like 1.5 or 4/3")
1197	}
1198	return s, nil
1199}
1200
1201// ParseMode parses "WxH" or "WxH@Hz" ("preferred" is accepted); hz is 0 when omitted.
1202func ParseMode(s string) (w, h int, hz float64, err error) {
1203	if s == "preferred" {
1204		return 0, 0, 0, nil
1205	}
1206	size, rate, hasRate := strings.Cut(s, "@")
1207	ws, hs, ok := strings.Cut(size, "x")
1208	w, e1 := strconv.Atoi(ws)
1209	h, e2 := strconv.Atoi(hs)
1210	if !ok || e1 != nil || e2 != nil || w <= 0 || h <= 0 {
1211		return 0, 0, 0, fmt.Errorf("must be off, preferred, WxH or WxH@Hz, got %q", s)
1212	}
1213	if hasRate {
1214		if hz, err = strconv.ParseFloat(rate, 64); err != nil || hz <= 0 {
1215			return 0, 0, 0, fmt.Errorf("invalid refresh rate in %q", s)
1216		}
1217	}
1218	return w, h, hz, nil
1219}
1220
1221func width(s string) bool {
1222	if s == "1" {
1223		return true
1224	}
1225	if n, ok := strings.CutSuffix(s, "%"); ok {
1226		v, e := strconv.Atoi(n)
1227		return e == nil && v > 0 && v <= 100
1228	}
1229	if strings.HasSuffix(s, "px") {
1230		n, e := strconv.Atoi(strings.TrimSuffix(s, "px"))
1231		return e == nil && n > 0
1232	}
1233	p := strings.Split(s, "/")
1234	if len(p) != 2 {
1235		return false
1236	}
1237	a, e1 := strconv.Atoi(p[0])
1238	b, e2 := strconv.Atoi(p[1])
1239	return e1 == nil && e2 == nil && a > 0 && a <= b
1240}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 26

Tags 10

↑↓ moveenter openesc close