From 2bff91db6f9f3f41dae0ad96be27aef22faf77cb Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Jun 2025 07:58:13 +0300 Subject: [PATCH 1/7] Initial implementation for command hinting and completion --- changelog.md | 4 ++ src/command_complete.rs | 112 ++++++++++++++++++++++++++++++++++++++++ src/config.rs | 13 +++++ src/main.rs | 4 +- 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 src/command_complete.rs diff --git a/changelog.md b/changelog.md index d69064d..57b02b6 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,9 @@ # Changelog +## Next release + +_Implement basic command completion with rustyline_ + ## 0.1.9 - 2025-06-12 _Add support for rustyline modes_ diff --git a/src/command_complete.rs b/src/command_complete.rs new file mode 100644 index 0000000..841df58 --- /dev/null +++ b/src/command_complete.rs @@ -0,0 +1,112 @@ +/* + * Copyright © 2025 Mitja Leino + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the “Software”), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS + * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +use rustyline::completion::{Completer, Pair}; +use rustyline::highlight::Highlighter; +use rustyline::hint::Hinter; +use rustyline::validate::{ValidationContext, ValidationResult, Validator}; +use rustyline::{Context, Helper}; +use std::borrow::Cow; + +pub(crate) struct CommandHelper { + commands: Vec, + file_commands: Vec, +} + +impl CommandHelper { + pub(crate) fn new(commands: Vec<&str>) -> Self { + CommandHelper { + commands: commands.iter().map(|s| s.to_string()).collect(), + file_commands: vec![], + } + } +} + +impl Completer for CommandHelper { + type Candidate = Pair; + + fn complete( + &self, + line: &str, + pos: usize, + _ctx: &Context<'_>, + ) -> rustyline::Result<(usize, Vec)> { + if line.starts_with(":") { + let parts: Vec<&str> = line.split(' ').collect(); + let command = parts[0]; + + if line.contains(" ") { + // Handle args + Ok((pos, vec![])) + } else { + // Handle command completion + let word_start = 1; + let word = &line[word_start..pos]; + + let matches: Vec = self + .commands + .iter() + .filter(|cmd| cmd.starts_with(word) && cmd.len() > word.len()) + .map(|cmd| Pair { + display: cmd.clone(), + replacement: cmd.clone(), + }) + .collect(); + + Ok((word_start, matches)) + } + } else { + Ok((pos, vec![])) + } + } +} + +impl Hinter for CommandHelper { + type Hint = String; + + fn hint(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Option { + // Simple hinting - can be expanded as needed + if line.starts_with(":") && !line.contains(" ") && pos == line.len() { + let command = &line[1..]; + // Only show hints at the end of the line + for cmd in &self.commands { + if cmd.starts_with(command) && cmd != command && cmd.len() > command.len() { + return Some((&cmd[command.len()..]).to_string()); + } + } + } + None + } +} + +impl Highlighter for CommandHelper { + fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> { + Cow::Borrowed(line) + } + + fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> { + Cow::Borrowed(hint) + } +} + +impl Validator for CommandHelper { + fn validate(&self, _ctx: &mut ValidationContext) -> rustyline::Result { + Ok(ValidationResult::Valid(None)) + } +} + +// This is the key trait that combines all the above functionality +impl Helper for CommandHelper {} diff --git a/src/config.rs b/src/config.rs index 92a940a..e0803df 100644 --- a/src/config.rs +++ b/src/config.rs @@ -15,6 +15,9 @@ * */ +use crate::command_complete::CommandHelper; +use rustyline::history::{DefaultHistory, FileHistory}; +use rustyline::Editor; use serde::Deserialize; use std::path::PathBuf; use std::{fs, io}; @@ -97,6 +100,16 @@ impl Config { } } + pub fn create_editor(&self) -> rustyline::Result> { + let config = self.create_rustyline_config(); + let commands = vec!["q", "help", "list", "switch", "edit"]; + let helper = CommandHelper::new(commands); + let mut editor = Editor::with_config(config)?; + editor.set_helper(Some(helper)); + + Ok(editor) + } + pub fn load() -> io::Result { let config_path = match get_config_path() { Ok(path) => path, diff --git a/src/main.rs b/src/main.rs index de4373f..ce45b7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,7 @@ * */ +mod command_complete; mod commands; mod config; mod history_file; @@ -85,8 +86,7 @@ fn main() -> io::Result<()> { "\nEnter your prompt or a command (type ':q' to end or ':help' for other commands)" ); - let rustyline_config = config.create_rustyline_config(); - let mut rl = match rustyline::DefaultEditor::with_config(rustyline_config) { + let mut rl = match config.create_editor() { Ok(r) => r, Err(e) => { eprintln!("Error initializing rustyline: {}", e); From ec43f7ba5fbc73e0d65fa805e082c4377c613846 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Jun 2025 08:03:59 +0300 Subject: [PATCH 2/7] Add sysprompt to commands --- src/config.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index e0803df..7d82e4e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -102,7 +102,7 @@ impl Config { pub fn create_editor(&self) -> rustyline::Result> { let config = self.create_rustyline_config(); - let commands = vec!["q", "help", "list", "switch", "edit"]; + let commands = vec!["q", "help", "list", "switch", "edit", "sysprompt"]; let helper = CommandHelper::new(commands); let mut editor = Editor::with_config(config)?; editor.set_helper(Some(helper)); From 9b2d17a0002e20775679393841cdf9783f3e34e3 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Jun 2025 08:20:38 +0300 Subject: [PATCH 3/7] Remove print about interrupting --- src/main.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index ce45b7f..ab9b27e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -77,7 +77,6 @@ fn main() -> io::Result<()> { println!("{}", history.get_content()); println!("You're conversing with {} model", &config.model); let mut ollama_client = OllamaClient::new(config.model.clone(), config.system_prompt.clone()); - println!("Press Enter during AI generation to interrupt the response."); // Main conversation loop loop { From cce8bcb3b3bc2bd0aea9f0f4fc20ee6ed97e6b13 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 13 Jun 2025 08:28:00 +0300 Subject: [PATCH 4/7] Rewrite the configuration documentation by showing a full toml --- readme.md | 40 ++++++++++++++-------------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/readme.md b/readme.md index 6d9680d..c1726d1 100644 --- a/readme.md +++ b/readme.md @@ -100,41 +100,29 @@ Update the system prompt for this session. Does not modify any configurations. You can configure your sllama by creating and modifying TOML configuration located at `~/.sllama.toml`/ `%USERPROFILE%\.sllama.toml`. -### Options - -#### rustyline - -##### mode - -Switch rustyline input mode between `Emacs` and `Vi`. - -Default: `Emacs` - -#### model - -Ollama model used +An example toml populated with the default values. -Default: `gemma3:12b` +```toml +# Ollama model used. +model = "gemma3:12b" -#### sllama_dir +# Path to the sllama directory. This will hold new history files by default. +# ~ is expanded to the user's home directory based on `$HOME` or `%USERPROFILE%`. (not verified on windows) +sllama_dir = "~/sllama" -Path to the sllama directory. This will hold new history files by default. - -Default: `~/sllama` - -#### system_prompt - -System prompt that configures the AI assistant's behavior. - -Default: - -``` +# System prompt that configures the AI assistant's behavior. +system_prompt = """ You are an AI assistant receiving input from a command-line application called silent-llama (sllama). The user may include additional context from another file. This supplementary content appears after the system prompt and before the history file content. Your responses are displayed in the terminal and saved to the history file. Keep your answers helpful, concise, and relevant to both the user's direct query and any file context provided. You can tell where you have previously responded by --- AI Response --- (added automatically). +""" + +[rustyline] +# Switch rustyline input mode between `Emacs` and `Vi`. +mode = "emacs" ``` ## TODO From 338c47188c0c74e81345578f38481e3779ded32f Mon Sep 17 00:00:00 2001 From: = Date: Sat, 14 Jun 2025 08:56:00 +0300 Subject: [PATCH 5/7] Add tests for command completion --- src/command_complete.rs | 166 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) diff --git a/src/command_complete.rs b/src/command_complete.rs index 841df58..cf0afeb 100644 --- a/src/command_complete.rs +++ b/src/command_complete.rs @@ -110,3 +110,169 @@ impl Validator for CommandHelper { // This is the key trait that combines all the above functionality impl Helper for CommandHelper {} + +#[cfg(test)] +mod tests { + use super::*; + use rustyline::history::DefaultHistory; + use rustyline::Context; + + #[test] + fn test_command_helper_new() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + + assert_eq!(helper.commands, vec!["help", "quit", "save"]); + assert!(helper.file_commands.is_empty()); + } + + #[test] + fn test_command_with_arguments() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let (pos, matches) = helper.complete(":save file.txt", 12, &ctx).unwrap(); + assert_eq!(pos, 12); + assert!(matches.is_empty()); + } + + #[test] + fn test_no_matches() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let (pos, matches) = helper.complete(":xyz", 4, &ctx).unwrap(); + assert_eq!(pos, 1); + assert!(matches.is_empty()); + } + + #[test] + fn test_complete_empty_line() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let (pos, matches) = helper.complete("", 0, &ctx).unwrap(); + assert_eq!(pos, 0); + assert!(matches.is_empty()); + } + + #[test] + fn test_complete_non_command_line() { + let commands = vec!["help", "quit", "save", "hey"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let (pos, matches) = helper.complete("Hey there", 0, &ctx).unwrap(); + assert_eq!(pos, 0); + assert!(matches.is_empty()); + } + + #[test] + fn test_hint_no_match() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let hint = helper.hint(":xyz", 4, &ctx); + assert_eq!(hint, None); + } + + #[test] + fn test_hint_with_space() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let hint = helper.hint(":help ", 6, &ctx); + assert_eq!(hint, None); + } + + #[test] + fn test_empty_commands_list() { + let helper = CommandHelper::new(vec![]); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + // Try to complete with an empty command list + let (pos, matches) = helper.complete(":h", 2, &ctx).unwrap(); + assert_eq!(pos, 1); + assert!(matches.is_empty()); + + // Try to get a hint with an empty command list + let hint = helper.hint(":h", 2, &ctx); + assert_eq!(hint, None); + } + + #[test] + fn test_complete_command() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + // Partial command + let (pos, matches) = helper.complete(":h", 2, &ctx).unwrap(); + assert_eq!(pos, 1); + assert_eq!(matches.len(), 1); + assert_eq!(matches[0].display, "help"); + + // Complete command + let (pos, matches) = helper.complete(":help", 5, &ctx).unwrap(); + assert_eq!(pos, 1); + assert!(matches.is_empty()); + } + + #[test] + fn multiple_matches() { + let commands = vec!["help", "quit", "switch", "sysprompt"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + let (pos, matches) = helper.complete(":s", 2, &ctx).unwrap(); + assert_eq!(pos, 1); + assert_eq!(matches.len(), 2); + + let match_strings: Vec = matches.iter().map(|m| m.display.clone()).collect(); + assert!(match_strings.contains(&"switch".to_string())); + assert!(match_strings.contains(&"sysprompt".to_string())); + } + + #[test] + fn test_hint() { + let commands = vec!["help", "quit", "save"]; + let helper = CommandHelper::new(commands); + let history = DefaultHistory::new(); + let ctx = Context::new(&history); + + // Partial command + let hint = helper.hint(":h", 2, &ctx); + assert_eq!(hint, Some("elp".to_string())); + + // Complete command + let hint = helper.hint(":help", 5, &ctx); + assert_eq!(hint, None); + } + + #[test] + fn test_highlighter() { + let helper = CommandHelper::new(vec!["help"]); + + // Test line highlighting (currently returns unchanged) + let highlighted = helper.highlight("test line", 4); + assert_eq!(highlighted, "test line"); + + // Test hint highlighting (currently returns unchanged) + let highlighted_hint = helper.highlight_hint("hint text"); + assert_eq!(highlighted_hint, "hint text"); + } +} From e1d1bd793bfa98f7aedf8aa8d61f01ef370ffe2d Mon Sep 17 00:00:00 2001 From: = Date: Sat, 14 Jun 2025 08:56:51 +0300 Subject: [PATCH 6/7] Update todo list --- readme.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index c1726d1..b907fee 100644 --- a/readme.md +++ b/readme.md @@ -130,7 +130,9 @@ mode = "emacs" - [x] Clarify how the prompt is formed - [x] Add a configuration file - [x] Integrate rustyline -- [ ] Implement completions with rustyline (commands and files) +- [ ] Implement completions with rustyline + - [x] Commands + - [ ] Files - [ ] Support multiline input with shift + enter (using rustyline) - [ ] Use `ollama server` and API calls instead - [ ] Allow changing the context file during a chat From 490220535c0db04d1a7dada013589a1a40323bec Mon Sep 17 00:00:00 2001 From: = Date: Sat, 14 Jun 2025 09:03:53 +0300 Subject: [PATCH 7/7] Increment version and add changelog --- Cargo.lock | 2 +- Cargo.toml | 2 +- changelog.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e322ee5..5044f46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -376,7 +376,7 @@ dependencies = [ [[package]] name = "sllama" -version = "0.1.9" +version = "0.1.10" dependencies = [ "clap", "rustyline", diff --git a/Cargo.toml b/Cargo.toml index 92dfe0c..c9a8597 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sllama" -version = "0.1.9" +version = "0.1.10" edition = "2024" [dependencies] diff --git a/changelog.md b/changelog.md index 57b02b6..cee881c 100644 --- a/changelog.md +++ b/changelog.md @@ -1,8 +1,8 @@ # Changelog -## Next release +## 0.1.10 - 2025-06-14 -_Implement basic command completion with rustyline_ +_Implement basic command completion and hinting with rustyline_ ## 0.1.9 - 2025-06-12