diff --git a/README.md b/README.md
index 902da15..7111bb6 100644
--- a/README.md
+++ b/README.md
@@ -1,341 +1,152 @@
# Bubblecomplete
-Bubblecomplete is a command suggestion and autocompletion component for [Bubble Tea](https://github.com/charmbracelet/bubbletea) applications.
+
+
+
+
+
+
-
+A polished command-prompt component for [Bubble Tea](https://github.com/charmbracelet/bubbletea). Type, Tab through suggestions, browse the filesystem inline, and hand the validated input back to the host. No parser required.
-## Installing
+
-First use `go get` to install the latest version of the library.
+## Features
-```shell
-go get -u github.com/dotopototo/bubblecomplete
-```
-
-Or alternatively, to get a specific branch:
-
-```shell
-go get -u github.com/dotopototo/bubblecomplete@beta
-```
-
-Next include bubblecomplete in your application.
-
-```go
-import "github.com/dotopototo/bubblecomplete"
-```
-
-## Usage
+- **Tab cycling** through commands, subcommands, flags, and positional arguments
+- **Live filesystem completion** for path arguments, with green / underline / red validity overlay on the typed token
+- **Shell ergonomics** — trailing slash on dir accepts, trailing space on file accepts, auto-quote on basenames with spaces, single-match auto-accept, drill-down on the next Tab
+- **Quote-aware parsing** — `'…'`, `"…"`, unclosed, and equals-form `--flag=…` all do what you'd expect
+- **Persistent history** — JSON-backed across sessions, with inline suggestions for last-typed commands
+- **Structured validation errors** — route on `ValidationErrorKind`, no string-matching
+- **Themable** — styles, key bindings, icons, and layout are all configurable
-See the [example](./example/main.go) for a full working implementation. Run it from the repo root:
+## Install
```shell
-go run ./example
-```
-
-The command structure expects the following:
-
-```
-command [subcommands] [flags] [positionalArguments]
+go get github.com/dotopototo/bubblecomplete
```
-- A command has **either** subcommands **or** positional arguments — never both.
- > `git stash` has subcommands (`pop`, `apply`, `drop`, …); `git push` has positional arguments (`origin main`).
-- Subcommands can be nested arbitrarily deep.
- > `git stash pop` is a subcommand of `stash`, which is a subcommand of `git`.
-- Any command or subcommand can also have flags, in any combination with positional arguments.
- > `cat file.txt -n` has both a positional argument and a flag.
-- The order of positional arguments matters.
- > `cp file.txt destination` is not the same as `cp destination file.txt`.
-- Flags marked `Persistent: true` are inherited by every subcommand of the command they're declared on.
- > A `--help` flag on `git` is also available as `git stash --help`.
-
-These rules are enforced by `Command.Validate()`, which `New` calls on every supplied command. Building a `Model` with conflicting subcommands and positional arguments, duplicate flag aliases, or invalid argument types returns an error.
+## Defining commands
-#### Setup
-
-Create a slice of `bubblecomplete.Command` structs to represent the available commands, with `bubblecomplete.PositionalArgument` structs for any required arguments and `bubblecomplete.Flag` structs for any flags that can be passed.
+Commands are plain struct literals — no DSL, no builder. A command has **either** subcommands **or** positional arguments (never both), and any number of flags:
```go
var commands = []*bubblecomplete.Command{
- {
- Command: "cp",
- Description: "Copy files and directories",
- PositionalArguments: []*bubblecomplete.PositionalArgument{
- {
- Name: "file",
- Description: "File to copy",
- Type: bubblecomplete.FileDirArgument,
- Required: true,
- },
- {
- Name: "destination",
- Description: "Destination to copy the file to",
- Type: bubblecomplete.DirArgument,
- Required: true,
- },
- },
- Flags: []*bubblecomplete.Flag{
- {
- ShortFlag: "-r",
- Description: "Copy directories recursively",
- Type: bubblecomplete.BoolArgument,
- },
- },
- },
+ {
+ Command: "cp",
+ Description: "Copy files and directories",
+ PositionalArguments: []*bubblecomplete.PositionalArgument{
+ {Name: "source", Type: bubblecomplete.FileDirArgument, Required: true},
+ {Name: "dest", Type: bubblecomplete.DirArgument, Required: true},
+ },
+ Flags: []*bubblecomplete.Flag{
+ {ShortFlag: "-r", Description: "Recursive", Type: bubblecomplete.BoolArgument},
+ },
+ },
}
```
-#### Commands
-
-| Field | Description | Type |
-| ------------------- | -------------------------------------------------------------------------------------- | -------------------------------------- |
-| Command | The command name | `string` |
-| Description | A description of the command | `string` |
-| SubCommands | A slice of `bubblecomplete.Command` structs representing subcommands | `[]*bubblecomplete.Command` |
-| PositionalArguments | A slice of `bubblecomplete.PositionalArgument` structs representing required arguments | `[]*bubblecomplete.PositionalArgument` |
-| Flags | A slice of `bubblecomplete.Flag` structs representing flags | `[]*bubblecomplete.Flag` |
-
-#### Positional Arguments
-
-| Field | Description | Type |
-| ----------- | -------------------------------- | ----------------------------- |
-| Name | The argument name | `string` |
-| Description | A description of the argument | `string` |
-| Type | The type of the argument | `bubblecomplete.ArgumentType` |
-| Required | Whether the argument is required | `bool` |
-
-#### Flags
-
-| Field | Description | Type |
-| ----------- | ---------------------------------------------------------------------------------- | ----------------------------- |
-| ShortFlag | Single-ASCII-letter short flag, e.g. `-v`. Use a long or PowerShell flag for non-letter names. | `string` |
-| LongFlag | The long flag identifier i.e. `--verbose` | `string` |
-| PsFlag | PowerShell-style flag, e.g. `-Verbose` (two or more characters; mutually exclusive with ShortFlag and LongFlag on the same Flag) | `string` |
-| Description | A description of the flag | `string` |
-| Type | The type of argument the flag expects | `bubblecomplete.ArgumentType` |
-| Persistent | A persistent flag is available to all subcommands of the command | `bool` |
-
-#### Argument Types
-
-| Type | Description |
-| --------------- | ---------------------------------------------------------------------------------- |
-| StringArgument | A string argument that can be set to any value |
-| IntArgument | An integer argument that can be set to any integer value |
-| FloatArgument | A float argument that can be set to any float value |
-| BoolArgument | A presence flag — the flag's presence in the input is true, its absence is false. No value follows the flag. |
-| FileArgument | A file argument that can be set to a valid file path |
-| DirArgument | A directory argument that can be set to a valid directory path |
-| FileDirArgument | A file or directory argument that can be set to a valid file or directory path |
-
-Create a `bubblecomplete.Model` struct with the commands and set any options you want to set, and assign it to your bubbletea program model.
+Argument types: `StringArgument`, `IntArgument`, `FloatArgument`, `BoolArgument`, `FileArgument`, `DirArgument`, `FileDirArgument`. Flags can be short (`-v`), long (`--verbose`), or PowerShell-style (`-Verbose`), and may be marked `Persistent: true` to propagate to subcommands. See the [godoc](https://pkg.go.dev/github.com/dotopototo/bubblecomplete#Command) for the full struct surface.
-```go
-type model struct {
- bubblecomplete bubblecomplete.Model
-}
+## Usage
-func createModel() tea.Model {
- bc, err := bubblecomplete.New(commands, 100,
- bubblecomplete.WithHistoryLimit(50),
- bubblecomplete.WithIcons(true),
- )
- if err != nil {
- panic(err)
- }
+Embed the component in your Bubble Tea model and forward `Update` / `View`:
- m := model{
- bubblecomplete: bc,
- }
+```go
+import (
+ "log"
- return m
-}
+ tea "charm.land/bubbletea/v2"
+ "github.com/dotopototo/bubblecomplete"
+)
-func (m model) View() tea.View {
- return m.bubblecomplete.View()
+type model struct {
+ bc bubblecomplete.Model
}
-```
-
-When composing Bubblecomplete with other content, use `Render()` to get the
-component's output as a string:
-```go
-func (m model) View() tea.View {
- return tea.NewView("Header\n" + m.bubblecomplete.Render())
+func initialModel() tea.Model {
+ bc, err := bubblecomplete.New(commands, 100,
+ bubblecomplete.WithFilesystemCompletions(true),
+ bubblecomplete.WithHistoryLimit(50),
+ )
+ if err != nil {
+ log.Fatal(err)
+ }
+ return model{bc: bc}
}
-```
-
-## Options
-
-Every option below has a matching `With*` construction option (for example
-`WithCompletionRows(5)` or `WithDescriptions(false)`). Most are also public
-fields on `Model` so they can be tweaked at runtime — exceptions are noted in
-their row. `Styles` and `KeyMap` are private; configure them via the dedicated
-`Styles()` / `SetStyles()` and `KeyMap()` / `SetKeyMap()` accessors documented
-below.
-
-#### General
-
-| Option | Description | Default |
-| ------------------------- | ---------------------------------------------------------------------------------------- | --------------- |
-| Autotrim | Trim extra whitespace from the ends of the input | `true` |
-| CompletionsOffset | The left margin offset of the completion list | `0` |
-| CompletionsPosition | The position of the completion list relative to the input | `PositionBelow` |
-| CompletionRows | The number of rows to show in the completion list before scrolling | `5` |
-| FilesystemCompletions | Enable live filesystem completion and validity colouring for file/dir argument values | `false` |
-| FilesystemCompletionLimit | Maximum filesystem candidates surfaced per keystroke | `200` |
-| HiddenFiles | Surface dotfiles even when the typed prefix does not start with `.` | `false` |
-| HistoryFilePath | The path to a `.json` file to store the command history for persistence between sessions (configure via `WithHistoryFilePath` / `SetHistoryFilePath` — no public field) | - |
-| HistoryLimit | The maximum number of history entries to store and save | `100` |
-| IndentCompletions | Indent the completion list to match the current input length | `true` |
-| ShowBorderScroll | Show different border colors around the completion list to indicate scrolling | `false` |
-| ShowScrollbar | Show a vertical scrollbar to indicate scrolling | `false` |
-| ShowDescriptions | Render the description column next to each completion name | `true` |
-
-#### Icons
-
-| Option | Description | Default |
-| ------------ | ---------------------------------- | ------- |
-| ShowIcons | Show type indicator icons | `false` |
-| CommandIcon | Icon for command completions | `›` |
-| ArgumentIcon | Icon for argument completions | `◆` |
-| FlagIcon | Icon for flag completions | `◇` |
-
-#### Styles
-
-Styles are grouped on a `Styles` struct accessed via `Styles()` / `SetStyles()`:
-
-```go
-s := bc.Styles()
-s.Input.Valid = lipgloss.NewStyle().Foreground(lipgloss.Color("10"))
-s.Completion.Match = lipgloss.NewStyle().Bold(true)
-bc.SetStyles(s)
-```
-| Field | Description | Default |
-| ------------------------ | ------------------------------------------------------------ | ----------------- |
-| Input.Valid | Style for valid user input | (green) |
-| Input.Invalid | Style for invalid user input | (muted text) |
-| Input.PathValid | Overlay on the typed path value when it resolves correctly | (green) |
-| Input.PathPartial | Overlay on the typed path value while mid-navigation | (underline) |
-| Input.PathInvalid | Overlay on the typed path value when it cannot resolve | (red) |
-| Completion.Match | Style for the matched prefix in completions | (bold pink) |
-| Completion.SelectedRow | Style for the selected completion row | (bold, highlight) |
-| Completion.Row | Style for odd completion rows | (subtle bg) |
-| Completion.AltRow | Style for even completion rows | (alt subtle bg) |
-| Completion.Border | Style for the completions border | (rounded border) |
-| Completion.Description | Style for completion descriptions | (muted) |
-| Completion.Icon | Style for type indicator icons | (pink) |
-| Scrollbar.Thumb | Style for the scrollbar thumb | (pink) |
-| Scrollbar.Track | Style for the scrollbar track | (border color) |
-
-#### Key Bindings
-
-Bindings are exposed via `KeyMap()` / `SetKeyMap()`:
+func (m model) Init() tea.Cmd { return nil }
-```go
-import "charm.land/bubbles/v2/key"
+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ var cmd tea.Cmd
+ m.bc, cmd = m.bc.Update(msg)
+ if sel, ok := msg.(bubblecomplete.SelectedCommandMsg); ok {
+ // sel.Command is the validated input; sel.Err is non-nil on validation failure.
+ _ = sel
+ }
+ return m, cmd
+}
-k := bc.KeyMap()
-k.Submit = key.NewBinding(key.WithKeys("enter", "ctrl+s"))
-bc.SetKeyMap(k)
+func (m model) View() tea.View { return m.bc.View() }
```
-| Field | Description | Default |
-| ---------------- | ------------------------------------------ | -------------------- |
-| NextCompletion | Cycle forward through completions | `tab`, `ctrl+n` |
-| PrevCompletion | Cycle backward through completions | `shift+tab`, `ctrl+p`|
-| AcceptCompletion | Accept the selected or inline completion | `right`, `ctrl+e` |
-| Submit | Submit the current input | `enter` |
-| HistoryPrev | Walk back through command history | `up` |
-| HistoryNext | Walk forward through command history | `down` |
-
-### History
-
-- The newest command is at `History[0]`. Trimming keeps the newest `HistoryLimit` entries.
-- A `HistoryLimit` of zero or less disables history entirely.
-- Adjacent duplicates are suppressed: pressing enter twice on the same input only stores one entry.
-- Invalid commands are stored — history is "what the user submitted," not "what validated."
-- `WithHistoryFilePath(path)` (or `SetHistoryFilePath`) loads history from a JSON file on startup and saves atomically on each submit. Errors during load or save surface via `Model.Error()`.
-
-### Input Parsing
-
-- Only the ASCII space character (`U+0020`) separates tokens. Tabs, newlines, and other Unicode whitespace are part of the token they appear in, not separators.
-- Tokens preserve their quote characters in their raw form. Inside double or single quotes, spaces become part of the token until the matching closing quote (or end of input for unclosed quotes).
-- The same tokenizer powers completion, validation, and quote-error reporting — they always see the same parse of the input.
-- Out of scope: shell escapes (`\"`), adjacent quoted segments (`"foo""bar"` is two tokens, not one), variable expansion, and globs. See [Non-Goals](#non-goals).
+A complete runnable program lives in [`./example`](./example/main.go) — `go run ./example` to try it.
-### Filesystem Argument Validation
+## Filesystem completions
-`FileArgument`, `DirArgument`, and `FileDirArgument` validate the value against the real filesystem using `os.Stat`. The value is run through a shared resolver first: a leading `~` (or `~/`) is expanded against `$HOME`; relative paths are joined with the process's working directory. Unclosed quotes (`"foo` with no closing `"`) surface as `UnclosedQuote`, matching how `StringArgument` already validates. Single-quoted values suppress tilde expansion, mirroring shell semantics. A configurable working-directory / filesystem abstraction is on the roadmap.
+Turn it on with `WithFilesystemCompletions(true)`. As the user types a value for a `FileArgument`, `DirArgument`, or `FileDirArgument`, the completion list shows real filesystem entries from the relevant parent directory — directories first (with trailing `/`), then files, sorted case-fold. Tab cycles, Shift+Tab reverses, Right (or any keystroke) accepts. Single matches auto-accept, and a second Tab drills into the just-accepted directory — matching standard shell tab-completion behaviour.
-### Filesystem Completions
+The typed value gets a validity overlay:
-`WithFilesystemCompletions(true)` enables live filesystem completion and per-token validity colouring for any `FileArgument`, `DirArgument`, or `FileDirArgument` value the user is editing. Default is off; the feature is opt-in.
+| State | Meaning |
+| --- | --- |
+| **green** | resolves to an entry of the expected kind |
+| **underlined** | strict prefix of one or more existing entries (mid-navigation) |
+| **red** | doesn't resolve, or resolves to the wrong kind |
-When active, the completion list is replaced wholesale with matching entries from the relevant parent directory — directories first (with a trailing `/` for navigation), then files, sorted case-fold. `Tab` cycles forward, `Shift+Tab` cycles backward, `Right` (or typing) accepts. Tab-accepting a directory adds the trailing slash so the next keystroke drills into it. When there's only **one** candidate, `Tab` auto-accepts immediately and exits cycling — so a second `Tab` lists the children of the just-accepted directory, matching shell tab-completion behaviour.
+> **Invariant:** when the overlay is shown, green means Enter accepts. The classifier and submit-time validator share a resolver, so the colour can't lie about whether submitting would succeed. (The overlay is suppressed in a few documented cases — wide inputs that overflow the terminal, file cycling — where Enter still behaves correctly but the colour is absent.)
-The typed value gets a coloured overlay reflecting its filesystem state:
+Tilde expansion (`~`, `~/`), quote handling (`"…"`, `'…'`, equals-form `--path="…"`), auto-quote on basenames with spaces, and a subtle `+ N more` footer when the directory exceeds the candidate limit are all built in. Full behaviour, limits, and caveats live in the [godoc](https://pkg.go.dev/github.com/dotopototo/bubblecomplete#WithFilesystemCompletions).
-- **green** — resolves to an entry of the expected kind
-- **underlined white** — strict prefix of one or more existing entries (mid-navigation)
-- **red** — does not resolve, or resolves to the wrong kind
+## Configuration
-The invariant the feature guarantees, *when the overlay is shown*: green ⇔ Enter accepts. Classifier and `validatePath` resolve and stat by the same rules. The overlay can be suppressed by the limitations listed below (overflow, cycling); in those cases a green-resolving path is still accepted on Enter, but the colour is absent.
+Common options:
-**Quoting.** Values are quote-aware: typing `cat "~/My Doc"` completes inside the quotes. If the user types `cat ~/M` and the matched basename contains a space, the inserted token is auto-quoted with double quotes. Equals-form flag values (`--path=~/foo`) preserve the `--path=` prefix; only the value portion is coloured.
+| Option | Default | Description |
+| ----------------------- | ------- | ----------- |
+| `FilesystemCompletions` | `false` | Opt into live filesystem completion + validity overlay |
+| `HistoryLimit` | `100` | Max history entries; `≤ 0` disables history |
+| `HistoryFilePath` | — | JSON file for history persistence (via `WithHistoryFilePath` / `SetHistoryFilePath`) |
+| `ShowIcons` | `false` | Type-indicator icons on each row |
+| `ShowDescriptions` | `true` | Render the description column |
+| `CompletionRows` | `5` | Visible rows before scrolling |
+| _…and more_ | — | _Layout, scrollbar, icon glyphs, hidden files, candidate cap — see [`Model` godoc](https://pkg.go.dev/github.com/dotopototo/bubblecomplete#Model)_ |
-**Tilde policy.** `~` and `~/` expand outside quotes and inside `"..."`; not inside `'...'`. This deviates pragmatically from strict POSIX (which would not expand inside `"..."`) — users who quote because of spaces still expect `~` to work.
-
-**Modal context.** While editing a path value, the completion list shows only filesystem entries. Flag suggestions are intentionally hidden in this mode — to surface them, move the cursor out of the value position (type a space or backspace out).
-
-**Caching.** Directory reads are cached for 2 seconds across up to 64 distinct parent directories. The first keystroke into a new directory pays one `os.ReadDir`; subsequent keystrokes avoid the repeat read but still scan the cached entries and may stat a bounded number of symlinks. Permission errors and missing directories are cached too, so a bad path doesn't trigger a retry storm.
-
-**Documented limitations.**
-
-- **Permission denied** silently falls back to the argument hint row. The whole-input style still signals the error via the validation system, but no specific "permission denied" row appears in the completion list.
-- **Devices, sockets, pipes** never appear as completion candidates regardless of `ArgumentType`. They still validate per kind if typed directly (a `FileArgument` accepts `/dev/null` because `!IsDir()` matches).
-- **Filenames containing literal quote characters** (`"` or `'`) are inserted verbatim and cannot be re-parsed by the tokenizer as a single token. Vanishingly rare in practice.
-- **Multi-token unquoted paths** like `cat ~/My Doc` are not recovered: once a space is typed, the tokenizer has split the path. Open a quote first (`cat "~/My Doc`) or rely on auto-quote (`cat ~/M` picks the spaced basename).
-- **Cold huge directories** (10k+ entries) produce a one-time stall on the first read. Subsequent keystrokes within the TTL window avoid the repeat read.
-- **Case sensitivity** is a heuristic: case-sensitive on Linux, case-insensitive on macOS and Windows. APFS case-sensitive volumes on macOS will surface completions the filesystem won't actually open.
-- **Unicode normalisation** on macOS HFS+: the filesystem stores filenames in NFD form, but users typically type in NFC. A typed `~/Documents/résumé.pdf` (NFC) won't match the on-disk `résumé.pdf` (NFD) and the path will silently colour red. Not fixed in v1; would require pulling in `golang.org/x/text/unicode/norm`.
-- **Inputs wider than the terminal** lose the validity overlay (the underlying textinput's scroll window can't be reliably indexed into for offset math).
-- **During Tab cycling**, the overlay refreshes per-cycle and tracks the cycled candidate's validity. Directory candidates (no trailing space) show their classification per cycle — `pathPartial` (mid-navigation) under `FileArgument`, `pathValid` under `DirArgument`. File candidates carry a trailing space (bash-style "token done"), which makes `activeFileArgument` inactive for that preview — files cycle without an overlay colour. The cycled file values are all real files by construction (they survived the candidate kind filter), so the missing colour signals nothing.
+Every option has a matching `With*` construction function, and most are also mutable public fields on `Model` for runtime tweaks. Styles and key bindings live on their respective accessors: [`Styles()` / `SetStyles`](https://pkg.go.dev/github.com/dotopototo/bubblecomplete#Model.Styles) and [`KeyMap()` / `SetKeyMap`](https://pkg.go.dev/github.com/dotopototo/bubblecomplete#Model.KeyMap).
## Roadmap
-- [x] Update to bubbletea v2
-- [x] Support PowerShell style flags
-- [ ] Support PowerShell aliases for flags i.e. `-v` for `-Verbose`
-- [x] Autocomplete for filepaths
- - [x] Underlined white if part of a valid path
- - [x] Green if full valid path
- - [x] Red if invalid path
-- [ ] Option to have flags disable other flags if they're mutually exclusive
-- [x] Improved documentation comments for public functions and structs
-- [x] Wider range of tests for more critical functions, for improved maintainability
-- [x] Option to not show the descriptions of the commands, flags etc
-- [x] More exposed color options for the completion list, scrolling etc
+- [ ] PowerShell flag aliases (e.g. `-v` for `-Verbose`)
+- [ ] Mutually-exclusive flags
+- [ ] Pluggable completion provider (for dynamic / remote sources)
## Non-Goals
-Some behaviors are intentionally out of scope. Don't expect:
+Bubblecomplete is a prompt component, not a shell. Don't expect:
-- Full POSIX shell parsing (e.g., command substitution, here-docs, redirections)
-- Executing commands — Bubblecomplete only reports the submitted string back to the host via `SelectedCommandMsg`
+- Executing commands — the component hands the submitted string back via `SelectedCommandMsg` and the host runs it
+- Full POSIX shell parsing (substitution, here-docs, redirections)
- Shell alias resolution
- Environment variable expansion (`$HOME`, `${FOO}`)
- Glob expansion (`*.go`)
-- Command-specific dynamic completions — until a provider API lands in Part 4
-
-If you need any of these, do them in the host application after receiving the submitted command.
## FAQ
-### Colors
+**Why do colours look off?** Bubble Tea components render best in 24-bit terminals. Make sure your terminal (and tmux config, if applicable) advertises truecolor — `$TERM=xterm-256color` and `$COLORTERM=truecolor`.
-Bubblecomplete (and Bubble Tea applications in general) work best with a terminal that supports 24-bit color. If you're using a terminal that doesn't support 24-bit color, you may see some odd colors. If you're using a terminal that supports 24-bit color, ensure that it's enabled in your terminal emulator, tmux config (if you're using tmux) etc and that your `$TERM` environment variable is set to a value that supports 24-bit color (such as `xterm-256color`) and your `$COLORTERM` environment variable is set to `truecolor`.
+**Is `Model` goroutine-safe?** No, and intentionally so. Bubble Tea runs `Update` on a single goroutine and all state changes happen there. Background work should return `tea.Msg` values for the next `Update` to consume — never mutate `Model` from another goroutine.
-### Concurrency
+## License
-`Model` is not goroutine-safe. This is intentional: Bubble Tea runs `Update` on a single goroutine, and all model state changes should happen there. Background work should return `tea.Msg` values that the next `Update` consumes; never mutate `Model` from another goroutine.
+[MIT](./LICENSE)
diff --git a/bubblecomplete.go b/bubblecomplete.go
index e99523d..9d4de2c 100644
--- a/bubblecomplete.go
+++ b/bubblecomplete.go
@@ -28,7 +28,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
- // Handle key presses
if keyMsg, ok := msg.(tea.KeyPressMsg); ok {
switch {
case key.Matches(keyMsg, m.keymap.NextCompletion):
@@ -51,11 +50,9 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
}
cmds = append(cmds, cmd)
- // Update the text input
m.input, cmd = m.input.Update(msg)
cmds = append(cmds, cmd)
- // If the input has changed, update the completions and validate the input
if m.input.Value() != "" && m.input.Value() != m.lastInput && m.completionHolder == "" && !m.showAll {
m.lastInput = m.input.Value()
m.recomputePathState()
@@ -63,9 +60,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
m.validationErr = m.validateInput()
m.applyInputValidationStyle()
} else if m.input.Value() == "" && m.lastInput != "" {
- // Input cleared. Always reset lastInput and pathState so a stale
- // path-completion overlay can't survive a delete-all; clear the
- // validation style only when there's an error to clear.
+ // Input cleared: reset pathState so a stale overlay can't survive delete-all.
m.lastInput = ""
m.pathState = pathState{}
if m.validationErr != nil {
@@ -74,7 +69,6 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
}
}
- // If not loaded, start the blinking cursor
if !m.loaded {
m.loaded = true
cmds = append(cmds, textinput.Blink)
@@ -83,8 +77,8 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
return m, tea.Batch(cmds...)
}
-// ShowingCompletions returns true if the completions are currently visible
-func (m *Model) ShowingCompletions() bool {
+// ShowingCompletions returns true if the completions are currently visible.
+func (m Model) ShowingCompletions() bool {
return len(m.completions) > 0 && m.historyIndex == -1 && (m.input.Value() != "" || m.showAll)
}
@@ -119,10 +113,8 @@ func (m Model) resetModel() Model {
return m
}
-// clearTransientCompletionState wipes the per-keystroke completion-cycling
-// and history-cycling state. Shared by resetModel (full submit reset) and
-// the keyBackspace / keyDefault paths, which need the same wipe without
-// touching the input value or validation state.
+// clearTransientCompletionState wipes per-keystroke completion- and history-
+// cycling state without touching the input value or validation error.
func (m Model) clearTransientCompletionState() Model {
m.completionHolder = ""
m.completionIndex = -1
@@ -191,9 +183,8 @@ func (m Model) keyDown() (Model, tea.Cmd) {
}
func (m Model) keyRight() (Model, tea.Cmd) {
- // If a tab completion is currently selected, accept it.
- // Completions and validation are recalculated by Update() since
- // clearing completionHolder makes its guard condition true.
+ // Clearing completionHolder makes Update's input-changed guard true, so
+ // completions and validation are recalculated against the accepted value.
if m.completionIndex >= 0 {
m.completionHolder = ""
m.completionIndex = -1
@@ -205,7 +196,6 @@ func (m Model) keyRight() (Model, tea.Cmd) {
return m, nil
}
- // Accept history inline suggestion
if len(m.input.MatchedSuggestions()) == 0 {
return m, nil
}
@@ -220,26 +210,22 @@ func (m Model) keyRight() (Model, tea.Cmd) {
func (m Model) keyTab(forward bool) (Model, tea.Cmd) {
trimmedInput := strings.TrimSpace(m.input.Value())
- // If the input is empty, show all completions
if trimmedInput == "" && !m.showAll {
m.showAll = true
m.completions, m.matchPrefix = m.getCompletions()
return m, nil
}
- // If there are no completions, do nothing
if len(m.completions) == 0 {
return m, nil
}
- // If there is only one completion and it matches the input, do nothing
if len(m.completions) == 1 {
if strings.HasSuffix(trimmedInput, m.completions[0].getName()) {
return m, nil
}
}
- // Cycle and update the completion index
if forward {
if m.completionIndex < len(m.completions)-1 {
m.completionIndex++
@@ -254,34 +240,26 @@ func (m Model) keyTab(forward bool) (Model, tea.Cmd) {
}
}
- // Save the current input if we haven't already
if m.completionHolder == "" && !m.showAll {
m.completionHolder = m.input.Value()
}
- // If the completion index is -1, reset the input to the completion holder
if m.completionIndex == -1 {
m.input.SetValue(m.completionHolder)
m.completionHolder = ""
- // Refresh pathState against the restored value. The input-changed
- // branch later in Update won't help here: the restored value
- // equals m.lastInput (set before cycling began), so the branch
- // skips. Without this refresh, pathState would still belong to
- // the last-cycled preview value — stale offsets, wrong validity,
- // or (after a cycled file's trailing space made it inactive) no
- // overlay at all on a path that should now show partial/invalid.
+ // Restored value equals m.lastInput, so Update's input-changed branch
+ // won't refresh pathState. Do it here to avoid stale cycling overlay.
m.recomputePathState()
return m, nil
}
- // If the completion is empty (aka positional arg), don't update the input
+ // Positional-argument completions have no insertion text — they're info-only rows.
if m.completions[m.completionIndex].getAutocomplete() == "" {
return m, nil
}
pretext := m.completionHolder
parts := splitInput(m.completionHolder)
- // If the pretext doesn't end in a space, add one
if !strings.HasSuffix(pretext, " ") && len(parts) > 0 {
pretext = strings.Join(parts[:len(parts)-1], " ")
if len(parts) > 1 {
@@ -289,34 +267,21 @@ func (m Model) keyTab(forward bool) (Model, tea.Cmd) {
}
}
- // Update the input with the current completion
m.input.SetValue(pretext + m.completions[m.completionIndex].getAutocomplete())
m.input.CursorEnd()
if len(m.completions) == 1 {
- // Single-match acceptance: treat Tab as a final accept rather than
- // entering cycling state. Clearing completionHolder here means the
- // input-changed branch later in this same Update call (after
- // textinput.Update) will recompute against the new input value —
- // populating fresh completions and pathState for the just-accepted
- // text. The next Tab then cycles among those new candidates, which
- // for a directory match enables the shell-style drill-down: Tab
- // on "cd Do" with a unique "Documents/" candidate accepts it AND
- // repopulates with Documents/'s children, so the second Tab
- // descends one level.
+ // Single-match: final accept (not cycling). Clearing completionHolder
+ // lets Update's input-changed branch recompute against the new value,
+ // enabling shell-style drill-down on directory matches (second Tab
+ // descends into the just-accepted dir).
m.completionHolder = ""
m.completionIndex = -1
m.showAll = false
} else {
- // Multi-match cycling: completionHolder stays set so the user can
- // continue cycling or revert to the original via Shift+Tab past
- // the start. The input-changed branch is therefore skipped on the
- // next Update tick. Refresh pathState here so the render overlay
- // reflects the *cycled* value's validity — without this, the
- // frozen offsets and validity would mis-style the preview (the
- // old cycling-bypass behaviour in renderedInput). m.completions
- // is intentionally NOT recomputed: the cycling list is the
- // candidates we entered cycling with.
+ // Multi-match cycling: refresh pathState so the overlay reflects the
+ // cycled preview's validity. m.completions is deliberately NOT
+ // recomputed — we cycle the list we entered with.
m.recomputePathState()
}
return m, nil
@@ -328,12 +293,10 @@ func (m Model) keyEnter() (Model, tea.Cmd) {
command = strings.TrimSpace(m.input.Value())
}
- // Re-validate against the current input to avoid stale errors from
- // before tab completion changed the value.
+ // Re-validate: tab completion may have changed the value since the last tick.
m.validationErr = m.validateInput()
validationErr := m.validationErr
- // HistoryLimit <= 0 disables history entirely.
if m.HistoryLimit > 0 && command != "" && (len(m.History) == 0 || m.History[0] != command) {
m.History = append([]string{command}, m.History...)
if len(m.History) > m.HistoryLimit {
@@ -341,9 +304,7 @@ func (m Model) keyEnter() (Model, tea.Cmd) {
}
}
m = m.resetModel()
- // When history is disabled, skip the save entirely — otherwise a
- // configured history file would get rewritten to {"history":null} on
- // every Enter. Clear any prior error since no operation was attempted.
+ // History disabled: skip save (would rewrite file to {"history":null}).
if m.HistoryLimit > 0 {
m.err = m.saveHistoryToFile()
} else {
diff --git a/completions.go b/completions.go
index 178d085..212de9f 100644
--- a/completions.go
+++ b/completions.go
@@ -75,24 +75,20 @@ func uniqueCompletions(completions *[]completion) {
*completions = list
}
-// getCompletions gets completions for the input based on the available commands
func getCompletions(input string, commands []*Command) ([]completion, string) {
var completions []completion
- // If the input is empty, return nothing
if strings.TrimSpace(input) == "" {
return []completion{}, ""
}
- // Split the input into parts so we can handle each part separately
parts := splitInput(input)
if len(parts) == 0 {
return []completion{}, ""
}
- // If there is only one part and the input doesn't end with a space, we're still typing the first command
+ // Still typing the first command word.
if len(parts) == 1 && !strings.HasSuffix(input, " ") {
- // Show all commands that start with the input
for _, c := range commands {
if strings.HasPrefix(c.Command, parts[0]) {
completions = append(completions, c)
@@ -101,16 +97,11 @@ func getCompletions(input string, commands []*Command) ([]completion, string) {
return completions, parts[0]
}
- // Otherwise we have at least one command entered so find the final valid command entered
finalCommand, commandDepth, globalFlags := walkToFinalCommand(input, parts, commands)
-
- // If we haven't found any command, it must be invalid input so return nothing
if finalCommand == nil {
return []completion{}, ""
}
- // From here it's if - return statements
-
argParts := parts[commandDepth:]
posArgs, flagArgs := splitPositionArgsAndFlags(argParts, finalCommand, globalFlags)
@@ -119,19 +110,16 @@ func getCompletions(input string, commands []*Command) ([]completion, string) {
matchPrefix = argParts[len(argParts)-1]
}
- // If the final command has subcommands
if len(finalCommand.SubCommands) > 0 {
completions = handleSubCommandCompletions(finalCommand, parts, commandDepth, input, flagArgs, globalFlags)
return completions, matchPrefix
}
- // If the final command has positional arguments
if len(finalCommand.PositionalArguments) > 0 {
completions = handlePositionalArgumentCompletions(finalCommand, posArgs, flagArgs, input, argParts, globalFlags)
return completions, matchPrefix
}
- // Otherwise show only the flags
flagCompletions, _ := getFlagCompletions(input, finalCommand, flagArgs, globalFlags)
completions = append(completions, flagCompletions...)
return completions, matchPrefix
@@ -147,12 +135,12 @@ func handleSubCommandCompletions(
) []completion {
var completions []completion
- // Show subcommands unless there's more parts than expected (i.e. invalid input or flags for parent command)
+ // Hide subcommands once parts have moved past the subcommand position
+ // (extra tokens mean the user is typing flags / args for the parent).
if len(parts) <= depth || (len(parts) == depth+1 && !strings.HasSuffix(input, " ")) {
completions = append(completions, getSubCommandCompletions(input, cmd, parts)...)
}
- // Append any flag completions
flagCompletions, solo := getFlagCompletions(input, cmd, flagArgs, globalFlags)
if solo {
return flagCompletions
@@ -170,7 +158,6 @@ func handlePositionalArgumentCompletions(
) []completion {
var completions []completion
- // Show the flag arguments if there are no positional arguments entered
if len(posArgs) == 0 {
flagCompletions, solo := getFlagCompletions(input, cmd, flagArgs, globalFlags)
if solo {
@@ -200,11 +187,9 @@ func handlePositionalArgumentCompletions(
func getSubCommandCompletions(input string, finalCommand *Command, parts []string) []completion {
completions := []completion{}
- // If we've started typing, show only subcommands that start with the input
if !strings.HasSuffix(input, " ") {
for _, command := range finalCommand.SubCommands {
if strings.HasPrefix(command.Command, parts[len(parts)-1]) {
- // Filter out commands that have already been entered
if !inputContainsCompletedToken(input, command.Command) {
completions = append(completions, command)
}
@@ -213,9 +198,7 @@ func getSubCommandCompletions(input string, finalCommand *Command, parts []strin
return completions
}
- // Otherwise show all subcommands
for _, command := range finalCommand.SubCommands {
- // Filter out commands that have already been entered
if !inputContainsCompletedToken(input, command.Command) {
completions = append(completions, command)
}
@@ -227,17 +210,14 @@ func getSubCommandCompletions(input string, finalCommand *Command, parts []strin
func getPositionalArgumentCompletions(input string, finalCommand *Command, posArgParts []string) []completion {
completions := []completion{}
- // If we haven't entered any positional arguments yet, show the first one
if len(posArgParts) == 0 {
return []completion{finalCommand.PositionalArguments[0]}
}
- // If we're entering a positional argument value, show only the positional argument for that value
if yes, arg := isEnteringPosArgValue(input, finalCommand, posArgParts); yes {
return []completion{arg}
}
- // Otherwise show the next positional argument if there is one
if len(posArgParts) < len(finalCommand.PositionalArguments) {
return []completion{finalCommand.PositionalArguments[len(posArgParts)]}
}
@@ -253,10 +233,9 @@ func isEnteringPosArgValue(input string, finalCommand *Command, posArgParts []st
lastArg := posArgParts[len(posArgParts)-1]
positionalArgument := finalCommand.PositionalArguments[len(posArgParts)-1]
- // Does the last arg start with a quote?
+ // Unclosed quoted value → still entering.
if strings.HasPrefix(lastArg, "\"") || strings.HasPrefix(lastArg, "'") {
quote := lastArg[0:1]
- // If the last arg doesn't end with a quote, we're entering a value
if !strings.HasSuffix(lastArg, quote) {
return true, positionalArgument
}
@@ -269,9 +248,9 @@ func isEnteringPosArgValue(input string, finalCommand *Command, posArgParts []st
return false, nil
}
-// getFlagCompletions gets completions for flags based on the input
-//
-// Returns a list of completions and a boolean indicating if this should be the only completion shown or not
+// getFlagCompletions returns flag completions for the current input. The
+// second return is true when the result should replace the completion list
+// entirely (e.g. when the user is mid-value for a known flag).
func getFlagCompletions(
input string,
finalCommand *Command,
@@ -282,7 +261,6 @@ func getFlagCompletions(
allFlags := slices.Concat(finalCommand.Flags, globalFlags)
- // If we haven't entered any flags yet, show all flags
if len(flagArgParts) == 0 {
for _, a := range allFlags {
completions = append(completions, a)
@@ -290,17 +268,14 @@ func getFlagCompletions(
return completions, false
}
- // If we're entering a flag value, show only the flag for that value
if yes, flag := isEnteringFlagValue(input, finalCommand, flagArgParts, globalFlags); yes {
return []completion{flag}, true
}
- // If we need to enter a flag value, show only the flag for that value
if yes, flag := needToEnterFlagValue(finalCommand, flagArgParts, globalFlags); yes {
return []completion{flag}, true
}
- // Otherwise if we end with a space, show all flags not yet entered
if strings.HasSuffix(input, " ") {
for _, flag := range allFlags {
if !containsFlag(input, flag) {
@@ -310,7 +285,6 @@ func getFlagCompletions(
return completions, false
}
- // Otherwise finally, show completions based on the argument being entered
finalPart := flagArgParts[len(flagArgParts)-1]
completions = append(completions, filterFlagsByPrefix(input, finalPart, allFlags)...)
return completions, false
@@ -359,7 +333,21 @@ func isEnteringFlagValue(
lastArg := flagArgParts[len(flagArgParts)-1]
allFlags := slices.Concat(finalCommand.Flags, globalFlags)
- // Check if we're entering a flag value with a space between the flag and value
+ // If the input ends with a space AND the last token is closed, the user
+ // has committed past the value — they're no longer entering it. This
+ // applies uniformly to all forms: `-m 'msg' `, `-m "msg" `, `-m hello `,
+ // `--message=value `, etc. The `Closed` field on the tokenizer's last
+ // token correctly distinguishes a fully-closed quoted value from an
+ // unclosed one whose body happens to end in a space (e.g. `-m "hi `,
+ // which is still entering the -m value because the quote never closed).
+ if strings.HasSuffix(input, " ") {
+ tokens := tokenize(input)
+ if len(tokens) > 0 && tokens[len(tokens)-1].Closed {
+ return false, nil
+ }
+ }
+
+ // Space-separated flag value (e.g. `--name foo`).
if len(flagArgParts) >= 2 {
lastFlag := flagArgParts[len(flagArgParts)-2]
lastValue := lastArg
@@ -367,7 +355,7 @@ func isEnteringFlagValue(
if strings.HasPrefix(lastFlag, "-") && !inputContainsUnquotedTokenBeforeLast(input, lastValue) {
flagValueToCompare := lastFlag
for _, flag := range allFlags {
- // If the last flag is a short flag, only compare the last character
+ // Combined short flag: the value belongs to the last char.
if flag.PsFlag == "" && !strings.HasPrefix(lastFlag, "--") && len(lastFlag) > 2 {
flagValueToCompare = "-" + lastFlag[len(lastFlag)-1:]
}
@@ -381,13 +369,12 @@ func isEnteringFlagValue(
}
}
- // If we're entering a flag value with an equals sign between the flag and value
+ // Equals-form flag value (e.g. `--name=foo`).
if strings.Contains(lastArg, "=") {
// Skip when the token is a fully-closed quoted value already followed
// by a space — that means we've moved past it, not into it.
if !stringEndsInQuoteWithoutEquals(lastArg) || !strings.HasSuffix(input, " ") {
for _, flag := range allFlags {
- // If the flag isn't a PowerShell flag, ensure it's a long flag
if flag.PsFlag == "" && !strings.HasPrefix(lastArg, "--") {
continue
}
@@ -406,7 +393,7 @@ func needToEnterFlagValue(finalCommand *Command, flagArgParts []string, globalFl
allFlags := slices.Concat(finalCommand.Flags, globalFlags)
for _, flag := range allFlags {
- // If the last argument is a combined short flag, only check for the last character flag
+ // Combined short flag: the value belongs to the last char.
flagToCompare := lastArgument
if flag.PsFlag == "" && !strings.HasPrefix(lastArgument, "--") && len(lastArgument) > 2 {
flagToCompare = "-" + lastArgument[len(lastArgument)-1:]
@@ -437,45 +424,36 @@ func stringEndsInQuoteWithoutEquals(s string) bool {
}
func splitPositionArgsAndFlags(argParts []string, command *Command, globalFlags []*Flag) ([]string, []string) {
- // For a given input, split the input into flags and their values and positional arguments
-
- // If the input is empty, return nothing
if len(argParts) == 0 {
return []string{}, []string{}
}
effectiveFlags := slices.Concat(command.Flags, globalFlags)
- // If there are no flags, return all positional arguments
if len(effectiveFlags) == 0 {
return argParts, []string{}
}
-
- // If there are no positional arguments, return all flags
if len(command.PositionalArguments) == 0 {
return []string{}, argParts
}
- // If there are both positional and flags
var positionalArgs []string
var flags []string
for i := 0; i < len(argParts); i++ {
- // If the argument is a flag, add it and its value to the flags
if strings.HasPrefix(argParts[i], "-") {
matched := findMatchingFlag(argParts[i], effectiveFlags)
if matched != nil {
flags = append(flags, argParts[i])
- // If the argument is a boolean, don't check for a value
+ // Bool flags don't consume the next token.
if matched.Type != BoolArgument && i+1 < len(argParts) {
flags = append(flags, argParts[i+1])
i++
}
} else {
- // Unknown flag — still record it as an entered flag for completion filtering
+ // Unknown flags are still recorded so completion can filter them out.
flags = append(flags, argParts[i])
}
} else {
- // If the argument is not a flag, add it to the positional arguments
positionalArgs = append(positionalArgs, argParts[i])
}
}
@@ -655,13 +633,10 @@ func containsLongFlag(command string, flag string) bool {
return false
}
+// containsPowerShellFlag reports whether command contains a token referencing
+// the given PsFlag. Flag.Validate guarantees PsFlag bodies are at least two
+// runes, so detection reuses the long-flag exact/equals-form matcher.
func containsPowerShellFlag(command string, flag string) bool {
- // If the powershell flag is a short flag, check for the short flag pattern
- if len(flag) == 2 && flag[0] == '-' {
- return containsShortFlag(command, flag)
- }
-
- // Otherwise check for the long flag pattern
return containsLongFlag(command, flag)
}
diff --git a/completions_test.go b/completions_test.go
index 97c57b0..229f4ec 100644
--- a/completions_test.go
+++ b/completions_test.go
@@ -559,6 +559,52 @@ func TestSortedGetCompletions(t *testing.T) {
input: "git commit --message=\"test message ",
expected: []string{"-m --message"},
},
+ // Space-separated flag values: trailing whitespace AFTER a closed
+ // value token (matched-quote or unquoted) means the user has
+ // committed past the value and we should surface remaining flags
+ // — NOT keep showing the value-taking flag as still-in-progress.
+ // The equals-form cases above already cover the same shape; these
+ // lock the parallel behaviour for space-separated values.
+ {
+ name: "git commit -m 'my message' ",
+ input: "git commit -m 'my message' ",
+ expected: []string{"--amend", "--help", "-a --all"},
+ },
+ {
+ name: "git commit -m \"my message\" ",
+ input: "git commit -m \"my message\" ",
+ expected: []string{"--amend", "--help", "-a --all"},
+ },
+ {
+ name: "git commit -m hello ",
+ input: "git commit -m hello ",
+ expected: []string{"--amend", "--help", "-a --all"},
+ },
+ {
+ name: "git commit --message 'my message' ",
+ input: "git commit --message 'my message' ",
+ expected: []string{"--amend", "--help", "-a --all"},
+ },
+ // Unclosed-quote variant: the trailing space is INSIDE the open
+ // quote so the value isn't committed — must still show -m/--message
+ // as the active value-taking flag.
+ {
+ name: "git commit -m \"my message (unclosed quote)",
+ input: "git commit -m \"my message ",
+ expected: []string{"-m --message"},
+ },
+ {
+ name: "git commit -m 'my message (unclosed quote)",
+ input: "git commit -m 'my message ",
+ expected: []string{"-m --message"},
+ },
+ // Mid-typing value (no trailing space): user is still entering it,
+ // completion list should remain pinned to the active flag.
+ {
+ name: "git commit -m hello (no trailing space)",
+ input: "git commit -m hello",
+ expected: []string{"-m --message"},
+ },
}
for _, tc := range testCases {
diff --git a/model.go b/model.go
index a4c1fed..6ae38da 100644
--- a/model.go
+++ b/model.go
@@ -30,7 +30,7 @@ type Model struct {
// ---- Commands ----
- // The commands available
+ // Commands is the command tree the user can complete against and submit.
Commands []*Command
validationErr error
@@ -44,7 +44,7 @@ type Model struct {
// ---- History ----
- // Slice that holds the history of commands
+ // History is the in-memory command history, most recent first.
History []string
filteredHistory []string
historyIndex int
@@ -58,31 +58,31 @@ type Model struct {
// ---- Options ----
- // The maximum number of history items to store
+ // HistoryLimit caps how many commands are retained. ≤ 0 disables history.
HistoryLimit int
- // Whether to indent completions to match the input
+ // IndentCompletions aligns the completion list with the active token.
IndentCompletions bool
- // Whether to trim the input on enter
+ // Autotrim strips surrounding whitespace from the submitted command.
Autotrim bool
- // The base offset from the left, applied to the completions
+ // CompletionsOffset is an additional left offset added to the completion list.
CompletionsOffset int
- // Whether to show different border styles to indicate scrolling
+ // ShowBorderScroll tints the top/bottom border when more rows exist off-screen.
ShowBorderScroll bool
- // Whether to show the horizontal scrollbar to indicate scrolling
+ // ShowScrollbar renders a vertical scrollbar on the completion list.
ShowScrollbar bool
- // The position of the completions relative to the input
+ // CompletionsPosition places the list above or below the input.
CompletionsPosition Position
- // The number of rows to show in the completions
+ // CompletionRows is the visible row count before scrolling.
CompletionRows int
- // Whether to show type indicator icons
+ // ShowIcons renders a type-indicator glyph on each row.
ShowIcons bool
- // Whether to render the description column next to each completion name
+ // ShowDescriptions renders the description column next to each name.
ShowDescriptions bool
- // The icon for command completions
+ // CommandIcon is the glyph used for command rows when ShowIcons is true.
CommandIcon string
- // The icon for argument completions
+ // ArgumentIcon is the glyph used for positional / filesystem rows when ShowIcons is true.
ArgumentIcon string
- // The icon for flag completions
+ // FlagIcon is the glyph used for flag rows when ShowIcons is true.
FlagIcon string
// ---- Filesystem completion (opt-in) ----
@@ -541,7 +541,6 @@ func (f *Flag) Validate() error {
}
}
- // Long flag validation
if f.LongFlag != "" {
if !strings.HasPrefix(f.LongFlag, "--") {
return errors.New("long flags must start with two dashes")
@@ -555,7 +554,6 @@ func (f *Flag) Validate() error {
}
}
- // PowerShell flag validation
if f.PsFlag != "" {
if !strings.HasPrefix(f.PsFlag, "-") {
return errors.New("powershell flags must start with a dash")
diff --git a/parse.go b/parse.go
index 0bee34f..53d6bd9 100644
--- a/parse.go
+++ b/parse.go
@@ -8,23 +8,16 @@ import (
// token is the unit produced by tokenize. It carries enough metadata for
// completion, validation, and quote-error reporting to share a single parse.
type token struct {
- // Raw is the token text as typed, including surrounding quote characters.
- // Sliced directly from the input so invalid UTF-8 bytes are preserved.
+ // Sliced from input verbatim so invalid UTF-8 bytes survive.
Raw string
- // Unquoted is the token text with quote characters removed. Note that
- // invalid UTF-8 sequences in the input are normalized to U+FFFD here
- // (unlike Raw which preserves bytes); use Raw when byte-fidelity matters.
- Unquoted string
- // Start is the byte offset in the input where the token begins.
- Start int
- // End is the byte offset in the input immediately after the token ends.
- End int
- // Quoted is true if the token opened with a quote character.
- Quoted bool
- // Quote is the quote character (' or ") if Quoted is true.
+ // Quote characters stripped. Invalid UTF-8 in input becomes U+FFFD here
+ // (unlike Raw); use Raw when byte-fidelity matters.
+ Unquoted string
+ Start, End int
+ Quoted bool
+ // Quote is the opener (' or "), valid only when Quoted is true.
Quote rune
- // Closed is true if a quoted token's closing quote was seen.
- // Always true for unquoted tokens.
+ // Closed is true if the opening quote was matched, or always for unquoted tokens.
Closed bool
}
@@ -52,7 +45,13 @@ func tokenize(input string) []token {
Unquoted: unquoted.String(),
Start: tokenStart,
End: end,
- Closed: closed || !quoted,
+ // Closed semantics: a token whose opener-quote was matched
+ // (closed), OR a token that did NOT open with a quote AND
+ // has no still-open inner quote at flush time. The
+ // inQuotes guard catches mid-token inner-quote forms like
+ // `--message="test ` where the token starts unquoted but
+ // opens an inner quote that never closes.
+ Closed: closed || (!quoted && !inQuotes),
}
if quoted {
tok.Quoted = true
diff --git a/parse_test.go b/parse_test.go
index d0464fd..22d2212 100644
--- a/parse_test.go
+++ b/parse_test.go
@@ -80,6 +80,22 @@ func TestTokenize(t *testing.T) {
{Raw: `--message="hello world"`, Unquoted: `--message=hello world`, Start: 0, End: 23, Closed: true},
},
},
+ {
+ // Counterpart to the previous case: same shape but the inner
+ // quote never closes. Quoted stays false (the token opened
+ // with '-'), but Closed must be false too — the
+ // closed-detection logic in flush has to account for the
+ // still-open inner quote (the inQuotes guard in parse.go).
+ // Without that guard, an unclosed-inner-quote token would
+ // falsely report Closed=true and downstream consumers (e.g.
+ // isEnteringFlagValue) would think the user committed past
+ // the value.
+ name: "unclosed inner quote leaves token open",
+ input: `--message="hello world`,
+ want: []token{
+ {Raw: `--message="hello world`, Unquoted: `--message=hello world`, Start: 0, End: 22, Closed: false},
+ },
+ },
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
diff --git a/path_integration_test.go b/path_integration_test.go
index 00185bb..636c064 100644
--- a/path_integration_test.go
+++ b/path_integration_test.go
@@ -1,7 +1,9 @@
package bubblecomplete
import (
+ "os"
"path/filepath"
+ "strings"
"testing"
tea "charm.land/bubbletea/v2"
@@ -274,6 +276,120 @@ func renderWithFeature(t *testing.T, on bool, input string) string {
return m.Render()
}
+// TestRender_TruncationFooter_AppearsWhenCandidatesDropped exercises the
+// "+ N more — type to narrow" footer end-to-end: types into a directory
+// with more matches than the configured limit, asserts (1) pathState
+// records the drop count, (2) the rendered output contains the footer
+// text, and (3) the footer is NOT inside m.completions (so Tab cycling
+// can't accidentally accept it as a row).
+func TestRender_TruncationFooter_AppearsWhenCandidatesDropped(t *testing.T) {
+ dir := t.TempDir()
+ // 8 files, all matching prefix "f", limit 3 → 5 dropped.
+ for i := range 8 {
+ mustWriteFile(t, filepath.Join(dir, "f"+string(rune('a'+i))+".txt"))
+ }
+
+ m, err := New(pathTestCommands(), 200,
+ WithFilesystemCompletions(true),
+ WithFilesystemCompletionLimit(3),
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ m = simulateTyping(t, m, "cat "+filepath.Join(dir, "f"))
+
+ if m.pathState.droppedSorted != 5 {
+ t.Errorf("pathState.droppedSorted = %d, want 5 (8 matches − limit 3)", m.pathState.droppedSorted)
+ }
+ if len(m.completions) != 3 {
+ t.Errorf("len(m.completions) = %d, want 3 (limit)", len(m.completions))
+ }
+ for _, c := range m.completions {
+ if strings.Contains(c.getName(), "more") {
+ t.Errorf("footer must NOT be a completion row (Tab would accept it): %q", c.getName())
+ }
+ }
+
+ out := m.Render()
+ if !strings.Contains(out, "+ 5 more") {
+ t.Errorf("expected '+ 5 more' footer text in render output; got:\n%s", out)
+ }
+ if !strings.Contains(out, "type to narrow") {
+ t.Errorf("expected 'type to narrow' hint in footer; got:\n%s", out)
+ }
+}
+
+// TestRender_TruncationFooter_UnresolvedOnly exercises the weaker-wording
+// branch end-to-end: a directory of symlinks where the stat budget can
+// resolve N (≤ limit) of them, leaving the rest unresolved with kind
+// unknown. The footer should use "symlinks unresolved — narrow to
+// filter", NOT the strong "+ N more" form, because we can't actually
+// claim the unresolved entries would be valid candidates.
+func TestRender_TruncationFooter_UnresolvedOnly(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "target.txt")
+ mustWriteFile(t, target)
+ // 20 symlinks. limit=16 so statBudget(16)=16 (the floor). 16 resolve to
+ // files, all pass the FileArgument inclusion filter; sort+truncate
+ // keeps all 16 (no sort drop). The remaining 4 symlinks are budget-
+ // skipped → unresolved.
+ const symlinkCount = 20
+ for i := range symlinkCount {
+ name := filepath.Join(dir, "ln"+string(rune('a'+i)))
+ if err := os.Symlink(target, name); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ m, err := New(pathTestCommands(), 500,
+ WithFilesystemCompletions(true),
+ WithFilesystemCompletionLimit(16),
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ m = simulateTyping(t, m, "cat "+filepath.Join(dir, "ln"))
+
+ if m.pathState.droppedSorted != 0 {
+ t.Errorf("droppedSorted = %d, want 0 (resolved set fits within limit)", m.pathState.droppedSorted)
+ }
+ if m.pathState.unresolvedEntries != 4 {
+ t.Errorf("unresolvedEntries = %d, want 4 (20 symlinks − statBudget floor 16)", m.pathState.unresolvedEntries)
+ }
+
+ out := m.Render()
+ if !strings.Contains(out, "4 symlinks unresolved") {
+ t.Errorf("expected 'N symlinks unresolved' weaker wording in render; got:\n%s", out)
+ }
+ if !strings.Contains(out, "narrow to filter") {
+ t.Errorf("expected 'narrow to filter' suffix in unresolved-only footer; got:\n%s", out)
+ }
+ if strings.Contains(out, "+ ") && strings.Contains(out, "more") {
+ t.Errorf("unresolved-only footer must NOT use the strong '+ N more' wording; got:\n%s", out)
+ }
+}
+
+// TestRender_TruncationFooter_HiddenWhenNoDrops asserts the footer does
+// not appear when the candidate list fit within the limit. Cheap
+// regression guard so we don't accidentally show "+ 0 more" or any
+// truncation hint when nothing was dropped.
+func TestRender_TruncationFooter_HiddenWhenNoDrops(t *testing.T) {
+ dir := t.TempDir()
+ mustWriteFile(t, filepath.Join(dir, "foo.txt"))
+
+ m := newPathTestModel(t, true)
+ m = simulateTyping(t, m, "cat "+filepath.Join(dir, "f"))
+
+ if m.pathState.droppedSorted != 0 || m.pathState.unresolvedEntries != 0 {
+ t.Fatalf("setup: expected both drop counts 0, got droppedSorted=%d unresolvedEntries=%d",
+ m.pathState.droppedSorted, m.pathState.unresolvedEntries)
+ }
+ out := m.Render()
+ if strings.Contains(out, "more") {
+ t.Errorf("did not expect 'more' anywhere in render when no drops; got:\n%s", out)
+ }
+}
+
// TestRender_OverlayChangesOutputByValidity asserts that the rendered output
// differs between valid/partial/invalid validity classes when the feature
// is enabled — i.e. the overlay is applied and the chosen style differs by
diff --git a/pathcomplete.go b/pathcomplete.go
index 4023ee0..0f575dc 100644
--- a/pathcomplete.go
+++ b/pathcomplete.go
@@ -59,6 +59,28 @@ type pathState struct {
// candidates is the list rendered in place of the normal completion
// rows when active and non-empty.
candidates []pathCompletion
+ // droppedSorted is the count of fully-verified matching entries that
+ // passed the kind/hidden/prefix filters but were truncated because
+ // the survivor list exceeded [Model.FilesystemCompletionLimit].
+ // These are real "+ N more" candidates the user could reach by
+ // narrowing the prefix — the renderer surfaces them as the primary
+ // truncation hint.
+ droppedSorted int
+ // unresolvedEntries is the count of symlink-OR-unknown-kind entries we
+ // could NOT verify because the per-pass stat budget was exhausted.
+ // Some might be valid candidates after resolution; some might be
+ // broken symlinks or the wrong kind for the active argument. The
+ // renderer surfaces this with weaker wording than droppedSorted —
+ // it's a "couldn't classify" signal, not a "found more" signal.
+ //
+ // The field name says "entries" because kindUnknown entries also count
+ // here, but the user-facing footer wording says "symlinks" because in
+ // practice the unknown-kind case is extremely rare (Go's stdlib
+ // resolves DT_UNKNOWN via lstat at readdir time, so kindUnknown only
+ // surfaces for non-standard fs.FS implementations). The naming
+ // asymmetry is deliberate: internal precision, UI clarity for the
+ // realistic case.
+ unresolvedEntries int
}
// pathCompletion is a [completion] backed by a filesystem entry under the
@@ -382,9 +404,22 @@ type candidateRequest struct {
// Symlink target kinds are resolved via [os.Stat] for entries that survive
// the prefix and hidden filters; [statBudget] bounds the worst-case stat
// count per pass.
-func generateCandidates(req candidateRequest) []pathCompletion {
+//
+// Returns the candidate list plus two separate drop counts:
+// - droppedSorted: matching entries that passed all filters but were
+// truncated because the survivor list exceeded the configured limit.
+// These are verified "+ N more" — narrowing the prefix would reach them.
+// - unresolvedEntries: symlink/unknown-kind entries the stat budget
+// couldn't classify in this pass. Some might be valid candidates if
+// resolved; some might be broken or the wrong kind. These get weaker
+// UI treatment than droppedSorted.
+//
+// Keeping the two counts separate (rather than summing them) lets the
+// renderer phrase the footer honestly: the strong "+ N more" claim only
+// applies to verified drops.
+func generateCandidates(req candidateRequest) (candidates []pathCompletion, droppedSorted, unresolvedEntries int) {
if req.entry.err != nil {
- return nil
+ return nil, 0, 0
}
limit := max(req.limit, 1)
@@ -413,12 +448,13 @@ func generateCandidates(req candidateRequest) []pathCompletion {
wasSymlink := k == kindSymlink
if k == kindSymlink || k == kindUnknown {
if statsRemaining <= 0 {
- continue // budget exhausted; drop
+ unresolvedEntries++
+ continue // budget exhausted; drop (kind unverified)
}
statsRemaining--
info, err := os.Stat(filepath.Join(req.parent, name))
if err != nil {
- continue // broken symlink or stat failure
+ continue // broken symlink or stat failure — verified failure, not a drop
}
switch {
case info.IsDir():
@@ -445,6 +481,7 @@ func generateCandidates(req candidateRequest) []pathCompletion {
})
if len(survivors) > limit {
+ droppedSorted = len(survivors) - limit
survivors = survivors[:limit]
}
@@ -452,7 +489,7 @@ func generateCandidates(req candidateRequest) []pathCompletion {
for i, s := range survivors {
out[i] = buildCompletion(s.name, s.isDir, s.isSymlink, req.tokenPrefix, req.userPrefix, req.openingQuote)
}
- return out
+ return out, droppedSorted, unresolvedEntries
}
// includeKind applies the candidate-inclusion table:
@@ -595,24 +632,28 @@ func (m *Model) recomputePathState() {
limit := max(m.FilesystemCompletionLimit, 1)
+ candidates, droppedSorted, unresolvedEntries := generateCandidates(candidateRequest{
+ kind: a.kind,
+ tokenPrefix: a.tokenPrefix,
+ userPrefix: userPrefix,
+ openingQuote: a.openingQuote,
+ base: base,
+ entry: entries,
+ limit: limit,
+ hiddenFiles: m.HiddenFiles,
+ parent: parent,
+ })
+
m.pathState = pathState{
- active: true,
- kind: a.kind,
- argName: a.name,
- valueStart: a.valueStart,
- valueEnd: a.valueEnd,
- base: base,
- validity: classify(a.kind, fullClean, base, entries),
- candidates: generateCandidates(candidateRequest{
- kind: a.kind,
- tokenPrefix: a.tokenPrefix,
- userPrefix: userPrefix,
- openingQuote: a.openingQuote,
- base: base,
- entry: entries,
- limit: limit,
- hiddenFiles: m.HiddenFiles,
- parent: parent,
- }),
+ active: true,
+ kind: a.kind,
+ argName: a.name,
+ valueStart: a.valueStart,
+ valueEnd: a.valueEnd,
+ base: base,
+ validity: classify(a.kind, fullClean, base, entries),
+ candidates: candidates,
+ droppedSorted: droppedSorted,
+ unresolvedEntries: unresolvedEntries,
}
}
diff --git a/pathcomplete_test.go b/pathcomplete_test.go
index ac6143e..0d5cce9 100644
--- a/pathcomplete_test.go
+++ b/pathcomplete_test.go
@@ -304,13 +304,13 @@ func TestGenerateCandidates_InclusionRules(t *testing.T) {
entry := c.read(dir)
// FileArgument: files + dirs (drill-down), no specials.
- fileCands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ fileCands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if !containsName(fileCands, "alpha.txt") || !containsName(fileCands, "subdir/") {
t.Errorf("FileArgument candidates missing files or dirs: %v", names(fileCands))
}
// DirArgument: dirs only.
- dirCands := generateCandidates(candidateRequest{kind: DirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ dirCands, _, _ := generateCandidates(candidateRequest{kind: DirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
for _, c := range dirCands {
if !c.isDir {
t.Errorf("DirArgument surfaced non-dir %q", c.displayName)
@@ -321,7 +321,7 @@ func TestGenerateCandidates_InclusionRules(t *testing.T) {
}
// FileDirArgument: files + dirs.
- fdCands := generateCandidates(candidateRequest{kind: FileDirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ fdCands, _, _ := generateCandidates(candidateRequest{kind: FileDirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if !containsName(fdCands, "alpha.txt") || !containsName(fdCands, "subdir/") {
t.Errorf("FileDirArgument candidates missing files or dirs: %v", names(fdCands))
}
@@ -333,19 +333,19 @@ func TestGenerateCandidates_HiddenFiles(t *testing.T) {
entry := c.read(dir)
// Default: dotfiles hidden when base prefix doesn't start with '.'.
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if containsName(cands, ".hidden") {
t.Errorf("dotfile leaked into candidates: %v", names(cands))
}
// Typed prefix "." surfaces dotfiles even without the option.
- cands = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: ".", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: ".", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if !containsName(cands, ".hidden") {
t.Errorf("dotfile not surfaced for '.' prefix: %v", names(cands))
}
// Option enabled: always surfaced.
- cands = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: true, parent: dir})
+ cands, _, _ = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: true, parent: dir})
if !containsName(cands, ".hidden") {
t.Errorf("dotfile not surfaced with HiddenFiles=true: %v", names(cands))
}
@@ -356,7 +356,7 @@ func TestGenerateCandidates_PrefixFilter(t *testing.T) {
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "alph", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "alph", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if !containsName(cands, "alpha.txt") {
t.Errorf("prefix 'alph' should match alpha.txt: %v", names(cands))
}
@@ -376,7 +376,7 @@ func TestGenerateCandidates_SymlinkResolution(t *testing.T) {
// FileArgument: link_alpha (symlink to file) included, link_dir
// (symlink to dir) also included (drill-down), link_broken excluded.
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if !containsName(cands, "link_alpha") {
t.Errorf("link_alpha should be included: %v", names(cands))
}
@@ -388,7 +388,7 @@ func TestGenerateCandidates_SymlinkResolution(t *testing.T) {
}
// DirArgument: only link_dir.
- dirCands := generateCandidates(candidateRequest{kind: DirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ dirCands, _, _ := generateCandidates(candidateRequest{kind: DirArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if containsName(dirCands, "link_alpha") {
t.Errorf("link_alpha (→file) should NOT be in DirArgument: %v", names(dirCands))
}
@@ -401,7 +401,7 @@ func TestGenerateCandidates_SortDirsFirst(t *testing.T) {
dir := makeTestDir(t)
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
// All directory entries should precede all file entries in the output.
sawFile := false
@@ -416,6 +416,93 @@ func TestGenerateCandidates_SortDirsFirst(t *testing.T) {
}
}
+// TestGenerateCandidates_DropCounts asserts that the two drop-count
+// returns (droppedSorted, unresolvedEntries) are populated independently.
+// droppedSorted is verified post-filter truncation; unresolvedEntries is
+// the budget-skipped count for symlinks the stat budget couldn't resolve.
+// Keeping them separate lets the renderer phrase the footer honestly:
+// "+ N more" only applies to verified drops, while unresolved entries get
+// weaker wording because their kind is unknown.
+func TestGenerateCandidates_DropCounts(t *testing.T) {
+ t.Run("sort-truncate drops counted", func(t *testing.T) {
+ dir := t.TempDir()
+ for i := range 10 {
+ mustWriteFile(t, filepath.Join(dir, "f"+padNum(i)+".txt"))
+ }
+ c := newDirCache()
+ entry := c.read(dir)
+
+ _, droppedSorted, unresolved := generateCandidates(candidateRequest{
+ kind: FileArgument,
+ base: "",
+ entry: entry,
+ limit: 3,
+ parent: dir,
+ })
+ // 10 files match prefix "", limit 3 → 7 dropped after sort.
+ if droppedSorted != 7 {
+ t.Errorf("droppedSorted = %d, want 7", droppedSorted)
+ }
+ if unresolved != 0 {
+ t.Errorf("unresolvedEntries = %d, want 0 (no symlinks present)", unresolved)
+ }
+ })
+
+ t.Run("budget-skipped symlinks counted separately", func(t *testing.T) {
+ dir := t.TempDir()
+ target := filepath.Join(dir, "target.txt")
+ mustWriteFile(t, target)
+ // Far more symlinks than statBudget(limit) can resolve: 50
+ // symlinks, limit 2 → budget floor 16. 50 - 16 = 34 unresolved.
+ // The 16 we DID resolve are all files; sort+truncate to limit 2
+ // drops 14 more (the dropped 14 are verified files).
+ const symlinkCount = 50
+ for i := range symlinkCount {
+ name := filepath.Join(dir, "ln"+padNum(i))
+ if err := os.Symlink(target, name); err != nil {
+ t.Fatal(err)
+ }
+ }
+ c := newDirCache()
+ entry := c.read(dir)
+
+ _, droppedSorted, unresolved := generateCandidates(candidateRequest{
+ kind: FileArgument,
+ base: "ln",
+ entry: entry,
+ limit: 2,
+ parent: dir,
+ })
+ if unresolved != 34 {
+ t.Errorf("unresolvedEntries = %d, want 34 (50 symlinks − statBudget floor 16)", unresolved)
+ }
+ if droppedSorted != 14 {
+ t.Errorf("droppedSorted = %d, want 14 (16 resolved − limit 2)", droppedSorted)
+ }
+ })
+
+ t.Run("no drops reports zero", func(t *testing.T) {
+ dir := t.TempDir()
+ for i := range 3 {
+ mustWriteFile(t, filepath.Join(dir, "f"+padNum(i)+".txt"))
+ }
+ c := newDirCache()
+ entry := c.read(dir)
+
+ _, droppedSorted, unresolved := generateCandidates(candidateRequest{
+ kind: FileArgument,
+ base: "",
+ entry: entry,
+ limit: 50,
+ parent: dir,
+ })
+ if droppedSorted != 0 || unresolved != 0 {
+ t.Errorf("no drops: droppedSorted=%d unresolved=%d, want both 0",
+ droppedSorted, unresolved)
+ }
+ })
+}
+
// TestGenerateCandidates_StatBudget pins the budget contract: with more
// symlinks than statBudget(limit), the surplus symlinks are silently
// dropped rather than triggering an unbounded stat storm. The output count
@@ -442,7 +529,7 @@ func TestGenerateCandidates_StatBudget(t *testing.T) {
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "ln", entry: entry, limit: 2, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "ln", entry: entry, limit: 2, hiddenFiles: false, parent: dir})
if len(cands) > 2 {
t.Errorf("candidates exceeded limit: got %d, want ≤ 2", len(cands))
}
@@ -470,7 +557,7 @@ func TestGenerateCandidates_UnknownTypeResolvedByStat(t *testing.T) {
foldNames: []string{"real.txt"},
kinds: []entryKind{kindUnknown}, // forced unknown
}
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "real", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "real", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
if len(cands) != 1 || cands[0].displayName != "real.txt" {
t.Errorf("kindUnknown entry should resolve to file via stat: got %v", names(cands))
}
@@ -481,7 +568,7 @@ func TestGenerateCandidates_Truncation(t *testing.T) {
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 2, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "", entry: entry, limit: 2, hiddenFiles: false, parent: dir})
if len(cands) != 2 {
t.Errorf("limit=2 → len=%d, want 2", len(cands))
}
@@ -492,7 +579,7 @@ func TestGenerateCandidates_CaseSensitivity(t *testing.T) {
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "BET", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "BET", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
if runtime.GOOS == "linux" {
// Case-sensitive: uppercase "BET" matches neither "beta.txt" nor
// "Beta/" because the third byte differs (t vs T).
@@ -519,19 +606,19 @@ func TestGenerateCandidates_InsertionStrings(t *testing.T) {
// Equals-form unquoted: tokenPrefix="--path=", openingQuote=0. File
// completions get a trailing space.
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "--path=", base: "alpha", entry: entry, limit: 10, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "--path=", base: "alpha", entry: entry, limit: 10, parent: dir})
if len(cands) == 0 || cands[0].insertion != "--path=alpha.txt " {
t.Errorf("equals-form insertion = %v, want --path=alpha.txt (with trailing space)", cands)
}
// Equals-form quoted: tokenPrefix=`--path="`, openingQuote='"'.
- cands = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: `--path="`, userPrefix: "", openingQuote: '"', base: "alpha", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
+ cands, _, _ = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: `--path="`, userPrefix: "", openingQuote: '"', base: "alpha", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
if len(cands) == 0 || cands[0].insertion != `--path="alpha.txt" ` {
t.Errorf("equals-quoted insertion = %v, want --path=\"alpha.txt\" (with trailing space)", cands)
}
// Positional quoted with userPrefix preserved.
- cands = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: `"`, userPrefix: "~/", openingQuote: '"', base: "alpha", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
+ cands, _, _ = generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: `"`, userPrefix: "~/", openingQuote: '"', base: "alpha", entry: entry, limit: 10, hiddenFiles: false, parent: dir})
if len(cands) == 0 || cands[0].insertion != `"~/alpha.txt" ` {
t.Errorf("quoted positional insertion = %v, want \"~/alpha.txt\" (with trailing space)", cands)
}
@@ -581,7 +668,7 @@ func TestGenerateCandidates_SymlinkDescription(t *testing.T) {
c := newDirCache()
entry := c.read(dir)
- cands := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
+ cands, _, _ := generateCandidates(candidateRequest{kind: FileArgument, tokenPrefix: "", userPrefix: "", openingQuote: 0, base: "link", entry: entry, limit: 50, hiddenFiles: false, parent: dir})
var alphaDesc, dirDesc string
for _, candidate := range cands {
diff --git a/render.go b/render.go
index 87e8857..1e50a2a 100644
--- a/render.go
+++ b/render.go
@@ -1,8 +1,8 @@
package bubblecomplete
import (
+ "fmt"
"strings"
- "unicode/utf8"
tea "charm.land/bubbletea/v2"
"charm.land/lipgloss/v2"
@@ -97,16 +97,15 @@ type completionRow struct {
func kindOf(c completion) completionKind {
switch c.(type) {
- case *Command, Command:
+ case *Command:
return commandKind
- case *PositionalArgument, PositionalArgument:
+ case *PositionalArgument:
return argumentKind
- case *Flag, Flag:
+ case *Flag:
return flagKind
- case pathCompletion, *pathCompletion:
+ case pathCompletion:
// Path candidates are filesystem entries surfaced for an argument
- // value — map to argumentKind so ShowIcons uses ArgumentIcon, not
- // the fallback CommandIcon.
+ // value — map to argumentKind so ShowIcons uses ArgumentIcon.
return argumentKind
}
return commandKind
@@ -229,17 +228,57 @@ func (m Model) showCompletionsRender() string {
style := m.getCompletionsStyle(start, end, len(rendered))
renderedBox := style.Margin(0, 0, 0, offset).Render(box)
+ // When path completions were dropped — either truncated post-sort or
+ // skipped because the symlink stat budget ran out — append a subtle
+ // footer line BELOW the box describing what's missing. The footer is
+ // render-only (never added to m.completions), so Tab cycling cannot
+ // select or accept it as a completion row. Left-aligned with the box.
+ if m.pathState.active && (m.pathState.droppedSorted > 0 || m.pathState.unresolvedEntries > 0) {
+ footer := m.renderTruncationFooter(offset)
+ renderedBox = lipgloss.JoinVertical(lipgloss.Left, renderedBox, footer)
+ }
+
if m.CompletionsPosition == PositionAbove {
return renderedBox + "\n" + m.renderedInput()
}
return m.renderedInput() + "\n" + renderedBox
}
+// renderTruncationFooter formats the hint that appears below the
+// completion box when generateCandidates dropped some matches. Two
+// distinct counts get distinct wording:
+//
+// - droppedSorted is verified — those entries passed the kind and prefix
+// filters and would be reachable by narrowing the prefix. Surfaced as
+// "+ N more".
+// - unresolvedEntries is unverified — symlinks the stat budget skipped.
+// Some might be valid, some might be broken or wrong-kind. Surfaced
+// with weaker "N unresolved" wording so we don't over-promise results.
+//
+// Combined wording when both counts are non-zero. Styled subtly (muted
+// foreground, italic) so it doesn't compete with the active completion
+// rows. Left margin matches the box.
+func (m Model) renderTruncationFooter(leftMargin int) string {
+ var text string
+ switch {
+ case m.pathState.droppedSorted > 0 && m.pathState.unresolvedEntries > 0:
+ text = fmt.Sprintf("+ %d more (%d unresolved) — type to narrow",
+ m.pathState.droppedSorted, m.pathState.unresolvedEntries)
+ case m.pathState.droppedSorted > 0:
+ text = fmt.Sprintf("+ %d more — type to narrow", m.pathState.droppedSorted)
+ default: // only unresolvedEntries > 0
+ text = fmt.Sprintf("%d symlinks unresolved — narrow to filter",
+ m.pathState.unresolvedEntries)
+ }
+ return m.styles.Completion.Description.
+ Italic(true).
+ MarginLeft(leftMargin).
+ Render(text)
+}
+
func (m Model) renderCompletionRow(row completionRow, titleWidth, completionsWidth int, selected, alt bool) string {
name := row.Name
- lowerPrefix := strings.ToLower(m.matchPrefix)
- prefixRuneLen := utf8.RuneCountInString(m.matchPrefix)
- if start, end := findMatchRange(name, lowerPrefix, prefixRuneLen); start >= 0 {
+ if start, end := findMatchRange(name, m.matchPrefix); start >= 0 {
name = lipgloss.StyleRanges(name, lipgloss.NewRange(start, end, m.styles.Completion.Match))
}
if m.ShowIcons {
@@ -248,6 +287,16 @@ func (m Model) renderCompletionRow(row completionRow, titleWidth, completionsWid
}
}
+ // Cap the rendered name at the box width minus the row's side padding
+ // (one space each side in the JoinHorizontal below). Without this, a
+ // long path completion like "/Users/jane/very/long/.../file.md" would
+ // overflow the box on a narrow terminal. ansi.Truncate is style-aware
+ // — it preserves any match-highlight or icon ANSI prefix.
+ maxNameWidth := max(0, completionsWidth-2)
+ if lipgloss.Width(name) > maxNameWidth {
+ name = ansi.Truncate(name, maxNameWidth, "…")
+ }
+
nameWidth := lipgloss.Width(name)
var rowText string
@@ -361,21 +410,39 @@ func (m Model) getCompletionsWidth(maxLineLength int) int {
return maxLineLength
}
-// findMatchRange finds the rune-based start and end positions where lowerPrefix
-// matches the beginning of any space-separated word in name.
-// This handles flag display names like "-m --message" where the prefix "--me"
-// should match the "--message" portion starting at rune position 3.
+// findMatchRange finds the CELL-based start and end positions within name
+// where matchPrefix (case-insensitively) matches the start of any
+// space-separated word. Cell-based so the returned range plugs directly
+// into [lipgloss.NewRange], which is column/cell-indexed — not rune-indexed.
+//
+// This handles flag display names like "-m --message" where the prefix
+// "--me" should highlight the "--me" portion of "--message". It also
+// handles wide-rune names ("日本.txt" with prefix "日") correctly: lipgloss
+// measures "日" as 2 cells, so the highlight covers both columns rather
+// than just one — the bug a naive rune-position implementation would hit.
+//
+// Best-effort caveat: the returned range uses lipgloss.Width(matchPrefix)
+// for the highlight length, which assumes case folding preserves cell
+// width. That's true for ASCII and for typical Latin/CJK casing, but a
+// few obscure Unicode codepoints (e.g. the Turkish dotless-İ pair, some
+// digraphs) fold to substrings whose cell width differs from the source.
+// In those rare cases the highlight may be off by one cell at the
+// trailing edge. Acceptable for the completion-row use case; revisit if
+// it surfaces in real filenames.
+//
// Returns (-1, -1) if no match is found.
-func findMatchRange(name, lowerPrefix string, prefixRuneLen int) (int, int) {
- if lowerPrefix == "" {
+func findMatchRange(name, matchPrefix string) (int, int) {
+ if matchPrefix == "" {
return -1, -1
}
- runePos := 0
+ lowerPrefix := strings.ToLower(matchPrefix)
+ prefixCells := lipgloss.Width(matchPrefix)
+ cellPos := 0
for word := range strings.SplitSeq(name, " ") {
if strings.HasPrefix(strings.ToLower(word), lowerPrefix) {
- return runePos, runePos + prefixRuneLen
+ return cellPos, cellPos + prefixCells
}
- runePos += utf8.RuneCountInString(word) + 1 // +1 for the space
+ cellPos += lipgloss.Width(word) + 1 // +1 for the space
}
return -1, -1
}
diff --git a/render_test.go b/render_test.go
index 049923c..67bad98 100644
--- a/render_test.go
+++ b/render_test.go
@@ -253,6 +253,80 @@ func TestRender_HistoryActivePathRendersJustTheInput(t *testing.T) {
}
}
+func TestRenderCompletionRow_LongNameTruncates(t *testing.T) {
+ // A completion name longer than the box's content width must be
+ // truncated with an ellipsis so the row fits inside completionsWidth.
+ // Without truncation the row overflows the box border, which is
+ // especially visible for long path completions like a full filesystem
+ // path on a narrow terminal.
+ m, err := New(TestCommands, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ longName := strings.Repeat("a", 60)
+ row := completionRow{Name: longName, Description: "ignored", Kind: argumentKind}
+
+ const completionsWidth = 20
+ rendered := m.renderCompletionRow(row, 5, completionsWidth, false, false)
+
+ // ANSI-stripped width must not exceed completionsWidth + 2 (one cell of
+ // side padding on each end via JoinHorizontal). Without the truncation
+ // fix, the full 60-cell name plus padding would render at ~62 cells.
+ const sidePadding = 2
+ if lipgloss.Width(rendered) > completionsWidth+sidePadding {
+ t.Errorf("rendered width = %d, want ≤ %d (long name should be truncated to fit box)",
+ lipgloss.Width(rendered), completionsWidth+sidePadding)
+ }
+ if !strings.Contains(rendered, "…") {
+ t.Errorf("expected ellipsis marker in truncated name, got: %q", rendered)
+ }
+}
+
+func TestRenderCompletionRow_LongNameTruncates_PreservesMatchHighlight(t *testing.T) {
+ // The truncation step runs AFTER match-highlight ANSI has been embedded
+ // into the name string. ansi.Truncate must therefore correctly handle
+ // the ANSI sequences — not split them mid-CSI and not over-count their
+ // width. This test plants a match-highlight on the first few cells of
+ // a long name and confirms:
+ // 1. lipgloss.Width still measures within the box budget
+ // (ANSI bytes must not inflate the displayed width)
+ // 2. the leading match-highlight bytes survive truncation
+ // (the highlighted prefix is what the user uses to orient,
+ // losing it would be a regression in user experience)
+ m, err := New(TestCommands, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Match the first three cells so the row carries match-highlight ANSI
+ // around "aaa" before truncation runs.
+ m.matchPrefix = "aaa"
+
+ longName := strings.Repeat("a", 60)
+ row := completionRow{Name: longName, Description: "ignored", Kind: argumentKind}
+
+ const completionsWidth = 20
+ rendered := m.renderCompletionRow(row, 5, completionsWidth, false, false)
+
+ const sidePadding = 2
+ if lipgloss.Width(rendered) > completionsWidth+sidePadding {
+ t.Errorf("rendered width with match-highlight = %d, want ≤ %d (ANSI bytes must not inflate width)",
+ lipgloss.Width(rendered), completionsWidth+sidePadding)
+ }
+ if !strings.Contains(rendered, "…") {
+ t.Errorf("expected ellipsis in truncated highlighted name, got: %q", rendered)
+ }
+ // The match-highlight style sets a foreground colour. After truncation
+ // the leading SGR sequence must still be present — verifiable by
+ // checking that the rendered string differs from an un-highlighted
+ // render of the same row (proves the ANSI survived the cut).
+ m.matchPrefix = ""
+ unhighlighted := m.renderCompletionRow(row, 5, completionsWidth, false, false)
+ if rendered == unhighlighted {
+ t.Errorf("truncation stripped the match-highlight ANSI:\n with %q\n without %q",
+ rendered, unhighlighted)
+ }
+}
+
func TestRenderCompletionRow_NarrowTerminalDoesNotPanic(t *testing.T) {
// completionsWidth < nameWidth would have passed negative values to
// lipgloss.Width / PaddingLeft before the clamp.
@@ -497,13 +571,21 @@ func TestFindMatchRange(t *testing.T) {
{"no match", "commit", "xx", -1, -1},
{"empty prefix", "commit", "", -1, -1},
{"case insensitive", "-FileDirArg", "-file", 0, 5},
+ // Wide-rune cases. lipgloss measures a CJK char as 2 cells, so the
+ // returned cell range must reflect that — a rune-based
+ // implementation would report (0, 1) and only highlight half the
+ // glyph.
+ {"wide-rune prefix matches in cells", "日本.txt", "日", 0, 2},
+ {"wide-rune prefix spans two chars", "日本.txt", "日本", 0, 4},
+ // Wide-rune word offset: when the matched word comes after a
+ // space-separated wide-rune word, the returned start must reflect
+ // cells (not runes) past the leading wide-rune word.
+ {"ASCII match after wide-rune word", "日 file.txt", "fi", 3, 5},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
- lower := strings.ToLower(c.prefix)
- runeLen := len([]rune(c.prefix))
- start, end := findMatchRange(c.displayName, lower, runeLen)
+ start, end := findMatchRange(c.displayName, c.prefix)
if start != c.expectedStart || end != c.expectedEnd {
t.Errorf("findMatchRange(%q, %q) = (%d, %d), want (%d, %d)",
c.displayName, c.prefix, start, end, c.expectedStart, c.expectedEnd)
@@ -511,3 +593,61 @@ func TestFindMatchRange(t *testing.T) {
})
}
}
+
+// TestRenderTruncationFooter_BranchWording locks each of the three footer
+// wording branches: verified-only ("+ N more"), unresolved-only ("N
+// symlinks unresolved"), and combined ("+ N more (M unresolved)"). The
+// integration test (TestRender_TruncationFooter_AppearsWhenCandidatesDropped)
+// exercises the verified-only case end-to-end through Update; this is the
+// direct unit-test counterpart for the wording dispatch.
+func TestRenderTruncationFooter_BranchWording(t *testing.T) {
+ m, err := New(TestCommands, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ m.pathState.active = true
+
+ cases := []struct {
+ name string
+ droppedSorted int
+ unresolvedEntries int
+ wantSubstr []string
+ dontWant []string
+ }{
+ {
+ name: "verified drops only",
+ droppedSorted: 5,
+ wantSubstr: []string{"+ 5 more", "type to narrow"},
+ dontWant: []string{"unresolved"},
+ },
+ {
+ name: "unresolved only (weaker wording)",
+ unresolvedEntries: 3,
+ wantSubstr: []string{"3 symlinks unresolved", "narrow to filter"},
+ dontWant: []string{"+ ", "more"},
+ },
+ {
+ name: "both drop kinds combined",
+ droppedSorted: 5,
+ unresolvedEntries: 3,
+ wantSubstr: []string{"+ 5 more", "3 unresolved", "type to narrow"},
+ },
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ m.pathState.droppedSorted = c.droppedSorted
+ m.pathState.unresolvedEntries = c.unresolvedEntries
+ got := m.renderTruncationFooter(0)
+ for _, want := range c.wantSubstr {
+ if !strings.Contains(got, want) {
+ t.Errorf("footer missing %q; got %q", want, got)
+ }
+ }
+ for _, no := range c.dontWant {
+ if strings.Contains(got, no) {
+ t.Errorf("footer should NOT contain %q; got %q", no, got)
+ }
+ }
+ })
+ }
+}
diff --git a/styles.go b/styles.go
index 9e488c9..852ab8f 100644
--- a/styles.go
+++ b/styles.go
@@ -5,8 +5,6 @@ import (
"charm.land/lipgloss/v2/compat"
)
-// Colors — Charm-inspired palette with semantic naming.
-// Pink accent, proper text hierarchy, subtle alternating rows.
var (
accentColor = compat.AdaptiveColor{Light: lipgloss.Color("#D6116B"), Dark: lipgloss.Color("#F5639A")}
accentBgColor = compat.AdaptiveColor{Light: lipgloss.Color("#FDE8F0"), Dark: lipgloss.Color("#3B1D2E")}
diff --git a/validation.go b/validation.go
index 5ab97df..35ad4a5 100644
--- a/validation.go
+++ b/validation.go
@@ -38,9 +38,9 @@ func validateCommandInput(input string, commands []*Command) error {
if parentCmd == nil {
return errInvalidCommand(part)
}
- // If no subcommand is found, stop looking for commands
+ // Reprocess current part as flag/positional under the parent.
isCommand = false
- i-- // Reprocess the current part as a flag or positional argument
+ i--
continue
}
parentCmd = cmd
@@ -106,7 +106,6 @@ func validateCommandInput(input string, commands []*Command) error {
return errUnexpectedArgument(part)
}
- // Check if all required positional arguments are present
expectedPositionalArgs := 0
for _, cmd := range parentCmd.PositionalArguments {
if cmd.Required {