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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Handler for the `batch` command: atomic multi-edit with rollback.
//!
//! Accepts an array of edits (string-match or line-range), validates all against
//! the original content, then applies bottom-to-top to prevent line drift.
//! Takes a single auto-backup before applying. No file modification on failure.
use std::path::Path;
use crate::context::AppContext;
use crate::edit::{self, line_col_to_byte};
use crate::protocol::{RawRequest, Response};
/// A validated edit ready to apply, carrying byte offsets into the original content.
struct ResolvedEdit {
byte_start: usize,
byte_end: usize,
replacement: String,
}
/// Handle a `batch` request.
///
/// Params:
/// - `file` (string, required) — target file path
/// - `edits` (array, required) — each element is either:
/// - `{ "match": "...", "replacement": "..." }` — string match-replace
/// - `{ "line_start": N, "line_end": N, "content": "..." }` — line range replacement (1-based, inclusive)
///
/// Returns on success: `{ file, edits_applied, syntax_valid?, backup_id? }`.
/// `syntax_valid` is absent when syntax validation could not run.
/// Returns on failure: error with the failing edit index.
pub fn handle_batch(req: &RawRequest, ctx: &AppContext) -> Response {
let op_id = crate::backup::new_op_id();
let file = match req.params.get("file").and_then(|v| v.as_str()) {
Some(f) => f,
None => {
return Response::error(
&req.id,
"invalid_request",
"batch: missing required param 'file'",
);
}
};
let edits = match req.params.get("edits").and_then(|v| v.as_array()) {
Some(e) => e,
None => {
return Response::error(
&req.id,
"invalid_request",
"batch: missing required param 'edits' (expected array)",
);
}
};
if edits.is_empty() {
return Response::error(
&req.id,
"invalid_request",
"batch: 'edits' array must not be empty",
);
}
let path = match ctx.validate_path(&req.id, Path::new(file)) {
Ok(path) => path,
Err(resp) => return resp,
};
if !path.exists() {
return Response::error(
&req.id,
"file_not_found",
format!("file not found: {}", file),
);
}
let source = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(e) => {
return Response::error(&req.id, "file_not_found", format!("{}: {}", file, e));
}
};
// Phase 1: Validate all edits and resolve to byte offsets
let mut resolved: Vec<ResolvedEdit> = Vec::with_capacity(edits.len());
for (i, edit_val) in edits.iter().enumerate() {
match resolve_edit(&source, edit_val, i, &req.id) {
Ok(r) => resolved.push(r),
Err(resp) => return resp,
}
}
// Phase 2: Auto-backup once before applying
let backup_id = match edit::auto_backup(
ctx,
req.session(),
&path,
"batch: pre-batch backup",
Some(&op_id),
) {
Ok(id) => id,
Err(e) => {
return Response::error(&req.id, e.code(), e.to_string());
}
};
// Phase 3: Sort edits by byte_start descending (bottom-to-top) to prevent drift
resolved.sort_by(|a, b| b.byte_start.cmp(&a.byte_start));
// Phase 3.5: Detect overlapping byte ranges after sort (sorted descending by byte_start)
for i in 0..resolved.len().saturating_sub(1) {
// resolved[i] has a HIGHER byte_start than resolved[i+1]
let higher = &resolved[i];
let lower = &resolved[i + 1];
// Overlap: lower's range extends into higher's range
if lower.byte_end > higher.byte_start {
return Response::error(
&req.id,
"overlapping_edits",
format!(
"batch: edits overlap — edit at bytes [{}..{}) overlaps with edit at bytes [{}..{})",
lower.byte_start, lower.byte_end, higher.byte_start, higher.byte_end
),
);
}
}
// Phase 4: Apply all edits sequentially to the content
let mut content = source.clone();
for r in &resolved {
content = match edit::replace_byte_range(&content, r.byte_start, r.byte_end, &r.replacement)
{
Ok(updated) => updated,
Err(e) => {
return Response::error(&req.id, e.code(), e.to_string());
}
};
}
// Phase 5: Write, format, and validate via shared pipeline
let mut write_result =
match edit::write_format_validate(&path, &content, &ctx.config(), &req.params) {
Ok(r) => r,
Err(e) => {
return Response::error(&req.id, e.code(), e.to_string());
}
};
if let Ok(final_content) = std::fs::read_to_string(&path) {
write_result.lsp_outcome = ctx.lsp_post_write(&path, &final_content, &req.params);
}
log::debug!("batch: {} edits in {}", edits.len(), file);
let mut result = serde_json::json!({
"file": file,
"edits_applied": edits.len(),
"formatted": write_result.formatted,
});
if let Some(valid) = write_result.syntax_valid {
result["syntax_valid"] = serde_json::json!(valid);
}
if let Some(ref reason) = write_result.format_skipped_reason {
result["format_skipped_reason"] = serde_json::json!(reason);
}
if write_result.validate_requested {
result["validation_errors"] = serde_json::json!(write_result.validation_errors);
}
if let Some(ref reason) = write_result.validate_skipped_reason {
result["validate_skipped_reason"] = serde_json::json!(reason);
}
if let Some(ref id) = backup_id {
result["backup_id"] = serde_json::json!(id);
}
write_result.append_lsp_diagnostics_to(&mut result);
Response::success(&req.id, result)
}
/// Resolve a single edit object to byte offsets against the original source.
///
/// Returns `Ok(ResolvedEdit)` on success, `Err(Response)` on validation failure.
fn resolve_edit(
source: &str,
edit_val: &serde_json::Value,
index: usize,
req_id: &str,
) -> Result<ResolvedEdit, Response> {
// Detect edit type: match-replace or line-range
// Accept both "match"/"replacement" and "oldString"/"newString" (backward compat)
let match_str = edit_val
.get("match")
.or_else(|| edit_val.get("oldString"))
.and_then(|v| v.as_str());
if let Some(match_str) = match_str {
// String match-replace with progressive fuzzy matching (same as edit_match)
let replacement = edit_val
.get("replacement")
.or_else(|| edit_val.get("newString"))
.and_then(|v| v.as_str())
.unwrap_or("");
let fuzzy_matches = crate::fuzzy_match::find_all_fuzzy(source, match_str);
if fuzzy_matches.is_empty() {
return Err(Response::error(
req_id,
"batch_edit_failed",
format!(
"batch: edit[{}] match '{}' not found in file",
index, match_str
),
));
}
if fuzzy_matches[0].pass > 1 {
log::debug!(
"batch: edit[{}] fuzzy match (pass {}) for '{}'",
index,
fuzzy_matches[0].pass,
match_str
);
}
if fuzzy_matches.len() > 1 {
// Check if an occurrence index is specified to disambiguate
if let Some(occ) = edit_val.get("occurrence").and_then(|v| v.as_u64()) {
let occ = occ as usize;
if occ >= fuzzy_matches.len() {
return Err(Response::error(
req_id,
"batch_edit_failed",
format!(
"batch: edit[{}] occurrence {} out of range (found {} occurrences)",
index,
occ,
fuzzy_matches.len()
),
));
}
let m = &fuzzy_matches[occ];
return Ok(ResolvedEdit {
byte_start: m.byte_start,
byte_end: m.byte_start + m.byte_len,
replacement: replacement.to_string(),
});
}
return Err(Response::error(
req_id,
"batch_edit_failed",
format!(
"batch: edit[{}] match '{}' is ambiguous ({} occurrences, expected 1). Use 'occurrence' field (0-indexed) to select which one.",
index,
match_str,
fuzzy_matches.len()
),
));
}
let m = &fuzzy_matches[0];
Ok(ResolvedEdit {
byte_start: m.byte_start,
byte_end: m.byte_start + m.byte_len,
replacement: replacement.to_string(),
})
} else if edit_val.get("line_start").is_some() {
// Line-range replacement
let line_start_1based = edit_val
.get("line_start")
.and_then(|v| v.as_u64())
.map(|v| v as usize)
.ok_or_else(|| {
Response::error(
req_id,
"invalid_request",
format!(
"batch: edit[{}] 'line_start' must be a positive integer (1-based)",
index
),
)
})?;
if line_start_1based == 0 {
return Err(Response::error(
req_id,
"invalid_request",
format!("batch: edit[{}] 'line_start' must be >= 1 (1-based)", index),
));
}
let line_start = line_start_1based - 1;
let line_end_1based = edit_val
.get("line_end")
.and_then(|v| v.as_u64())
.map(|v| v as usize)
.ok_or_else(|| {
Response::error(
req_id,
"invalid_request",
format!(
"batch: edit[{}] 'line_end' must be a positive integer (1-based)",
index
),
)
})?;
if line_end_1based == 0 {
return Err(Response::error(
req_id,
"invalid_request",
format!("batch: edit[{}] 'line_end' must be >= 1 (1-based)", index),
));
}
let line_end = line_end_1based - 1;
let content = edit_val
.get("content")
.and_then(|v| v.as_str())
.unwrap_or("");
let lines: Vec<&str> = source.lines().collect();
let total_lines = lines.len();
// Allow line_start == total_lines for appending at end of file
if line_start > total_lines {
return Err(Response::error(
req_id,
"batch_edit_failed",
format!(
"batch: edit[{}] line_start {} out of range (file has {} lines)",
index, line_start_1based, total_lines
),
));
}
// Append at EOF: line_start == total_lines means insert after last line
if line_start == total_lines {
let byte_pos = source.len();
let mut replacement_str = content.to_string();
if !source.ends_with('\n') && !replacement_str.starts_with('\n') {
replacement_str.insert(0, '\n');
}
if !replacement_str.ends_with('\n') {
replacement_str.push('\n');
}
return Ok(ResolvedEdit {
byte_start: byte_pos,
byte_end: byte_pos,
replacement: replacement_str,
});
}
// Allow pure insert: line_start == line_end + 1 means insert before line_start
if line_start > line_end + 1 {
return Err(Response::error(
req_id,
"invalid_request",
format!(
"batch: edit[{}] line_start {} > line_end {}",
index, line_start_1based, line_end_1based
),
));
}
// Pure insert mode: line_start == line_end + 1 (zero-length range)
if line_start == line_end + 1
|| (line_end == 0
&& line_start == 0
&& edit_val
.get("line_end")
.and_then(|v| v.as_u64())
.map(|v| v as usize)
== Some(0)
&& line_start > line_end)
{
let byte_pos = line_col_to_byte(source, line_start as u32, 0);
let mut replacement_str = content.to_string();
if !replacement_str.ends_with('\n') {
replacement_str.push('\n');
}
return Ok(ResolvedEdit {
byte_start: byte_pos,
byte_end: byte_pos,
replacement: replacement_str,
});
}
// Clamp line_end to last valid line instead of hard error
let line_end = if line_end >= total_lines {
total_lines - 1
} else {
line_end
};
// Convert line range to byte offsets
let byte_start = line_col_to_byte(source, line_start as u32, 0);
// line_end is inclusive: end byte is at the end of line_end (including its newline if present)
let byte_end = line_col_to_byte(source, line_end.saturating_add(1) as u32, 0);
// Empty content = delete lines entirely (no trailing newline added)
// Non-empty content = if the replaced range had a trailing newline, auto-append
// one to prevent the next line from merging.
let mut replacement_str = content.to_string();
if !replacement_str.is_empty() {
let range_has_trailing_nl = byte_end > 0
&& byte_end <= source.len()
&& source.as_bytes()[byte_end - 1] == b'\n';
if range_has_trailing_nl && !replacement_str.ends_with('\n') {
replacement_str.push('\n');
}
}
Ok(ResolvedEdit {
byte_start,
byte_end,
replacement: replacement_str,
})
} else {
Err(Response::error(
req_id,
"invalid_request",
format!(
"batch: edit[{}] must have either 'match' or 'line_start'/'line_end'",
index
),
))
}
}