Lines
95.83 %
Functions
37.5 %
Branches
100 %
//! Command-line palette completion helpers.
use crate::app::App;
use crate::palette;
use crate::widgets::Editor;
use cli_core::{command_tree, complete};
/// Complete the trailing command-line token using the command tree, leaving
/// the cursor at the end of the rebuilt buffer.
///
/// With one candidate the token is replaced and a trailing space appended.
/// With multiple candidates the longest common prefix is applied and all
/// candidates are stored in `app.cmdline.completions` for display.
pub(super) fn apply_command_completion(app: &mut App) {
let buffer = app.cmdline.editor.buffer().to_string();
let tree = command_tree();
let candidates = complete(&tree, &buffer);
let lcp = palette::longest_common_prefix(&candidates);
let new_buffer = build_completed_buffer(&buffer, &candidates, &lcp);
if new_buffer != buffer {
app.cmdline.editor = Editor::with_buffer(app.edit_mode, new_buffer);
}
app.cmdline.completions = candidates;
fn build_completed_buffer(buffer: &str, candidates: &[String], lcp: &str) -> String {
if lcp.is_empty() {
buffer.to_string()
} else if candidates.len() == 1 {
format!("{} ", replace_last_token(buffer, lcp))
} else {
replace_last_token(buffer, lcp)
fn replace_last_token(buffer: &str, completion: &str) -> String {
if buffer.ends_with(' ') {
format!("{buffer}{completion}")
let start = buffer.rfind(' ').map_or(0, |i| i + 1);
format!("{}{completion}", &buffer[..start])