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|/edit|/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|self|nodes|fn|break|continue|include|true|false|None|match|import|module|do|var|macro|quote|unquote)\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 =
55 r"(\/\/=|<<|>>|\|\||\?\?|<=|>=|==|!=|=~|&&|\+=|-=|\*=|\/=|\|=|=|\||:|;|\?|!|\+|-|\*|\/|%|<|>|@)";
56 if let Ok(re) = regex_lite::Regex::new(operators_pattern) {
57 result = re
58 .replace_all(&result, |caps: ®ex_lite::Captures| {
59 caps[0].bright_yellow().to_string()
60 })
61 .to_string();
62 }
63
64 Cow::Owned(result)
65}
66
67fn get_prompt() -> &'static str {
69 if is_char_available() { "❯ " } else { "> " }
70}
71
72fn is_char_available() -> bool {
74 if let Ok(term) = std::env::var("TERM") {
76 if term.contains("xterm") || term.contains("screen") || term.contains("tmux") {
78 return true;
79 }
80 }
81
82 if let Ok(lang) = std::env::var("LANG")
84 && (lang.to_lowercase().contains("utf-8") || lang.to_lowercase().contains("utf8"))
85 {
86 return true;
87 }
88
89 for var in ["LC_ALL", "LC_CTYPE"] {
91 if let Ok(locale) = std::env::var(var)
92 && (locale.to_lowercase().contains("utf-8") || locale.to_lowercase().contains("utf8"))
93 {
94 return true;
95 }
96 }
97
98 false
100}
101
102pub struct MqLineHelper {
103 command_context: Rc<RefCell<CommandContext>>,
104 file_completer: FilenameCompleter,
105}
106
107impl MqLineHelper {
108 pub fn new(command_context: Rc<RefCell<CommandContext>>) -> Self {
109 Self {
110 command_context,
111 file_completer: FilenameCompleter::new(),
112 }
113 }
114}
115
116impl Hinter for MqLineHelper {
117 type Hint = String;
118}
119
120impl Highlighter for MqLineHelper {
121 fn highlight_prompt<'b, 's: 'b, 'p: 'b>(&'s self, prompt: &'p str, _default: bool) -> Cow<'b, str> {
122 prompt.cyan().to_string().into()
123 }
124
125 fn highlight_char(&self, _line: &str, _pos: usize, _kind: CmdKind) -> bool {
126 true
127 }
128
129 fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
130 highlight_mq_syntax(line)
131 }
132}
133
134impl Validator for MqLineHelper {
135 fn validate(&self, ctx: &mut ValidationContext<'_>) -> Result<ValidationResult, ReadlineError> {
136 let input = ctx.input();
137 if input.is_empty() || input.ends_with("\n") || input.starts_with("/") {
138 return Ok(ValidationResult::Valid(None));
139 }
140
141 if mq_lang::parse_recovery(input).1.has_errors() {
142 Ok(ValidationResult::Incomplete)
143 } else {
144 Ok(ValidationResult::Valid(None))
145 }
146 }
147
148 fn validate_while_typing(&self) -> bool {
149 false
150 }
151}
152
153impl Completer for MqLineHelper {
154 type Candidate = Pair;
155
156 fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Result<(usize, Vec<Pair>), ReadlineError> {
157 let (start, matches) = self.command_context.borrow().completions(line, pos);
158
159 let mut completions = matches
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((start, completions))
173 }
174}
175
176impl Helper for MqLineHelper {}
177
178pub struct Repl {
179 command_context: Rc<RefCell<CommandContext>>,
180}
181
182pub fn config_dir() -> Option<std::path::PathBuf> {
183 std::env::var_os("MQ_CONFIG_DIR")
184 .map(std::path::PathBuf::from)
185 .or_else(|| dirs::config_dir().map(|d| d.join("mq")))
186}
187
188impl Repl {
189 pub fn new(input: Vec<mq_lang::RuntimeValue>) -> Self {
190 let mut engine = mq_lang::DefaultEngine::default();
191
192 engine.load_builtin_module();
193
194 Self {
195 command_context: Rc::new(RefCell::new(CommandContext::new(engine, input))),
196 }
197 }
198
199 fn print_welcome() {
200 println!();
201 println!(
202 " {}",
203 "mq - A jq-like command-line tool for Markdown processing".bright_cyan()
204 );
205 println!();
206 println!(" Welcome to mq. Start by typing commands or expressions.");
207 println!(" Type {} to see available commands.", "/help".bright_cyan());
208 println!();
209 }
210
211 pub fn run(&self) -> miette::Result<()> {
212 let config = Config::builder()
213 .history_ignore_space(true)
214 .completion_type(CompletionType::List)
215 .edit_mode(EditMode::Emacs)
216 .color_mode(rustyline::ColorMode::Enabled)
217 .build();
218 let mut editor = Editor::with_config(config).into_diagnostic()?;
219 let helper = MqLineHelper::new(Rc::clone(&self.command_context));
220
221 editor.set_helper(Some(helper));
222 editor.bind_sequence(
223 KeyEvent(KeyCode::Left, Modifiers::CTRL),
224 Cmd::Move(Movement::BackwardWord(1, Word::Big)),
225 );
226 editor.bind_sequence(
227 KeyEvent(KeyCode::Right, Modifiers::CTRL),
228 Cmd::Move(Movement::ForwardWord(1, At::AfterEnd, Word::Big)),
229 );
230 editor.bind_sequence(
232 KeyEvent(KeyCode::Char('c'), Modifiers::ALT),
233 Cmd::Kill(Movement::WholeBuffer),
234 );
235 editor.bind_sequence(
237 KeyEvent(KeyCode::Char('o'), Modifiers::ALT),
238 Cmd::Insert(1, "/edit\n".to_string()),
239 );
240
241 let config_dir = config_dir();
242
243 if let Some(config_dir) = &config_dir {
244 let history = config_dir.join("history.txt");
245 fs::create_dir_all(config_dir).ok();
246 if editor.load_history(&history).is_err() {
247 println!("No previous history.");
248 }
249 }
250
251 Self::print_welcome();
252
253 loop {
254 let prompt = format!("{}", get_prompt().cyan());
255 let readline = editor.readline(&prompt);
256
257 match readline {
258 Ok(line) => {
259 editor.add_history_entry(&line).unwrap();
260
261 match self.command_context.borrow_mut().execute(&line) {
262 Ok(CommandOutput::String(s)) => println!("{}", s.join("\n")),
263 Ok(CommandOutput::Value(runtime_values)) => {
264 let lines = runtime_values
265 .iter()
266 .filter_map(|runtime_value| {
267 if runtime_value.is_none() {
268 return Some("None".to_string());
269 }
270
271 let s = runtime_value.to_string();
272 if s.is_empty() { None } else { Some(s) }
273 })
274 .collect::<Vec<_>>();
275
276 if !lines.is_empty() {
277 println!("{}", lines.join("\n"))
278 }
279 }
280 Ok(CommandOutput::None) => (),
281 Err(e) => {
282 eprintln!("{:?}", e)
283 }
284 }
285 }
286 Err(ReadlineError::Interrupted) => {
287 continue;
288 }
289 Err(ReadlineError::Eof) => {
290 break;
291 }
292 Err(err) => {
293 eprintln!("Error: {:?}", err);
294 break;
295 }
296 }
297
298 if let Some(config_dir) = &config_dir {
299 let history = config_dir.join("history.txt");
300 editor.save_history(&history.to_string_lossy().to_string()).unwrap();
301 }
302 }
303
304 Ok(())
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 #[test]
313 fn test_config_dir() {
314 unsafe { std::env::set_var("MQ_CONFIG_DIR", "/tmp/test_mq_config") };
315 assert_eq!(config_dir(), Some(std::path::PathBuf::from("/tmp/test_mq_config")));
316
317 unsafe { std::env::remove_var("MQ_CONFIG_DIR") };
318 let config_dir = config_dir();
319 assert!(config_dir.is_some());
320 if let Some(dir) = config_dir {
321 assert!(dir.ends_with("mq"));
322 }
323 }
324
325 #[test]
326 fn test_highlight_mq_syntax() {
327 let result = highlight_mq_syntax("let x = 42");
329 assert!(result.contains("let"));
330
331 let result = highlight_mq_syntax("/help");
333 assert!(result.contains("help"));
334
335 let result = highlight_mq_syntax("x = 1 + 2");
337 assert!(result.contains("="));
338 assert!(result.contains("+"));
339
340 let result = highlight_mq_syntax(r#""hello world""#);
342 assert!(result.contains("hello world"));
343
344 let result = highlight_mq_syntax("42");
346 assert!(result.contains("42"));
347 }
348
349 #[test]
350 fn test_is_char_available_utf8_env() {
351 let orig_term = std::env::var("TERM").ok();
353 let orig_lang = std::env::var("LANG").ok();
354 let orig_lc_all = std::env::var("LC_ALL").ok();
355 let orig_lc_ctype = std::env::var("LC_CTYPE").ok();
356
357 unsafe { std::env::set_var("TERM", "xterm-256color") };
359 assert!(is_char_available());
360
361 unsafe { std::env::remove_var("TERM") };
363 unsafe { std::env::set_var("LANG", "en_US.UTF-8") };
364 assert!(is_char_available());
365
366 unsafe { std::env::remove_var("LANG") };
368 unsafe { std::env::set_var("LC_ALL", "ja_JP.utf8") };
369 assert!(is_char_available());
370
371 unsafe { std::env::remove_var("LC_ALL") };
373 unsafe { std::env::set_var("LC_CTYPE", "fr_FR.UTF-8") };
374 assert!(is_char_available());
375
376 unsafe { std::env::remove_var("LC_CTYPE") };
378 assert!(!is_char_available());
379
380 if let Some(val) = orig_term {
382 unsafe { std::env::set_var("TERM", val) };
383 } else {
384 unsafe { std::env::remove_var("TERM") };
385 }
386 if let Some(val) = orig_lang {
387 unsafe { std::env::set_var("LANG", val) };
388 } else {
389 unsafe { std::env::remove_var("LANG") };
390 }
391 if let Some(val) = orig_lc_all {
392 unsafe { std::env::set_var("LC_ALL", val) };
393 } else {
394 unsafe { std::env::remove_var("LC_ALL") };
395 }
396 if let Some(val) = orig_lc_ctype {
397 unsafe { std::env::set_var("LC_CTYPE", val) };
398 } else {
399 unsafe { std::env::remove_var("LC_CTYPE") };
400 }
401 }
402}