input.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. use std::borrow::Cow;
  2. use std::cell::RefCell;
  3. use std::io::{self, IsTerminal, Write};
  4. use rustyline::completion::{Completer, Pair};
  5. use rustyline::error::ReadlineError;
  6. use rustyline::highlight::{CmdKind, Highlighter};
  7. use rustyline::hint::Hinter;
  8. use rustyline::history::DefaultHistory;
  9. use rustyline::validate::Validator;
  10. use rustyline::{
  11. Cmd, CompletionType, Config, Context, EditMode, Editor, Helper, KeyCode, KeyEvent, Modifiers,
  12. };
  13. #[derive(Debug, Clone, PartialEq, Eq)]
  14. pub enum ReadOutcome {
  15. Submit(String),
  16. Cancel,
  17. Exit,
  18. }
  19. struct SlashCommandHelper {
  20. completions: Vec<String>,
  21. current_line: RefCell<String>,
  22. }
  23. impl SlashCommandHelper {
  24. fn new(completions: Vec<String>) -> Self {
  25. Self {
  26. completions,
  27. current_line: RefCell::new(String::new()),
  28. }
  29. }
  30. fn reset_current_line(&self) {
  31. self.current_line.borrow_mut().clear();
  32. }
  33. fn current_line(&self) -> String {
  34. self.current_line.borrow().clone()
  35. }
  36. fn set_current_line(&self, line: &str) {
  37. let mut current = self.current_line.borrow_mut();
  38. current.clear();
  39. current.push_str(line);
  40. }
  41. }
  42. impl Completer for SlashCommandHelper {
  43. type Candidate = Pair;
  44. fn complete(
  45. &self,
  46. line: &str,
  47. pos: usize,
  48. _ctx: &Context<'_>,
  49. ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
  50. let Some(prefix) = slash_command_prefix(line, pos) else {
  51. return Ok((0, Vec::new()));
  52. };
  53. let matches = self
  54. .completions
  55. .iter()
  56. .filter(|candidate| candidate.starts_with(prefix))
  57. .map(|candidate| Pair {
  58. display: candidate.clone(),
  59. replacement: candidate.clone(),
  60. })
  61. .collect();
  62. Ok((0, matches))
  63. }
  64. }
  65. impl Hinter for SlashCommandHelper {
  66. type Hint = String;
  67. }
  68. impl Highlighter for SlashCommandHelper {
  69. fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
  70. self.set_current_line(line);
  71. Cow::Borrowed(line)
  72. }
  73. fn highlight_char(&self, line: &str, _pos: usize, _kind: CmdKind) -> bool {
  74. self.set_current_line(line);
  75. false
  76. }
  77. }
  78. impl Validator for SlashCommandHelper {}
  79. impl Helper for SlashCommandHelper {}
  80. pub struct LineEditor {
  81. prompt: String,
  82. editor: Editor<SlashCommandHelper, DefaultHistory>,
  83. }
  84. impl LineEditor {
  85. #[must_use]
  86. pub fn new(prompt: impl Into<String>, completions: Vec<String>) -> Self {
  87. let config = Config::builder()
  88. .completion_type(CompletionType::List)
  89. .edit_mode(EditMode::Emacs)
  90. .build();
  91. let mut editor = Editor::<SlashCommandHelper, DefaultHistory>::with_config(config)
  92. .expect("rustyline editor should initialize");
  93. editor.set_helper(Some(SlashCommandHelper::new(completions)));
  94. editor.bind_sequence(KeyEvent(KeyCode::Char('J'), Modifiers::CTRL), Cmd::Newline);
  95. editor.bind_sequence(KeyEvent(KeyCode::Enter, Modifiers::SHIFT), Cmd::Newline);
  96. Self {
  97. prompt: prompt.into(),
  98. editor,
  99. }
  100. }
  101. pub fn push_history(&mut self, entry: impl Into<String>) {
  102. let entry = entry.into();
  103. if entry.trim().is_empty() {
  104. return;
  105. }
  106. let _ = self.editor.add_history_entry(entry);
  107. }
  108. pub fn read_line(&mut self) -> io::Result<ReadOutcome> {
  109. if !io::stdin().is_terminal() || !io::stdout().is_terminal() {
  110. return self.read_line_fallback();
  111. }
  112. if let Some(helper) = self.editor.helper_mut() {
  113. helper.reset_current_line();
  114. }
  115. match self.editor.readline(&self.prompt) {
  116. Ok(line) => Ok(ReadOutcome::Submit(line)),
  117. Err(ReadlineError::Interrupted) => {
  118. let has_input = !self.current_line().is_empty();
  119. self.finish_interrupted_read()?;
  120. if has_input {
  121. Ok(ReadOutcome::Cancel)
  122. } else {
  123. Ok(ReadOutcome::Exit)
  124. }
  125. }
  126. Err(ReadlineError::Eof) => {
  127. self.finish_interrupted_read()?;
  128. Ok(ReadOutcome::Exit)
  129. }
  130. Err(error) => Err(io::Error::other(error)),
  131. }
  132. }
  133. fn current_line(&self) -> String {
  134. self.editor
  135. .helper()
  136. .map_or_else(String::new, SlashCommandHelper::current_line)
  137. }
  138. fn finish_interrupted_read(&mut self) -> io::Result<()> {
  139. if let Some(helper) = self.editor.helper_mut() {
  140. helper.reset_current_line();
  141. }
  142. let mut stdout = io::stdout();
  143. writeln!(stdout)
  144. }
  145. fn read_line_fallback(&self) -> io::Result<ReadOutcome> {
  146. let mut stdout = io::stdout();
  147. write!(stdout, "{}", self.prompt)?;
  148. stdout.flush()?;
  149. let mut buffer = String::new();
  150. let bytes_read = io::stdin().read_line(&mut buffer)?;
  151. if bytes_read == 0 {
  152. return Ok(ReadOutcome::Exit);
  153. }
  154. while matches!(buffer.chars().last(), Some('\n' | '\r')) {
  155. buffer.pop();
  156. }
  157. Ok(ReadOutcome::Submit(buffer))
  158. }
  159. }
  160. fn slash_command_prefix(line: &str, pos: usize) -> Option<&str> {
  161. if pos != line.len() {
  162. return None;
  163. }
  164. let prefix = &line[..pos];
  165. if prefix.contains(char::is_whitespace) || !prefix.starts_with('/') {
  166. return None;
  167. }
  168. Some(prefix)
  169. }
  170. #[cfg(test)]
  171. mod tests {
  172. use super::{slash_command_prefix, LineEditor, SlashCommandHelper};
  173. use rustyline::completion::Completer;
  174. use rustyline::highlight::Highlighter;
  175. use rustyline::history::{DefaultHistory, History};
  176. use rustyline::Context;
  177. #[test]
  178. fn extracts_only_terminal_slash_command_prefixes() {
  179. assert_eq!(slash_command_prefix("/he", 3), Some("/he"));
  180. assert_eq!(slash_command_prefix("/help me", 5), None);
  181. assert_eq!(slash_command_prefix("hello", 5), None);
  182. assert_eq!(slash_command_prefix("/help", 2), None);
  183. }
  184. #[test]
  185. fn completes_matching_slash_commands() {
  186. let helper = SlashCommandHelper::new(vec![
  187. "/help".to_string(),
  188. "/hello".to_string(),
  189. "/status".to_string(),
  190. ]);
  191. let history = DefaultHistory::new();
  192. let ctx = Context::new(&history);
  193. let (start, matches) = helper
  194. .complete("/he", 3, &ctx)
  195. .expect("completion should work");
  196. assert_eq!(start, 0);
  197. assert_eq!(
  198. matches
  199. .into_iter()
  200. .map(|candidate| candidate.replacement)
  201. .collect::<Vec<_>>(),
  202. vec!["/help".to_string(), "/hello".to_string()]
  203. );
  204. }
  205. #[test]
  206. fn ignores_non_slash_command_completion_requests() {
  207. let helper = SlashCommandHelper::new(vec!["/help".to_string()]);
  208. let history = DefaultHistory::new();
  209. let ctx = Context::new(&history);
  210. let (_, matches) = helper
  211. .complete("hello", 5, &ctx)
  212. .expect("completion should work");
  213. assert!(matches.is_empty());
  214. }
  215. #[test]
  216. fn tracks_current_buffer_through_highlighter() {
  217. let helper = SlashCommandHelper::new(Vec::new());
  218. let _ = helper.highlight("draft", 5);
  219. assert_eq!(helper.current_line(), "draft");
  220. }
  221. #[test]
  222. fn push_history_ignores_blank_entries() {
  223. let mut editor = LineEditor::new("> ", vec!["/help".to_string()]);
  224. editor.push_history(" ");
  225. editor.push_history("/help");
  226. assert_eq!(editor.editor.history().len(), 1);
  227. }
  228. }