1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
//! Targeted in-place HJSON edits used by the live-toggle
//! chords (`Ctrl+B L` switches LLM provider, `Ctrl+B E`
//! toggles sound). The strategy is a surgical text edit (no
//! full re-serialisation) so the carefully-annotated default
//! HJSON template — comments, key ordering, indentation,
//! trailing per-line comments — survives a toggle.
//!
//! Extracted from `tui::app` in the 1.2.7 refactor.
/// Rewrite `<block>.<key> = <value_lit>` in an existing HJSON
/// config file in place, preserving every other byte.
///
/// `value_lit` is the literal text to write (already quoted /
/// formatted by the caller — e.g. `"ollama"` for a string,
/// `true` for a bool). When the key isn't present we insert
/// it right after the opening `{` of the block.
///
/// Returns Err with a human-readable reason when the file
/// shape doesn't match our expectations (no block of that
/// name, unterminated braces). The brace counter doesn't
/// understand HJSON strings — it would miscount a `{` / `}`
/// inside a quoted string. Fine for our shipped template,
/// which uses braces only for nested objects.
pub(super) fn set_key_in_hjson_block(
raw: &str,
block: &str,
key: &str,
value_lit: &str,
) -> Result<String, String> {
let lines: Vec<&str> = raw.split_inclusive('\n').collect();
if lines.is_empty() {
return Err("config file is empty".into());
}
let block_prefix = format!("{block}:");
let block_open_idx = lines.iter().position(|l| {
let trimmed = l.trim_start();
!trimmed.starts_with("//") && trimmed.starts_with(&block_prefix)
});
let block_open_idx = block_open_idx
.ok_or_else(|| format!("no `{block}:` block found in HJSON"))?;
// Walk forward tracking brace depth (ignoring `//` line
// comments) so we know where the block ends.
let mut depth: i32 = 0;
let mut block_started = false;
let mut block_end: Option<usize> = None;
for (i, line) in lines.iter().enumerate().skip(block_open_idx) {
let code = line.split("//").next().unwrap_or("");
for c in code.chars() {
match c {
'{' => {
depth += 1;
block_started = true;
}
'}' => depth -= 1,
_ => {}
}
}
if block_started && depth == 0 {
block_end = Some(i);
break;
}
}
let block_end = block_end
.ok_or_else(|| format!("unterminated `{block}: {{` block — check brace balance"))?;
// Scan for the target key as a *direct* child of the
// block (depth == 1 at the time the line starts being
// read).
let key_unquoted = format!("{key}:");
let key_quoted = format!("\"{key}\":");
let mut depth: i32 = 0;
let mut target_idx: Option<usize> = None;
for (i, line) in lines.iter().enumerate().take(block_end + 1).skip(block_open_idx) {
let depth_before = depth;
let code = line.split("//").next().unwrap_or("");
for c in code.chars() {
match c {
'{' => depth += 1,
'}' => depth -= 1,
_ => {}
}
}
if i == block_open_idx {
continue;
}
if depth_before == 1 {
let trimmed = line.trim_start();
if trimmed.starts_with("//") {
continue;
}
if trimmed.starts_with(&key_unquoted) || trimmed.starts_with(&key_quoted) {
target_idx = Some(i);
break;
}
}
}
let mut out = String::with_capacity(raw.len() + value_lit.len());
match target_idx {
Some(idx) => {
let mut rewrote = false;
for (i, line) in lines.iter().enumerate() {
if i == idx {
rewrote = true;
let (eol, core): (&str, &str) =
if let Some(stripped) = line.strip_suffix("\r\n") {
("\r\n", stripped)
} else if let Some(stripped) = line.strip_suffix('\n') {
("\n", stripped)
} else {
("", *line)
};
let colon_pos = core.find(':').ok_or_else(|| {
format!("`{key}` line missing `:` separator — unexpected HJSON")
})?;
let head = &core[..=colon_pos]; // includes ":"
let tail = &core[colon_pos + 1..];
let comment_pos = tail.find("//");
let (_old_value, comment_suffix) = match comment_pos {
Some(p) => (&tail[..p], &tail[p..]),
None => (tail, ""),
};
if comment_suffix.is_empty() {
out.push_str(&format!("{head} {value_lit}{eol}"));
} else {
// Keep one space between the new value
// and the trailing comment so it doesn't
// slide left.
out.push_str(&format!("{head} {value_lit} {comment_suffix}{eol}"));
}
} else {
out.push_str(line);
}
}
if !rewrote {
return Err("internal error: target line not rewritten".into());
}
Ok(out)
}
None => {
// Insert the missing key right after the block-
// opening line, using two extra spaces of
// indentation relative to it.
let block_indent: String = lines[block_open_idx]
.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect();
let child_indent = format!("{block_indent} ");
for (i, line) in lines.iter().enumerate() {
out.push_str(line);
if i == block_open_idx {
let eol = if line.ends_with("\r\n") {
"\r\n"
} else if line.ends_with('\n') {
"\n"
} else {
"\n"
};
out.push_str(&format!("{child_indent}{key}: {value_lit}{eol}"));
}
}
Ok(out)
}
}
}
/// Wrapper that quotes `new_default` if needed and delegates
/// to `set_key_in_hjson_block` for the `llm.default` slot.
pub(super) fn set_llm_default_in_hjson(
raw: &str,
new_default: &str,
) -> Result<String, String> {
let quote_needed = new_default.is_empty()
|| !new_default
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
let value_lit = if quote_needed {
format!(
"\"{}\"",
new_default.replace('\\', "\\\\").replace('"', "\\\"")
)
} else {
new_default.to_string()
};
set_key_in_hjson_block(raw, "llm", "default", &value_lit)
}
/// Set `sound.enabled = true|false` in inkhaven.hjson.
/// Inserts the key (and synthesises the block when missing)
/// when the user has stripped them from an older config.
pub(super) fn set_sound_enabled_in_hjson(
raw: &str,
enabled: bool,
) -> Result<String, String> {
let value_lit = if enabled { "true" } else { "false" };
match set_key_in_hjson_block(raw, "sound", "enabled", value_lit) {
Ok(s) => Ok(s),
Err(reason) if reason.contains("no `sound:` block") => {
insert_sound_block_before_root_close(raw, value_lit)
}
Err(other) => Err(other),
}
}
/// Append a fresh `sound: { ... }` block just *inside* the
/// root object's closing `}`. Older configs predating the
/// sound feature don't have the block at all — the toggle
/// synthesises one. The previous version of this helper
/// appended after the file end, which landed the block
/// *outside* the root and broke parsing on next launch.
pub(super) fn insert_sound_block_before_root_close(
raw: &str,
value_lit: &str,
) -> Result<String, String> {
let lines: Vec<&str> = raw.split_inclusive('\n').collect();
// Scan backward for the root object's closing brace —
// the last line whose first non-whitespace character is
// `}` and whose code (stripped of `//` comments)
// contains *only* whitespace + `}`.
let root_close_idx = lines.iter().enumerate().rev().find_map(|(i, l)| {
let code = l.split("//").next().unwrap_or("");
let trimmed = code.trim();
if trimmed == "}" {
Some(i)
} else {
None
}
});
let root_close_idx = root_close_idx.ok_or_else(|| {
"no root closing `}` found — file shape unrecognised".to_string()
})?;
let block = format!(
"\n // Typewriter SFX (Ctrl+B E to toggle).\n sound: {{\n enabled: {value_lit}\n volume: 0.6\n }}\n"
);
let mut out = String::with_capacity(raw.len() + block.len());
for (i, line) in lines.iter().enumerate() {
if i == root_close_idx {
out.push_str(&block);
}
out.push_str(line);
}
Ok(out)
}