Repository navigation
Unified Completions - #18791
Unified Completions#18791
Conversation
|
@philocalyst Also how much work on completions do you think we will have to do in reedline still? Just out of interest. Do you have any plans? |
|
Hey! Yeah, I just need to update the description here, but this is basically ready for review. My thoughts on where to go with completions needs more thought on what people/core-team think the scope of nushell should be, so I'll try to file an issue on the landscape as I see it, and then we can work from there! |
|
Sounds good, thanks! |
|
it would be great to have a green ci |
|
Does #18879 still work? |
|
CI Should be green and the description is updated! Basically I removed the opt out and just replaced it with an attr, and did some kind of low-key overloading so you can easily opt-in to full context if you're say, carapace. Idk if overloading is common, but I wanted to avoid |
|
@blindFS I'd love your thoughts honestly |
TBH, I think what you wrote in the description looks good. But so many new stuff that I have trouble understanding the code. I can't give you any suggestion about the implementation details. Maybe AI agents can help. Hopefully you can keep maintaining this part in the future. Thanks in advance and wish you good luck. |
There was a problem hiding this comment.
Pull request overview
Unifies custom completer inputs, output validation, menu integration, and interactive execution.
Changes:
- Adds unified
{token, place}/{contexts, place}inputs. - Adds
@interactiveand removes the global background option. - Expands validation, documentation, and completion tests.
Reviewed changes
Copilot reviewed 26 out of 26 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
typos.toml |
Ignores intentional test misspellings. |
tests/repl/test_commandline.rs |
Tests unified input inspection. |
tests/fixtures/lsp/completion/custom.nu |
Updates LSP fixture API. |
tests/fixtures/lsp/completion/command.nu |
Updates command-wide fixture. |
crates/nu-lsp/src/completion.rs |
Uses borrowed completion state. |
crates/nu-explore/src/explore_config/example_data.rs |
Migrates menu examples. |
crates/nu-experimental/src/options/mod.rs |
Removes background option registration. |
crates/nu-experimental/src/options/background_completions.rs |
Removes obsolete option. |
crates/nu-config/default_files/doc_config.nu |
Documents unified completers. |
crates/nu-cmd-lang/src/default_context.rs |
Registers @interactive. |
crates/nu-cmd-lang/src/core_commands/attr/mod.rs |
Exports interactive attribute. |
crates/nu-cmd-lang/src/core_commands/attr/interactive.rs |
Implements @interactive. |
crates/nu-cmd-lang/src/core_commands/attr/complete.rs |
Updates completion example. |
crates/nu-cli/tests/completions/mod.rs |
Expands completion coverage. |
crates/nu-cli/src/util.rs |
Removes terminal guard. |
crates/nu-cli/src/repl.rs |
Uses cache-backed completer. |
crates/nu-cli/src/menus/menu_completions.rs |
Unifies menu completion handling. |
crates/nu-cli/src/completions/mod.rs |
Exports new completion components. |
crates/nu-cli/src/completions/custom_completions/output.rs |
Parses and validates outputs. |
crates/nu-cli/src/completions/custom_completions/mod.rs |
Implements shared user completers. |
crates/nu-cli/src/completions/custom_completions/input.rs |
Builds unified input records. |
crates/nu-cli/src/completions/custom_completions.rs |
Removes legacy implementation. |
crates/nu-cli/src/completions/completion_common.rs |
Prevents subtraction underflow. |
crates/nu-cli/src/completions/completer.rs |
Refactors dispatch, caching, and threading. |
crates/nu-cli/src/completions/arg_value_completion.rs |
Reuses unified context. |
crates/nu-cli/src/commands/commandline/complete.rs |
Adds input inspection flags. |
Suppressed comments (7)
crates/nu-explore/src/explore_config/example_data.rs:723
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n open $nu.history-path | get history.command_line | to text\n | fzf -f $buffer\n | lines\n | each {|v| {value: ($v | str trim)} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:741
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n ls $env.PWD | where type == dir\n | sort-by name | get name | to text\n | fzf -f $buffer\n | each {|v| {value: ($v | str trim)} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:758
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n scope commands\n | where name =~ $buffer\n | each {|it| {value: $it.name description: $it.usage} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:773
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n scope variables\n | where name =~ $buffer\n | sort-by name\n | each {|it| {value: $it.name description: $it.type} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:792
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n scope commands\n | where name =~ $buffer\n | each {|it| {value: $it.name description: $it.usage} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:809
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n scope aliases\n | where name == $buffer\n | each {|it| {value: $it.expansion} }\n }"
crates/nu-explore/src/explore_config/example_data.rs:824
inputis not a recognized unified-input field name, so it is bound tonothingand$input.texterrors. Rename this positional totokenand read itstextfield.
"source": "{|input|\n let buffer = $input.text\n history -l\n | where session_id == (history session)\n | select command\n | where command =~ $buffer\n | each {|it| {value: $it.command} }\n | reverse\n | uniq\n }"
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
Hey, just a bot checking in! You edited files related to the configuration. |
|
Fixed all of the review comments, the files i modified related to configuration are fixes towards the new API |
|
@philocalyst help me understand how to get your example working. I put it in a file and sourced it and it gives errors. @interactive
def pick-file [token] { ls | get name | to text | ^fzf --query $token.text }~/src/nushell> source f-test.nu
~/src/nushell> pick-file c
Error: nu::shell::incompatible_path_access
× Data cannot be accessed with a cell path
╭─[/Users/fdncred/src/nushell/f-test.nu:2:71]
1 │ @interactive
2 │ def pick-file [token] { ls | get name | to text | ^fzf --query $token.text }
· ──┬─
· ╰── string doesn't support cell paths
3 │
╰────I then tried the demo.nu file from #18879 with # launch with
# nu --no-config-file --execute 'source demo.nu'
#
@interactive
export def generate-candidates [--fuzzy(-f), tokens: list<string>, ] {
let pattern = $tokens | skip 1 | last
let candidates = ls | where name has $pattern | get name
if ($candidates | length) <= 1 or not $fuzzy {
$candidates
} else {
# $candidates | input list --fuzzy | default $pattern | [$in]
$candidates | to text | ^fzf --reverse | lines | default --empty [$pattern] # <--- FZF
}
}
const fuzzy = true
$env.config.show_banner = false
$env.config.completions.external.completer = {|tokens|
generate-candidates --fuzzy=$fuzzy $tokens
}
export def tokenize [buffer: string, cursor: number] {
let prefix = $buffer | str substring ..<$cursor
let parsed = ast --flatten $prefix
if $parsed != [] and ($parsed | last).span.end < ($prefix | str length) {
$parsed.content ++ ['']
} else {
$parsed.content
}
}
$env.config.keybindings ++= [
{
name: demo-keybinding
modifier: control
keycode: char_t
mode: [emacs vi_insert vi_normal]
event: {
until: [
{send: Menu, name: demo-menu}
{send: MenuNext}
{edit: Complete}
]
}
}
]
$env.config.menus ++= [
{
name: demo-menu
marker: '| '
only_buffer_difference: false
type: { layout: columnar }
style: {}
source: {|buffer, cursor|
let tokens = tokenize $buffer $cursor
let span = {start: ($cursor - ($tokens | last | str length)), end: $cursor}
generate-candidates --fuzzy=$fuzzy $tokens
| wrap value
| insert span $span
}
}
]I'd also like to get the nushell script working that is generated from fzf. fzf --nushell | save -f ($nu.default-config-dir | path join "autoload" "_fzf_integration.nu") |
|
Should be solid, now? |
|
Oh shoot wanted to clarify, it should look like below: export def generate-candidates [--fuzzy(-f), tokens: list<string>] {
let pattern = $tokens | skip 1 | last
let candidates = ls | where name has $pattern | get name
if ($candidates | length) <= 1 or not $fuzzy {
$candidates
} else {
# $candidates | input list --fuzzy | default $pattern | [$in]
$candidates | to text | ^fzf --reverse | lines | default --empty [$pattern]
}
}
const fuzzy = true
$env.config.show_banner = false
$env.config.completions.external.completer = {
closure: {|contexts|
generate-candidates --fuzzy=$fuzzy ($contexts.tokens | get text)
}
interactive: true
}
export def tokenize [buffer: string, cursor: number] {
let prefix = $buffer | str substring ..<$cursor
let parsed = ast --flatten $prefix
if $parsed != [] and ($parsed | last).span.end < ($prefix | str length) {
$parsed.content ++ ['']
} else {
$parsed.content
}
}
$env.config.keybindings ++= [
{
name: demo-keybinding
modifier: control
keycode: char_t
mode: [emacs vi_insert vi_normal]
event: {
until: [
{send: Menu, name: demo-menu}
{send: MenuNext}
{edit: Complete}
]
}
}
]
$env.config.menus ++= [
{
name: demo-menu
marker: '| '
only_buffer_difference: false
type: { layout: columnar }
style: {}
source: {|buffer, cursor|
let tokens = tokenize $buffer $cursor
let span = {
start: ($cursor - ($tokens | last | str length))
end: $cursor
}
generate-candidates --fuzzy=$fuzzy $tokens
| wrap value
| insert span $span
}
}
] |
|
And I see/recognize $env.config.completions.external.completer = {
closure: {|contexts|
generate-candidates --fuzzy=$fuzzy ($contexts.tokens | get text)
}
interactive: true
}is a bit boilerplatey, the cleaner solution would be to have attribute support on closures, but that's not a reality right now. there are other approaches, as well, maybe external.interactive_completor = CLOSURE ? |
1b2528e to
186fcc2
Compare
I don't understand the point of And I get this error message with it. cargo r -- --no-config-file --execute 'source demo2.nu'
Finished [`dev` profile [unoptimized + debuginfo]](https://doc.rust-lang.org/cargo/reference/profiles.html#default-profiles) target(s) in 0.87s
Running `target/debug/nu --no-config-file --execute 'source demo2.nu'`
Error: nu::shell::invalid_config
× Encountered 1 error(s) when updating config
Error: nu::shell::type_mismatch
× Type mismatch at $env.config.completions.external.completer
╭─[/Users/fdncred/src/nushell/demo2.nu:17:48]
16 │
17 │ ╭─▶ $env.config.completions.external.completer = {
18 │ │ closure: {|contexts|
19 │ │ generate-candidates --fuzzy=$fuzzy ($contexts.tokens | get text)
20 │ │ }
21 │ │ interactive: true
22 │ ├─▶ }
· ╰──── expected closure or nothing, but got record<closure: closure, interactive: bool>
23 │
╰────
help: Check the value assigned to $env.config.completions.external.completer. Expected type: closure or nothing, found: record<closure:
closure, interactive: bool>.I'm beginning to think that I'm doing something wrong. I can't get the ❯ source f-test.nu
❯ pick-file c
Error: nu::shell::incompatible_path_access
× Data cannot be accessed with a cell path
╭─[/Users/fdncred/src/nushell/f-test.nu:2:71]
1 │ @interactive
2 │ def pick-file [token] { ls | get name | to text | ^fzf --query $token.text }
· ──┬─
· ╰── string doesn't support cell paths
3 │
╰────I confirmed that I'm on 186fcc2 so I'm not sure what is going on. |
|
I will get some time to test it out now maybe i find out whats wrong. |
Screen.Recording.2026-08-28.at.11.43.10.mov @interactive
def fzf-files [token: record] {
let query = $token.text
let choices = ls | where name has $query | get name
if ($choices | length) <= 1 {
$choices
} else {
$choices | to text | ^fzf --reverse --query $query | lines
}
}
$env.config.completions.external.completer = {|token| fzf-files $token }Works exactly with that configuration! |
|
All resolved! |
|
Thanks @philocalyst !! |
|
Tested the 2,6,7 from the HackMD again, they now all work as expected now. |
|
woot ! |
|
Nice job all who participated! |
…input is deprecated (#4297) Nushell [0.116.0](https://github.com/nushell/nushell/releases/tag/0.116.0) (released 2026-09-26) binds custom completer inputs by parameter name ([nushell/nushell#18791](nushell/nushell#18791)). Our completer's parameter is still named `spans`, the old name, so sourcing the `wt` integration on 0.116 prints a multi-line `nu::shell::deprecated` warning ("Positional completer input deprecated") at every shell startup. Completions still work, but only through a compatibility bridge that Nushell says will be removed in a future release. After that, the completer would receive `nothing` and `wt` tab completion would stop working. This PR renames the parameter to `place`, the name Nushell's migration table suggests. On 0.116, `place` is a record whose `command` field holds the same token list `spans` used to. On older versions the argument is still the plain spans list, because they pass it positionally regardless of the parameter's name. The completer checks which of the two it received, so a single template works on both. Tested by generating the integration (`wt config shell init nu`) from this branch and running `commandline complete` against it on Nushell 0.115.1 and 0.116.0: - Neither version prints a warning. On main, 0.116.0 prints it. - Both versions give identical results for `wt ` (subcommands), `wt switch ` (branches), and `wt config sh` (→ `shell`, `show`). These match what the `spans` version returns today. - Integration tests matching `nu`/`completion`/`git_error_display` under `--features shell-integration-tests` give the same results on both versions. The only two failures are fish `config show` snapshots, which fail identically on unmodified main in this sandbox. The `init_nu` snapshot changes to match the template. The CI Nushell pin bump to 0.116.0 is in a separate PR and doesn't depend on this one. Co-authored-by: worktrunk-bot <[email protected]>
Weekly CI pin bump: Nushell `0.115.1` → `0.116.0`, the latest [`nushell/nushell` release](https://github.com/nushell/nushell/releases/tag/0.116.0) (published 2026-09-26). Seven sites move together: - the five `hustcer/setup-nu` inputs: `coverage.yaml`, `benchmarks.yaml`, `nightly.yaml`, and `.github/actions/{test,tend}-setup/action.yaml` - `NU_VERSION` in `.codex/cloud.sh`, which the weekly checklist keeps level with `test-setup` - `NU_VERSION` in `Taskfile.yaml`'s `setup-web` The `nu-0.116.0-x86_64-unknown-linux-gnu.tar.gz` asset that `cloud.sh` and `setup-web` download is published on the release. This is in its own PR because Nushell's version moves PTY snapshots under `--all-features`, and this PR's CI is the only place the bump is tested on macOS and Windows. The release's one breaking change that touches this repo is the unified completer input ([nushell/nushell#18791](nushell/nushell#18791)). `templates/nushell.nu` already handles it: #4297 moved the completer to the new `place` input, so 0.116 no longer warns when the integration is sourced. Locally, with 0.116.0 on `PATH`, the `shell` integration-test subset gives the same results as with 0.115.1: 193 passed, and the same 16 failures, which are sandbox-environment snapshot failures present on main. Co-authored-by: worktrunk-bot <[email protected]>
…close and reopen (#19129) ## Description Since #18791 every completion menu closes as soon as the typed text matches nothing, with `persistent_menus` on too (#19096). `SourcedMenu::abandon_if_empty` closes on any settled empty answer, and #18791 wrapped the default columnar and ide menus in it as well. The abandon exists for cancelled pickers: an `@interactive` completer or menu source cancelled with Esc answers empty, and an open empty menu would relaunch it on the next keystroke. A cancelled picker is always the first answer after activation though, while typing past all matches comes after the menu has shown values. So `SourcedMenu` now remembers whether it has shown values since the last `Activate`, and only abandons when the first answer is empty. Testing the picker path turned up two older bugs, both also on `main`: - **Stray indicator.** With `quick` off, the opening `can_partially_complete` probe is the first fetch, but the wrapper skipped the abandon check there. The menu only closed on the next repaint, after the prompt had drawn its indicator, so a `| ` stayed until the next keypress. The probe now checks too; a probe that fetched nothing is still covered by `is_awaiting_first_answer`. - **Picker would not reopen.** `NuCompleter` kept the cancelled picker's empty answer in `latest`, so Tab on the same line served it again instead of running the picker. Interactive answers are now kept only when non-empty, which still dedupes the repeated asks of one keystroke. ## User-facing changes (Release notes) ### Completion menus stay open when nothing matches An open completion menu no longer closes when the typed text stops matching. It shows `NO RECORDS FOUND` and fills again once the text matches, as it did before 0.116. Cancelling an `@interactive` picker with Esc now closes its menu right away, and Tab on the same line opens the picker again. ## Additional notes fixes #19096
Completion inputs, output contracts, and interactive completers
This PR unifies how parameter completers, command-wide completers, external completers, and menu sources receive completion state and return suggestions !!!
It also adds an explicit
@interactiveattribute for completers that need the terminal, such as fzf orinput list.What changes
Previously, custom completion entry points used incompatible calling conventions:
[context, offset][spans]{|spans| ...}{|buffer, position| ...}Each completer had to decide how to interpret its input, reconstruct context when it needed more information, and often call
commandlineto retrieve editor state.Now all custom completion entry points use the same named inputs:
token: the token at the cursor.place: the resolved completion site and replacement range.buffer: the original command line up to the cursor.This applies to:
arg: string@completer@complete completer$env.config.completions.external.completersource: {|token| ...}Completion inputs
A completer declares the information it needs by naming positional parameters. This is not record destructuring: the completion engine binds the declared names directly.
The recognized input names are
token,place, andbuffer. They may be declared in any order. An unrecognized positional name receivesnothingand emits a diagnostic in the completion log.tokentokenis the semantic token being completed:{ text: "mai" kind: "value" span: {start: 3, end: 6} }Its fields are:
textstring""for a fresh empty argument slot.kindstringhead,flag,value, orblock.span{start: int, end: int}ornothingbuffer. Alias-expanded tokens do not have a source span.A cursor after a space still has a token: an empty
valuetoken whose span starts and ends at the cursor. This means normal completion still works for a fresh argument slot.placeplacedescribes what Nushell is completing and what text a selected suggestion replaces:{ cursor: 11 target: {start: 9, end: 11} kind: "positional" index: 0 shape: "string" }Its common fields are:
cursorintbuffer.target{start: int, end: int}kindstringcommand,flag-name,flag-value, orpositional, when applicable.flagstringindexintshapestringUse
place.targetrather thantoken.spanwhen returning a custom span. They differ for completion sites that cover more than one token, such as a multi-word command head or a cell path.bufferbufferis the exact command-line text from the beginning of the line through the cursor:"git checkout mai"It includes text before pipes, inside closures, and after control-flow separators. It intentionally preserves what the user typed rather than reconstructing text from parser output.
This is the input for completers that need the whole line, such as Carapace:
Use
bufferinstead of callingcommandlinefrom inside a completer.bufferalways represents the line currently being completed;commandlinecan be empty in some editor states, including after;.For completers that want a normalized parser view,
std structureconverts a buffer into{text, kind, span}rows while removing duplicate parser spans:std structureis useful for completion logic, but it remains a parsed view. Usebufferwhenever exact source text matters.Inspecting completion state
commandline complete --inputreturns all three inputs without running a custom completer:{ token: {text: mai, kind: value, span: {start: 13, end: 16}} place: { cursor: 16 target: {start: 13, end: 16} kind: positional index: 0 shape: string } buffer: "git checkout mai" }This is the supported way to develop and debug a completer. It also works for an
@interactivecompleter, which cannot run outside the line editor.commandline completeadditionally gains:--detailed: return suggestions in the custom-completer output format.--type directory|path|glob|command|variable|env-var: run one built-in source, useful when composing built-in and custom completions.--input: inspect completion inputs instead of producing suggestions. It cannot be combined with--detailedor--type.For example, a command completer can add its own result beside Nushell’s command-name completion:
Attaching completers
A parameter completer is attached to a signature parameter:
A command-wide completer covers every argument and flag position of a command:
An internal wrapper can opt into the configured external completer:
Aliases resolve through to their completion command, including whether that command is interactive.
Completer output
A completer may return:
nullto decline and let the next completion source run;completions,options, andfallback.The smallest useful completer returns strings:
A suggestion record can control insertion and display:
Supported suggestion fields are:
valuedisplay_overridevalue.descriptionkindvalue,command,cell-path,directory,file,flag,module,operator, orvariable.stylespan{start, end}replacement override. Either end may be omitted.extraappend_whitespacematch_indicesThe envelope form controls filtering and source chaining:
optionssupports:filtersortcase_sensitivematch_descriptioncompletion_algorithmpositionalParameter completers are filtered by default. Command-wide and external completers are not, because they commonly perform their own filtering. Set
options.filterexplicitly when a completer needs the other behavior.fallback: truekeeps this completer’s results and continues to the next source, allowing custom results to appear beside built-in file completion or another completer.Malformed output is isolated where possible. A malformed suggestion, style, span, or option is reported in the completion log without discarding unrelated valid suggestions.
Interactive completers
Ordinary completers run on a background worker. They are non-blocking and have stdin suppressed, which is correct for normal completion but prevents terminal-owning commands from working.
Use
@interactivefor a completer that needs the terminal:When completing
open-file <Tab>,pick-fileruns inline on the line-editor thread with stdin and the terminal available. The picker blocks the editor while it is open, then returns its selection as normal suggestions.@interactivechanges execution placement only. It does not attach a completer to a command, and callingpick-filedirectly is not the intended test because a completer receives its input from the completion engine.External completers are closures and cannot carry an attribute themselves. To make one interactive, have the closure call an
@interactivecommand:The completion engine recognizes that dispatch and runs it inline. A plain external-completer closure remains on the background worker.
Behaviour changes
background-completionsoption is removed.@interactiveis the per-completer replacement.null, allowing file completion or another source to answer.Migration
def comp [input pos] { ... }def comp [token: record] { $token.text | ... }def comp [spans] { ... }def comp [buffer: string] { $buffer | split row " " | ... }when whole-line input is needed{ |spans| ... }external completer{ |buffer: string| ... }{ |buffer position| ... }menu source{ |token: record| ... },{ |place: record| ... }, or{ |buffer: string| ... }@interactiveon the terminal-owning completion commandUser-facing changes (Release notes)
::: warning
This needs a proper changelog entry.
:::