// 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 } // Rename gives every entry of key old the key new, in place. Only the key // is replaced, so indentation and the formatting of the value stay as they // were. func (f *File) Rename(old, new string) { for i, l := range f.Lines { if l.Key != old { continue } at := strings.Index(l.Raw, old) // the key is the first word of the line f.Lines[i].Raw = l.Raw[:at] + new + l.Raw[at+len(old):] f.Lines[i].Key = new } } // 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 .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 }