From 3e05a515a4c4db949859a880a540a11e593e5a9b Mon Sep 17 00:00:00 2001 From: garvitrakhecha Date: Sun, 29 Nov 2026 21:54:58 +0530 Subject: [PATCH 1/2] fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632) --- crates/engine/src/session/cmdline.rs | 133 ++++++++++++++++++++------- crates/ui-egui/src/cmdline.rs | 82 ++++++++++++++++- docs/autolisp.md | 10 +- 3 files changed, 187 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 695616a6f..6874cc16a 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -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,95 @@ 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 block 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> { + 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; + } + } + } + '"' => 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 2)")); + assert!(!s.space_is_text("!x")); + assert!(!s.space_is_text("line")); + assert_eq!(next_token("(+ 1 ;| ) |; 2) rest"), ("(+ 1 ;| ) |; 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(); } } diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 501307993..c08c4e236 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -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,80 @@ 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) { + 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 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"); + } +} diff --git a/docs/autolisp.md b/docs/autolisp.md index 46ef99565..7fe4fd771 100644 --- a/docs/autolisp.md +++ b/docs/autolisp.md @@ -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 From a323e94b698122592129368c463df5df1ef89fc1 Mon Sep 17 00:00:00 2001 From: garvitrakhecha Date: Mon, 30 Nov 2026 15:50:07 +0530 Subject: [PATCH 2/2] fix(cmdline): insert spaces inside unclosed AutoLISP expressions (#3632) --- crates/engine/src/session/cmdline.rs | 12 +++++++++++- crates/ui-egui/src/cmdline.rs | 5 +++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/session/cmdline.rs b/crates/engine/src/session/cmdline.rs index 6874cc16a..f8e1cd274 100644 --- a/crates/engine/src/session/cmdline.rs +++ b/crates/engine/src/session/cmdline.rs @@ -228,7 +228,7 @@ 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, quoted strings and block comments +/// a LISP expression runs to its closing parenthesis (spaces, quoted strings and comments /// inside it). fn next_token(rest: &str) -> (&str, Option<&str>) { match lisp_token_end(rest) { @@ -278,6 +278,13 @@ fn lisp_token_end(rest: &str) -> Option> { } } } + ';' => { + for (_, lc) in chars.by_ref() { + if lc == '\n' { + break; + } + } + } '"' => in_str = true, '(' => depth += 1, ')' => { @@ -304,10 +311,13 @@ mod tests { 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")); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index c08c4e236..388910153 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -1429,6 +1429,11 @@ mod lisp_space_tests { }); 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");