1use colored::*;
2use miette::IntoDiagnostic;
3use rustyline::{
4 At, Cmd, CompletionType, Config, Context, EditMode, Editor, Helper, KeyCode, KeyEvent, Modifiers, Movement, Word,
5 completion::{Completer, FilenameCompleter, Pair},
6 error::ReadlineError,
7 highlight::{CmdKind, Highlighter},
8 hint::Hinter,
9 validate::{ValidationContext, ValidationResult, Validator},
10};
11use std::{borrow::Cow, cell::RefCell, fs, rc::Rc};
12
13use crate::command_context::{Command, CommandContext, CommandOutput};
14
15fn highlight_mq_syntax(line: &str) -> Cow<'_, str> {
17 let mut result = line.to_string();
18
19 let commands_pattern = r"^(/copy|/env|/help|/quit|/load|/vars|/version)\b";
20 if let Ok(re) = regex_lite::Regex::new(commands_pattern) {
21 result = re
22 .replace_all(&result, |caps: ®ex_lite::Captures| {
23 caps[0].bright_green().to_string()
24 })
25 .to_string();
26 }
27
28 let keywords_pattern = r"\b(def|let|if|elif|else|end|while|foreach|until|self|nodes|fn|break|continue|include|true|false|None|match|import|module|do)\b";
29 if let Ok(re) = regex_lite::Regex::new(keywords_pattern) {
30 result = re
31 .replace_all(&result, |caps: ®ex_lite::Captures| caps[0].bright_blue().to_string())
32 .to_string();
33 }
34
35 if let Ok(re) = regex_lite::Regex::new(r#""([^"\\]|\\.)*""#) {
37 result = re
38 .replace_all(&result, |caps: ®ex_lite::Captures| {
39 caps[0].bright_green().to_string()
40 })
41 .to_string();
42 }
43
44 if let Ok(re) = regex_lite::Regex::new(r"\b\d+\b") {
46 result = re
47 .replace_all(&result, |caps: ®ex_lite::Captures| {
48 caps[0].bright_magenta().to_string()
49 })
50 .to_string();
51 }
52
53 let operators_pattern = r"(->|<=|>=|==|!=|&&|[=|:;?!+\-*/%<>])";
55 if let Ok(re) = regex_lite::Regex::new(operators_pattern) {
56 result = re
57 .replace_all(&result, |caps: ®ex_lite::Captures| {
58 caps[0].bright_yellow().to_string()
59 })
60 .to_string();
61 }
62
63 Cow::Owned(result)
64}
65
66fn get_prompt() -> &'static str {
68 if is_char_available() { "❯ " } else { "> " }
69}
70
71fn is_char_available() -> bool {
73 if let Ok(term) = std::env::var("TERM") {
75 if term.contains("xterm") || term.contains("screen") || term.contains("tmux") {
77 return true;
78 }
79 }
80
81 if let Ok(lang) = std::env::var("LANG")
83 && (lang.to_lowercase().contains("utf-8") || lang.to_lowercase().contains("utf8"))
84 {
85 return true;
86 }
87
88 for var in ["LC_ALL", "LC_CTYPE"] {
90 if let Ok(locale) = std::env::var(var)
91 && (locale.to_lowercase().contains("utf-8") || locale.to_lowercase().contains("utf8"))
92 {
93 return true;
94 }
95 }
96
97 false
99}
100
101pub struct MqLineHelper {
102 command_context: Rc<RefCell<CommandContext>>,
103 file_completer: FilenameCompleter,
104}
105
106impl MqLineHelper {
107 pub fn new(command_context: Rc<RefCell<CommandContext>>) -> Self {
108 Self {
109 command_context,
110 file_completer: FilenameCompleter::new(),
111 }
112 }
113}
114
115impl Hinter for MqLineHelper {
116 type Hint = String;
117}
118
119impl Highlighter for MqLineHelper {
120 fn highlight_prompt<'b, 's: 'b, 'p: 'b>(&'s self, prompt: &'p str, _default: bool) -> Cow<'b, str> {
121 prompt.cyan().to_string().into()
122 }
123
124 fn highlight_char(&self, _line: &str, _pos: usize, _kind: CmdKind) -> bool {
125 true
126 }
127
128 fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
129 highlight_mq_syntax(line)
130 }
131}
132
133impl Validator for MqLineHelper {
134 fn validate(&self, ctx: &mut ValidationContext<'_>) -> Result<ValidationResult, ReadlineError> {
135 let input = ctx.input();
136 if input.is_empty() || input.ends_with("\n") || input.starts_with("/") {
137 return Ok(ValidationResult::Valid(None));
138 }
139
140 if mq_lang::parse_recovery(input).1.has_errors() {
141 Ok(ValidationResult::Incomplete)
142 } else {
143 Ok(ValidationResult::Valid(None))
144 }
145 }
146
147 fn validate_while_typing(&self) -> bool {
148 false
149 }
150}
151
152impl Completer for MqLineHelper {
153 type Candidate = Pair;
154
155 fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Result<(usize, Vec<Pair>), ReadlineError> {
156 let mut completions = self
157 .command_context
158 .borrow()
159 .completions(line, pos)
160 .iter()
161 .map(|cmd| Pair {
162 display: cmd.clone(),
163 replacement: format!("{}{}", cmd, &line[pos..]),
164 })
165 .collect::<Vec<_>>();
166
167 if line.starts_with(Command::LoadFile("".to_string()).to_string().as_str()) {
168 let (_, file_completions) = self.file_completer.complete_path(line, pos)?;
169 completions.extend(file_completions);
170 }
171
172 Ok((0, completions))
173 }
174}
175
176impl Helper for MqLineHelper {}
177
178pub struct Repl {
179 command_context: Rc<RefCell<CommandContext>>,
180}
181
182impl Repl {
183 pub fn new(input: Vec<mq_lang::RuntimeValue>) -> Self {
184 let mut engine = mq_lang::DefaultEngine::default();
185
186 engine.set_optimization_level(mq_lang::OptimizationLevel::None);
187 engine.load_builtin_module();
188
189 Self {
190 command_context: Rc::new(RefCell::new(CommandContext::new(engine, input))),
191 }
192 }
193
194 fn print_welcome() {
195 println!();
196 println!(
197 " {}",
198 "mq - A jq-like command-line tool for Markdown processing".bright_cyan()
199 );
200 println!();
201 println!(" Welcome to mq. Start by typing commands or expressions.");
202 println!(" Type {} to see available commands.", "/help".bright_cyan());
203 println!();
204 }
205
206 pub fn config_dir() -> Option<std::path::PathBuf> {
207 std::env::var_os("MDQ_CONFIG_DIR")
208 .map(std::path::PathBuf::from)
209 .or_else(|| dirs::config_dir().map(|d| d.join("mq")))
210 }
211
212 pub fn run(&self) -> miette::Result<()> {
213 let config = Config::builder()
214 .history_ignore_space(true)
215 .completion_type(CompletionType::List)
216 .edit_mode(EditMode::Emacs)
217 .color_mode(rustyline::ColorMode::Enabled)
218 .build();
219 let mut editor = Editor::with_config(config).into_diagnostic()?;
220 let helper = MqLineHelper::new(Rc::clone(&self.command_context));
221
222 editor.set_helper(Some(helper));
223 editor.bind_sequence(
224 KeyEvent(KeyCode::Left, Modifiers::CTRL),
225 Cmd::Move(Movement::BackwardWord(1, Word::Big)),
226 );
227 editor.bind_sequence(
228 KeyEvent(KeyCode::Right, Modifiers::CTRL),
229 Cmd::Move(Movement::ForwardWord(1, At::AfterEnd, Word::Big)),
230 );
231
232 let config_dir = Self::config_dir();
233
234 if let Some(config_dir) = &config_dir {
235 let history = config_dir.join("history.txt");
236 fs::create_dir_all(config_dir).ok();
237 if editor.load_history(&history).is_err() {
238 println!("No previous history.");
239 }
240 }
241
242 Self::print_welcome();
243
244 loop {
245 let prompt = format!("{}", get_prompt().cyan());
246 let readline = editor.readline(&prompt);
247
248 match readline {
249 Ok(line) => match self.command_context.borrow_mut().execute(&line) {
250 Ok(CommandOutput::String(s)) => println!("{}", s.join("\n")),
251 Ok(CommandOutput::Value(runtime_values)) => {
252 let lines = runtime_values
253 .iter()
254 .filter_map(|runtime_value| {
255 if runtime_value.is_none() {
256 return Some("None".to_string());
257 }
258
259 let s = runtime_value.to_string();
260 if s.is_empty() { None } else { Some(s) }
261 })
262 .collect::<Vec<_>>();
263
264 if !lines.is_empty() {
265 println!("{}", lines.join("\n"))
266 }
267
268 editor.add_history_entry(&line).unwrap();
269 }
270 Ok(CommandOutput::None) => (),
271 Err(e) => {
272 eprintln!("{:?}", e)
273 }
274 },
275 Err(ReadlineError::Interrupted) => {
276 continue;
277 }
278 Err(ReadlineError::Eof) => {
279 break;
280 }
281 Err(err) => {
282 eprintln!("Error: {:?}", err);
283 break;
284 }
285 }
286
287 if let Some(config_dir) = &config_dir {
288 let history = config_dir.join("history.txt");
289 editor.save_history(&history.to_string_lossy().to_string()).unwrap();
290 }
291 }
292
293 Ok(())
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 #[test]
302 fn test_config_dir() {
303 unsafe { std::env::set_var("MDQ_CONFIG_DIR", "/tmp/test_mq_config") };
304 let config_dir = Repl::config_dir();
305 assert_eq!(config_dir, Some(std::path::PathBuf::from("/tmp/test_mq_config")));
306
307 unsafe { std::env::remove_var("MDQ_CONFIG_DIR") };
308 let config_dir = Repl::config_dir();
309 assert!(config_dir.is_some());
310 if let Some(dir) = config_dir {
311 assert!(dir.ends_with("mq"));
312 }
313 }
314
315 #[test]
316 fn test_highlight_mq_syntax() {
317 let result = highlight_mq_syntax("let x = 42");
319 assert!(result.contains("let"));
320
321 let result = highlight_mq_syntax("/help");
323 assert!(result.contains("help"));
324
325 let result = highlight_mq_syntax("x = 1 + 2");
327 assert!(result.contains("="));
328 assert!(result.contains("+"));
329
330 let result = highlight_mq_syntax(r#""hello world""#);
332 assert!(result.contains("hello world"));
333
334 let result = highlight_mq_syntax("42");
336 assert!(result.contains("42"));
337 }
338
339 #[test]
340 fn test_is_char_available_utf8_env() {
341 let orig_term = std::env::var("TERM").ok();
343 let orig_lang = std::env::var("LANG").ok();
344 let orig_lc_all = std::env::var("LC_ALL").ok();
345 let orig_lc_ctype = std::env::var("LC_CTYPE").ok();
346
347 unsafe { std::env::set_var("TERM", "xterm-256color") };
349 assert!(is_char_available());
350
351 unsafe { std::env::remove_var("TERM") };
353 unsafe { std::env::set_var("LANG", "en_US.UTF-8") };
354 assert!(is_char_available());
355
356 unsafe { std::env::remove_var("LANG") };
358 unsafe { std::env::set_var("LC_ALL", "ja_JP.utf8") };
359 assert!(is_char_available());
360
361 unsafe { std::env::remove_var("LC_ALL") };
363 unsafe { std::env::set_var("LC_CTYPE", "fr_FR.UTF-8") };
364 assert!(is_char_available());
365
366 unsafe { std::env::remove_var("LC_CTYPE") };
368 assert!(!is_char_available());
369
370 if let Some(val) = orig_term {
372 unsafe { std::env::set_var("TERM", val) };
373 } else {
374 unsafe { std::env::remove_var("TERM") };
375 }
376 if let Some(val) = orig_lang {
377 unsafe { std::env::set_var("LANG", val) };
378 } else {
379 unsafe { std::env::remove_var("LANG") };
380 }
381 if let Some(val) = orig_lc_all {
382 unsafe { std::env::set_var("LC_ALL", val) };
383 } else {
384 unsafe { std::env::remove_var("LC_ALL") };
385 }
386 if let Some(val) = orig_lc_ctype {
387 unsafe { std::env::set_var("LC_CTYPE", val) };
388 } else {
389 unsafe { std::env::remove_var("LC_CTYPE") };
390 }
391 }
392}