diff options
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | .run/src/bin/install-mling.ps1 | 2 | ||||
| -rwxr-xr-x[-rw-r--r--] | .run/src/bin/install-mling.sh | 2 | ||||
| -rw-r--r-- | CHANGELOG.md | 51 | ||||
| -rw-r--r-- | arg_picker/src/arg.rs | 4 | ||||
| -rw-r--r-- | docs/dev/pages/issues/the-shit-time.md | 13 | ||||
| -rw-r--r-- | mingling/src/picker/global.rs | 72 | ||||
| -rw-r--r-- | mingling/src/setups/picker/basic.rs | 8 | ||||
| -rw-r--r-- | mingling/src/setups/picker/structural_renderer.rs | 19 | ||||
| -rw-r--r-- | mingling_cli/src/linter/mlint_report.rs | 12 | ||||
| -rw-r--r-- | mingling_core/src/comp.rs | 80 | ||||
| -rw-r--r-- | mingling_core/src/comp/suggest.rs | 66 | ||||
| -rw-r--r-- | mingling_core/tmpls/comps/bash.sh | 43 | ||||
| -rw-r--r-- | mingling_core/tmpls/comps/zsh.zsh | 8 |
14 files changed, 305 insertions, 76 deletions
@@ -13,6 +13,7 @@ docs/cov-test/ __*.md __*/ __*.py +__*.rs # Fuck nul diff --git a/.run/src/bin/install-mling.ps1 b/.run/src/bin/install-mling.ps1 index bebe9ff..7fba62e 100644 --- a/.run/src/bin/install-mling.ps1 +++ b/.run/src/bin/install-mling.ps1 @@ -1,4 +1,4 @@ -cargo install --path mling +cargo install --path mingling_cli New-Item -ItemType Directory -Force -Path .temp/comp | Out-Null # Copy all files containing _comp from the debug directory diff --git a/.run/src/bin/install-mling.sh b/.run/src/bin/install-mling.sh index 5f2ee7a..5b5e7b2 100644..100755 --- a/.run/src/bin/install-mling.sh +++ b/.run/src/bin/install-mling.sh @@ -1,6 +1,6 @@ #!/bin/bash -cargo install --path mling +cargo install --path mingling_cli mkdir -p .temp/comp cp .temp/target/release/*_comp.* .temp/comp/ 2>/dev/null || echo "No matching files found" diff --git a/CHANGELOG.md b/CHANGELOG.md index c954123..aa80b79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,25 @@ None #### Fixes: -None +1. **[`comps:zsh`]** Fixed zsh completion script to properly escape colons in completion descriptions. The zsh completion script generated for the `zsh` output format now escapes colon characters in completion items (`${item//:/\\:}`) and description parts (`${match[1]//:/\\:}`) so that descriptions containing colons don't break the `_describe` command's parsing. Additionally, fixed the simple-completions branch to iterate over the original `completions` array (with the colon-escaped format matching) rather than the already-parsed `parsed_completions` array, correctly extracting the completion item when no description is present. + +2. **[`comps:bash`]** Reworked the bash completion script template to fix word-index tracking when the cursor is in the middle of a word and to add colon-ltrimming for completion descriptions. The script now computes the current word (`cur`) using `COMP_LINE` truncated to `COMP_POINT` (taking the last whitespace-delimited token) rather than relying on `COMP_WORDS[COMP_CWORD]`, which fails when the cursor is in the middle of a word. The word index is derived from the count of words preceding the current cursor position (`before_words`), and `prev` is the last word in that preceding set. The option flags to the underlying completion engine are now passed as `-f value`/`-C value`/etc. (space-separated) instead of `-f=value`/`-C=value`/etc. (equals-separated), since the engine expects space-delimited argument pairs. Additionally, when the current word contains a colon and `COMP_WORDBREAKS` includes `:`, the completion items are trimmed of the colon prefix before being inserted into `COMPREPLY` — this prevents completions like `foo:bar` from being double-prefixed with the literal `foo:bar` when bash would otherwise append the full word. + +3. **[`core:comp`]** Fixed the completion engine to correctly resolve command nodes when global parameters (flags and their values) precede the subcommand. Previously, the engine matched the command tree starting from the first argument after the program name, treating every leading argument as part of the command path — so `prog [PARAM]... <subcommand>` style invocations would fail to match any node. Now: + + - A new helper `first_command_arg_index::<P>(args)` scans the argument list and returns the index of the first argument that matches the head of a registered command node (excluding node names starting with `_`). Everything before that index is treated as global parameters and skipped during command tree matching. + - In `CompletionHelper::complete`, the dispatch args are sliced to start at the first command-node match (`all_args[start..]`); if no node match is found, the args are empty (`Vec::new()`). + - In `default_completion`, the input path resolution skips the leading global-parameter arguments the same way, so `prog -v hello` correctly suggests the `hello` node even though `-v` precedes it. + - In the unmatched-dispatcher branch: when a command node _has_ been matched (`first_cmd_match.is_some()`), the `EntryFallback` handler is **skipped** and only `default_completion` runs, since global parameters do not warrant invoking the fallback. When no node was matched, the previous behavior is retained (fallback combined with default completion). + + This enables `prog [PARAM]... <subcommand>` style invocations to resolve the subcommand correctly, while a "broken" path such as `prog -v hello -a someone` still fails to match a `hello someone` node (since `-a someone` lies _after_ the first matched node and participates normally). + +4. **[`core:comp`]** Added `add_prefix()` and `add_suffix()` methods to `Suggest` for batch-transforming suggestion text: + + - **`add_prefix(self, prefix: impl Into<String>) -> Suggest`** — Takes the current `Suggest` value and prepends the given prefix to the suggestion text of every item. If the `Suggest` value is `Suggest::FileCompletion`, it is returned unchanged. For example, `["foo", "bar"]` with prefix `"--"` becomes `["--foo", "--bar"]`. + - **`add_suffix(self, suffix: impl Into<String>) -> Suggest`** — Takes the current `Suggest` value and appends the given suffix to the suggestion text of every item. If the `Suggest` value is `Suggest::FileCompletion`, it is returned unchanged. For example, `["foo", "bar"]` with suffix `"="` becomes `["foo=", "bar="]`. + + Both methods consume the original `Suggest` value and return a new one, enabling ergonomic chaining with the existing `combine()` method for transforming completion suggestion sets. #### Optimizations: @@ -168,6 +186,29 @@ None Also reorganized the `[features]` section of `mingling/Cargo.toml` into logical subsections (Presets, Core, Special features, Features, LEGACY) for improved maintainability and documentation. +8. **[`core`]** **[`macros`]** Added the `#[completion(EntryFallback)]` syntax to the `#[completion]` macro, mirroring the `#[help(EntryFallback)]` pattern. When the `EntryFallback` identifier is passed (either as a bare path in the attribute arguments), the macro generates a chain handler for the `EntryFallback` type (the program's fallback entry pack type generated by `gen_program!()`). This handler is invoked during the default-completion path when no explicit dispatcher match is found. + + When the program's dispatcher fails to find a match in the completion pipeline, the `CompletionHelper::complete` method now: + + - Checks for an explicit completion handler via the chain pipeline for the `EntryFallback` type (calling `P::do_comp(&P::build_entry_fallback(vec![]), ctx)`). + - If that produces suggestions, they are combined with the default completion suggestions via `Suggest::combine()` (which merges `BTreeSet`s for `Suggest::Suggest` values). + - Falls back to the standard `default_completion::<P>(ctx)` behavior when no explicit fallback handler yields results. + + This enables users to provide custom completion suggestions for the fallback/unmatched case: + + ```rust,ignore + #[completion(EntryFallback)] + fn complete_fallback(_ctx: &ShellContext) -> Suggest { + suggest! { "fallback" } + } + ``` + + The generated chain handler for `EntryFallback` is identical to how `#[chain]`-annotated functions targeting entry pack types work — the `EntryFallback` type name is resolved through the same `chain` code-generation path used for `Entry{Type}` types, allowing users to write a dedicated completion function for the fallback entry point without manually registering it in the program's dispatcher. + + Internal changes: + - `mingling_macros/src/attr/completion.rs` updated to detect the `EntryFallback` identifier in attribute arguments. + - `CompletionHelper::complete` in `mingling_core/src/comp.rs` now invokes the fallback completion handler via `P::do_comp(&P::build_entry_fallback(vec![]), ctx)` and merges results with `Suggest::combine()`. + #### **BREAKING CHANGES** (API CHANGES): 1. **[`macros`]** **[BREAKING]** Renamed the `extra_macros` feature to `extras`. All feature-gated macro re-exports in `mingling/src/lib.rs` (and throughout the codebase) have been updated from `#[cfg(feature = "extra_macros")]` to `#[cfg(feature = "extras")]`. @@ -212,6 +253,14 @@ None _No behavioral changes — this is a pure rename of the internal fallback type and its associated `ProgramCollect` methods. The type's semantics, shape (wrapping `Vec<String>`), and rendering behavior are unchanged. +3. **[`picker:global`]** **[`setups:picker`]** Refactored the global picker utility functions into a trait-based API. The standalone functions `pick_global_flag(program, flag)` and `pick_global_argument(program, arg)` in `mingling::picker` have been replaced by the `PickerHelper<C>` trait, implemented for `Program<C>`. This trait provides `pick_flag(&mut self, flag: &PickerArg<Flag>) -> bool` and `pick_argument<A>(&mut self, arg: &PickerArg<A>) -> Option<A>`, and is backed by the `take_args` / `replace_args` methods on `Program`. + + **Migration guide:** + + - `pick_global_flag(program, flag)` → `program.pick_flag(flag)` + - `pick_global_argument(program, arg)` → `program.pick_argument(arg)` + - Import `mingling::picker::PickerHelper` instead of `mingling::picker::{pick_global_flag, pick_global_argument}` + --- ### Release 0.3.0 (2026-07-27) diff --git a/arg_picker/src/arg.rs b/arg_picker/src/arg.rs index 0b5176d..32824ea 100644 --- a/arg_picker/src/arg.rs +++ b/arg_picker/src/arg.rs @@ -1,4 +1,4 @@ -use crate::{Pickable, PickerArgInfo, SinglePickable, parselib::ParserStyle}; +use crate::{Pickable, PickerArgInfo, parselib::ParserStyle}; use std::marker::PhantomData; /// Represents a constraint definition for a parameter selection. @@ -166,7 +166,7 @@ where impl<'a, Type> From<PickerArg<'a, Type>> for Vec<String> where - Type: SinglePickable, + Type: Pickable<'a>, { fn from(value: PickerArg<'a, Type>) -> Self { let mut result = Vec::new(); diff --git a/docs/dev/pages/issues/the-shit-time.md b/docs/dev/pages/issues/the-shit-time.md index 9d6c429..ece670e 100644 --- a/docs/dev/pages/issues/the-shit-time.md +++ b/docs/dev/pages/issues/the-shit-time.md @@ -9,7 +9,7 @@ Of course, you can also contribute to this document. --- -## Why is there no fallback completion logic? +## Why is there no fallback completion logic? (Solved) (completion) (fallback) @@ -35,6 +35,17 @@ fn complete(ctx: &ShellContext) -> Suggest { } ``` +Final implementation: + +By adding support for `EntryFallback` (formerly `ErrorDispatcherNotFound`) to the Completion system, `EntryFallback` can now be used as a completion entry point when no subcommand is matched: + +```rust +#[completion(EntryFallback)] +fn complete_fallback(_ctx: &ShellContext) -> Suggest { + suggest! { "fallback" } +} +``` + --- ## Why can't I register descriptions for commands? diff --git a/mingling/src/picker/global.rs b/mingling/src/picker/global.rs index c203524..f062671 100644 --- a/mingling/src/picker/global.rs +++ b/mingling/src/picker/global.rs @@ -3,33 +3,65 @@ use mingling_core::{Program, ProgramCollect}; use crate::consts::REMAINS; -/// Picks a global flag from the program's arguments. +/// Provides helper methods for picking arguments from a [`Program`]'s argument list. /// -/// This function takes ownership of the program's current arguments, picks the specified `flag` -/// from them, and then returns the remaining arguments back to the program. It returns the -/// boolean value of the flag. -pub fn pick_global_flag<C>(program: &mut Program<C>, flag: &PickerArg<Flag>) -> bool +/// This trait abstracts the functionality of extracting specific arguments or flags +/// from the program's current arguments, while restoring any remaining arguments +/// back into the program. +pub trait PickerHelper<C> where C: ProgramCollect<Enum = C>, { - let args = program.take_args(); - let (flag, args) = args.pick(flag).pick(&REMAINS).unwrap(); - program.replace_args(args.into()); - *flag + /// Takes ownership of the program's current arguments. + /// + /// Returns the program's argument list as a [`Vec<String>`], leaving the program + /// with no arguments until [`replace_args`] is called. + /// + /// [`replace_args`]: PickerHelper::replace_args + fn take_args(&mut self) -> Vec<String>; + + /// Replaces the program's current arguments with the provided list. + /// + /// Returns the previous argument list that was replaced. + fn replace_args(&mut self, args: Vec<String>) -> Vec<String>; + + /// Picks a flag from the program's arguments. + /// + /// This function takes ownership of the program's current arguments, picks the specified `flag` + /// from them, and then returns the remaining arguments back to the program. It returns the + /// boolean value of the flag. + fn pick_flag(&mut self, flag: &PickerArg<Flag>) -> bool { + let args = self.take_args(); + let (flag, args) = args.pick(flag).pick(&REMAINS).unwrap(); + self.replace_args(args.into()); + *flag + } + + /// Picks a argument from the program's arguments. + /// + /// This function takes ownership of the program's current arguments, picks the specified `arg` + /// from them, and then returns the remaining arguments back to the program. It returns the + /// picked argument value, or `None` if the argument was not present. + fn pick_argument<A>(&mut self, arg: &PickerArg<A>) -> Option<A> + where + A: for<'a> Pickable<'a> + Default, + { + let args = self.take_args(); + let (arg, remains) = args.pick(arg).pick(&REMAINS).unpack(); + self.replace_args(remains.unwrap().into()); + arg + } } -/// Picks a global argument from the program's arguments. -/// -/// This function takes ownership of the program's current arguments, picks the specified `arg` -/// from them, and then returns the remaining arguments back to the program. It returns the -/// picked argument value, or `None` if the argument was not present. -pub fn pick_global_argument<C, A>(program: &mut Program<C>, arg: &PickerArg<A>) -> Option<A> +impl<C> PickerHelper<C> for Program<C> where - A: for<'a> Pickable<'a> + Default, C: ProgramCollect<Enum = C>, { - let args = program.take_args(); - let (arg, remains) = args.pick(arg).pick(&REMAINS).unpack(); - program.replace_args(remains.unwrap().into()); - arg + fn take_args(&mut self) -> Vec<String> { + self.take_args() + } + + fn replace_args(&mut self, args: Vec<String>) -> Vec<String> { + self.replace_args(args) + } } diff --git a/mingling/src/setups/picker/basic.rs b/mingling/src/setups/picker/basic.rs index c9f82b3..52bda3d 100644 --- a/mingling/src/setups/picker/basic.rs +++ b/mingling/src/setups/picker/basic.rs @@ -3,7 +3,7 @@ use mingling_core::{Program, ProgramCollect, setup::ProgramSetup}; use crate::{ consts::{CONFIRM_FLAG, HELP_FLAG, QUIET_FLAG}, - picker::pick_global_flag, + picker::PickerHelper, }; /// Performs basic program initialization: @@ -43,7 +43,7 @@ where C: ProgramCollect<Enum = C>, { fn setup(self, program: &mut Program<C>) { - let help = pick_global_flag(program, self.flag); + let help = program.pick_flag(self.flag); if help { program.user_context.help = true; } @@ -75,7 +75,7 @@ where C: ProgramCollect<Enum = C>, { fn setup(self, program: &mut Program<C>) { - let help = pick_global_flag(program, self.flag); + let help = program.pick_flag(self.flag); if help { program.stdout_setting.quiet = true; } @@ -107,7 +107,7 @@ where C: ProgramCollect<Enum = C>, { fn setup(self, program: &mut Program<C>) { - let help = pick_global_flag(program, self.flag); + let help = program.pick_flag(self.flag); if help { program.user_context.confirm = true; } diff --git a/mingling/src/setups/picker/structural_renderer.rs b/mingling/src/setups/picker/structural_renderer.rs index 1fa48fd..91848e4 100644 --- a/mingling/src/setups/picker/structural_renderer.rs +++ b/mingling/src/setups/picker/structural_renderer.rs @@ -1,9 +1,6 @@ use mingling_core::{Program, ProgramCollect, setup::ProgramSetup}; -use crate::{ - consts::RENDERER_ARG, - picker::{pick_global_argument, pick_global_flag}, -}; +use crate::{consts::RENDERER_ARG, picker::PickerHelper}; /// Sets up the structural renderer for the program: /// @@ -15,7 +12,7 @@ where C: ProgramCollect<Enum = C>, { fn setup(self, program: &mut Program<C>) { - if let Some(renderer) = pick_global_argument(program, &RENDERER_ARG) { + if let Some(renderer) = program.pick_argument(&RENDERER_ARG) { program.structural_renderer_name = renderer.into(); } } @@ -49,27 +46,27 @@ where { fn setup(self, program: &mut Program<C>) { #[cfg(feature = "json_serde_fmt")] - if pick_global_flag(program, &crate::consts::JSON_FLAG) { + if program.pick_flag(&crate::consts::JSON_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::Json; } #[cfg(feature = "json_serde_fmt")] - if pick_global_flag(program, &crate::consts::JSON_PRETTY_FLAG) { + if program.pick_flag(&crate::consts::JSON_PRETTY_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::JsonPretty; } #[cfg(feature = "yaml_serde_fmt")] - if pick_global_flag(program, &crate::consts::YAML_FLAG) { + if program.pick_flag(&crate::consts::YAML_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::Yaml; } #[cfg(feature = "toml_serde_fmt")] - if pick_global_flag(program, &crate::consts::TOML_FLAG) { + if program.pick_flag(&crate::consts::TOML_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::Toml; } #[cfg(feature = "ron_serde_fmt")] - if pick_global_flag(program, &crate::consts::RON_FLAG) { + if program.pick_flag(&crate::consts::RON_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::Ron; } #[cfg(feature = "ron_serde_fmt")] - if pick_global_flag(program, &crate::consts::RON_PRETTY_FLAG) { + if program.pick_flag(&crate::consts::RON_PRETTY_FLAG) { program.structural_renderer_name = crate::StructuralRendererSetting::RonPretty; } } diff --git a/mingling_cli/src/linter/mlint_report.rs b/mingling_cli/src/linter/mlint_report.rs index 0472056..b594b9d 100644 --- a/mingling_cli/src/linter/mlint_report.rs +++ b/mingling_cli/src/linter/mlint_report.rs @@ -10,7 +10,7 @@ use cargo_metadata::{Message, PackageId}; use annotate_snippets::level::{ERROR, HELP, NOTE, WARNING}; use annotate_snippets::{AnnotationKind, Group, Patch, Renderer, Snippet}; use mingling::macros::{buffer, chain, pack, r_append, r_eprintln, renderer}; -use mingling::{AnyOutput, ProgramCollect, Routable}; +use mingling::{RendererInvoker, Routable}; use crate::Next; use crate::metadata::setup::ResUsingJson; @@ -437,9 +437,13 @@ pub fn render_lint_reports(reports: ResultLintReportsAnnotateSnippet) { } #[renderer(buffer)] -pub fn render_lint_reports_json(reports: ResultLintReportsJson) { +pub fn render_lint_reports_json( + reports: ResultLintReportsJson, + message_renderer: &RendererInvoker<Message>, +) { for report in reports.inner { - // DIRTY: Dispatch to the Message renderer using AnyOutput to obtain the render result and append it to the Buffer - r_append!(|| { crate::ThisProgram::render(AnyOutput::new(report.to_compiler_message())) }); + let message = report.to_compiler_message(); + let result = message_renderer.invoke(message); + r_append!(result); } } diff --git a/mingling_core/src/comp.rs b/mingling_core/src/comp.rs index 952fb87..5f851ca 100644 --- a/mingling_core/src/comp.rs +++ b/mingling_core/src/comp.rs @@ -107,7 +107,17 @@ impl CompletionHelper { trace_ctx(ctx); }; - let args = ctx.all_words.iter().skip(1).cloned().collect::<Vec<_>>(); + // Everything before the first argument that matches a command node + // is treated as global parameters (flags and their values), which do + // not participate in command tree matching. The dispatch path starts + // at that first match, enabling `prog [PARAM]... <subcommand>` + // style invocations. + let all_args = ctx.all_words.iter().skip(1).cloned().collect::<Vec<_>>(); + let first_cmd_match = first_command_arg_index::<P>(&all_args); + let args = match first_cmd_match { + Some(start) => all_args[start..].to_vec(), + None => Vec::new(), + }; trace!("arguments=\"{}\"", args.join(", ")); #[cfg(not(feature = "dispatch_tree"))] @@ -138,11 +148,10 @@ impl CompletionHelper { debug!("dispatch_args_trie OK, member_id = {:?}", any.member_id); trace!("entry type: {}", any.member_id); - let dispatcher_not_found = - <P::EntryFallback as crate::Grouped<P>>::member_id(); + let entry_fallback = <P::EntryFallback as crate::Grouped<P>>::member_id(); - if dispatcher_not_found == any.member_id { - debug!("dispatcher_not_found matched"); + if entry_fallback == any.member_id { + debug!("entry_fallback matched"); trace!("begin not Ok"); None } else { @@ -163,8 +172,22 @@ impl CompletionHelper { suggest } None => { - trace!("using default completion"); - default_completion::<P>(ctx) + if first_cmd_match.is_some() { + // A command node has been matched: the global + // EntryFallback must not run afterwards, only the + // command path is completed. + trace!("command node matched, skipping EntryFallback"); + default_completion::<P>(ctx) + } else { + trace!("using default completion"); + let fallback = P::do_comp(&P::build_entry_fallback(vec![]), ctx); + let default = default_completion::<P>(ctx); + if fallback == Suggest::FileCompletion { + default + } else { + fallback.combine(default) + } + } } } } @@ -212,6 +235,30 @@ impl CompletionHelper { } } +/// Finds the index of the first argument that matches the head of a +/// registered command node. +/// +/// Everything before this index is treated as global parameters (flags and +/// their values), which do not participate in command tree matching. This +/// allows `prog [PARAM]... <subcommand>` style invocations to resolve the +/// subcommand, while a "broken" path such as `prog -v hello -a someone` +/// still fails to match the `hello someone` node. +fn first_command_arg_index<P>(args: &[String]) -> Option<usize> +where + P: ProgramCollect<Enum = P> + Display + 'static, +{ + let cmd_heads: Vec<String> = this::<P>() + .get_nodes() + .into_iter() + .filter(|(s, _)| !s.starts_with('_')) + .map(|(s, _)| s.split(' ').next().unwrap_or("").to_string()) + .collect(); + + args.iter().position(|arg| { + !arg.is_empty() && cmd_heads.iter().any(|head| head.starts_with(arg.as_str())) + }) +} + fn default_completion<P>(ctx: &ShellContext) -> Suggest where P: ProgramCollect<Enum = P> + Display + 'static, @@ -238,14 +285,17 @@ where &ctx.all_words.get(1..input_end).unwrap_or(&[]) ); - let input_path: Vec<&str> = ctx - .all_words - .get(1..input_end) - .unwrap_or(&[]) - .iter() - .filter(|s| !s.is_empty()) - .map(std::string::String::as_str) - .collect(); + // Skip global parameters (arguments before the first command node match) + // when resolving the command path, so `prog [PARAM]... <subcommand>` + // style invocations suggest the subcommand. + let input_slice = ctx.all_words.get(1..input_end).unwrap_or(&[]); + let input_path: Vec<&str> = match first_command_arg_index::<P>(input_slice) { + Some(start) => input_slice[start..] + .iter() + .map(std::string::String::as_str) + .collect(), + None => Vec::new(), + }; debug!( "input_path={:?}, current_word='{}'", input_path, ctx.current_word diff --git a/mingling_core/src/comp/suggest.rs b/mingling_core/src/comp/suggest.rs index dda5026..804d622 100644 --- a/mingling_core/src/comp/suggest.rs +++ b/mingling_core/src/comp/suggest.rs @@ -92,6 +92,72 @@ impl Suggest { self.insert(SuggestItem::WithDescription(item, desc_str.clone())); } } + + /// Adds a prefix to every suggestion in the `Suggest` set. + /// + /// This method takes the current `Suggest` value and prepends the given + /// prefix to the suggestion text of each item. If the `Suggest` value is + /// [`Suggest::FileCompletion`], it is returned unchanged. + /// + /// # Arguments + /// + /// * `prefix` — The string to prepend to each suggestion. Must implement + /// `Into<String>`. + /// + /// # Returns + /// + /// A new `Suggest` value where each item's suggestion text is prefixed + /// with the given string. For example, `["foo", "bar"]` with prefix `"--"` + /// becomes `["--foo", "--bar"]`. + pub fn add_prefix(self, prefix: impl Into<String>) -> Suggest { + let suggest = match self { + Suggest::Suggest(s) => s, + Suggest::FileCompletion => return Suggest::FileCompletion, + }; + let prefix = prefix.into(); + let prefixed = suggest + .into_iter() + .map(|item| { + let mut new_item = item; + new_item.set_suggest(format!("{}{}", prefix, new_item.suggest())); + new_item + }) + .collect(); + Suggest::Suggest(prefixed) + } + + /// Appends a suffix to every suggestion in the `Suggest` set. + /// + /// This method takes the current `Suggest` value and appends the given + /// suffix to the suggestion text of each item. If the `Suggest` value is + /// [`Suggest::FileCompletion`], it is returned unchanged. + /// + /// # Arguments + /// + /// * `suffix` — The string to append to each suggestion. Must implement + /// `Into<String>`. + /// + /// # Returns + /// + /// A new `Suggest` value where each item's suggestion text is suffixed + /// with the given string. For example, `["foo", "bar"]` with suffix `"="` + /// becomes `["foo=", "bar="]`. + pub fn add_suffix(self, suffix: impl Into<String>) -> Suggest { + let suggest = match self { + Suggest::Suggest(s) => s, + Suggest::FileCompletion => return Suggest::FileCompletion, + }; + let suffix = suffix.into(); + let suffixed = suggest + .into_iter() + .map(|item| { + let mut new_item = item; + new_item.set_suggest(format!("{}{}", new_item.suggest(), suffix)); + new_item + }) + .collect(); + Suggest::Suggest(suffixed) + } } impl<T> From<T> for Suggest diff --git a/mingling_core/tmpls/comps/bash.sh b/mingling_core/tmpls/comps/bash.sh index 1af4f6c..edec28d 100644 --- a/mingling_core/tmpls/comps/bash.sh +++ b/mingling_core/tmpls/comps/bash.sh @@ -1,22 +1,31 @@ #!/usr/bin/env bash _<<<bin_name>>>_bash_completion() { - local cur="${COMP_WORDS[COMP_CWORD]}" + local line="${COMP_LINE:0:COMP_POINT}" + local cur="${line##* }" local prev="" - [ $COMP_CWORD -gt 0 ] && prev="${COMP_WORDS[COMP_CWORD-1]}" + local word_index=1 - local word_index=$((COMP_CWORD + 1)) + local before="${line:0:$(( ${#line} - ${#cur} ))}" + local -a before_words + if [[ -n "$before" ]]; then + read -ra before_words <<< "$before" + word_index=$(( ${#before_words[@]} + 1 )) + if [[ $word_index -gt 1 ]]; then + prev="${before_words[${#before_words[@]}-1]}" + fi + fi local args=() - args+=(-f="${COMP_LINE//-/^}") - args+=(-C="$COMP_POINT") - args+=(-w="${cur//-/^}") - args+=(-p="${prev//-/^}") - args+=(-c="${COMP_WORDS[0]//-/^}") - args+=(-i="$word_index") - args+=(-F="bash") + args+=(-f "${COMP_LINE//-/^}") + args+=(-C "$COMP_POINT") + args+=(-w "${cur//-/^}") + args+=(-p "${prev//-/^}") + args+=(-c "${COMP_WORDS[0]//-/^}") + args+=(-i "$word_index") + args+=(-F "bash") for word in "${COMP_WORDS[@]}"; do - args+=(-a="${word//-/^}") + args+=(-a "${word//-/^}") done local suggestions @@ -36,7 +45,17 @@ _<<<bin_name>>>_bash_completion() { [ -z "$cur" ] || [[ "$suggestion" == "$cur"* ]] && filtered+=("$suggestion") done - [ ${#filtered[@]} -gt 0 ] && COMPREPLY=("${filtered[@]}") + if [ ${#filtered[@]} -gt 0 ]; then + COMPREPLY=("${filtered[@]}") + if [[ "$cur" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then + local colon_prefix="${cur%"${cur##*:}"}" + local -a ltrimmed=() + for suggestion in "${COMPREPLY[@]}"; do + ltrimmed+=("${suggestion#"$colon_prefix"}") + done + COMPREPLY=("${ltrimmed[@]}") + fi + fi return fi fi diff --git a/mingling_core/tmpls/comps/zsh.zsh b/mingling_core/tmpls/comps/zsh.zsh index c1c18bb..f665133 100644 --- a/mingling_core/tmpls/comps/zsh.zsh +++ b/mingling_core/tmpls/comps/zsh.zsh @@ -38,9 +38,9 @@ _<<<bin_name>>>_completion() { local -a parsed_completions for item in "${completions[@]}"; do if [[ "$item" =~ '^([^$]+)\$\((.+)\)$' ]]; then - parsed_completions+=("${match[1]}:${match[2]}") + parsed_completions+=("${match[1]//:/\\:}:${match[2]}") else - parsed_completions+=("$item") + parsed_completions+=("${item//:/\\:}") fi done @@ -48,8 +48,8 @@ _<<<bin_name>>>_completion() { _describe '<<<bin_name>>> commands' parsed_completions else local -a simple_completions - for item in "${parsed_completions[@]}"; do - if [[ "$item" =~ '^([^:]+):(.+)$' ]]; then + for item in "${completions[@]}"; do + if [[ "$item" =~ '^([^$]+)\$\((.+)\)$' ]]; then simple_completions+=("${match[1]}") else simple_completions+=("$item") |
