Merge #3646: fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632)

This commit is contained in:
Tanish Manku
2026-11-30 13:24:34 -07:00
3 changed files with 202 additions and 38 deletions
+111 -32
View File
@@ -16,6 +16,21 @@ impl Session {
self.input_line(t, false)
}
/// Whether Space with `typed` on the command line types a space instead of submitting: at a
/// free-text prompt, or inside an unclosed parenthesised LISP expression where the command
/// line evaluates one.
pub fn space_is_text(&self, typed: &str) -> bool {
if self.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point && !p.accept.number) {
return true;
}
let accepts_lisp = match self.current_prompt() {
None => self.lisp_prompt().is_none(),
Some(p) => !p.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo(),
};
let rest = if self.running.is_none() { typed.trim_start() } else { typed };
accepts_lisp && matches!(lisp_token_end(rest), Some(None))
}
/// One line of input: each space ends an input and an empty input (two spaces in a row, a
/// trailing space, an empty line) is Enter, which at `Command:` repeats the last command. In a
/// script, a free-text prompt (TEXT/MTEXT contents) takes the rest of the line, a prompt with
@@ -213,41 +228,105 @@ fn lisp_expression(t: &str) -> bool {
}
/// The next command-line input in `rest` and what follows it: up to a space or tab, except that
/// a LISP expression runs to its closing parenthesis (spaces and quoted strings inside it).
/// a LISP expression runs to its closing parenthesis (spaces, quoted strings and comments
/// inside it).
fn next_token(rest: &str) -> (&str, Option<&str>) {
let lead = rest.len() - rest.trim_start_matches('!').len();
if rest.get(lead..).is_some_and(|r| r.starts_with('(')) {
let (mut depth, mut in_str, mut escaped) = (0i32, false, false);
for (i, c) in rest.char_indices().skip(lead) {
if in_str {
match (escaped, c) {
(true, _) => escaped = false,
(false, '\\') => escaped = true,
(false, '"') => in_str = false,
_ => {}
}
continue;
}
match c {
'"' => in_str = true,
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
let end = i + 1;
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
return (&rest[..end], more);
}
}
_ => {}
}
match lisp_token_end(rest) {
Some(Some(end)) => {
// As after any input, a space ends it and a trailing one is Enter.
let more = rest.get(end..).filter(|m| !m.is_empty()).map(|m| m.strip_prefix([' ', '\t']).unwrap_or(m));
(&rest[..end], more)
}
// Unbalanced: all of it (the reader reports the error).
return (rest, None);
Some(None) => (rest, None),
None => match rest.split_once([' ', '\t']) {
Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
},
}
match rest.split_once([' ', '\t']) {
Some((tok, more)) => (tok, Some(more)),
None => (rest, None),
}
/// For `rest` starting a parenthesised LISP form (`(…` or `!(…`), the byte offset past its
/// matching `)`, or `Some(None)` while it is still open; `None` when `rest` is not one.
fn lisp_token_end(rest: &str) -> Option<Option<usize>> {
let lead = rest.len() - rest.trim_start_matches('!').len();
let body = rest.get(lead..)?;
if !body.starts_with('(') {
return None;
}
let mut depth = 0i32;
let mut in_str = false;
let mut chars = body.char_indices().peekable();
while let Some((i, c)) = chars.next() {
if in_str {
match c {
'\\' => {
chars.next();
}
'"' => in_str = false,
_ => {}
}
continue;
}
match c {
';' if chars.peek().is_some_and(|(_, n)| *n == '|') => {
chars.next();
while let Some((_, bc)) = chars.next() {
if bc == '|' && chars.peek().is_some_and(|(_, n)| *n == ';') {
chars.next();
break;
}
}
}
';' => {
for (_, lc) in chars.by_ref() {
if lc == '\n' {
break;
}
}
}
'"' => in_str = true,
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(Some(lead + i + 1));
}
}
_ => {}
}
}
Some(None)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn open_lisp_forms_treat_space_as_text_only_where_lisp_evaluates() {
let mut s = Session::new();
assert!(s.space_is_text("(+ 1"));
assert!(s.space_is_text(" (+ 1"));
assert!(s.space_is_text("!(+ 1"));
assert!(s.space_is_text("(princ \"a ) b\""));
assert!(s.space_is_text("(princ ;| ) |; 1"));
assert!(s.space_is_text("(+ 1 ; )"));
assert!(!s.space_is_text("(+ 1 ; )\n 2)"));
assert!(!s.space_is_text("(+ 1 2)"));
assert!(!s.space_is_text("!x"));
assert!(!s.space_is_text("line"));
assert_eq!(next_token("(+ 1 ;| ) |; 2) rest"), ("(+ 1 ;| ) |; 2)", Some("rest")));
assert_eq!(next_token("(+ 1 ; )\n 2) rest"), ("(+ 1 ; )\n 2)", Some("rest")));
s.cmdline("circle").unwrap();
assert!(s.space_is_text("(list 1"));
assert!(!s.space_is_text("(list 1 2)"));
s.cancel();
// Prompts inside a waiting LISP routine (`getpoint`) do not evaluate LISP expressions.
s.cmdline("(getpoint)").unwrap();
assert!(!s.space_is_text("(+ 1"));
s.cancel();
}
}
+85 -2
View File
@@ -379,9 +379,10 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
options_still_fit(app);
for ev in events {
app.cmd.forget_stale_first(dyn_frame(app).is_some());
let space_is_text = app.session.space_is_text(&app.cmd.buffer);
// The options menu takes the arrows, Enter and Escape; typing closes it.
if app.cmd.options.is_some() {
let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !text_prompt;
let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !space_is_text;
match &ev {
_ if space => {
if let Some(k) = app.cmd.options.as_ref().and_then(|m| m.current()).map(str::to_owned) {
@@ -412,7 +413,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
}
match ev {
egui::Event::Text(t) => {
if t == " " && !text_prompt {
if t == " " && !space_is_text {
submit(app);
} else {
app.cmd.preedit.clear();
@@ -1356,3 +1357,85 @@ mod dyn_tab_tests {
assert!(!app.cmd.first_active());
}
}
#[cfg(test)]
mod lisp_space_tests {
use super::*;
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec2;
fn run_frame(app: &mut CadApp, ctx: &egui::Context, events: Vec<egui::Event>) {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
}
#[test]
fn space_types_inside_an_open_lisp_expression_and_submits_once_closed() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
run_frame(&mut app, &ctx, Vec::new());
let send = |app: &mut CadApp, text: &str| {
let mut events = Vec::new();
for c in text.chars() {
if c == ' ' {
events.push(egui::Event::Key {
key: egui::Key::Space,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
});
}
events.push(egui::Event::Text(c.to_string()));
}
run_frame(app, &ctx, events);
};
// Nested forms, an escaped quote, a `)` inside a string and a `;| ... |;` block comment
// stay open across spaces; once the outer `)` closes the form, Space evaluates it.
send(&mut app, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))");
assert_eq!(app.cmd.buffer, "(defun c:greet () (princ \"hi \\\" ) there\") ;| ) |; (princ))");
send(&mut app, " ");
assert!(app.cmd.buffer.is_empty());
send(&mut app, "greet ");
assert_eq!(app.session.log.last().map(String::as_str), Some("hi \" ) there"));
// At point and number prompts (including with the Dynamic Input options menu open),
// spaces stay inside `(...)` and Space after `)` answers the prompt.
send(&mut app, "(setq r 5) ");
send(&mut app, "circle ");
run_frame(
&mut app,
&ctx,
vec![egui::Event::Key { key: egui::Key::ArrowDown, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }],
);
assert!(app.cmd.options.is_some());
send(&mut app, "(list 3 4) (* 2 r) ");
assert!(app.session.running.is_none());
let circle = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind {
EntityKind::Circle(c) => Some((c.center.xy(), c.radius)),
_ => None,
});
assert_eq!(circle, Some((Vec2::new(3.0, 4.0), 10.0)));
// A `)` inside a `;` line comment does not close the form, so Space keeps typing text.
send(&mut app, "(+ 1 ; ) ");
assert_eq!(app.cmd.buffer, "(+ 1 ; ) ");
escape(&mut app);
// A free-text prompt still keeps spaces after a closing parenthesis as text.
send(&mut app, "-text 0,0 2.5 0 (3+4) 5");
assert_eq!(app.cmd.buffer, "(3+4) 5");
}
}
+6 -4
View File
@@ -17,10 +17,12 @@ CADCraft runs AutoLISP routines (`.lsp` files). What is here and what is not yet
- **`(defun c:NAME …)`** defines a command: type `NAME` at the command line. Built-in commands
keep their names.
- **At the command line**, `(expression)` evaluates and shows the value, and `!variable` shows a
variable. Typed at a command's prompt (not a free-text one), an expression's value answers it:
`CIRCLE 0,0 (* 2 r)`. The prompt waits for that value, so the window doesn't redraw and Esc
doesn't reach the expression until it ends: one that takes more than 20 million steps (its
callbacks included) stops with an error. Run long routines at `Command:` instead.
variable. Space types a space while a `(...)` expression is open, and Space or Enter after its
closing parenthesis evaluates it. Typed at a command's prompt (not a free-text one), an
expression's value answers it: `CIRCLE 0,0 (* 2 r)`. The prompt waits for that value, so the
window doesn't redraw and Esc doesn't reach the expression until it ends: one that takes more
than 20 million steps (its callbacks included) stops with an error. Run long routines at
`Command:` instead.
- **Programmatically** (scripts, the control channel, MCP, the CLI): `lisp {code, inputs?}` and
`appload {path} | {name, text | data}` run to the end and return `{value, output, error?}`.
`appload` also returns `commands`, the `c:` commands the file defined, and a JSON call never