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 out = String::with_capacity(text.len());
192        let mut hits = 0usize;
193        for (i, line) in text.split('\n').enumerate() {
194            if i > 0 {
195                out.push('\n');
196            }
197            if global {
198                let n = line.matches(pat).count();
199                hits += n;
200                out.push_str(&line.replace(pat, repl));
201            } else if let Some(p) = line.find(pat) {
202                hits += 1;
203                out.push_str(&line[..p]);
204                out.push_str(repl);
205                out.push_str(&line[p + pat.len()..]);
206            } else {
207                out.push_str(line);
208            }
209        }
210        if hits == 0 {
211            self.message = format!("pattern not found: {pat}");
212            return;
213        }
214        self.tx_begin();
215        {
216            let mut b = self.buf_mut();
217            b.delete(strop_core::Range::charwise(s0, e0));
218            b.insert(s0, &out);
219        }
220        self.tx_commit();
221        self.set_head(self.buf().clamp_boundary(s0));
222        self.clamp_cursor();
223        let end = (s0 + out.len()).min(self.buf().len_bytes());
224        self.flash(strop_core::Range::charwise(s0, end));
225        self.message = format!("{hits} substitution{}", if hits == 1 { "" } else { "s" });
226    }
227
228    pub(crate) fn run_ex(&mut self, cmdline: &str) {
229        // vim ex ranges: [%, N, N.M, ., $, +/-offsets] prefix the
230        // command. Bare :N is goto-line.
231        let (range, rest) = self.parse_ex_range(cmdline);
232        if let Some(range) = range {
233            self.run_ranged_ex(range, rest);
234            return;
235        }
236        let (cmd, arg) = cmdline.split_once(' ').unwrap_or((cmdline, ""));
237        if self.run_remote_ex(cmd, arg) {
238            return;
239        }
240        match cmd {
241            _ if cmdline.starts_with('!') => self.shell_run(&cmdline[1..]),
242            "w" | "w!" => {
243                // vim: readonly buffers refuse plain :w (surfaces, :view);
244                // :w! forces through the mutation boundary's rule
245                // Container files have no write path (0037 DC1b): refuse
246                // both forms — never a local-path fallback, never w!.
247                if matches!(
248                    self.cur().source,
249                    crate::editor::document::DocumentSource::Container { .. }
250                ) {
251                    self.message =
252                        "container files are read-only (0037 DC1b); no in-container save".into();
253                    return;
254                }
255                if self.buf().readonly && cmd != "w!" && self.remote_file().is_none() {
256                    let name = self.buf().name.as_deref().unwrap_or("readonly buffer");
257                    self.message = format!("{name}: readonly — :w! to force");
258                    return;
259                }
260                self.request_save((!arg.is_empty()).then(|| arg.into()), cmd == "w!", false);
261            }
262            "wq" | "wq!" => {
263                if matches!(
264                    self.cur().source,
265                    crate::editor::document::DocumentSource::Container { .. }
266                ) {
267                    self.message =
268                        "container files are read-only (0037 DC1b); no in-container save".into();
269                    return;
270                }
271                self.request_save((!arg.is_empty()).then(|| arg.into()), cmd == "wq!", true);
272            }
273            "set" => {
274                // vim's option surface, narrowly: ro/noro only for now
275                match arg {
276                    "ro" | "readonly" => {
277                        self.buf_mut().readonly = true;
278                        self.message = "readonly".into();
279                    }
280                    "noro" | "noreadonly" => {
281                        if self.remote_file().is_some() && !self.remote_edit_authorized() {
282                            self.message =
283                                "remote file is read-only; use :remote edit first".into();
284                        } else {
285                            self.buf_mut().readonly = false;
286                            self.message = "writable".into();
287                        }
288                    }
289                    _ => self.message = format!("unknown option: {arg}"),
290                }
291            }
292            "view" => {
293                // vim view: edit readonly — no arg marks the current
294                // buffer readonly
295                if arg.is_empty() {
296                    self.buf_mut().readonly = true;
297                    self.message = "readonly".into();
298                } else {
299                    self.request_user_open(
300                        arg,
301                        super::super::io::OpenIntent::Switch { readonly: true },
302                    );
303                }
304            }
305            "q" => {
306                self.close_pane_or_buffer(false);
307            }
308            "q!" => {
309                self.close_pane_or_buffer(true);
310            }
311            "qa" | "qall" => self.quit_all(false),
312            "qa!" | "qall!" => self.quit_all(true),
313            _ if cmdline.starts_with("s/") => {
314                // :s without a range = the current line (vim)
315                let line = self.buf().line_of(self.head());
316                self.substitute_range(line, line, &cmdline[2..]);
317            }
318            "trust" => self.request_trust(),
319            "noh" => {
320                // nohlsearch: the persistent highlight drops (0001 §5.8)
321                self.last_search = None;
322            }
323            _ if cmdline.bytes().all(|b| b.is_ascii_digit()) && !cmdline.is_empty() => {
324                // :30 jumps to line 30 (vim); past EOF clamps to the last
325                // content line, never the phantom past a trailing newline
326                let n: usize = cmdline.parse().unwrap_or(1);
327                let mut last = self.buf().len_lines().saturating_sub(1);
328                if self.buf().line_start(last) >= self.buf().len_bytes() {
329                    last = last.saturating_sub(1);
330                }
331                self.push_jump(); // :N is a jump — record before moving
332                self.set_head(self.buf().line_start(n.saturating_sub(1).min(last)));
333                self.clamp_cursor();
334            }
335            "vs" | "vsplit" => self.split(true, if arg.is_empty() { None } else { Some(arg) }),
336            "sp" | "split" => self.split(false, if arg.is_empty() { None } else { Some(arg) }),
337            "help" | "h" => self.open_help(),
338            "jumps" => self.open_jumps_picker(),
339            "symbols" => self.lsp_document_symbols_pub(),
340            "explain" => self.open_explain(),
341            "containers" => self.request_containers(),
342            "format" => self.lsp_format(),
343            "rename" => {
344                if arg.is_empty() {
345                    self.message = ":rename needs a new name".into();
346                } else {
347                    self.lsp_rename(arg);
348                }
349            }
350            "undo-change" => self.undo_last_change(),
351            "e" | "e!" => {
352                if arg.is_empty() && cmd == "e!" && self.refresh_remote() {
353                    return;
354                }
355                if arg.is_empty() {
356                    self.message = ":e needs a path".into();
357                } else if self.buf().dirty && cmd == "e" {
358                    self.message = "unsaved changes — :e! to force".into();
359                } else {
360                    self.request_user_open(
361                        arg,
362                        super::super::io::OpenIntent::Switch { readonly: false },
363                    );
364                }
365            }
366            other => self.message = format!("unknown ex: :{other}"),
367        }
368    }
369}