Skip to main content

strop_engine/editor/normal/
ex.rs

1//! normal/ex.rs — the ex command line: ranges, substitute, :w/:q family.
2
3use crate::editor::Editor;
4
5use crate::editor::Register;
6
7impl Editor {
8    /// Ex-completion candidates for the pending prefix (name, doc).
9    pub fn ex_candidates(&self) -> Vec<(&'static str, &'static str)> {
10        let Some(prefix) = self.pending.text().strip_prefix(':') else {
11            return Vec::new();
12        };
13        if prefix.contains(' ') {
14            return Vec::new();
15        }
16        super::EX_COMMANDS
17            .iter()
18            .filter(|(name, _)| name.starts_with(prefix))
19            .copied()
20            .collect()
21    }
22
23    /// Tab on the ex line: cycle the completion candidates — command
24    /// names for a bare prefix; remote hosts/paths for a file
25    /// command's `ssh://` operand (editor/remote_completion.rs).
26    pub(super) fn ex_tab_complete(&mut self) {
27        if self.remote_completion_tab() {
28            return;
29        }
30        let cands = self.ex_candidates();
31        if cands.is_empty() {
32            return;
33        }
34        let prefix = self.pending.text().strip_prefix(':').unwrap_or("");
35        let next = cands
36            .iter()
37            .position(|(name, _)| *name == prefix)
38            .map_or(cands[0].0, |i| cands[(i + 1) % cands.len()].0);
39        self.feed_pending_event(crate::editor::pending::PendingEvent::CompleteEx(
40            next.to_owned(),
41        ));
42    }
43
44    /// Parse a leading ex range: `%`, `.`, `$`, `N`, `N,M`, with
45    /// +/- offsets. Returns 0-indexed inclusive line bounds + the
46    /// remaining command text, or None when no range leads.
47    fn parse_ex_range<'a>(&self, cmdline: &'a str) -> (Option<(usize, usize)>, &'a str) {
48        let buf = self.buf();
49        let last = buf.last_content_line();
50        let cur = buf.line_of(self.head());
51        let addr = |tok: &str| -> Option<(usize, usize)> {
52            // one address + the bytes it consumed
53            match tok.as_bytes().first()? {
54                b'%' => Some((0, 1)),
55                b'.' => Some((cur, 1)),
56                b'$' => Some((last, 1)),
57                b if b.is_ascii_digit() => {
58                    let n: usize = tok
59                        .chars()
60                        .take_while(|c| c.is_ascii_digit())
61                        .collect::<String>()
62                        .parse()
63                        .ok()?;
64                    Some((n.saturating_sub(1).min(last), n.to_string().len()))
65                }
66                _ => None,
67            }
68        };
69        let (mut first, mut used) = match addr(cmdline) {
70            Some(v) => v,
71            None => return (None, cmdline),
72        };
73        let mut second = None;
74        if cmdline.as_bytes().get(used) == Some(&b',') {
75            match addr(&cmdline[used + 1..]) {
76                Some((l2, u2)) => {
77                    second = Some(l2);
78                    used += 1 + u2;
79                }
80                None => return (None, cmdline),
81            }
82        }
83        // +/- offsets trail an address (:+3, :-2, :.-1,$-1)
84        let whole = cmdline[..used].to_string();
85        let mut tail = &cmdline[used..];
86        let apply_off = |line: usize, tail: &str| -> (usize, usize) {
87            let b = tail.as_bytes();
88            let mut i = 0;
89            let mut line = line;
90            while i < tail.len() && (b[i] == b'+' || b[i] == b'-') {
91                let neg = b[i] == b'-';
92                i += 1;
93                let digits: String = tail[i..]
94                    .chars()
95                    .take_while(|c| c.is_ascii_digit())
96                    .collect();
97                let n: usize = if digits.is_empty() {
98                    1
99                } else {
100                    digits.parse().unwrap_or(1)
101                };
102                i += digits.len();
103                line = if neg {
104                    line.saturating_sub(n)
105                } else {
106                    (line + n).min(last)
107                };
108            }
109            (line, i)
110        };
111        let (f, fu) = apply_off(first, tail);
112        first = f;
113        tail = &tail[fu..];
114        let mut last_line = second.unwrap_or(first);
115        if second.is_some() {
116            let (l, lu) = apply_off(last_line, tail);
117            last_line = l;
118            tail = &tail[lu..];
119        }
120        if whole == "%" {
121            return (Some((0, last)), tail);
122        }
123        if first > last_line {
124            return (None, cmdline); // backwards range: vim errors
125        }
126        (Some((first.min(last), last_line.min(last))), tail)
127    }
128
129    /// Ranged commands: `:N` alone jumps; `d`/`y` delete/yank the
130    /// lines; `s/a/b/[g]` substitutes (LITERAL pattern — vim's regex
131    /// substitute is a documented deviation until 0016's grammar work).
132    fn run_ranged_ex(&mut self, range: (usize, usize), rest: &str) {
133        let (lo, hi) = range;
134        if rest.is_empty() {
135            // :N — goto line
136            let s = self.buf().line_start(lo);
137            self.set_head(s);
138            self.clamp_cursor();
139            self.scroll_to_cursor(self.view_rows());
140            return;
141        }
142        match rest {
143            "d" | "d!" => {
144                let s = self.buf().line_start(lo);
145                let e = if hi + 1 < self.buf().len_lines() {
146                    self.buf().line_start(hi + 1)
147                } else {
148                    self.buf().len_bytes()
149                };
150                let text = self.buf().text().byte_slice(s..e).to_string();
151                self.set_register(None, Register::linewise(text));
152                self.tx_begin();
153                self.buf_mut().delete(strop_core::Range::charwise(s, e));
154                self.tx_commit();
155                self.set_head(self.buf().clamp_boundary(s));
156                self.clamp_cursor();
157                self.message = format!("{} lines deleted", hi - lo + 1);
158            }
159            "y" => {
160                let s = self.buf().line_start(lo);
161                let e = if hi + 1 < self.buf().len_lines() {
162                    self.buf().line_start(hi + 1)
163                } else {
164                    self.buf().len_bytes()
165                };
166                let text = self.buf().text().byte_slice(s..e).to_string();
167                self.set_register(None, Register::linewise(text));
168                self.message = format!("{} lines yanked", hi - lo + 1);
169            }
170            _ if rest.starts_with("s/") => self.substitute_range(lo, hi, &rest[2..]),
171            _ => self.message = format!("unsupported ranged command: {rest}"),
172        }
173    }
174
175    /// `:[range]s/pat/repl/[g]` — literal pattern, vim's flag letter g.
176    fn substitute_range(&mut self, lo: usize, hi: usize, spec: &str) {
177        let parts: Vec<&str> = spec.split('/').collect();
178        if parts.len() < 2 {
179            self.message = ":s needs /pat/repl/".into();
180            return;
181        }
182        let (pat, repl) = (parts[0], parts[1]);
183        let global = parts.get(2).is_some_and(|f| f.contains('g'));
184        if pat.is_empty() {
185            self.message = "empty pattern".into();
186            return;
187        }
188        let s0 = self.buf().line_start(lo);
189        let e0 = self.buf().line_end(hi);
190        let text = self.buf().text().byte_slice(s0..e0).to_string();
191        let mut edits = Vec::new();
192        let mut offset = s0;
193        for line in text.split_inclusive('\n') {
194            for (start, _) in line.match_indices(pat) {
195                edits.push(strop_core::Replacement::new(
196                    strop_core::Range::charwise(offset + start, offset + start + pat.len()),
197                    repl,
198                ));
199                if !global {
200                    break;
201                }
202            }
203            offset += line.len();
204        }
205        let hits = edits.len();
206        if hits == 0 {
207            self.message = format!("pattern not found: {pat}");
208            return;
209        }
210        if let Err(error) = self.apply(
211            self.current(),
212            self.buf().revision(),
213            crate::editor::transact::ChangeSet {
214                edits,
215                undo_open: false,
216            },
217        ) {
218            self.message = format!("substitution failed: {error}");
219            return;
220        }
221        self.set_head(self.buf().clamp_boundary(s0));
222        self.clamp_cursor();
223        let end = e0
224            .saturating_add_signed((repl.len() as isize - pat.len() as isize) * hits as isize)
225            .min(self.buf().len_bytes());
226        self.flash(strop_core::Range::charwise(s0, end));
227        self.message = format!("{hits} substitution{}", if hits == 1 { "" } else { "s" });
228    }
229
230    pub(crate) fn run_ex(&mut self, cmdline: &str) {
231        // vim ex ranges: [%, N, N.M, ., $, +/-offsets] prefix the
232        // command. Bare :N is goto-line.
233        let (range, rest) = self.parse_ex_range(cmdline);
234        if let Some(range) = range {
235            self.run_ranged_ex(range, rest);
236            return;
237        }
238        let (cmd, arg) = cmdline.split_once(' ').unwrap_or((cmdline, ""));
239        if self.run_remote_ex(cmd, arg) {
240            return;
241        }
242        match cmd {
243            _ if cmdline.starts_with('!') => self.shell_run(&cmdline[1..]),
244            "w" | "w!" if self.collections.contains_key(&self.current()) => {
245                self.collection_save((!arg.is_empty()).then(|| arg.into()), cmd == "w!", false);
246            }
247            "w" | "w!" => {
248                // vim: readonly buffers refuse plain :w (surfaces, :view);
249                // :w! forces through the mutation boundary's rule
250                // Container files have no write path (0037 DC1b): refuse
251                // both forms — never a local-path fallback, never w!.
252                if matches!(
253                    self.cur().source,
254                    crate::editor::document::DocumentSource::Container { .. }
255                ) {
256                    self.message =
257                        "container files are read-only (0037 DC1b); no in-container save".into();
258                    return;
259                }
260                if self.buf().readonly && cmd != "w!" && self.remote_file().is_none() {
261                    let name = self.buf().name.as_deref().unwrap_or("readonly buffer");
262                    self.message = format!("{name}: readonly — :w! to force");
263                    return;
264                }
265                self.request_save((!arg.is_empty()).then(|| arg.into()), cmd == "w!", false);
266            }
267            "wq" | "wq!" if self.collections.contains_key(&self.current()) => {
268                self.collection_save(None, cmd == "wq!", true);
269            }
270            "wq" | "wq!" => {
271                if matches!(
272                    self.cur().source,
273                    crate::editor::document::DocumentSource::Container { .. }
274                ) {
275                    self.message =
276                        "container files are read-only (0037 DC1b); no in-container save".into();
277                    return;
278                }
279                self.request_save((!arg.is_empty()).then(|| arg.into()), cmd == "wq!", true);
280            }
281            "set" => {
282                // vim's option surface, narrowly: ro/noro only for now
283                match arg {
284                    "ro" | "readonly" => {
285                        self.buf_mut().readonly = true;
286                        self.message = "readonly".into();
287                    }
288                    "noro" | "noreadonly" => {
289                        if self.remote_file().is_some() && !self.remote_edit_authorized() {
290                            self.message =
291                                "remote file is read-only; use :remote edit first".into();
292                        } else {
293                            self.buf_mut().readonly = false;
294                            self.message = "writable".into();
295                        }
296                    }
297                    _ => self.message = format!("unknown option: {arg}"),
298                }
299            }
300            "view" => {
301                // vim view: edit readonly — no arg marks the current
302                // buffer readonly
303                if arg.is_empty() {
304                    self.buf_mut().readonly = true;
305                    self.message = "readonly".into();
306                } else {
307                    self.request_user_open(
308                        arg,
309                        super::super::io::OpenIntent::Switch { readonly: true },
310                    );
311                }
312            }
313            "q" => {
314                self.close_pane_or_buffer(false);
315            }
316            "q!" => {
317                self.close_pane_or_buffer(true);
318            }
319            "qa" | "qall" => self.quit_all(false),
320            "qa!" | "qall!" => self.quit_all(true),
321            _ if cmdline.starts_with("s/") => {
322                // :s without a range = the current line (vim)
323                let line = self.buf().line_of(self.head());
324                self.substitute_range(line, line, &cmdline[2..]);
325            }
326            "trust" => self.request_trust(),
327            "noh" => {
328                // nohlsearch: the persistent highlight drops (0001 §5.8)
329                self.last_search = None;
330            }
331            _ if cmdline.bytes().all(|b| b.is_ascii_digit()) && !cmdline.is_empty() => {
332                // :30 jumps to line 30 (vim); past EOF clamps to the last
333                // content line, never the phantom past a trailing newline
334                let n: usize = cmdline.parse().unwrap_or(1);
335                let mut last = self.buf().len_lines().saturating_sub(1);
336                if self.buf().line_start(last) >= self.buf().len_bytes() {
337                    last = last.saturating_sub(1);
338                }
339                self.push_jump(); // :N is a jump — record before moving
340                self.set_head(self.buf().line_start(n.saturating_sub(1).min(last)));
341                self.clamp_cursor();
342            }
343            "vs" | "vsplit" => self.split(true, if arg.is_empty() { None } else { Some(arg) }),
344            "sp" | "split" => self.split(false, if arg.is_empty() { None } else { Some(arg) }),
345            "help" | "h" => self.open_help_topic(arg),
346            "jumps" => self.open_jumps_picker(),
347            "search-options" => self.open_search_options(),
348            "tab-size" => self.tab_size_command(arg),
349            "indent-style" => self.indent_style_command(arg),
350            "apply-change" => self.review_apply_pub(),
351            "select-next" => self.occurrence_next_pub(),
352            "select-all" => self.occurrence_all_pub(),
353            "select-skip" => self.occurrence_skip_pub(),
354            "select-pop" => self.occurrence_pop_pub(),
355            "cancel-change" => self.review_cancel_pub(),
356            "collection" if arg == "source" => self.collection_open_source(),
357            "collection" if arg == "expand" => self.collection_context_step(true),
358            "collection" if arg == "contract" => self.collection_context_step(false),
359            "collection" => {
360                self.message = ":collection source — open the full source at the caret".into()
361            }
362            "symbols" => self.lsp_document_symbols_pub(),
363            "explain" => self.open_explain(),
364            "containers" => self.request_containers(),
365            "format" => self.lsp_format(),
366            "rename" => {
367                if arg.is_empty() {
368                    self.message = ":rename needs a new name".into();
369                } else {
370                    self.lsp_rename(arg);
371                }
372            }
373            "undo-change" => self.undo_last_change(),
374            "save-change" => self.save_changed_files_pub(),
375            "e" | "e!" => {
376                if arg.is_empty() && cmd == "e!" && self.refresh_remote() {
377                    return;
378                }
379                if arg.is_empty() {
380                    self.message = ":e needs a path".into();
381                } else if self.buf().dirty && cmd == "e" {
382                    self.message = "unsaved changes — :e! to force".into();
383                } else {
384                    self.request_user_open(
385                        arg,
386                        super::super::io::OpenIntent::Switch { readonly: false },
387                    );
388                }
389            }
390            other => self.message = format!("unknown ex: :{other}"),
391        }
392    }
393}