Skip to main content

hjkl_engine/
substitute.rs

1//! Public substitute command parser and applicator.
2//!
3//! Exposes [`parse_substitute`] and [`apply_substitute`] for the
4//! `:[range]s/pattern/replacement/[flags]` ex command.
5//!
6//! ## Vim compatibility notes (v1 limitations)
7//!
8//! - Delimiter is **always `/`**. Alternate delimiters (`s|x|y|`,
9//!   `s#x#y#`) are not supported. The parser returns an error when the
10//!   first character after the keyword is not `/`.
11//! - The `c` (confirm) flag triggers interactive replacement. Each match
12//!   is presented one-by-one; the user chooses y/n/a/q/l. See
13//!   [`collect_substitute_matches`] and [`apply_collected_matches`].
14//! - Patterns are translated from vim's default-magic syntax (and the
15//!   `\v` / `\V` / `\m` / `\M` mode switches) into rust-`regex` syntax by
16//!   [`crate::search::resolve_case_mode`] before compiling — see that
17//!   module for the full transform table. `\1`-`\9` **backreferences in the
18//!   pattern** (as opposed to the replacement, which supports them) are not
19//!   supported by the rust `regex` crate (no backtracking engine).
20//! - The replacement is kept in raw vim notation and expanded per match by
21//!   [`expand_replacement`]: capture refs (`&`, `\0`…`\9`), case escapes
22//!   (`\u`/`\l`/`\U`/`\L`/`\E`), control chars (`\r`/`\t`/`\n`), and `~` (the
23//!   previous replacement). A plain `$` is literal.
24//! - Flags: `g` (all), `i`/`I` (case), `c` (confirm), `n` (report count only,
25//!   no change), `e` (accepted — hjkl already succeeds on no match),
26//!   `p`/`#`/`l` (print the last changed line, optionally with number /
27//!   `:list`-style — surfaced by the ex layer), and `&` (reuse the previous
28//!   substitute's flags — resolved by the ex layer). A trailing `[count]`
29//!   operates on `count` lines from the range's last line.
30//!
31//! See vim's `:help :substitute` for the full spec.
32
33use regex::Regex;
34
35use crate::Editor;
36
37/// Error type returned by [`parse_substitute`] and [`apply_substitute`].
38pub type SubstError = String;
39
40/// Parsed `:s/pattern/replacement/flags` command.
41///
42/// Produced by [`parse_substitute`]. Pass to [`apply_substitute`].
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct SubstituteCmd {
45    /// The literal pattern string. `None` means "reuse `last_search`
46    /// from the editor" (the user typed `:s//replacement/`).
47    pub pattern: Option<String>,
48    /// The replacement string in **raw vim notation** (`&`, `~`, `\0`…`\9`,
49    /// `\u`/`\U`/`\l`/`\L`/`\E`, `\r`/`\t`/`\n`). Expanded per match by
50    /// [`expand_replacement`]. Empty string deletes the match.
51    pub replacement: String,
52    /// Parsed flags.
53    pub flags: SubstFlags,
54    /// Optional trailing `[count]` (`:s/a/b/g 3`): operate on `count` lines
55    /// starting at the range's last line (vim semantics). `None` = no count.
56    pub count: Option<usize>,
57}
58
59/// Flags for the substitute command.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61pub struct SubstFlags {
62    /// `g` — replace all occurrences on each line (default: first only).
63    pub all: bool,
64    /// `i` — case-insensitive (overrides editor `ignorecase`).
65    pub ignore_case: bool,
66    /// `I` — case-sensitive (overrides editor `ignorecase`).
67    pub case_sensitive: bool,
68    /// `c` — confirm mode. When set, [`apply_substitute`] skips all matches
69    /// and the caller must use [`collect_substitute_matches`] +
70    /// [`apply_collected_matches`] for interactive replacement.
71    pub confirm: bool,
72    /// `n` — report the match count only; do not modify the buffer or move
73    /// the cursor. [`apply_substitute`] counts matches and returns without
74    /// mutating.
75    pub report_only: bool,
76    /// `e` — do not treat "pattern not found" as an error. hjkl already
77    /// returns success on no match, so this is accepted for compatibility.
78    pub no_error: bool,
79    /// `p` / `#` / `l` — print the last changed line (optionally with line
80    /// number `#` or `:list`-style `l`). Parsed and accepted; the print
81    /// itself is surfaced by the ex/host layer.
82    pub print: bool,
83    /// `#` — print with line number (implies `print`).
84    pub print_num: bool,
85    /// `l` — print `:list`-style (implies `print`).
86    pub print_list: bool,
87    /// `&` — reuse the flags from the previous substitute (`:h :s_flags`).
88    /// Resolved by the ex handler, which merges the stored `last_substitute`
89    /// flags into this command's before applying.
90    pub reuse_previous: bool,
91}
92
93/// Result of [`apply_substitute`].
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
95pub struct SubstituteOutcome {
96    /// Total number of individual replacements made across all lines.
97    pub replacements: usize,
98    /// Number of lines that had at least one replacement.
99    pub lines_changed: usize,
100    /// 0-based row of the last changed line (where the cursor lands). `None`
101    /// when nothing changed. Used by the ex layer to print the line for the
102    /// `p` / `#` / `l` flags.
103    pub last_row: Option<usize>,
104}
105
106/// Parse the tail of a substitute command (everything after the leading
107/// `s` / `substitute` keyword).
108///
109/// # Examples
110///
111/// ```
112/// use hjkl_engine::substitute::parse_substitute;
113///
114/// let cmd = parse_substitute("/foo/bar/gi").unwrap();
115/// assert_eq!(cmd.pattern.as_deref(), Some("foo"));
116/// assert_eq!(cmd.replacement, "bar");
117/// assert!(cmd.flags.all);
118/// assert!(cmd.flags.ignore_case);
119///
120/// // Empty pattern — reuse last_search.
121/// let cmd = parse_substitute("//bar/").unwrap();
122/// assert!(cmd.pattern.is_none());
123/// assert_eq!(cmd.replacement, "bar");
124/// ```
125///
126/// # Errors
127///
128/// Returns an error when:
129/// - `s` is not followed by `/` (no delimiter or alternate delimiter).
130/// - The flag string contains an unknown character.
131/// - The separator `/` is absent (less than two fields).
132pub fn parse_substitute(s: &str) -> Result<SubstituteCmd, SubstError> {
133    // Require leading `/`. Alternate delimiters are out of scope for v1.
134    let rest = s
135        .strip_prefix('/')
136        .ok_or_else(|| format!("substitute: expected '/' delimiter, got {s:?}"))?;
137
138    // Split on unescaped `/`, collecting at most 3 segments:
139    // [pattern, replacement, flags?]
140    let parts = split_on_slash(rest);
141
142    if parts.len() < 2 {
143        return Err("substitute needs /pattern/replacement/".into());
144    }
145
146    let raw_pattern = &parts[0];
147    let raw_replacement = &parts[1];
148    let raw_flags = parts.get(2).map_or("", String::as_str);
149
150    // Empty pattern → reuse last_search.
151    let pattern = if raw_pattern.is_empty() {
152        None
153    } else {
154        Some(raw_pattern.clone())
155    };
156
157    // Keep the replacement in raw vim notation; `expand_replacement` resolves
158    // capture refs, case escapes, and `~` per match.
159    let replacement = raw_replacement.clone();
160
161    let (flags, count) = parse_flags(raw_flags)?;
162
163    Ok(SubstituteCmd {
164        pattern,
165        replacement,
166        flags,
167        count,
168    })
169}
170
171/// Parse a substitute flags+count tail: `[flag-chars][ optional trailing
172/// count]`, e.g. `"g"`, `"gi 3"`, `""`. This is the segment after the
173/// closing `/` delimiter in `:s/pat/rep/flags`, and — for [B17] bare
174/// `:s [flags] [count]` (repeat-last-substitute) — the ENTIRE argument
175/// string, since there's no delimiter at all in that form.
176///
177/// # Errors
178///
179/// Returns an error on an unrecognized flag character or non-numeric
180/// trailing text.
181pub fn parse_flags(raw_flags: &str) -> Result<(SubstFlags, Option<usize>), SubstError> {
182    let mut flags = SubstFlags::default();
183    let mut count: Option<usize> = None;
184    let mut chars = raw_flags.chars().peekable();
185    while let Some(&ch) = chars.peek() {
186        match ch {
187            'g' => flags.all = true,
188            'i' => flags.ignore_case = true,
189            'I' => flags.case_sensitive = true,
190            'c' => flags.confirm = true,
191            'n' => flags.report_only = true,
192            'e' => flags.no_error = true,
193            'p' => flags.print = true,
194            '#' => {
195                flags.print = true;
196                flags.print_num = true;
197            }
198            'l' => {
199                flags.print = true;
200                flags.print_list = true;
201            }
202            // `&` — reuse the previous substitute's flags. Resolved by the ex
203            // handler (which holds `last_substitute`).
204            '&' => flags.reuse_previous = true,
205            ' ' | '\t' => {}
206            c if c.is_ascii_digit() => break, // trailing count begins
207            other => return Err(format!("unknown flag '{other}' in substitute")),
208        }
209        chars.next();
210    }
211    // Trailing count: the remainder (after any whitespace) must be a number.
212    let rest: String = chars.collect();
213    let rest = rest.trim();
214    if !rest.is_empty() {
215        match rest.parse::<usize>() {
216            Ok(n) if n > 0 => count = Some(n),
217            _ => return Err(format!("trailing characters in substitute: {rest:?}")),
218        }
219    }
220    Ok((flags, count))
221}
222
223/// Apply a parsed substitute command to `line_range` (0-based inclusive)
224/// in the editor's buffer.
225///
226/// # Pattern resolution
227///
228/// If `cmd.pattern` is `None` (user typed `:s//rep/`), the editor's
229/// `last_search()` is used. Returns an error with `"no previous regular
230/// expression"` when both are empty.
231///
232/// # Case-sensitivity precedence
233///
234/// `flags.case_sensitive` wins over `flags.ignore_case`, which wins over
235/// the editor's `settings().ignore_case`.
236///
237/// # Cursor
238///
239/// After a successful substitution the cursor is placed on the first
240/// non-blank of the **last line that changed**, matching vim semantics. When
241/// no replacements are made the cursor is left unchanged.
242///
243/// # Undo
244///
245/// One undo snapshot is pushed before the first edit. If no replacements
246/// occur the snapshot is popped so the undo stack stays clean.
247///
248/// # Errors
249///
250/// Returns an error when pattern resolution fails or the regex is invalid.
251pub fn apply_substitute<H: crate::types::Host>(
252    ed: &mut Editor<hjkl_buffer::View, H>,
253    cmd: &SubstituteCmd,
254    line_range: std::ops::RangeInclusive<u32>,
255) -> Result<SubstituteOutcome, SubstError> {
256    // Resolve pattern.
257    let pattern_str: String = match &cmd.pattern {
258        Some(p) => p.clone(),
259        None => ed
260            .last_search()
261            .ok_or_else(|| "no previous regular expression".to_string())?,
262    };
263
264    // Previous `:s` replacement text (this command is stored only after it
265    // succeeds, so this is the *prior* one). Serves double duty: pattern-side
266    // magic `~` expands to it, and replacement-side `~` re-expands it per match.
267    let prev_replacement = ed.last_substitute_replacement();
268
269    // Case-sensitivity. Inline `\c` / `\C` overrides `/i` and `/I`.
270    let effective_pattern = {
271        use crate::search::{CaseMode, resolve_case_mode};
272        let base = if cmd.flags.case_sensitive {
273            CaseMode::Sensitive
274        } else if cmd.flags.ignore_case {
275            CaseMode::Insensitive
276        } else {
277            CaseMode::from_options(ed.settings().ignore_case, ed.settings().smartcase)
278        };
279        let (stripped, mode) = resolve_case_mode(&pattern_str, base, &prev_replacement);
280        if mode == CaseMode::Insensitive {
281            format!("(?i){stripped}")
282        } else {
283            stripped
284        }
285    };
286
287    let regex = Regex::new(&effective_pattern).map_err(|e| format!("bad pattern: {e}"))?;
288
289    ed.push_undo();
290
291    let start = *line_range.start() as usize;
292    let end = *line_range.end() as usize;
293    let rope = crate::types::Query::rope(ed.buffer());
294    let total = rope.len_lines();
295
296    let clamp_end = end.min(total.saturating_sub(1));
297    let mut new_lines: Vec<String> = crate::rope_util::rope_to_lines_vec(&rope);
298    let mut replacements = 0usize;
299    let mut lines_changed = 0usize;
300    let mut last_changed_row = 0usize;
301
302    if start <= clamp_end {
303        for (row, line) in new_lines[start..=clamp_end].iter_mut().enumerate() {
304            let (replaced, n) = do_replace(
305                &regex,
306                line,
307                &cmd.replacement,
308                &prev_replacement,
309                cmd.flags.all,
310            );
311            if n > 0 {
312                *line = replaced;
313                replacements += n;
314                lines_changed += 1;
315                last_changed_row = start + row;
316            }
317        }
318    }
319
320    if replacements == 0 {
321        ed.pop_last_undo();
322        return Ok(SubstituteOutcome {
323            replacements: 0,
324            lines_changed: 0,
325            last_row: None,
326        });
327    }
328
329    // `n` flag: report the match count without touching the buffer or cursor.
330    // Still refresh `last_search` so `n`/`N` can repeat the pattern.
331    if cmd.flags.report_only {
332        ed.pop_last_undo();
333        ed.set_last_search(Some(pattern_str), true);
334        return Ok(SubstituteOutcome {
335            replacements,
336            lines_changed,
337            last_row: None,
338        });
339    }
340
341    // `last_changed_row` above is a PRE-split row index into `new_lines`: it
342    // counts one entry per original row, even though a `\r`/newline in the
343    // replacement can turn one entry into several physical rows once joined
344    // and re-split by the buffer. Map it into POST-split row space before
345    // placing the cursor: earlier rows may have grown (shifting this row's
346    // start down), and this row's own replacement may itself have split into
347    // multiple physical lines — vim lands on the LAST of those.
348    let newlines_before: usize = new_lines[..last_changed_row]
349        .iter()
350        .map(|l| l.matches('\n').count())
351        .sum();
352    let newlines_within = new_lines[last_changed_row].matches('\n').count();
353    let last_changed_row = last_changed_row + newlines_before + newlines_within;
354
355    // Apply the new content in one shot.
356    ed.buffer_mut().replace_all(&new_lines.join("\n"));
357
358    // Cursor lands on the first non-blank of the last changed line (vim). Clamp
359    // the row defensively in case of any off-by-one at buffer edges.
360    let final_total = crate::types::Query::rope(ed.buffer()).len_lines();
361    let cursor_row = last_changed_row.min(final_total.saturating_sub(1));
362    let first_non_blank = crate::buf_helpers::buf_line(ed.buffer(), cursor_row)
363        .unwrap_or_default()
364        .chars()
365        .take_while(|c| *c == ' ' || *c == '\t')
366        .count();
367    let line_len = crate::buf_helpers::buf_line(ed.buffer(), cursor_row)
368        .unwrap_or_default()
369        .chars()
370        .count();
371    let cursor_col = first_non_blank.min(line_len.saturating_sub(1));
372    ed.buffer_mut()
373        .set_cursor(hjkl_buffer::Position::new(cursor_row, cursor_col));
374
375    ed.mark_content_dirty();
376
377    // Update last_search so n/N can repeat the same pattern.
378    ed.set_last_search(Some(pattern_str), true);
379
380    Ok(SubstituteOutcome {
381        replacements,
382        lines_changed,
383        last_row: Some(cursor_row),
384    })
385}
386
387/// A single candidate match discovered by [`collect_substitute_matches`].
388///
389/// Positions are 0-based byte offsets within their line. The `replacement`
390/// field already has all capture-group references expanded (e.g. `$1`) to
391/// their literal values so the caller can display it and apply without
392/// running the regex again.
393#[derive(Debug, Clone, PartialEq, Eq)]
394pub struct SubstituteMatch {
395    /// 0-based row index in the buffer.
396    pub row: u32,
397    /// Byte offset of the first byte of the match within that row's text.
398    pub byte_start: u32,
399    /// Byte offset one past the last byte of the match (exclusive).
400    pub byte_end: u32,
401    /// The literal replacement string (captures expanded).
402    pub replacement: String,
403}
404
405/// Collect all candidate matches for a `:s/pat/rep/[gc]` command without
406/// mutating the buffer.
407///
408/// Uses the same pattern-resolution and case-sensitivity logic as
409/// [`apply_substitute`]. The returned vec is in document order (low row +
410/// low byte first). Each entry's `replacement` has capture groups already
411/// expanded so the caller can display it without re-running the regex.
412///
413/// # Errors
414///
415/// Returns an error when pattern resolution fails or the regex is invalid.
416pub fn collect_substitute_matches<H: crate::types::Host>(
417    ed: &crate::Editor<hjkl_buffer::View, H>,
418    cmd: &SubstituteCmd,
419    line_range: std::ops::RangeInclusive<u32>,
420) -> Result<Vec<SubstituteMatch>, SubstError> {
421    // Resolve pattern — same logic as apply_substitute.
422    let pattern_str: String = match &cmd.pattern {
423        Some(p) => p.clone(),
424        None => ed
425            .last_search()
426            .ok_or_else(|| "no previous regular expression".to_string())?,
427    };
428
429    // Previous `:s` replacement — pattern-side magic `~` expands to it, and
430    // replacement-side `~` re-expands it per match (same as apply_substitute).
431    let prev_replacement = ed.last_substitute_replacement();
432
433    let effective_pattern = {
434        use crate::search::{CaseMode, resolve_case_mode};
435        let base = if cmd.flags.case_sensitive {
436            CaseMode::Sensitive
437        } else if cmd.flags.ignore_case {
438            CaseMode::Insensitive
439        } else {
440            CaseMode::from_options(ed.settings().ignore_case, ed.settings().smartcase)
441        };
442        let (stripped, mode) = resolve_case_mode(&pattern_str, base, &prev_replacement);
443        if mode == CaseMode::Insensitive {
444            format!("(?i){stripped}")
445        } else {
446            stripped
447        }
448    };
449
450    let regex = Regex::new(&effective_pattern).map_err(|e| format!("bad pattern: {e}"))?;
451
452    let start = *line_range.start() as usize;
453    let end = *line_range.end() as usize;
454    let rope = crate::types::Query::rope(ed.buffer());
455    let total = rope.len_lines();
456    let clamp_end = end.min(total.saturating_sub(1));
457
458    let mut matches: Vec<SubstituteMatch> = Vec::new();
459
460    // Expand the raw vim replacement against the match at `m.start()`. Capture
461    // against the whole line (not the isolated substring) so anchors /
462    // lookaround keep their context and group expansion matches what was found.
463    let expand = |line: &str, start: usize| {
464        regex
465            .captures_at(line, start)
466            .map(|caps| expand_replacement(&cmd.replacement, &caps, &prev_replacement))
467            .unwrap_or_default()
468    };
469
470    if start <= clamp_end {
471        for row in start..=clamp_end {
472            let line = hjkl_buffer::rope_line_str(&rope, row);
473            // Strip trailing newline so byte offsets refer to printable content.
474            let line = line.trim_end_matches('\n');
475
476            if cmd.flags.all {
477                for m in regex.find_iter(line) {
478                    matches.push(SubstituteMatch {
479                        row: row as u32,
480                        byte_start: m.start() as u32,
481                        byte_end: m.end() as u32,
482                        replacement: expand(line, m.start()),
483                    });
484                }
485            } else if let Some(m) = regex.find(line) {
486                // First match per line only.
487                matches.push(SubstituteMatch {
488                    row: row as u32,
489                    byte_start: m.start() as u32,
490                    byte_end: m.end() as u32,
491                    replacement: expand(line, m.start()),
492                });
493            }
494        }
495    }
496
497    Ok(matches)
498}
499
500/// Apply a subset of matches collected by [`collect_substitute_matches`].
501///
502/// Applies the matches in REVERSE document order (high row → low row, and
503/// within a row high byte → low byte) so earlier byte offsets remain valid
504/// after each replacement. Only matches for which the corresponding
505/// `accepted` entry is `true` are written; all others are skipped.
506///
507/// Returns the number of replacements actually applied.
508///
509/// # Panics
510///
511/// Panics when `accepted.len() != matches.len()`.
512pub fn apply_collected_matches<H: crate::types::Host>(
513    ed: &mut crate::Editor<hjkl_buffer::View, H>,
514    matches: &[SubstituteMatch],
515    accepted: &[bool],
516) -> usize {
517    assert_eq!(
518        matches.len(),
519        accepted.len(),
520        "apply_collected_matches: accepted.len() must equal matches.len()"
521    );
522
523    // Collect accepted matches and sort reverse — high row first, high
524    // byte_start first within the same row.
525    let mut to_apply: Vec<&SubstituteMatch> = matches
526        .iter()
527        .zip(accepted.iter())
528        .filter_map(|(m, &ok)| if ok { Some(m) } else { None })
529        .collect();
530
531    if to_apply.is_empty() {
532        return 0;
533    }
534
535    to_apply.sort_unstable_by(|a, b| b.row.cmp(&a.row).then(b.byte_start.cmp(&a.byte_start)));
536
537    let rope = crate::types::Query::rope(ed.buffer());
538    let mut lines_vec: Vec<String> = crate::rope_util::rope_to_lines_vec(&rope);
539    let mut applied = 0usize;
540    let mut last_changed_row: Option<usize> = None;
541
542    for sm in &to_apply {
543        let row = sm.row as usize;
544        if row >= lines_vec.len() {
545            continue;
546        }
547        let line = &lines_vec[row];
548        let bs = sm.byte_start as usize;
549        let be = sm.byte_end as usize;
550        if be > line.len() || bs > be {
551            continue;
552        }
553        // Stale matches (buffer changed between collect and apply) can land
554        // mid-char on multibyte text; skip instead of panicking on the slice.
555        if !line.is_char_boundary(bs) || !line.is_char_boundary(be) {
556            continue;
557        }
558        // Splice the replacement in.
559        let mut new_line = String::with_capacity(line.len() + sm.replacement.len());
560        new_line.push_str(&line[..bs]);
561        new_line.push_str(&sm.replacement);
562        new_line.push_str(&line[be..]);
563        lines_vec[row] = new_line;
564        applied += 1;
565        // Matches are applied high-row-first (reverse document order) so
566        // earlier byte offsets stay valid; track the HIGHEST row touched so
567        // the cursor lands on the last-in-document-order changed line (vim),
568        // not merely the last one processed by this loop.
569        last_changed_row = Some(last_changed_row.map_or(row, |lr: usize| lr.max(row)));
570    }
571
572    if applied > 0 {
573        ed.buffer_mut().replace_all(&lines_vec.join("\n"));
574        if let Some(row) = last_changed_row {
575            // `row` is a PRE-split index into `lines_vec`: a `\r`/newline in
576            // an accepted replacement can turn one entry into several
577            // physical rows once joined and re-split by the buffer. Map into
578            // POST-split row space the same way `apply_substitute` does.
579            let newlines_before: usize = lines_vec[..row]
580                .iter()
581                .map(|l| l.matches('\n').count())
582                .sum();
583            let newlines_within = lines_vec[row].matches('\n').count();
584            let row = row + newlines_before + newlines_within;
585            ed.buffer_mut()
586                .set_cursor(hjkl_buffer::Position::new(row, 0));
587        }
588        ed.mark_content_dirty();
589    }
590
591    applied
592}
593
594/// Split `s` on unescaped `/`. Each `\/` in `s` becomes a literal `/`
595/// in the output segment. Other `\x` sequences pass through unchanged
596/// (so regex escape syntax survives).
597///
598/// Returns at most 3 segments: `[pattern, replacement, flags]`. Anything
599/// after the third `/` is absorbed into the flags segment.
600fn split_on_slash(s: &str) -> Vec<String> {
601    let mut out: Vec<String> = Vec::new();
602    let mut cur = String::new();
603    let mut chars = s.chars().peekable();
604    while let Some(c) = chars.next() {
605        if c == '\\' {
606            match chars.peek() {
607                Some(&'/') => {
608                    // Escaped delimiter → literal slash in this segment.
609                    cur.push('/');
610                    chars.next();
611                }
612                Some(_) => {
613                    // Any other escape: preserve both chars so regex
614                    // syntax (\d, \s, \1, \n …) survives.
615                    let next = chars.next().unwrap();
616                    cur.push('\\');
617                    cur.push(next);
618                }
619                None => cur.push('\\'),
620            }
621        } else if c == '/' {
622            if out.len() < 2 {
623                out.push(std::mem::take(&mut cur));
624            } else {
625                // Third delimiter found: treat rest as flags.
626                // Everything up to this point was the replacement;
627                // collect the flags into `cur` and break.
628                cur.push(c);
629                // Keep going to collect remaining chars as flags.
630                // (Actually we already consumed the `/`, so just let
631                // the outer loop continue accumulating into cur.)
632            }
633        } else {
634            cur.push(c);
635        }
636    }
637    out.push(cur);
638    out
639}
640
641/// The persistent (span) case transformation set by `\U` / `\L`, cleared by
642/// `\E` / `\e`.
643#[derive(Clone, Copy, PartialEq)]
644enum SpanCase {
645    None,
646    /// `\U` — uppercase until `\E`.
647    Upper,
648    /// `\L` — lowercase until `\E`.
649    Lower,
650}
651
652/// The one-shot case transformation set by `\u` / `\l`. Takes priority over
653/// [`SpanCase`] for exactly the next char, then reverts to whatever span was
654/// active — it does NOT clear the span (vim: `\U\l&` on `"hello"` produces
655/// `"hELLO"`, not `"hello"` — the lowercase-next-char applies, then the
656/// active `\U` span resumes for the rest of the match).
657#[derive(Clone, Copy, PartialEq)]
658enum OneShotCase {
659    Upper,
660    Lower,
661}
662
663/// Combined case-transformation state threaded through [`expand_into`].
664#[derive(Clone, Copy, PartialEq)]
665struct CaseState {
666    span: SpanCase,
667    one_shot: Option<OneShotCase>,
668}
669
670impl CaseState {
671    fn new() -> Self {
672        Self {
673            span: SpanCase::None,
674            one_shot: None,
675        }
676    }
677}
678
679/// Push `ch` into `out`, applying the active case state. A pending one-shot
680/// (`\u`/`\l`) wins for this single char and is then consumed, falling back
681/// to the span (`\U`/`\L`) state — which persists — for subsequent chars.
682fn push_cased(out: &mut String, case: &mut CaseState, ch: char) {
683    let effective = match case.one_shot.take() {
684        Some(OneShotCase::Upper) => Some(SpanCase::Upper),
685        Some(OneShotCase::Lower) => Some(SpanCase::Lower),
686        None => match case.span {
687            SpanCase::None => None,
688            other => Some(other),
689        },
690    };
691    match effective {
692        None => out.push(ch),
693        Some(SpanCase::Upper) => out.extend(ch.to_uppercase()),
694        Some(SpanCase::Lower) => out.extend(ch.to_lowercase()),
695        Some(SpanCase::None) => unreachable!(),
696    }
697}
698
699/// Expand a raw vim replacement string against a single regex match.
700///
701/// Handles vim's `:h sub-replace-special` tokens:
702/// - `&` / `\0` — whole match; `\1`…`\9` — capture groups; `\&` — literal `&`.
703/// - `\r` — line break, `\t` — tab, `\n` — NUL.
704/// - `\u`/`\l` — upper/lowercase the next char; `\U`/`\L` … `\E`/`\e` — upper/
705///   lowercase a run.
706/// - `~` — the previous replacement string (`prev`), re-expanded against this
707///   match; `\~` — literal `~`.
708/// - `\\` — literal backslash; any other `\x` — literal `x`.
709///
710/// A plain `$` is literal (unlike the regex crate's `$`-expansion, which this
711/// deliberately does not use).
712fn expand_replacement(raw: &str, caps: &regex::Captures, prev: &str) -> String {
713    let mut out = String::with_capacity(raw.len() + 8);
714    expand_into(&mut out, raw, caps, prev, true);
715    out
716}
717
718fn expand_into(out: &mut String, raw: &str, caps: &regex::Captures, prev: &str, allow_tilde: bool) {
719    let mut case = CaseState::new();
720    let mut chars = raw.chars();
721    while let Some(c) = chars.next() {
722        match c {
723            '&' => {
724                let g = caps.get(0).map_or("", |m| m.as_str());
725                for ch in g.chars() {
726                    push_cased(out, &mut case, ch);
727                }
728            }
729            '~' if allow_tilde => {
730                // Previous replacement, re-expanded against this match. A `~`
731                // nested inside `prev` is treated literally to avoid recursion.
732                let mut tmp = String::new();
733                expand_into(&mut tmp, prev, caps, "", false);
734                for ch in tmp.chars() {
735                    push_cased(out, &mut case, ch);
736                }
737            }
738            '\\' => match chars.next() {
739                Some('&') => push_cased(out, &mut case, '&'),
740                Some('~') => push_cased(out, &mut case, '~'),
741                Some('\\') => push_cased(out, &mut case, '\\'),
742                // Control chars ignore case state (nothing to case).
743                Some('r') => out.push('\n'),
744                Some('t') => out.push('\t'),
745                Some('n') => out.push('\0'),
746                Some(d @ '0'..='9') => {
747                    let idx = d as usize - '0' as usize;
748                    let g = caps.get(idx).map_or("", |m| m.as_str());
749                    for ch in g.chars() {
750                        push_cased(out, &mut case, ch);
751                    }
752                }
753                Some('u') => case.one_shot = Some(OneShotCase::Upper),
754                Some('l') => case.one_shot = Some(OneShotCase::Lower),
755                Some('U') => case.span = SpanCase::Upper,
756                Some('L') => case.span = SpanCase::Lower,
757                Some('e') | Some('E') => case.span = SpanCase::None,
758                Some(other) => push_cased(out, &mut case, other),
759                None => {} // trailing backslash ignored
760            },
761            _ => push_cased(out, &mut case, c),
762        }
763    }
764}
765
766/// Replace the first or all occurrences of `regex` in `text`, expanding the
767/// raw vim `replacement` (with `prev` for `~`) per match. Returns
768/// `(new_text, count)`.
769fn do_replace(
770    regex: &Regex,
771    text: &str,
772    replacement: &str,
773    prev: &str,
774    all: bool,
775) -> (String, usize) {
776    let matches = regex.find_iter(text).count();
777    if matches == 0 {
778        return (text.to_string(), 0);
779    }
780    let rep = |caps: &regex::Captures| expand_replacement(replacement, caps, prev);
781    let replaced = if all {
782        regex.replace_all(text, rep).into_owned()
783    } else {
784        regex.replace(text, rep).into_owned()
785    };
786    let count = if all { matches } else { 1 };
787    (replaced, count)
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793    use crate::types::{DefaultHost, Options};
794    use hjkl_buffer::View;
795
796    fn editor_with(content: &str) -> Editor<View, DefaultHost> {
797        let mut e = Editor::new(View::new(), DefaultHost::new(), Options::default());
798        e.set_content(content);
799        e
800    }
801
802    fn buf_line(e: &Editor<View, DefaultHost>, row: usize) -> String {
803        hjkl_buffer::rope_line_str(&e.buffer().rope(), row)
804    }
805
806    // ── Parser tests ─────────────────────────────────────────────────
807
808    #[test]
809    fn parse_basic() {
810        let cmd = parse_substitute("/foo/bar/").unwrap();
811        assert_eq!(cmd.pattern.as_deref(), Some("foo"));
812        assert_eq!(cmd.replacement, "bar");
813        assert!(!cmd.flags.all);
814    }
815
816    #[test]
817    fn parse_trailing_slash_optional() {
818        let cmd = parse_substitute("/foo/bar").unwrap();
819        assert_eq!(cmd.pattern.as_deref(), Some("foo"));
820        assert_eq!(cmd.replacement, "bar");
821    }
822
823    #[test]
824    fn parse_global_flag() {
825        let cmd = parse_substitute("/x/y/g").unwrap();
826        assert!(cmd.flags.all);
827    }
828
829    #[test]
830    fn parse_ignore_case_flag() {
831        let cmd = parse_substitute("/x/y/i").unwrap();
832        assert!(cmd.flags.ignore_case);
833    }
834
835    #[test]
836    fn parse_case_sensitive_flag() {
837        let cmd = parse_substitute("/x/y/I").unwrap();
838        assert!(cmd.flags.case_sensitive);
839    }
840
841    #[test]
842    fn parse_confirm_flag_accepted() {
843        let cmd = parse_substitute("/x/y/c").unwrap();
844        assert!(cmd.flags.confirm);
845    }
846
847    #[test]
848    fn parse_multi_flags() {
849        let cmd = parse_substitute("/x/y/gi").unwrap();
850        assert!(cmd.flags.all);
851        assert!(cmd.flags.ignore_case);
852    }
853
854    #[test]
855    fn parse_unknown_flag_errors() {
856        let err = parse_substitute("/x/y/z").unwrap_err();
857        assert!(err.to_string().contains("unknown flag 'z'"), "{err}");
858    }
859
860    #[test]
861    fn parse_empty_pattern_is_none() {
862        let cmd = parse_substitute("//bar/").unwrap();
863        assert!(cmd.pattern.is_none());
864        assert_eq!(cmd.replacement, "bar");
865    }
866
867    #[test]
868    fn parse_empty_replacement_ok() {
869        let cmd = parse_substitute("/foo//").unwrap();
870        assert_eq!(cmd.pattern.as_deref(), Some("foo"));
871        assert_eq!(cmd.replacement, "");
872    }
873
874    #[test]
875    fn parse_escaped_slash_in_pattern() {
876        let cmd = parse_substitute("/a\\/b/c/").unwrap();
877        assert_eq!(cmd.pattern.as_deref(), Some("a/b"));
878    }
879
880    #[test]
881    fn parse_escaped_slash_in_replacement() {
882        let cmd = parse_substitute("/a/b\\/c/").unwrap();
883        // Replacement is already translated; literal / survives.
884        assert_eq!(cmd.replacement, "b/c");
885    }
886
887    // The parser stores the replacement in RAW vim notation; expansion (below)
888    // resolves `&` / `\1` / `\&` etc. per match.
889    #[test]
890    fn parse_keeps_replacement_raw() {
891        assert_eq!(parse_substitute("/foo/[&]/").unwrap().replacement, "[&]");
892        assert_eq!(parse_substitute("/foo/\\&/").unwrap().replacement, "\\&");
893        assert_eq!(parse_substitute("/(foo)/\\1/").unwrap().replacement, "\\1");
894        assert_eq!(parse_substitute("/(x)/\\9/").unwrap().replacement, "\\9");
895    }
896
897    #[test]
898    fn parse_wrong_delimiter_errors() {
899        let err = parse_substitute("|foo|bar|").unwrap_err();
900        assert!(err.to_string().contains("'/'"), "{err}");
901    }
902
903    #[test]
904    fn parse_too_few_fields_errors() {
905        let err = parse_substitute("/foo").unwrap_err();
906        assert!(
907            err.to_string().contains("needs /pattern/replacement"),
908            "{err}"
909        );
910    }
911
912    // ── Apply tests ──────────────────────────────────────────────────
913
914    #[test]
915    fn apply_single_line_first_only() {
916        let mut e = editor_with("foo foo");
917        let cmd = parse_substitute("/foo/bar/").unwrap();
918        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
919        assert_eq!(out.replacements, 1);
920        assert_eq!(out.lines_changed, 1);
921        assert_eq!(buf_line(&e, 0), "bar foo");
922    }
923
924    #[test]
925    fn apply_single_line_global() {
926        let mut e = editor_with("foo foo foo");
927        let cmd = parse_substitute("/foo/bar/g").unwrap();
928        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
929        assert_eq!(out.replacements, 3);
930        assert_eq!(out.lines_changed, 1);
931        assert_eq!(buf_line(&e, 0), "bar bar bar");
932    }
933
934    #[test]
935    fn apply_multi_line_range() {
936        let mut e = editor_with("foo\nfoo foo\nbar");
937        let cmd = parse_substitute("/foo/xyz/g").unwrap();
938        let out = apply_substitute(&mut e, &cmd, 0..=2).unwrap();
939        assert_eq!(out.replacements, 3);
940        assert_eq!(out.lines_changed, 2);
941        assert_eq!(buf_line(&e, 0), "xyz");
942        assert_eq!(buf_line(&e, 1), "xyz xyz");
943        assert_eq!(buf_line(&e, 2), "bar");
944    }
945
946    #[test]
947    fn apply_no_match_returns_zero() {
948        let mut e = editor_with("hello");
949        let original = buf_line(&e, 0);
950        let cmd = parse_substitute("/xyz/abc/").unwrap();
951        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
952        assert_eq!(out.replacements, 0);
953        assert_eq!(out.lines_changed, 0);
954        assert_eq!(buf_line(&e, 0), original);
955    }
956
957    #[test]
958    fn apply_case_insensitive_flag() {
959        let mut e = editor_with("Foo FOO foo");
960        let cmd = parse_substitute("/foo/bar/gi").unwrap();
961        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
962        assert_eq!(out.replacements, 3);
963        assert_eq!(buf_line(&e, 0), "bar bar bar");
964    }
965
966    #[test]
967    fn apply_case_sensitive_flag_overrides_editor_setting() {
968        let mut e = editor_with("Foo foo");
969        // Enable ignorecase on the editor.
970        e.settings_mut().ignore_case = true;
971        // `I` (capital) forces case-sensitive.
972        let cmd = parse_substitute("/foo/bar/I").unwrap();
973        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
974        // Only the lowercase "foo" matches.
975        assert_eq!(out.replacements, 1);
976        assert_eq!(buf_line(&e, 0), "Foo bar");
977    }
978
979    #[test]
980    fn apply_inline_case_override_wins_over_flag() {
981        let mut insensitive = editor_with("Foo FOO foo");
982        let cmd = parse_substitute("/\\cFOO/bar/I").unwrap();
983        let out = apply_substitute(&mut insensitive, &cmd, 0..=0).unwrap();
984        assert_eq!(out.replacements, 1);
985        assert_eq!(buf_line(&insensitive, 0), "bar FOO foo");
986
987        let mut sensitive = editor_with("Foo FOO foo");
988        let cmd = parse_substitute("/\\Cfoo/bar/i").unwrap();
989        let out = apply_substitute(&mut sensitive, &cmd, 0..=0).unwrap();
990        assert_eq!(out.replacements, 1);
991        assert_eq!(buf_line(&sensitive, 0), "Foo FOO bar");
992    }
993
994    #[test]
995    fn apply_empty_pattern_reuses_last_search() {
996        let mut e = editor_with("hello world");
997        e.set_last_search(Some("world".to_string()), true);
998        let cmd = parse_substitute("//planet/").unwrap();
999        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1000        assert_eq!(out.replacements, 1);
1001        assert_eq!(buf_line(&e, 0), "hello planet");
1002    }
1003
1004    #[test]
1005    fn apply_empty_pattern_no_last_search_errors() {
1006        let mut e = editor_with("hello");
1007        let cmd = parse_substitute("//bar/").unwrap();
1008        let err = apply_substitute(&mut e, &cmd, 0..=0).unwrap_err();
1009        assert!(
1010            err.to_string().contains("no previous regular expression"),
1011            "{err}"
1012        );
1013    }
1014
1015    #[test]
1016    fn apply_updates_last_search() {
1017        let mut e = editor_with("foo");
1018        let cmd = parse_substitute("/foo/bar/").unwrap();
1019        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1020        assert_eq!(e.last_search(), Some("foo".to_string()));
1021    }
1022
1023    #[test]
1024    fn apply_empty_replacement_deletes_match() {
1025        let mut e = editor_with("hello world");
1026        let cmd = parse_substitute("/world//").unwrap();
1027        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1028        assert_eq!(out.replacements, 1);
1029        assert_eq!(buf_line(&e, 0), "hello ");
1030    }
1031
1032    #[test]
1033    fn apply_undo_reverts_in_one_step() {
1034        let mut e = editor_with("foo");
1035        let cmd = parse_substitute("/foo/bar/").unwrap();
1036        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1037        assert_eq!(buf_line(&e, 0), "bar");
1038        e.undo();
1039        assert_eq!(buf_line(&e, 0), "foo");
1040    }
1041
1042    #[test]
1043    fn apply_ampersand_in_replacement() {
1044        let mut e = editor_with("foo");
1045        let cmd = parse_substitute("/foo/[&]/").unwrap();
1046        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1047        assert_eq!(buf_line(&e, 0), "[foo]");
1048    }
1049
1050    #[test]
1051    fn apply_capture_group_reference() {
1052        let mut e = editor_with("hello world");
1053        // Vim default magic: groups need `\(` `\)`; `+` needs `\+`.
1054        let cmd = parse_substitute("/\\(\\w\\+\\)/<<\\1>>/g").unwrap();
1055        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1056        assert_eq!(buf_line(&e, 0), "<<hello>> <<world>>");
1057    }
1058
1059    #[test]
1060    fn apply_backslash_r_splits_line() {
1061        // `\r` in the replacement inserts a line break (the split-on-delimiter
1062        // idiom): `:s/,/\r/g` turns one line into three.
1063        let mut e = editor_with("a,b,c");
1064        let cmd = parse_substitute("/,/\\r/g").unwrap();
1065        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1066        assert_eq!(buf_line(&e, 0), "a");
1067        assert_eq!(buf_line(&e, 1), "b");
1068        assert_eq!(buf_line(&e, 2), "c");
1069    }
1070
1071    /// Audit A5 regression: `:%s/,/\r/` across a multi-row range where an
1072    /// earlier row's replacement also splits into extra rows. The recorded
1073    /// "last changed row" must be adjusted into POST-substitution row space
1074    /// (vim lands on the first non-blank of the last changed line, `d`, real
1075    /// row 3) — not the PRE-split row index (which would land on `b`, row 1).
1076    #[test]
1077    fn apply_backslash_r_multi_row_cursor_lands_on_final_split_row() {
1078        let mut e = editor_with("a,b\nc,d\n");
1079        let cmd = parse_substitute("/,/\\r/").unwrap();
1080        let total = crate::types::Query::rope(e.buffer()).len_lines();
1081        let out = apply_substitute(&mut e, &cmd, 0..=(total.saturating_sub(1)) as u32).unwrap();
1082        assert_eq!(buf_line(&e, 0), "a");
1083        assert_eq!(buf_line(&e, 1), "b");
1084        assert_eq!(buf_line(&e, 2), "c");
1085        assert_eq!(buf_line(&e, 3), "d");
1086        assert_eq!(
1087            out.last_row,
1088            Some(3),
1089            "cursor should land on the last changed line ('d', real row 3) \
1090             in post-split coordinates, not the pre-split row index"
1091        );
1092        assert_eq!(e.buffer().cursor().row, 3);
1093    }
1094
1095    /// Single-row case: `\r` splitting one line into several must still put
1096    /// the cursor on the LAST resulting physical line (vim semantics for a
1097    /// single `:s` invocation whose replacement itself contains newlines).
1098    #[test]
1099    fn apply_backslash_r_single_row_cursor_lands_on_last_split_line() {
1100        let mut e = editor_with("a,b");
1101        let cmd = parse_substitute("/,/\\r/").unwrap();
1102        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1103        assert_eq!(buf_line(&e, 0), "a");
1104        assert_eq!(buf_line(&e, 1), "b");
1105        assert_eq!(out.last_row, Some(1));
1106        assert_eq!(e.buffer().cursor().row, 1);
1107    }
1108
1109    /// Guard the common (no-newline) multi-row path: cursor still lands on
1110    /// the last changed row with no coordinate adjustment needed.
1111    #[test]
1112    fn apply_no_newline_multi_row_cursor_unaffected() {
1113        let mut e = editor_with("a\na\na");
1114        let cmd = parse_substitute("/a/X/").unwrap();
1115        let out = apply_substitute(&mut e, &cmd, 0..=2).unwrap();
1116        assert_eq!(buf_line(&e, 0), "X");
1117        assert_eq!(buf_line(&e, 1), "X");
1118        assert_eq!(buf_line(&e, 2), "X");
1119        assert_eq!(out.last_row, Some(2));
1120        assert_eq!(e.buffer().cursor().row, 2);
1121    }
1122
1123    #[test]
1124    fn apply_backslash_t_inserts_tab() {
1125        let mut e = editor_with("a,b");
1126        let cmd = parse_substitute("/,/\\t/").unwrap();
1127        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1128        assert_eq!(buf_line(&e, 0), "a\tb");
1129    }
1130
1131    #[test]
1132    fn apply_literal_dollar_in_replacement() {
1133        // A literal `$` in the replacement stays literal (vim uses `\1` for
1134        // groups, so `$5` is not a capture ref).
1135        let mut e = editor_with("x");
1136        let cmd = parse_substitute("/x/$5/").unwrap();
1137        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1138        assert_eq!(buf_line(&e, 0), "$5");
1139    }
1140
1141    #[test]
1142    fn apply_backslash_zero_is_whole_match() {
1143        // `\0` is the whole match (like `&`).
1144        let mut e = editor_with("foo");
1145        let cmd = parse_substitute("/foo/[\\0]/").unwrap();
1146        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1147        assert_eq!(buf_line(&e, 0), "[foo]");
1148    }
1149
1150    #[test]
1151    fn apply_group_ref_then_literal_digits() {
1152        // Braced capture refs let a digit follow a group ref: `\1` then `1`.
1153        let mut e = editor_with("ab");
1154        let cmd = parse_substitute("/\\(.\\)/\\11/g").unwrap();
1155        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1156        assert_eq!(buf_line(&e, 0), "a1b1");
1157    }
1158
1159    // ── expand_replacement: case escapes + ~ ──────────────────────────────────
1160
1161    fn expand(raw: &str, pat: &str, text: &str, prev: &str) -> String {
1162        let re = Regex::new(pat).unwrap();
1163        let caps = re.captures(text).unwrap();
1164        expand_replacement(raw, &caps, prev)
1165    }
1166
1167    #[test]
1168    fn expand_case_upper_run_and_end() {
1169        // `\U…\E` uppercases a run; text after `\E` is unaffected.
1170        assert_eq!(expand("\\U\\0\\Ex", "foo", "foo", ""), "FOOx");
1171        assert_eq!(expand("\\L&\\E", "FOO", "FOO", ""), "foo");
1172    }
1173
1174    #[test]
1175    fn expand_case_one_shot() {
1176        // `\u` / `\l` affect only the next char.
1177        assert_eq!(expand("\\u\\0", "foo", "foo", ""), "Foo");
1178        assert_eq!(expand("\\l\\0", "FOO", "FOO", ""), "fOO");
1179    }
1180
1181    #[test]
1182    fn expand_case_applies_to_group() {
1183        // Case escape applied across a capture group and a following literal.
1184        assert_eq!(expand("\\U\\1-y\\E", "(f)oo", "foo", ""), "F-Y");
1185    }
1186
1187    /// B18: `\u&` on a whole-word match — matches vim's
1188    /// `:s/\w\+/\u&/` on `"hello world"` → `"Hello world"` (verified
1189    /// against nvim v0.12.4).
1190    #[test]
1191    fn expand_backslash_u_uppercases_first_char_of_group() {
1192        assert_eq!(expand("\\u\\1", "(\\w+)", "hello world", ""), "Hello");
1193    }
1194
1195    /// A one-shot `\u`/`\l` takes priority for exactly the next char, then
1196    /// FALLS BACK to any active `\U`/`\L` span rather than clearing it —
1197    /// verified against nvim: `:s/\w\+/\U\l&/` on `"hello"` → `"hELLO"`
1198    /// (not `"hello"`, and not `"HELLO"`).
1199    #[test]
1200    fn expand_one_shot_falls_back_to_active_span() {
1201        assert_eq!(expand("\\U\\l\\0", "hello", "hello", ""), "hELLO");
1202        // Same interaction the other way around: `\l\U\1 \2` on
1203        // "hello world" → "hELLO WORLD" (nvim-verified).
1204        assert_eq!(
1205            expand("\\l\\U\\1 \\2", "(\\w+) (\\w+)", "hello world", ""),
1206            "hELLO WORLD"
1207        );
1208    }
1209
1210    #[test]
1211    fn expand_literal_dollar_and_amp() {
1212        assert_eq!(expand("$\\0", "x", "x", ""), "$x");
1213        assert_eq!(expand("[&]", "foo", "foo", ""), "[foo]");
1214        assert_eq!(expand("\\&", "foo", "foo", ""), "&");
1215    }
1216
1217    #[test]
1218    fn expand_tilde_uses_previous_replacement() {
1219        // `~` expands to the previous replacement, re-evaluated against caps.
1220        assert_eq!(expand("~!", "x", "x", "PREV"), "PREV!");
1221        assert_eq!(expand("~", "(.)", "a", "[\\1]"), "[a]");
1222        // `\~` is a literal tilde.
1223        assert_eq!(expand("\\~", "x", "x", "PREV"), "~");
1224    }
1225
1226    // ── `n` flag: report count, no mutation ───────────────────────────────────
1227
1228    #[test]
1229    fn apply_report_only_counts_without_mutating() {
1230        let mut e = editor_with("foo foo foo");
1231        let cmd = parse_substitute("/foo/bar/gn").unwrap();
1232        assert!(cmd.flags.report_only);
1233        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1234        assert_eq!(out.replacements, 3);
1235        // View is untouched.
1236        assert_eq!(buf_line(&e, 0), "foo foo foo");
1237    }
1238
1239    // ── case escapes through the full apply path ──────────────────────────────
1240
1241    #[test]
1242    fn apply_upper_run() {
1243        let mut e = editor_with("hello world");
1244        let cmd = parse_substitute("/world/\\U&\\E/").unwrap();
1245        apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1246        assert_eq!(buf_line(&e, 0), "hello WORLD");
1247    }
1248
1249    // ── smartcase + \c/\C tests ───────────────────────────────────────────────
1250
1251    /// `:s/foo/bar/` on `"Foo"` — ignorecase+smartcase on by default, all-
1252    /// lowercase pattern → Insensitive → matches `Foo` → becomes `bar`.
1253    #[test]
1254    fn substitute_respects_smartcase() {
1255        let mut e = editor_with("Foo");
1256        // Default Options has ignorecase=true, smartcase=true.
1257        let cmd = parse_substitute("/foo/bar/").unwrap();
1258        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1259        assert_eq!(out.replacements, 1);
1260        assert_eq!(buf_line(&e, 0), "bar");
1261    }
1262
1263    /// `:s/Foo/bar/i` — `/i` flag overrides smartcase (mixed pattern would
1264    /// normally be Sensitive) → case-insensitive → matches `"foo"`.
1265    #[test]
1266    fn substitute_i_flag_overrides_c() {
1267        let mut e = editor_with("foo");
1268        // /i forces insensitive regardless of pattern case or smartcase.
1269        let cmd = parse_substitute("/Foo/bar/i").unwrap();
1270        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1271        assert_eq!(out.replacements, 1, "expected match on 'foo' with /i flag");
1272        assert_eq!(buf_line(&e, 0), "bar");
1273    }
1274
1275    /// `\c` inline override in a pattern with no `/i`/`/I` flag — forces
1276    /// insensitive even though `Foo` has uppercase (smartcase trip).
1277    #[test]
1278    fn substitute_lower_c_inline_overrides_smartcase() {
1279        let mut e = editor_with("FOO");
1280        // \cFoo — override wins, Insensitive → matches "FOO"
1281        let cmd = parse_substitute("/\\cFoo/bar/").unwrap();
1282        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1283        assert_eq!(out.replacements, 1);
1284        assert_eq!(buf_line(&e, 0), "bar");
1285    }
1286
1287    // ── collect_substitute_matches tests ────────────────────────────────────
1288
1289    #[test]
1290    fn collect_inline_case_override_wins_over_flag() {
1291        let e = editor_with("Foo FOO foo");
1292        let cmd = parse_substitute("/\\cFOO/bar/I").unwrap();
1293        assert_eq!(
1294            collect_substitute_matches(&e, &cmd, 0..=0).unwrap().len(),
1295            1
1296        );
1297
1298        let cmd = parse_substitute("/\\Cfoo/bar/i").unwrap();
1299        assert_eq!(
1300            collect_substitute_matches(&e, &cmd, 0..=0).unwrap().len(),
1301            1
1302        );
1303    }
1304
1305    #[test]
1306    fn collect_substitute_matches_finds_all_occurrences() {
1307        let e = editor_with("foo bar foo");
1308        let cmd = parse_substitute("/foo/baz/g").unwrap();
1309        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1310        assert_eq!(matches.len(), 2, "expected 2 matches for /g flag");
1311        assert_eq!(matches[0].byte_start, 0);
1312        assert_eq!(matches[0].byte_end, 3);
1313        assert_eq!(matches[1].byte_start, 8);
1314        assert_eq!(matches[1].byte_end, 11);
1315        assert_eq!(matches[0].replacement, "baz");
1316        assert_eq!(matches[1].replacement, "baz");
1317    }
1318
1319    #[test]
1320    fn collect_substitute_matches_respects_g_flag() {
1321        // Without /g only the first match per line.
1322        let e = editor_with("foo foo foo");
1323        let cmd = parse_substitute("/foo/baz/").unwrap();
1324        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1325        assert_eq!(matches.len(), 1, "expected 1 match without /g");
1326        assert_eq!(matches[0].byte_start, 0);
1327    }
1328
1329    #[test]
1330    fn collect_substitute_matches_respects_range() {
1331        let e = editor_with("foo\nfoo\nfoo\nfoo\nfoo");
1332        let cmd = parse_substitute("/foo/bar/g").unwrap();
1333        // Only rows 1 and 2 (0-based) — should return 2 matches, not 5.
1334        let matches = collect_substitute_matches(&e, &cmd, 1..=2).unwrap();
1335        assert_eq!(matches.len(), 2);
1336        assert_eq!(matches[0].row, 1);
1337        assert_eq!(matches[1].row, 2);
1338    }
1339
1340    #[test]
1341    fn collect_substitute_matches_expands_template() {
1342        let e = editor_with("hello world");
1343        // /\(\w\+\)/<<\1>>/ — the replacement template has a capture group.
1344        let cmd = parse_substitute("/\\(\\w\\+\\)/<<\\1>>/g").unwrap();
1345        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1346        assert_eq!(matches.len(), 2);
1347        assert_eq!(matches[0].replacement, "<<hello>>");
1348        assert_eq!(matches[1].replacement, "<<world>>");
1349    }
1350
1351    // ── apply_collected_matches tests ───────────────────────────────────────
1352
1353    #[test]
1354    fn apply_collected_matches_reverse_order_preserves_offsets() {
1355        // Three matches at byte offsets 0..3, 4..7, 8..11.
1356        // Applying in forward order would shift byte offsets; reverse must
1357        // keep the final buffer consistent.
1358        let mut e = editor_with("foo bar baz");
1359        let cmd = parse_substitute("/\\(foo\\|bar\\|baz\\)/X/g").unwrap();
1360        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1361        assert_eq!(matches.len(), 3);
1362        let accepted = vec![true; 3];
1363        let applied = apply_collected_matches(&mut e, &matches, &accepted);
1364        assert_eq!(applied, 3);
1365        assert_eq!(buf_line(&e, 0), "X X X");
1366    }
1367
1368    #[test]
1369    fn apply_collected_matches_subset_only() {
1370        // 3 matches; accept only first and third.
1371        let mut e = editor_with("foo bar foo");
1372        let cmd = parse_substitute("/foo/ZZZ/g").unwrap();
1373        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1374        assert_eq!(matches.len(), 2, "expected 2 foo matches");
1375        // Accept only the first (index 0), skip the second (index 1).
1376        let accepted = vec![true, false];
1377        let applied = apply_collected_matches(&mut e, &matches, &accepted);
1378        assert_eq!(applied, 1);
1379        // First "foo" replaced; second "foo" untouched.
1380        assert_eq!(buf_line(&e, 0), "ZZZ bar foo");
1381    }
1382
1383    #[test]
1384    fn apply_collected_matches_zero_accepted() {
1385        let mut e = editor_with("foo bar foo");
1386        let cmd = parse_substitute("/foo/ZZZ/g").unwrap();
1387        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1388        let accepted = vec![false; matches.len()];
1389        let applied = apply_collected_matches(&mut e, &matches, &accepted);
1390        assert_eq!(applied, 0);
1391        assert_eq!(buf_line(&e, 0), "foo bar foo");
1392    }
1393
1394    #[test]
1395    fn apply_collected_matches_expands_template() {
1396        let mut e = editor_with("hello world");
1397        let cmd = parse_substitute("/\\(\\w\\+\\)/<<\\1>>/g").unwrap();
1398        let matches = collect_substitute_matches(&e, &cmd, 0..=0).unwrap();
1399        let accepted = vec![true; matches.len()];
1400        let applied = apply_collected_matches(&mut e, &matches, &accepted);
1401        assert_eq!(applied, 2);
1402        assert_eq!(buf_line(&e, 0), "<<hello>> <<world>>");
1403    }
1404
1405    // ── V5: magic `~` on the PATTERN side of `:s` and `/`/`?` ─────────────────
1406    // `apply_substitute` does NOT store `last_substitute` itself (the ex layer
1407    // does), so these tests set it explicitly to simulate a prior `:s`.
1408
1409    /// nvim-verified: `:s/foo/BAR/` then `:s/~/baz/` — the second command's
1410    /// pattern `~` expands to `BAR`, matches the just-inserted `BAR`, → `baz`.
1411    #[test]
1412    fn pattern_tilde_expands_to_last_substitute() {
1413        let mut e = editor_with("foo");
1414        let first = parse_substitute("/foo/BAR/").unwrap();
1415        apply_substitute(&mut e, &first, 0..=0).unwrap();
1416        assert_eq!(buf_line(&e, 0), "BAR");
1417        e.set_last_substitute(first); // ex layer normally does this
1418
1419        let second = parse_substitute("/~/baz/").unwrap();
1420        let out = apply_substitute(&mut e, &second, 0..=0).unwrap();
1421        assert_eq!(out.replacements, 1, "pattern `~` must match `BAR`");
1422        assert_eq!(buf_line(&e, 0), "baz");
1423    }
1424
1425    /// nvim-verified: `\~` in the pattern is a literal tilde — it matches a real
1426    /// `~` character and does NOT expand to the last-substitute text.
1427    #[test]
1428    fn pattern_escaped_tilde_stays_literal() {
1429        let mut e = editor_with("a~b");
1430        // Prior `:s` set the last replacement to BAR; `\~` must ignore it.
1431        e.set_last_substitute(parse_substitute("/x/BAR/").unwrap());
1432        let cmd = parse_substitute("/\\~/X/").unwrap();
1433        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1434        assert_eq!(out.replacements, 1, "`\\~` must match the literal tilde");
1435        assert_eq!(buf_line(&e, 0), "aXb");
1436    }
1437
1438    /// No previous substitute → pattern `~` expands to empty (documented
1439    /// divergence from nvim's `E33`; the empty choice never corrupts text).
1440    /// Here `:s/a~b/X/` on `"ab"` becomes pattern `ab`, which matches → `X`.
1441    #[test]
1442    fn pattern_tilde_no_previous_substitute_expands_empty() {
1443        let mut e = editor_with("ab");
1444        assert!(e.last_substitute().is_none());
1445        let cmd = parse_substitute("/a~b/X/").unwrap();
1446        let out = apply_substitute(&mut e, &cmd, 0..=0).unwrap();
1447        assert_eq!(out.replacements, 1, "`~`→empty so pattern is `ab`");
1448        assert_eq!(buf_line(&e, 0), "X");
1449    }
1450
1451    /// A `/` search routes through the SAME `resolve_case_mode` path as the
1452    /// `:s` LHS (`Editor::push_search_pattern`), so one test covers the shared
1453    /// path: after a prior `:s/foo/BAR/`, searching `/~` compiles a regex that
1454    /// matches `BAR`. nvim-verified: `/~` finds the last-substitute text.
1455    #[test]
1456    fn search_pattern_tilde_shares_expansion_path() {
1457        let mut e = editor_with("BAR");
1458        e.set_last_substitute(parse_substitute("/foo/BAR/").unwrap());
1459        e.push_search_pattern("~");
1460        let re = e
1461            .search_state()
1462            .pattern
1463            .as_ref()
1464            .expect("`/~` must compile to a pattern");
1465        assert!(re.is_match("BAR"), "search `~` must expand to `BAR`");
1466        assert!(
1467            !re.is_match("~"),
1468            "search `~` must not match a literal tilde"
1469        );
1470    }
1471}