2055 Commits
Author SHA1 Message Date
f00b54e118 Ignore commented-out parameters in signature descriptions (#19625)
## Description

Fixes #7377. A standalone comment line inside a signature that comments
out a flag was included in the previous flag's completion description.
The parser now skips a comment-only line only when it starts like a flag
or rest parameter, i.e. it comments out a parameter. Any other
comment-only line keeps the documented behavior and continues the
previous parameter's description, and inline comments describe their
argument as before. This applies to `def` and `extern` signatures alike,
since both go through the same signature parsing.

Example signature:

```nu
export extern "comp-me" [
  --opt # opt docs
  # --comment-out # commented-out docs
  --arg # arg docs
]
```

### Before

The standalone comment line leaked into the completion description of
the preceding flag: `--opt` was described with `opt docs` plus the `#
--comment-out # commented-out docs` line, so a commented-out flag showed
up in the completions for this extern.

### After

The commented-out line is ignored. Completions for the same signature
are:

- `--opt` with description `opt docs`
- `--arg` with description `arg docs`

`--comment-out` does not appear anywhere. Multi-line descriptions are
unchanged: a comment-only line that does not start like a parameter
still continues the previous parameter's description, and a description
written on the line below its parameter still applies.

## User-facing changes (Release notes)

Comment-only lines in a `def` or `extern` signature that comment out a
parameter no longer show up in the previous parameter's description.

## Additional notes

- Fixes #7377
- Regression tests: `cargo test -p nu-cli --test tests
completions::external_flag_completions_ignore_standalone_comments`,
`cargo test -p nu-cli --test tests
completions::external_flag_completions_multiline_descriptions`, `cargo
test --test tests repl::test_parser::param_description`
- Formatting check: Rust 1.98.1 `rustfmt --check` on the workspace

---------

Co-authored-by: pei711 <pei711@users.noreply.github.com>
Co-authored-by: pei711 <3922088406@qq.com>
2026-11-26 07:47:12 -06:00
Darren Schroeder bf111f1aca Drop 18 crates from Cargo.lock and stop building nu-protocol twice (#19665)
## Description

I'm not sure how helpful this will be since we change things all the
time but it's probably a good practice to look around and see how we can
reduce the amount of crates we use.

This PR removes dependencies nushell can do without. Rewriting `random
pass` without aegis turned up three bugs in it, and moving `get_umask`
turned up a race in `umask`. The PR fixes those too.

- `nu-cmd-extra`'s build script included `theme.rs`, which derives
`nu_protocol::IntoValue`. To read one JSON file, cargo built a second
copy of nu-protocol and everything under it. The build script now has
its own serde struct, and the generated theme list is byte-identical.
- `nu-system` depended on uucore (with clap, fluent and ICU) only for
`get_umask`, and only nu-command calls it. nu-command now has that
function, so every plugin drops 44 crates. `nu_system::get_umask` stays
as a deprecated function that reads the umask through nix.
- `random pass` uses `rand` 0.10 directly instead of
`aegis-password-generator`, which pulled in rand 0.9 and thiserror 1.
- `random uuid -v 3` hashes with the `md-5` 0.11 crate that `hash md5`
already uses, instead of uuid's `v3` feature and its older RustCrypto
stack.
- Hand-written setters with the same signatures replace `derive_setters`
and darling 0.21. `ParseOptions::with_keep_styles` is now deprecated,
like the `keep_styles` field it sets.
- `UniqueString` wraps a `Box<str>` instead of byteyarn's `Yarn`, which
brought zerocopy 0.7.
- parking_lot, lru and nix go back one minor version to match crossterm,
ratatui and uucore, so each one is built once.
- Lockfile bumps of instability and kasuari let ratatui share darling
0.24 and hashbrown 0.17. serde-saphyr stays at 2.1.1 but now resolves
base64 0.23, which its `>=0.21, <0.24` range already allows.
- 31 unused entries are gone from crate manifests, along with the
`dirs-sys` and `webpki-roots` workspace entries that nothing uses.

The `random pass` fixes:

- `--chars` below 4 returned 4 characters, because the password always
took one character from each enabled set. It now returns the requested
length. `--require-each-type` with fewer than 4 characters is an error.
- `--include-ambiguous` and `--include-similar` did nothing, because
aegis ignored them. Passwords now leave out `O 0 l 1 i` by default, as
the help text says, and each flag adds its characters back.
- A negative `--chars` failed with "must be less than or equal to 128".
It now says "greater than 0", and length errors point at the `--chars`
value.

The `umask` fix: reading the umask sets it to 0 for a moment. `umask
<mask>` didn't take the lock that reads take, so a set that landed in
that moment reported `rwxrwxrwx` as the previous mask, and the read then
undid it. Reads and sets now share one lock.

| macOS, default features | main | this PR |
|---|---|---|
| crates in the `nu` build | 582 | 554 |
| crates in a plugin build (`nu_plugin_inc`) | 209 | 150 |
| crates in `nu_plugin_polars` | 481 | 448 |
| packages in `Cargo.lock` | 1029 | 1011 |
| compile units, `cargo build` | 648 | 572 |
| compile units, `cargo build --release` | 740 | 587 |


## User-facing changes (Release notes)

- `random pass --chars` returns exactly the requested length. Below 4 it
used to return 4 characters.
- `random pass` leaves out the look-alike characters `O 0 l 1 i` unless
`--include-ambiguous` or `--include-similar` is given, as its help says.
- `umask <mask>` no longer reports `rwxrwxrwx` as the previous mask, or
loses the new one, when another thread reads the umask at the same time.
- Plugins built on `nu-plugin` compile 59 fewer crates (209 to 150 for
`nu_plugin_inc` on macOS).


## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-25 13:11:24 -06:00
Darren Schroeder 346ea7027a Destructure values with patterns in let, for, closures and assignment (#19643)
## Description

`let`, `mut`, `const`, `for`, closure parameters and assignment now take
patterns, so a record or list comes apart in one step. They use the
patterns `match` already has, with `$name` for each binding.

A pattern has the same shape as the value. `{...}` takes a record apart
by field name, and `[...]` takes a list apart by position. A table is a
list of records, so its pattern nests one in the other. `[{...}]` takes
apart a table with one row, and `[{...}, ..]` takes its first row. `for`
and `each` get one row at a time, so they take `{...}`. Run `describe`
on the value to see which it needs. `split row` gives a `list<string>`,
which takes `[$key, $value]`. `parse` gives a table even for one match,
which takes `[{$user, $host}]`.

Patterns get three new pieces, which work in `match` too:

- `$y?` binds `null` when the field or item is missing.
- `$port = 8080` gives a default. In a list, this works only in
bindings, because `=` in a `match` list is still a string.
- `{$name, ..$rest}` puts the other fields in `$rest`.

A type annotation can cover a whole pattern, as in `let {$x}: record<x:
int> = $r`.

If a value doesn't fit, the error names the missing field or the item
count. `const` reports it at parse time. A destructuring assignment
checks the whole value before it assigns anything.

`match` changes in four places:

- Quoted keys like `{"a b": $x}` match.
- `{a: $x?}` binds `$x`.
- A range pattern tests the interval between its ends.
- A list pattern matches an int range, and binds the rest as a range.

The language server handles pattern variables for hover, references,
highlights and rename. Renaming `$name` when the shorthand `{$name}`
binds it writes `{name: $new}`, so the pattern still reads the field
`name`.

### Examples

Each line runs on its own and the `# =>` lines under it are what it
prints. Each block also runs top to bottom as a script. On main, every
line in the first block fails to parse. In the second block, a `# main:`
comment shows what main gives when it differs.

```nushell
# Records
let {$name, $age} = {name: "nu", age: 5}; $"($name) is ($age)"
# => nu is 5
let {name: $who} = {name: "nu"}; $who
# => nu
let {server: {$host, $port}} = {server: {host: "localhost", port: 80}}; $"($host):($port)"
# => localhost:80
let {"Content-Type": $ctype} = {"Content-Type": "text/html"}; $ctype
# => text/html
let {$host, $port?} = {host: "localhost"}; $port == null
# => true
let {$host, $port = 8080} = {host: "localhost"}; $port
# => 8080
let {$name, ..$rest} = {name: "a", size: 1, type: "file"}; $rest | to nuon
# => {size: 1, type: file}

# Lists
let [$first, $second] = [1 2]; $first + $second
# => 3
let [$head, ..$tail] = [1 2 3]; $tail | to nuon
# => [2, 3]
let [.., $last] = [1 2 3]; $last
# => 3
let [$a, _, $c] = [1 2 3]; $a + $c
# => 4
let [[$a, $b], [$c, $d]] = [[1 2] [3 4]]; $a + $d
# => 5
let [$x, $y?] = [1]; $y == null
# => true
let [$x, $y = 0] = [1]; $x + $y
# => 1

# Tables are lists of records
let [{$name}, ..] = [[name size]; [a 1] [b 2]]; $name
# => a
[[name size]; [a 1] [b 2]] | each {|{$name, $size}| $"($name)=($size)" } | str join ", "
# => a=1, b=2
mut names = []; for {$name} in [[name size]; [a 1] [b 2]] { $names ++= [$name] }; $names | str join ", "
# => a, b

# Int ranges work like lists, and the rest stays a range
let [$a, $b, ..$rest] = 1..5; $rest | to nuon
# => 3..5
let [$first, ..$rest] = 1..; $rest | to nuon
# => 2..
let [$x, $y, ..] = 0..10..100; $x + $y
# => 10

# Strings, durations, dates and cell paths, through the commands that take them apart
let [$key, $value] = "key=value" | split row "="; $value
# => value
# `split row` returns a list, but `parse` returns a table, a list of records, even for one match
let [{$user, $host}] = "alice@example.com" | parse "{user}@{host}"; $host
# => example.com
let {$hour, $minute} = 90min | into record; $"($hour)h ($minute)m"
# => 1h 30m
let {$year, $month, $day} = 2024-03-15 | into record; $"($year)/($month)/($day)"
# => 2024/3/15
let [{value: $first}, ..] = $.a.b | split cell-path; $first
# => a

# Errors in catch
try { error make {msg: "boom"} } catch {|{$msg}| $msg }
# => boom

# Scalars, globs and closures bind whole
let [$n, $flag] = [1 true]; $flag
# => true
let [$docs] = ["*.md"] | into glob; $docs | describe
# => glob
let [$inc, $double] = [{|x| $x + 1} {|x| $x * 2}]; do $double (do $inc 2)
# => 6

# A type annotation, const, and the pipeline form
let {$x, $y}: record<x: int, y: int> = {x: 1, y: 2}; $x + $y
# => 3
const [$a, $b] = [1 2]; $a + $b
# => 3
{a: 1, b: 2} | let {$a, $b}; $a + $b
# => 3

# Assigning to existing mut variables
mut a = 1; mut b = 2; [$a, $b] = [$b, $a]; $"($a) ($b)"
# => 2 1
mut x = 0; mut y = 0; {$x, $y} = {x: 3, y: 4}; $x * $y
# => 12
```

```nushell
# Range patterns test the interval between their ends
match 3.5 { 1..5 => "in", _ => "out" }  # main: out
# => in
match 2 { 1..3..9 => "in", _ => "out" }  # main: out
# => in
match (-5) { ..0 => "up to 0", _ => "other" }  # main: other
# => up to 0
match 100 { 1.. => "positive", _ => "other" }
# => positive
match 5 { 1..<5 => "in", _ => "out" }
# => out
match 7 { 10..1 => "in", _ => "out" }
# => in

# List patterns match int ranges
match 1..5 { [$a, ..$rest] => ($rest | to nuon), _ => "no match" }  # main: no match
# => 2..5
match 1.. { [$a, $b, ..] => ($a + $b), _ => "no match" }  # main: no match
# => 3
match [1] { [$a, $b?] => ($b == null), _ => "no match" }  # main: error: Variable not found.
# => true

# Record patterns
match {"a b": 1} { {"a b": $x} => $x, _ => "no match" }  # main: no match
# => 1
match {a: 1} { {b: $x?} => ($x == null), _ => "no match" }  # main: error: Variable not found.
# => true
match {a: 1} { {$a, $b = 2} => ($a + $b), _ => "no match" }  # main: error: Parse mismatch: expected record.
# => 3
match {a: 1, b: 2} { {$a, ..$rest} => ($rest | to nuon), _ => "no match" }  # main: error: Parse mismatch: expected record.
# => {b: 2}
```

A value that doesn't fit, on this branch:

```nushell
Error: nu::shell::pattern_mismatch

  × Pattern doesn't fit the value
   ╭─[source:1:13]
 1 │ let {$name, $mtime} = {name: "a", size: 1}
   ·             ───┬──
   ·                ╰── record has no field `mtime`
   ╰────
  help: The record has name, size. Add `?` after the pattern if the field can
        be missing.
```

`let [$a, $b] = [1 2 3]` says `list has 3 items, the pattern takes 2`
and suggests `..`.

When the shape is wrong, the help names the right one. On a table, `let
{$user, $host} = ...` suggests `[{...}]`, and so does `let [$user,
$host] = ...` when the row count doesn't match the pattern. On a record,
`let [{$name}] = ...` suggests `{...}`.

```nushell
Error: nu::shell::pattern_mismatch

  × Pattern doesn't fit the value
   ╭─[source:1:5]
 1 │ let [$user, $host] = "alice@example.com" | parse "{user}@{host}"
   ·     ───────┬──────
   ·            ╰── list has 1 item, the pattern takes 2
   ╰────
  help: The list is a table, so each variable here gets a whole row. Write
        `[{...}]` to take the fields of one row.
```

## User-facing changes (Release notes)

- `let`, `mut`, `const` and `for` take patterns: `let {$name, $size} =
ls | first`, `let [$head, ..$tail] = $list`, `for {$name, $type} in (ls)
{ ... }`.
- Closure parameters take patterns: `ls | each {|{$name, $size}| ... }`,
`catch {|{$msg}| ... }`.
- `[$a, $b] = [$b, $a]` assigns to existing `mut` variables.
- New pattern pieces:
  - `$x?` binds `null` when a field or item is missing.
  - `$port = 8080` sets a default.
  - `{$name, ..$rest}` collects the other fields.
  - `let {$x}: record<x: int> = ...` checks the type.
- When a value doesn't fit a pattern, the error names the missing field
or the item count. If the pattern has the wrong shape for a table or a
record, the help suggests `[{...}]` or `{...}`.
- Breaking change: in `match`, a range pattern tests the interval
between its ends. `1..5` matches 3.5, `1..3..9` matches 2, and `..0`
matches any number up to 0 instead of only 0.
- Breaking change: in `match`, a list pattern matches an int range.
`match 1..5 { [$a, ..] => ... }` used to skip that arm.
- `match` record patterns accept quoted keys like `{"a b": $x}`, and
`{a: $x?}` binds `$x`.
- The language server supports hover, references, highlights and rename
on pattern variables.

## Additional notes

- closes #19591 
- closes #6021
- `def` parameters don't take patterns, on purpose. `help`, completions
and `--help` need a parameter's name and type, and a pattern has
neither. Instead, take a record parameter and destructure it with `let`
in the body.
- Bindings use `$name`, as in `match`. A bare word is still a string, so
`let [a, b] = ...` fails with a hint to write `$a`.
- Without an annotation, pattern variables get their parse-time types
from the value, the same as `$value.field`. With the `cell-path-types`
experimental option turned off, they're `any` until run time.
- Public API changes:
  - `Pattern` gains `Optional` and `Interval`.
  - `Expr` gains `Pattern` and `AssignmentPattern`.
  - `Block` gains `parameter_patterns`.
  - IR gains a `destructure` instruction.
  - `ShellError` and `ParseError` each gain `PatternMismatch`.
- `nu_protocol::engine` gains the help texts
`TABLE_FOR_RECORD_PATTERN_HELP` and `RECORD_FOR_LIST_PATTERN_HELP`.
- Left for later:
  - `++` prefix patterns for strings and binary.
- List patterns on float ranges. Their items can't be counted exactly,
so they don't match.
- `for` ignores a pattern's type annotation, as it does for a plain
variable.
  - `(..0)` in parentheses still means `0..0`.
2026-11-25 11:18:47 -06:00
Darren Schroeder 72286fccfd Show parse-time evaluation errors on one line (#19635)
## Description

When evaluation fails at parse time, as in `hide $env.bar` or `const x =
[] | first --strict`, `ShellError::wrap` made a `ParseError` whose
message was the whole rendered report, with box drawing, source snippet
and color codes. Everything that shows an error as one line got that
report. The REPL status line printed it with each line break as a
literal `\n`. The language server, `nu --ide-check`, the debug adapter
and `nu check --debug` passed it on as the message.

`wrap` now builds a new `ParseError::ParseTimeEval`. Its message is
still the report, so printed errors don't change, but it also keeps the
evaluation error. The one-line places show that error's headline and
first label. Editors underline the label's span instead of the whole
value. The MCP server gets the evaluation error's own code, message,
help and labels.

## User-facing changes (Release notes)

- The REPL status line no longer crams a whole error report onto one row
for errors from parse-time evaluation, such as `hide $env.bar`. It shows
`✗ Not a constant: Value is not a parse-time constant`.
- The language server, `nu --ide-check`, the debug adapter and `nu check
--debug` show these errors as one line. Editors underline the part that
failed, such as `into int` in `const d = ('abc' | into int)`.
- The MCP server reports these errors with the evaluation error's own
code, message, help and labels.

## Additional notes
2026-11-23 08:27:31 -06:00
Darren Schroeder 7e1fe77d46 Turn on native-clip and cell-path-types by default (#19634)
## Description

This PR changes two experimental options from opt-in to opt-out, so
they're on by default. Both have been opt-in for more than three months.

- `native-clip` arrived in 0.110.1, tracked in #17665. It adds the
built-in `clip copy` and `clip paste` commands, which use the OS
clipboard API instead of OSC 52.
- `cell-path-types` arrived in 0.111.1, tracked in #17683. It infers the
types of cell paths like `$foo.a.b` at parse time, so the parser reports
a type mismatch before the script runs.

`dc-glob` is old enough too, but it stays opt-in for now.

Since both options are now on for everyone, this PR also fixes three
bugs that were reachable only with an option turned on:

- `cell-path-types` typed an optional path like `$list.5?` as the
element type, `int`, so `let x: nothing = $list.5?` failed to parse. Now
a path with any `?` member is typed `oneof<int, nothing>`.
- On Linux, `clip copy` always used the background clipboard thread,
because `$env.config.clip.resident_mode = false` was ignored. The
setting now works, and the old `plugins.clip.NO_RESIDENT` key still
overrides it when set.
- If the OS refused to start that thread, `clip copy` panicked. Now it
returns an error.


## User-facing changes (Release notes)

- The `native-clip` experimental option is now on by default. `clip
copy` and `clip paste` are built-in commands that use the system
clipboard directly. `use std/clip` still adds the OSC 52 commands `clip
copy52` and `clip paste52`.
- This breaks `"text" | clip` on Windows, which used to run `clip.exe`.
Now `clip` is the built-in command and that line fails to parse. Use
`clip copy`, or `^clip` to run `clip.exe`.
- The `cell-path-types` experimental option is now on by default.
Nushell infers the type of cell paths such as `$record.field` while
parsing, so assigning one to a variable of the wrong type fails before
the script runs. Before, the error appeared only when the line ran.
- On Linux, `$env.config.clip.resident_mode = false` now turns off the
background clipboard thread.
- To get the old behavior, turn either option off with `nu
--experimental-options '[native-clip=false, cell-path-types=false]'`, or
set `NU_EXPERIMENTAL_OPTIONS=native-clip=false,cell-path-types=false`
for sessions that load your config.

## Additional notes
2026-11-23 08:26:54 -06:00
Darren Schroeder aa8bb3fd81 Move dates from chrono to jiff (#19626)
## Description

chrono is unmaintained, so this PR moves nushell's dates to jiff 1.0.
`Value::Date` now holds `nu_protocol::DateTime`, which stores Unix
seconds, nanoseconds and a jiff `Offset`. It is 16 bytes and `Copy`,
like chrono's type, so `Value` stays at 48 bytes. jiff does the
calendar, time zones, parsing and `strftime`. Its range, years -9999 to
9999, is now nushell's.

Output only changes where the release notes say so. `Display`, `Debug`,
RFC 3339, RFC 2822, serde and `format date` print what chrono printed,
localized names included. Input goes through jiff. Date literals, `from
nuon`, `FromStr` and serde use its RFC 3339 reader. `into datetime
--format`, `seq date --input-format` and `from kdl` use its strptime,
plus a small table that keeps chrono's meaning for `%c %x %X %r %v %+
%Z`, nushell's `%J` and `%Q`, and offsets with or without colons. `date
from-human` reads GNU `date` syntax through parse_datetime, after a few
rewrites such as `in 3 days` and `overmorrow`.

chrono-tz, chrono-humanize and human-date-parser leave the dependency
tree, along with the chrono features of rusqlite and calamine. chrono
stays in `Cargo.lock` because rmcp and polars use it. The
chrono-humanize wording and chrono's UTC offset readers are ported under
the MIT license, and each file keeps its notice.

## Before and after

main is 3d8a9cc6e. Both ran with `TZ=America/New_York` on 2026-11-21 at
13:38. Error cells are cut to the reason.

| Command | main | branch |
|---|---|---|
| `2025-04-18T16:04:32.02649+05:30 \| format date '%N'` | `× invalid
format` | `026490000` |
| `'9999-12-31' \| into datetime \| to nuon` |
`9999-12-31T00:00:00-05:00` | `× datetime parsing failed` |
| `2001-02-03T04:05Z \| to nuon` | `× Command 2001-02-03T04:05Z not
found` | `2001-02-03T04:05:00+00:00` |
| `2016-12-31T23:59:60.5Z \| to nuon` | `2016-12-31T23:59:60.500+00:00`
| `2016-12-31T23:59:59.500+00:00` |
| `'Today at 6pm' \| date from-human \| format date '%H:%M'` | `13:38` |
`18:00` |
| `'today at 6pm blah' \| date from-human \| format date '%H:%M'` |
`13:38` | `× Cannot parse as humanized date` |
| `'next hour' \| date from-human \| format date '%H:%M'` | `× Main
thread panicked.` | `14:38` |
| `'6pm tomorrow' \| date from-human \| format date '%a %H:%M'` | `×
Cannot parse as humanized date` | `Sun 18:00` |
| `'TZ="Europe/Paris" 2025-04-18 04:04' \| date from-human \| to nuon` |
`× Cannot parse as humanized date` | `2025-04-18T04:04:00+02:00` |
| `'2025-03-09 02:00' \| into datetime \| to nuon` |
`2025-03-09T02:00:00-05:00` | `2025-03-09T03:00:00-04:00` |
| `'2025-03-09 02:30' \| into datetime --format '%F %H:%M' \| to nuon` |
`× datetime parsing failed` | `2025-03-09T03:30:00-04:00` |
| `2026-07-01T16:00:00Z \| date to-timezone local \| to nuon` |
`2026-07-01T11:00:00-05:00` | `2026-07-01T12:00:00-04:00` |
| `'2021-02-30 10:00' \| into datetime --format '%F %H:%M' \| to nuon` |
`2026-11-21T10:00:00-05:00` | `× … parameter 'day' for 2021-02 is
invalid, must be in range 1..=28 …` |
| `'-5' \| into datetime --format '%s' \| to nuon` | `× can't convert
input contains invalid characters …` | `1969-12-31T23:59:55+00:00` |
| `'07/20/69' \| into datetime --format '%D' \| to nuon` |
`2069-07-20T00:00:00-04:00` | `1969-07-20T00:00:00-04:00` |
| `'Jan 05 2024' \| into datetime --format '%B %d %Y' \| to nuon` |
`2024-01-05T00:00:00-05:00` | `× … %B failed: unrecognized month name …`
|
| `'2021-03-04 10:00 PST' \| into datetime --format '%F %H:%M %Z' \| to
nuon` | `2021-03-04T10:00:00-05:00` | `× can't convert input contains
invalid characters …` |
| `'2021-03-04 10:00:00 -0800 GMT' \| into datetime --format '%F %T %z
%Z' \| to nuon` | `2021-03-04T10:00:00-08:00` | `× can't convert no
possible date and time matching input …` |
| `2100-07-01T12:00:00Z \| date to-timezone America/New_York \| format
date '%:z'` | `-05:00` | `-04:00` |

## Release notes

- Dates run from year -9999 to 9999, where main reached 262142.
9999-12-31 at UTC is past jiff's last instant, so `'9999-12-31' | into
datetime` is an error, and `from toml` and `from msgpack` keep such a
date as text.
- Date literals and `from nuon` read `2001-02-03T04:05Z`,
`[2024-01-15T10:00]` and offsets like `+0530` and `-08` as dates.
`2024-01-15T1030` is still a string, and a fraction longer than 9 digits
no longer reads.
- Second 60 reads as second 59 everywhere.
- `into datetime --format`, `seq date --input-format` and `from kdl`
follow jiff's strptime. A date that doesn't exist or a weekday that
doesn't match is an error, where main gave today at that time. `%B` and
`%A` take only full names, and `%b` and `%a` only abbreviations.
Two-digit years run from 1969 to 2068. `%s` can be negative, and it wins
over a date in the same text.
- `%Z` reads `UTC`, `GMT` and offsets. Other names such as `PST` are an
error, unless `%z` gives the offset, so `+0900 JST` reads. `UTC` or
`GMT` next to a different offset, as in `-0800 GMT`, is an error.
- `format date` and `$env.config.datetime_format` accept `%N`, `%#z` and
the `^` flag, and `datetime_format` drops `%E` and `%O` the way `format
date` does. `seq date --output-format` prints `+0000` for `%z` instead
of failing.
- `date from-human` reads GNU `date` syntax: `6pm tomorrow`, `today
1430`, `@1744972472`, and a leading `TZ="Europe/Paris"`. `next month`,
`next hour` and `today at 6pm` give the right date, where main misread
them or panicked. Text after a date is an error.
- A local time in a DST gap moves forward by the jump, with or without
`--format`. Wall-clock times get the offset of their own date, not
today's, in records, `date to-timezone local`, `date from-human`, `from
xlsx` and `from ods`.
- Time zones come from the system's tzdata, with a bundled 2026f copy as
the fallback, instead of chrono-tz's 2025b. 13 zones have a different
offset today than on main, and DST rules continue past 2099.
- RFC 3339, RFC 2822 and TOML text round a local mean time offset to the
minute and move the clock with it, so the text names the same instant. A
record's `timezone` keeps its seconds.
- polars rejects a date outside 1677-09-21 to 2262-04-11, where main
stored 1970-01-01 or null. A record `year` too large for 32 bits is an
error, and `to plist` rejects years before 0 instead of crashing.
- For plugin authors, `Value::date` and `Value::as_date` take
`nu_protocol::DateTime`. nu-protocol's `chrono` feature converts to and
from `chrono::DateTime<FixedOffset>`. Older plugins keep working, since
dates cross the wire as the same text.
2026-11-23 08:26:13 -06:00
Ted LukinandDarren Schroeder 3dbf050604 make string hooks behave like closure ones (#19600)
<!--
Thanks for contributing to Nushell!

Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md

This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->

## Description
<!--
Explain what this PR does and why.

This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant

Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."

Write as much or as little as needed for reviewers to understand your
changes.
-->
~~pure refactor, semantically everything (i hope) should be the same.~~
removed like 50 lines of code duplication (`eval_string_hook`), also
changed `let mut output; match { x => output = ... }` to just `let
output = match { ... } and eventually went to also fix some stuff, see
release notes

## User-facing changes (Release notes)
<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/

Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.

Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."

If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar

This tells us the change should not appear in the changelog.

Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise

You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure

Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."

You may leave this blank until the PR is ready.
-->
Did you know that you could cause internal panic with
`$env.config.hooks.command_not_found = "hello"; try { world }`? Well now
you can't. String hooks should now match the behavior of closure ones,
for example they no longer are just printed and then swallowed, so you
can correctly catch them.
The only difference remaining is formatting of errors happening inside
the hook itself - string hooks can only point at their source string in
general, whereas closure hooks point at the exact place the error
occurred.
<!--
## Additional notes
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2026-11-22 18:23:07 -06:00
Abdul karim mia 976d8946fa fix(cli): prevent carriage returns (^M) in help menu on Windows (#19629)
## Description

In `crates/nu-cli/src/menus/help_completions.rs`, `NuHelpCompleter` was
hardcoding `\r\n` line separators and transforming command examples with
`.replace('\n', "\r\n")`. In raw terminal mode, reedline splits
completion descriptions by `\n`, leaving behind unstripped carriage
returns (`\r`) at the end of each line which render as literal `^M`
glyphs in the F1 help menu. Furthermore, multiline examples sourced from
CRLF files preserved `\r\n`.

This PR standardizes `NuHelpCompleter` on `\n` line endings, normalizes
multiline examples via `.replace("\r\n", "\n")`, and adds a
comprehensive test asserting that no command's completion description or
example contains carriage returns.

## User-facing changes (Release notes)

- Fixed literal `^M` characters in the F1 help menu.

## Additional notes

closes #19617

---------

Signed-off-by: Abdul karim mia <akmia51@gmail.com>
2026-11-22 18:16:05 -06:00
Martin Kronberger 3b036537d2 fix(config): let the prompt indicators take a closure again (#19612)
## Description

#18734 moved the prompt into `$env.config.prompt`, but the indicator
keys only took a string.
`$env.PROMPT_INDICATOR` and the other indicator variables always took a
closure too, thus migrating an indicator that changes with
`$env.LAST_EXIT_CODE` to the new keys was not possible.

This was never a decision.
The indicators moved first, typed as `String`, before `left` and `right`
joined the PR.
When those followed it turned out config can hold closures after all
(`Hooks` already does), but the indicator keys were never widened.

The indicators now go through the same path as `left` and `right`:
- **config**: the transient keys parse with `update_prompt_source`, the
live keys with an `update_indicator` that differs only by rejecting
`null`, since every edit mode draws an indicator.
- **resolution**: every segment resolves through
`resolve_prompt_source`, `vi_visual` (no variable) through `render`
directly.
- **removed**: `update_optional_string`, `resolve_indicator` and
`resolve_transient_indicator`, which only existed to carry the narrower
type.

A closure that fails to render reports its error and falls back to the
built-in indicator.
`input --reedline` renders the keys the same way.

**Scrutinize**: `crates/nu-cli/src/prompt_update.rs`, the evaluation
order of the segments is kept since any of them may have side effects
now.
**Skim**: the test updates in `crates/nu-protocol/src/config/prompt.rs`,
mostly `"x".into()` to `Value::test_string("x")`.

Tests: `nu-protocol` `config::prompt` 15/15, `nu-cli` `prompt` 28/28
including a new `configured_indicators_accept_closures` that parses and
renders real closures, `nu-command` `reedline_prompt` 1/1.
Clippy with CI flags clean on the touched crates.

## User-facing changes (Release notes)

`$env.config.prompt.indicator`, `vi_insert`, `vi_normal`, `vi_visual`
and `multiline`, plus their `transient` counterparts, now accept a
closure as well as a string, the same as `$env.PROMPT_INDICATOR` and
friends always did.

```nu
$env.config.prompt.indicator = {||
    if $env.LAST_EXIT_CODE == 0 { "> " } else { $"(ansi red)> (ansi reset)" }
}
```

## Additional notes

Follow-up to #18734.

[![AI:W
WRITE](https://img.shields.io/badge/AI-WRITE-grey?style=flat&logoSize=auto&labelColor=13171f)](https://0rwx.com)
2026-11-22 11:31:41 +01:00
Martin Kronberger e6ab229a55 fix(prompt): restore the clock in the fallback right prompt (#19613)
## Description

reedline 0.53 dropped its built-in `CurrentDateTime` segment as part of
removing chrono (nushell/reedline#1248), since a clock needs the local
timezone and std cannot provide one.
`DefaultPrompt::default()` now has an empty right prompt.

Nushell falls back to `DefaultPrompt` whenever no right prompt is set,
so under `--no-config-file` or with `$env.config.prompt.right = null`
the clock silently disappeared.
That was missed when bumping reedline.

The fallback now builds its own `DefaultPrompt` with a
`DefaultPromptSegment::Dynamic` clock rendered by jiff, in the same
`%m/%d/%Y %I:%M:%S %p` format reedline used.
The left side stays the working directory.

Sessions with a config are unaffected, since the default right prompt
there is still the Nu closure in `DEFAULT_PROMPTS`.

Tests: `nu-cli` `prompt::` 7/7, including a new
`the_fallback_right_prompt_is_a_clock`.

## User-facing changes (Release notes)

Fixed the right prompt being empty when running without a config file.
It shows the current date and time again.

## Additional notes

Follow-up to the reedline 0.53 bump.

[![AI:W
WRITE](https://img.shields.io/badge/AI-WRITE-grey?style=flat&logoSize=auto&labelColor=13171f)](https://0rwx.com)
2026-11-22 11:30:58 +01:00
Darren Schroeder bc405a2232 Let an alias end with a flag that takes a value (#19623)
## Description

`alias myfind = find -r` was accepted, but `myfind "txt$"` searched for
the literal text `txt$` and returned an empty list with no error. The
alias kept `-r` without a value, so the next word went to `find`'s other
parameters.

Now the first word after such an alias becomes the flag's value, the way
bash, zsh and fish expand aliases. If no word follows, the parser
reports the missing value at the alias name. `--help` and `-h` still
show help, and tab completion after the alias offers the flag's values.

Names in the alias still resolve where it's defined, so `alias ls = ls
-a` still doesn't call itself.

Examples, main against this branch.

These work now:

| Code | main | this branch |
|---|---|---|
| `alias myfind = find -r; ["file.txt" "x"] \| myfind "txt$"` | empty
list | `[file.txt]` |
| `alias myfind = find -r; ["FILE.TXT" "x"] \| myfind "txt$" -i` | empty
list | `[FILE.TXT]` |
| `alias hex = into int --radix; "ff" \| hex 16` | error: Data cannot be
accessed with a cell path | `255` |
| `alias j = to json -i; {a: 1} \| j 4` | error: Extra positional
argument | JSON indented by 4 spaces |

These don't change:

| Code | main | this branch |
|---|---|---|
| `extern "/bin/echo" [--foo: string, ...rest: string]; alias e =
/bin/echo --foo; e bar` | `--foo bar` | `--foo bar` |
| `alias rep = str replace -a; "aaa" \| rep a b` | `bbb` | `bbb` |
| `alias myfind = find -r; [] \| myfind --help` | help for `find` | help
for `find` |
| `alias myfind = find -r; [] \| myfind -h` | help for `find` | help for
`find` |

These are now an error, the same one you get typing the expansion alone:

| Code | main | this branch |
|---|---|---|
| `alias j = to json -i; {a: 1} \| j` | JSON indented by 2 spaces |
error: Missing flag argument |
| `alias myfind = find -r; ["file.txt"] \| myfind` | error: Missing
parameter: search term or --regex | error: Missing flag argument |
| `extern "/bin/echo" [--foo: string, ...rest: string]; alias e =
/bin/echo --foo; e` | `--foo` | error: Missing flag argument |
| `def cmd [--opt: any] { $opt }; alias c = cmd --opt; c` | `true` |
error: Missing flag argument |

## User-facing changes (Release notes)

- An alias that ends with a flag that takes a value now takes the value
from the first word after it. With `alias myfind = find -r`, `myfind
"txt$"` runs `find -r "txt$"`. Before, the flag got no value and the
alias could return wrong results with no error.
- Breaking change. Using such an alias with nothing after it is now a
"Missing flag argument" error, as typing its expansion alone already
was. This includes aliases of commands declared with `extern`.

### Breaking Changes

**1. Using the alias with nothing after it is now a parse error**

```nushell
alias j = to json -i
{a: 1} | j
```
- **Before:** it runs and ignores `-i`, so you get the default 2-space
indent.
- **After:** `MissingFlagParam`, pointing at `j`.

Because it fails at parse time, a `config.nu` or module that uses such
an alias this way anywhere now fails to load, not just that one line.
The memory note for this branch already records this as the intended
break.

**2. The first word after the alias now goes to the flag instead of to
the positional arguments**

```nushell
def cmd [--opt: string, ...rest] { {opt: $opt, rest: $rest} }
alias c = cmd --opt
c x y
```
- **Before:** `{opt: true, rest: [x, y]}`. A string flag got the boolean
`true`.
- **After:** `{opt: x, rest: [y]}`.

If the flag is typed `int`, the same call used to run with `opt: true`.
Now `x` fails the type check as a parse error.

## Additional notes

- Reported in
https://github.com/nushell/nushell/discussions/19616#discussioncomment-19779865.
- The `--help` and `-h` exception applies only to aliases. `find -r
--help` still searches for `--help`.
2026-11-21 07:15:19 -06:00
Darren Schroeder 75ead0b200 Keep failures in $env.LAST_EXIT_CODE until something resets them (#19607)
## Description

A failure now stays in `$env.LAST_EXIT_CODE` until another command sets
a code or you reset it with `$env.LAST_EXIT_CODE = 0`. Three places
dropped it. `try` without `catch` kept the old code. The REPL set 0
after every line that didn't error, so a failure the line handled never
reached the prompt. A hook that failed without catching it left the code
alone, and so did one ending in a failing external.

This works like PowerShell's `$LASTEXITCODE`, which error handling never
resets. `catch` can keep or reset the code, `finally` sees it, and `nu
-c 'try { error make {msg: x} }'` still exits 0.

A record hook with a string `code` (`{code: "..."}`) now runs like a
plain string hook. It gets the hook's input and doesn't inherit the
caller's output redirection.

Tables compare main with this branch.

| `$env.LAST_EXIT_CODE = 5`, then | main | this branch |
|---|---|---|
| `try { ^sh -c "exit 7" }` | 5 | 7 |
| `try { error make {msg: x} }` | 5 | 1 |
| `try { ^sh -c "exit 7" } catch { }` | 7 | 7 |
| `try { ^sh -c "exit 7" } catch { $env.LAST_EXIT_CODE = 0 }` | 0 | 0 |
| `try { "fine" }` | 5 | 5 |

| Line typed at the prompt | main | this branch |
|---|---|---|
| `try { ^sh -c "exit 7" }` | 0 | 7 |
| `try { ^sh -c "exit 7" } catch { }` | 0 | 7 |
| `try { ^sh -c "exit 7" } catch { $env.LAST_EXIT_CODE = 0 }` | 0 | 0 |
| `try { ^sh -c "exit 7" }; ^true` | 0 | 0 |
| `$env.LAST_EXIT_CODE = 4` | 0 | 4 |
| `ls \| ignore` | 0 | 0 |

| Hook, code at the next prompt | main | this branch |
|---|---|---|
| `pre_prompt = [{\|\| ^sh -c "exit 9"; null }]` | 0 | 9 |
| `pre_prompt = [{\|\| ^sh -c "exit 8" }]` | 0 | 8 |
| `env_change.FOO = [{\|\| ^sh -c "exit 8" }]`, then `$env.FOO = 1` | 0
| 8 |
| `display_output = [{\|\| try { ^sh -c "exit 7" } catch { } } {\|\|
table }]`, then `1` | 0 | 7 |

| Record hook with a string `code` | main | this branch |
|---|---|---|
| `display_output = {code: "$in \| describe"}`, then `[1 2 3]` |
`nothing` | `list<int>` |
| `pre_prompt = [{code: 'try { "x" }'}]` | prints `x` before each prompt
| prints nothing, like the plain string |
| `command_not_found = {code: "^echo from-hook"}`, then `try { nosuch }
catch { "caught" }` | `caught` | `from-hook`, `caught` |


## User-facing changes (Release notes)

- `try` without `catch` sets `$env.LAST_EXIT_CODE` to the code of the
failure it handles, or 1 if the error has none.
- At the prompt, `$env.LAST_EXIT_CODE` keeps a code the line set, so
`try { ^false }` shows 1 instead of 0.
- A failing `pre_prompt`, `pre_execution` or `env_change` hook sets
`$env.LAST_EXIT_CODE`, also when the failure is an external at the end
of the hook. A failing `env_change` hook runs once per change instead of
before every prompt.
- A record hook with a string `code` gets the hook's input, so
`display_output = {code: "table -e"}` prints the table. In `pre_prompt`
and `env_change` it no longer prints a value it ends with, and in
`command_not_found` an external it runs writes to the terminal.

## Additional notes

- `do -i` still sets 0 for a failing external. Eating errors is its job.
- An external at the end of a `command_not_found` or `display_output`
list hook still isn't checked. In `command_not_found`, checking it would
replace the "command not found" error with, say, `pkgfile`'s exit
status.
- After a `command_not_found` hook runs, env vars set earlier in the
same line or script are gone, `$env.LAST_EXIT_CODE` included. Main does
the same.
2026-11-20 07:58:15 -06:00
Piepmatz b9d514df7b Replace old Playground usages with the new one (#18915)
## Description

This PR replaces all the `Playground::setup` calls with the new injected
`Playground`.

Most of the changes are done via [this
script](https://tangled.org/cptpiepmatz.de/nushell_playground_asr) which
uses the rust-analyzer internals to replace code via the AST.

All the test should behave exactly the same as before but they don't
need to manually set up a playground anymore. Also this removes quite a
lot of lines, which is nice.

## User-facing changes (Release notes)

n/a

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>
2026-11-19 14:29:12 +01:00
Ted Lukin 16817a88f3 make hook lists still return a value (#19597)
<!--
Thanks for contributing to Nushell!

Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md

This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->

## Description
<!--
Explain what this PR does and why.

This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant

Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."

Write as much or as little as needed for reviewers to understand your
changes.
-->
Title (issue https://github.com/nushell/nushell/issues/19596 - check
related discussion).
Really this is only applicable for `command not found`.
Also, while I was at, removed some vecs being passed around and cloned
in `nu-cmd-base::hook`, where slices are enough.
 
## User-facing changes (Release notes)
<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/

Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.

Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."

If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar

This tells us the change should not appear in the changelog.

Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise

You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure

Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."

You may leave this blank until the PR is ready.
-->
You can now have a list of closures still modify the returned error
message of `command not found`, it takes the first non-empty return
value.

<!--
## Additional notes
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-18 14:55:23 -06:00
Piepmatz 651f0e4e3e Run some cwd-recovery related tests not on local Windows machines (#19594) 2026-11-18 16:13:26 +01:00
Peder Bergan ab0ca72acc Add table --no-headers (#19578)
## Description

I added `table --no-headers` so rendered table data can go to selection
tools without manually stripping column labels.

The flag hides column headers in normal, expanded and collapsed tables,
including nested tables and repeated footer labels. Record keys and data
rows remain visible. Indexes keep their existing behavior and can be
hidden separately with `--index false`.

```nushell
[[name status]; [alpha ready] [beta waiting]] | table --no-headers --index false
```

## User-facing changes (Release notes)

Added `table --no-headers` to render tables without column labels or
repeated footer labels.

## Additional notes

Implements the header suppression requested in #17114.
2026-11-18 06:28:57 -06:00
Junpei Zhangandpei711 3899f91fac docs(print): explain how to keep values in the pipeline (#19579)
## Description
Clarifies that `print` consumes its input and points users to `inspect`
when they want to display a value while continuing the pipeline.

## User-facing changes (Release notes)
Documentation now clarifies that `print` consumes its input; use
`inspect` to display a value while keeping it in the pipeline.

## Additional notes
- Verification: `cargo test -p nu-cli --test tests` (408 passed, 2
ignored) and `cargo fmt --all -- --check`.
- Fixes #14658

Co-authored-by: pei711 <pei711@users.noreply.github.com>
2026-11-18 06:20:33 -06:00
Abdul karim miaandAbdul karim mia bec4408312 feat(help): enable command name completions after help (#19549)
## Description

In this PR, command name completion is added to the positional rest
argument of `help`, `help commands`, and `help externs`.

Previously, running `help wi<Tab>` or `"help wi" | commandline complete`
yielded no completions because the `rest` parameter in `help`'s
signature was configured without a completion provider. Commands like
`which` already declare:
```rust
.completion(Completion::Builtin(BuiltinCompletion::Command { internal_only: false }))
```
This change applies the same `BuiltinCompletion::Command {
internal_only: false }` definition to `help`, `help commands`, and `help
externs`, allowing users to easily tab-complete command names after
typing `help <prefix>`.

A regression test `help_command_completions` has been added to
`crates/nu-cli/tests/completions/mod.rs` covering both `help <command>`
and `help commands <command>`.

## User-facing changes (Release notes)

Command name completions are now supported when typing arguments after
`help`, `help commands`, and `help externs` (e.g. `help with<Tab>` now
autocompletes to `help with-env`).

## Additional notes

Closes #4190

---------

Signed-off-by: Abdul karim mia <abdulkarimmia.dev@gmail.com>
Signed-off-by: Abdul karim mia <97598943+abdul-karim-mia@users.noreply.github.com>
Co-authored-by: Abdul karim mia <abdulkarimmia.dev@gmail.com>
2026-11-16 15:51:54 -06:00
Darren Schroeder 97361530d9 Flag completion: keep the external completer's flags next to an argument completer, and drop carapace duplicates (#19554)
## Description

Two problems with flag completion on externs that use `@complete
external`, such as the ones `generate completions` writes.

**An argument completer hid the external completer's flags.** Take an
extern with `...args: external_arg@"nu-complete git remotes"`. At `git
remote prune -<Tab>`, the argument completer answered (with remote
names), and since #19130 an answering argument completer overrides the
command-wide one. So flags that only the external completer knows, such
as `-n` from carapace, never showed up. Now, at a flag token, the
command-wide completer's flags are added to whatever the argument
completer answers. The command-wide completer still runs only once per
Tab, because the same result is also the argument completer's fallback.
Argument positions keep the existing contract, so `git remote prune
<Tab>` still lists only remotes. When either completer is
`@interactive`, the command-wide one runs only as the fallback. An
`@interactive` command-wide completer isn't the site's first completer.
An `@interactive` argument completer (a picker) runs without it, so
neither a pick nor a cancel gets the command-wide completer's flags
mixed in.

**carapace duplicated every declared flag.** carapace returns values
like `--limit ` with a trailing space, so that a space follows the flag.
The dedupe against declared flags compared values exactly, so `jj log
--li<Tab>` offered both `--limit` and `--limit `. A trailing space no
longer makes a value new.

## User-facing changes (Release notes)

- At a flag token, the flags that `@complete` or the external completer
lists now show up even when the argument's own completer answers.
Argument values still come from the argument's completer alone.
- Flags that carapace returns with a trailing space are no longer listed
a second time next to the declared flag.

## Additional notes
2026-11-16 15:29:05 -06:00
Sanjay Santhanam d4aadf72d8 fix(repl): report the real history session id during startup (#19214)
Fixes #18321

Right now `history session` prints `0` if you call it from your config
file, and only starts returning the real id once the REPL is up. The
session id was created when the line editor was built, which happens
after the startup config is evaluated.

This moves session id creation to the very start of `run_repl`, before
the config file runs, and reuses that same id when history gets set up.
So `history session` is stable and correct from initialization through
the whole session. I checked that the id is still only handed to the
history backend and the editor when `history.isolation` is on, so
history behavior itself is unchanged.

Repro (before):
```
# config.nu
$env.config.history.isolation = true
print $"session: (history session)"
```
printed `session: 0` at startup, then the real id at the first prompt.
After the fix both print the same nonzero id (verified with isolation on
and off).

Tests:
- `cargo test -p nu-cli --lib` : 171 passed, including 2 new regression
tests (`setup_history_reuses_startup_session_id`,
`setup_history_keeps_startup_session_id_without_isolation`) plus the
existing `are_session_ids_in_sync`
- `cargo test -p nu-cli --features sqlite --test tests -- history` : 12
passed
- `cargo clippy -p nu-cli --all-targets` and `cargo clippy --bin nu
--all-targets` : clean
- `cargo fmt --all -- --check` : clean
2026-11-16 15:14:35 -06:00
João V. Farias 4864b13b58 feat: implement cwd recovery for inaccessible directories (#19523)
## Description

Fixes #17284
Fixes #17817

When `$env.PWD` points to a directory that was removed or moved,
commands in the REPL print repeated `$env.PWD points to a non-existent
directory` errors across `merge_env`, hooks, and commands like `ls` or
`table`, and `cd ..` resolves against `$nu.home-dir` and lands in home's
parent instead of the deleted directory's parent. Similarly, launching
Nushell from a parent environment whose `PWD` has a trailing slash (e.g.
`/Users/name/`) kept the unstripped path because
`same_file::is_same_file` treated it as equal to the process cwd,
causing repeated `$env.PWD contains trailing slashes` errors in the
REPL.

I stripped non-root trailing slashes from inherited `PWD` values at
startup (`src/main.rs`), added automatic `$env.PWD` normalization and
recovery to the interactive REPL (`crates/nu-cli/src/repl.rs`) along
with a `ShellWarning::CwdRecovered` (`nu::shell::cwd_recovered`)
diagnostic in `crates/nu-protocol/src/errors/shell_warning.rs`, and
updated `cd` (`crates/nu-command/src/filesystem/cd.rs`) to fall back to
the raw `$env.PWD` path before `$nu.home-dir`.

At startup (`resolve_current_dir` in `src/main.rs`), non-root trailing
slashes are removed via `nu_path::strip_trailing_slash` without
canonicalizing symlinks. In the REPL, initial recovery now runs at the
start of `evaluate_repl` (even without `-e`) as well as at the start of
each REPL iteration before `merge_env`. `recover_cwd_if_needed` strips
any non-root trailing slashes first:

- If the stripped path is an existing accessible directory, it silently
updates `$env.PWD` via `Stack::set_cwd` without emitting
`ShellWarning::CwdRecovered` or polling for pending terminal input,
while still firing `env_change.PWD` hooks and refreshing terminal
`cwd`/title shell integration once `merge_env` completes.
- If the directory is missing, not a directory, or inaccessible, it
polls for pending terminal input
(`crossterm::event::poll(Duration::from_millis(1))`) first and skips
recovery for that prompt if input is already queued (or if polling
fails), so normal prompts avoid the 1ms poll while typed-ahead or pasted
lines still fail safely in the missing directory instead of running in a
parent directory (e.g. `rm *`). When no input is queued, it walks up
logical ancestors (`ancestors().skip(1)`) from the stripped path,
falling back to `$nu.home-dir`, until it finds an accessible directory,
updates `$env.PWD` via `Stack::set_cwd`, emits
`ShellWarning::CwdRecovered`, and refreshes terminal `cwd`/title shell
integration sequences.

Because recovery runs before `merge_env` and `eval_env_change_hook`,
`env_change.PWD` hooks fire with the old and new paths, while
`$env.OLDPWD` stays unchanged so `cd -` still returns to the previous
valid directory.

Non-interactive scripts and `nu -c` do not auto-recover on missing
directories; `cd ..` from a missing directory in both interactive (when
recovery was skipped) and non-interactive sessions now resolves against
`$env.PWD` instead of `$nu.home-dir`. `EngineState::cwd` remains strict
on trailing slashes, and other malformed `$env.PWD` values (missing,
non-string, or relative paths) are left alone so `EngineState::cwd`
still reports them as errors.

## User-facing changes (Release notes)

- When the current working directory is deleted, moved, or becomes
inaccessible in an interactive REPL session, Nushell now automatically
changes `$env.PWD` to the nearest existing ancestor directory (falling
back to `$nu.home-dir`) before drawing the next prompt, refreshes
terminal working-directory/title shell integration, and prints a
`nu::shell::cwd_recovered` warning showing the old and new paths.
`$env.OLDPWD` is preserved so `cd -` still works, and recovery waits
until after any already-queued typed-ahead or pasted commands fail
rather than running them in a parent directory.
- Inherited `PWD` values with non-root trailing slashes are now stripped
at startup and silently normalized in the interactive REPL instead of
failing repeatedly with `$env.PWD contains trailing slashes`.
- `cd` now falls back to the raw `$env.PWD` path before `$nu.home-dir`
when the current directory no longer exists, so `cd ..` resolves to its
logical parent directory instead of the parent of home.
2026-11-16 15:09:22 -06:00
Darren Schroeder 4e0328f49f Bump jiff, nix, parking_lot, sysinfo, ureq and v_htmlescape (#19564)
<!--
Thanks for contributing to Nushell!

Before submitting, please read the contributing guide:
https://github.com/nushell/nushell/blob/main/CONTRIBUTING.md

This template helps reviewers understand your changes and allows us to
generate high-quality release notes.
-->

## Description

This PR bumps six workspace dependencies and fixes what they broke:

| crate | from | to | code changes |
|---|---|---|---|
| sysinfo | 0.39.6 | 0.40.3 | constructors (`System::new`,
`Disks::new_with_refreshed_list`, ...) and statics (`kernel_version`,
`uptime`, `load_average`, ...) return `Result`; `Cpu::cpu_usage` is now
`usage`; network names are `OsString` |
| jiff | 0.2.23 | 1.0.0 | `Zoned` is now `ZonedDateTime` |
| parking_lot | 0.12.5 | 0.13.0 | `const_rwlock` is gone; `RwLock::new`
is `const` |
| nix | 0.31.3 | 0.32.0 | none |
| ureq | ~3.4.0 | ~3.5.2 | none; still tilde-pinned for the
`unversioned` API |
| v_htmlescape | 0.17.0 | 1.0.0 | none; same escape table |

When sysinfo doesn't support the platform, `sys cpu`, `sys mem`, `sys
disks`, `sys net`, `sys temp`, `sys users` and `debug info` now return
"Unable to read system information". Before, they gave empty or zeroed
output. `sys host` still leaves out the fields it can't read.

parse_datetime 0.17, the latest, still returns jiff 0.2's `Zoned`.
Relative dates (`"3 days ago" | into datetime`) therefore convert
through the offset, seconds and nanoseconds rather than the type.

<!--
Explain what this PR does and why.

This section is intentionally flexible:
- Describe the problem
- Explain your approach
- Include technical details if relevant

Good examples:
- "In this PR, I fixed..."
- "In this PR, I added support for..."
- "This change improves X by..."

Write as much or as little as needed for reviewers to understand your
changes.
-->

## User-facing changes (Release notes)

- On Windows, `sys cpu` shows `load_average` as `0.00, 0.00, 0.00`.
sysinfo no longer estimates a load average there.
- `http ... --pool` now percent-decodes credentials in `HTTP_PROXY`
(`%41` is sent as `A`), so a literal `%` must be written as `%25`.
Without `--pool`, credentials are still sent exactly as written.

<!--
This section is used (mostly as-is) for https://www.nushell.sh/blog/

Describe how Nushell behavior changes from a user's perspective.
Do NOT describe internal Rust changes here.

Write in a release note style, for example:
- "Added support for..."
- "Fixed an issue where..."
- "Nushell now supports..."
- "Improved performance of..."

If your changes do NOT affect users (internal refactors, cleanup, etc.),
just write:
- "n/a"
- "nan"
- or similar

This tells us the change should not appear in the changelog.

Tips:
- Focus on observable behavior
- Include examples if helpful
- Keep it concise

You can:
- Write a short paragraph (will appear as a bullet point), OR
- Use headings (###) if your change needs more structure

Avoid writing things like:
- "In this PR, I refactored..."
- "This updates internal code..."

You may leave this blank until the PR is ready.
-->

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-16 08:27:45 -06:00
Tarık Köşkerandarmadavalor fe2b181595 Resolve drive-relative paths like C: against $env.PWD in ls, path expand and friends (#19478)
## Description

Follow-up to #19332. That PR taught `cd` and auto-cd how to handle
Windows drive-relative paths (`C:`, `C:foo`) with
`nu_path::resolve_drive_relative`, but everything else that goes through
`nu_path::expand_path_with` / `canonicalize_with` still got it wrong.

`join_path_relative` does `relative_to.join(path)`. On Windows, joining
a path that has a drive prefix but no root *replaces* the base, so
`$env.PWD.join("C:")` is just `C:`. The OS then resolves that against
the process's current directory. In the REPL that directory follows
`$env.PWD` at each prompt, but in scripts, `nu -c`, or after a `cd` on
the same line it does not. So with `$env.PWD` set to `C:\work\proj`:

```nushell
ls C:                     # => names like `C:foo` instead of `foo`
"C:sub" | path expand -n  # => C:sub (not expanded at all)
# in a script, or after `cd` on the same line:
"C:" | path expand        # => nu's process directory, not C:\work\proj
```

The fix: `join_path_relative` now runs the path through
`resolve_drive_relative` before joining, the same way `cd` already did.
On the current drive, `C:` becomes `$env.PWD` and `C:sub` becomes
`$env.PWD\sub`. Another drive's `D:` resolves through
`std::path::absolute` (that drive's current directory, or its root). On
non-Windows platforms `resolve_drive_relative` returns the path
unchanged, so nothing changes there.

Since nu_path now handles it, the explicit `resolve_drive_relative`
calls in `cd` and auto-cd are removed. With the opt-in dc-glob backend,
`glob C:*.txt` handed the pattern straight to the walker, so it gets the
same resolution: the `C:` prefix is resolved and used as the walk base,
and only the rest of the pattern is globbed. The default wax backend
already rejects `C:*.txt` with an error asking for `C:/`, so it is
unchanged.

Tests:
- `nu-path`: unit test for `expand_path_with` with `c:`, `C:src`, `c:..`
- `nu-command`: `"<drive>:" | path expand` and `"<drive>:menu" | path
expand` resolve against `$env.PWD`; `ls <drive>:` and `ls <drive>:sub`
list `$env.PWD` with relative names (`andres.txt`, `sub\jt.txt`); with
dc-glob, `glob <drive>*.txt` and `glob <drive>sub/*.txt` match in
`$env.PWD`, also when it contains `[`

All of these tests failed before the change.

## User-facing changes (Release notes)

On Windows, drive-relative paths such as `C:` or `C:folder` now resolve
against `$env.PWD` when it is on that drive, matching `cd`. Before, `ls
C:` listed names like `C:foo`, `path expand -n` left `C:folder`
unexpanded, and in scripts or after a `cd` on the same line these paths
resolved against nu's process directory instead of `$env.PWD`. With the
dc-glob backend, `glob C:*.txt` follows the same rule.

## Additional notes

Closes #10174

Tested on Windows 10: `cargo test -p nu-path` passes. `cargo test -p
nu-command --test tests` filtered to `cd`, `glob`, `ls`, `path expand`
and the drive-relative tests gives 110 passed and 5 failed; the 5 are
symlink tests that fail the same way on `main` on this machine because
it doesn't have the symlink privilege (os error 1314). An earlier full
run of that target gave 4669 passed and 21 failed, all symlink tests.
`cargo test -p nu-cli` has one failure, `auto_cd_symlink`, for the same
reason. `cargo fmt --all` and `cargo clippy -p nu-path -p nu-command -p
nu-cli --all-targets -- -D warnings` are clean. I didn't run `typos` or
the full workspace `cargo nuclippy`.

---------

Co-authored-by: armadavalor <we@westudio.com.tr>
2026-11-15 15:18:48 -06:00
Manuel Thalmann cea2b3aee2 Add tests for the use of the main module (#19551)
## Description
Changes in this PR will add tests to proof that calling sub-commands
from a `main` module works properly from a CLI.

## User-facing changes (Release notes)
- "n/a"

## Additional notes
Up until now, it hasn't really been clear whether or not making
subcommands from other modules available via CLI is possible, see
#11440.

Furthermore, the `Subcommands` chapter in the nushell book only points
out the possibility to declare subcommands using declarations such as
`def "main build" [] {}`:
https://www.nushell.sh/book/scripts.html#subcommands

However, it turns out that in case you have a `main` function in your
script, all functions exposed via a `use`d `main` module are callable,
too:

***test.nu***
```nushell
def main [] {}
module main {
    export def test [] { "this is a test" }
}
use main
```

This results in:
```sh
nu test.nu test # prints "this is a test"
```

Perhaps, it does make sense to add a remark to that to the `Subcommands`
chapter, too (?)

- related #11440
2026-11-15 14:36:16 -06:00
Darren Schroederandkronberger-droid 5821d70d6e fix(repl): print background job output above the prompt (#19542)
## Description

A background job that prints while the prompt waits for input writes
straight to the terminal, on top of the prompt (#19502). Since
nushell/reedline#1312 (in main through #19538) the lines no longer
stairstep. They still start right after the prompt, though, and
reedline's next repaint erases them. The first key you type wipes the
job's output off the screen.

With this PR, what a background job writes to the terminal while the
REPL waits for input goes into a queue. That covers `print` (strings,
tables, streams, `--raw`) and error and warning reports. reedline's
external printer prints the queue above the prompt and redraws the
prompt, so the output stays when you type. reedline prints whole lines.
A partial line from `print -n` waits for its newline until no output
arrived for 100ms, or no job thread is running, and then gets a line of
its own. The chunks of one stream arrive back to back and stay together.
Of a line a job redraws with `\r`, like a progress bar, only what
follows the last `\r` is kept. Anything still queued when you press
Enter is written after the submitted line, and ends with a newline so
the next output starts on a line of its own.

`input`, `input list` and `input listen` switch to raw mode through
nushell's `RawModeGuard`, which calls crossterm directly, so reedline's
fix doesn't reach them, and a job that prints while they wait still
stairsteps. `RawModeGuard` now turns `OPOST` and `ONLCR` back on after
crossterm's switch, as readline, zsh and reedline do.

`input` also holds the queue while it reads a line. It prints what jobs
queued above that line and draws the prompt and the typed text again
below it, so job output no longer lands in the middle of what you type.
Ctrl+C in `input` now ends the line before the error report.

## User-facing changes (Release notes)

- Output from a background job (`print`, tables, errors) that arrives
while the prompt waits for input now prints above the prompt. Before, it
was written after the prompt and disappeared at the next key press.
- Output from a background job no longer stairsteps while `input`,
`input list` or `input listen` waits for a key.
- While `input` reads a line, output from a background job prints above
that line instead of into it.

## Additional notes

closes #19502
Related to #19475

---------

Co-authored-by: kronberger-droid <kronberger@proton.me>
2026-11-15 14:32:51 -06:00
Darren Schroeder e42dc22a33 fix(repl): stop polling at the prompt once background jobs end (#19541)
## Description

After a `job spawn`, nu woke up 10 times a second while it sat at the
prompt, and it kept doing so after the job ended. When jobs exist at
prompt build time, the REPL hands reedline a repaint callback so
`commandline set-prompt` can redraw the prompt, and reedline polls for
input instead of blocking while anything holds that handle. Nothing
removed the callback until the next prompt. So a `PROMPT_COMMAND` that
spawns a job, like the async starship prompt in the issue, kept nu
polling at every prompt. A frozen job did the same, even though it can
never push a prompt.

Now the last job thread to end drops the callback, and only thread jobs
count when the prompt is built. Both happen under the jobs lock, so a
job can't end between the REPL's check and the install and leave a
callback nothing removes.

## User-facing changes (Release notes)

Fixed nushell waking up 10 times a second at the prompt after background
jobs ended, or while a job was frozen. Prompts that update themselves
from a background job with `commandline set-prompt` no longer keep
nushell busy once the job finishes.

## Additional notes

closes #19475
2026-11-15 14:08:34 -06:00
Manav Kumar Dubey 515b6e5114 fix(completion): complete active overlay names for overlay hide (#19543)
## Description

Fixes #11570

Add overlay-name completion for `overlay hide` using the existing
built-in completion framework.

Suggestions include overlays active in both the runtime stack and the
permanent parser state, excluding the default `zero` overlay. Using the
permanent parser state keeps the current target available even when the
temporary completion parse has already hidden it.

Completion matches decoded names and quotes them when needed for
insertion. Suggestions remain available while typing unfinished
double-quoted escapes. Results are not cached across prompts, so
activating or hiding an overlay is reflected in subsequent completions.

```nu
overlay new spam
"overlay hide sp" | commandline complete
# => [spam]
```

## User-facing changes (Release notes)

`overlay hide` now completes active overlay names, including names that
require quoting.

## Additional notes

- Regression coverage includes empty and partial input, hidden overlays,
parser/runtime disagreements, quoting, incomplete escapes, replacement
spans, Unicode, flags, and overlay changes across prompts.
- Escape-sensitive tests apply and execute the completed command.
- On macOS arm64, all 428 CLI unit tests and 394 CLI integration tests
passed, with two existing integration tests ignored.
- Both Clippy checks, formatting, `typos`, and whitespace checks passed.
- Built the executable and verified completion through `commandline
complete`. Windows/Linux execution, the full workspace suite, and manual
Tab-menu verification of this revision remain unverified.
- Tracking earlier unexecuted commands in the buffer and fixing the
underlying parser/runtime discrepancy from #19458 remain outside this
change.
2026-11-15 14:07:22 -06:00
Jérôme Lécuyer 892bc29a0b Add commandline get-selection command (#18938) 2026-11-14 19:32:26 +01:00
Tinoandkronberger-droid e68d2b76e1 Add support for selecting menu entries with a mouse (#19310)
## Description

This PR implements menu entry selection with a mouse.
https://github.com/nushell/reedline/pull/1260 Contains a more in-depth
description of the feature.


## User-facing changes (Release notes)

Menus now allow the selection to be modified with a mouse by clicking on
an entry.

## Additional notes

Related https://github.com/nushell/reedline/pull/1260

---------

Co-authored-by: kronberger-droid <kronberger@proton.me>
2026-11-14 18:53:21 +01:00
Asuka 40c64acbdc Fix fuzzy argument completion for resolved commands (#19347)
## Description

Fixes #19338

Prevent unrelated fuzzy command matches such as `semver bump` from
hiding file arguments for `mv ` and external aliases

Restrict subcommands to typed or resolved parent names while respecting
`completions.case_sensitive` and Unicode case folding, so default prefix
completion still offers `str upcase` and `str uppercase` for `STR up`

Use visible scope names for module aliases, falling back to active
overlay declarations when `hide` only toggled visibility, so hidden
targets keep their qualification while private module targets stay
unresolved and cannot select unrelated top-level subcommands

Preserve mistyped command correction for unresolved bare heads such as
`sr upc`, `fod br` and `foot bar` without letting corrections suppress
file completion

Reuse `editor_is_resolved` to preserve executable names and its global
PATH fallback when the current directory is unavailable

## Release notes summary

Fixed fuzzy argument completion hiding files while preserving valid
subcommands, case-insensitive matching, module and hidden-target
aliases, and mistyped command correction

## Tests

Verified locally on macOS ARM64 with Rust 1.97.1

Reproduced the mis-cased head, Unicode case folding, hidden
ordinary/module/module-main alias, and private module command alias
failures before applying the fixes

- `cargo test --locked --profile ci -p nu-cli --test tests --
command_argument_completions` — 34 passed
- `cargo test --locked --profile ci -p nu-cli --test tests --
subcommand_head_case_sensitivity` — 2 passed
- `CARGO_BUILD_JOBS=1 cargo test --locked --profile ci -p nu-cli
--no-fail-fast` — 200 unit and 311 integration tests passed, 2 existing
ignored
- `CARGO_BUILD_JOBS=1 cargo nuclippy` and `CARGO_BUILD_JOBS=1 cargo
nuclippy-tests` — passed
- `CARGO_BUILD_JOBS=1 cargo check --locked --profile ci
--no-default-features --bin nu` — passed
- `cargo fmt --all --check`, `typos` and `git diff --check` — passed

Linux and Windows validation is pending GitHub CI for the updated commit
2026-11-14 10:18:34 -06:00
Martin Kronberger 32d1af6b6a feat(config)!: move the prompt into $env.config.prompt (#18734)
## Description

The prompt was configured through twelve bare environment variables.
Six of them were seeded from Rust at REPL startup, two more by
`default_env.nu`, and nothing kept them in step with the config.
All of it now lives in `$env.config.prompt`, together with
`render_right_prompt_on_last_line`.

The old variables still take precedence when a session sets them, and
nothing warns yet.
Thus every init script that writes them (starship, oh-my-posh, Dorothy,
Couchbase Shell) keeps working unchanged.
The warning can follow once those have moved.

The default left and right prompts are still Nu closures.
A closure needs a parsed block, so they cannot sit in
`Config::default()`.
`nu-cli` evaluates them into `$env.config.prompt` before any config file
runs, which keeps `view source $env.config.prompt.left` working and lets
a config wrap the default.

The indicators cannot move into the prompt closure, since reedline hands
`render_prompt_indicator` the current `PromptEditMode`, which the
closure cannot see.

`input --reedline` reads the same config now and drops its own hardcoded
indicators.

## User-facing changes (Release notes)

### The prompt is configured through `$env.config.prompt`

| key | default | replaces |
| --- | --- | --- |
| `left` | closure showing the directory | `$env.PROMPT_COMMAND` |
| `right` | closure showing time and exit code |
`$env.PROMPT_COMMAND_RIGHT` |
| `indicator` | `"> "` | `$env.PROMPT_INDICATOR` |
| `vi_insert` | `"> "` | `$env.PROMPT_INDICATOR_VI_INSERT` |
| `vi_normal` | `": "` | `$env.PROMPT_INDICATOR_VI_NORMAL` |
| `vi_visual` | `"+ "` | new |
| `multiline` | `"::: "` | `$env.PROMPT_MULTILINE_INDICATOR` |
| `render_right_on_last_line` | `false` |
`$env.config.render_right_prompt_on_last_line` |
| `transient.left` | `null` | `$env.TRANSIENT_PROMPT_COMMAND` |
| `transient.right` | `""` | `$env.TRANSIENT_PROMPT_COMMAND_RIGHT` |
| `transient.indicator` | `null` | `$env.TRANSIENT_PROMPT_INDICATOR` |
| `transient.vi_insert` | `null` |
`$env.TRANSIENT_PROMPT_INDICATOR_VI_INSERT` |
| `transient.vi_normal` | `null` |
`$env.TRANSIENT_PROMPT_INDICATOR_VI_NORMAL` |
| `transient.vi_visual` | `null` | new |
| `transient.multiline` | `""` |
`$env.TRANSIENT_PROMPT_MULTILINE_INDICATOR` |

A transient key set to `null` keeps whatever the live prompt showed.

The twelve environment variables are deprecated.
They still win over the config when you set them, so a config or init
script that assigns them keeps working.

### Breaking changes

- **The variables are no longer seeded.**
`$env.PROMPT_COMMAND`, `$env.PROMPT_INDICATOR` and the rest now exist
only if you set them yourself.
Code that reads one to find the current prompt, like `let old =
$env.PROMPT_COMMAND`, has to read `$env.config.prompt.left` instead.
`hide-env TRANSIENT_PROMPT_COMMAND_RIGHT`, the old way to keep the right
prompt in the transient prompt, now errors as well.
  Set `$env.config.prompt.transient.right = null` instead.
- **`$env.config.render_right_prompt_on_last_line` can no longer be
read.**
  Assigning the old name still sets `prompt.render_right_on_last_line`.
- **The vi indicators follow reedline's defaults.**
Insert mode shows `"> "` (was `": "`), normal mode `": "` (was `"> "`).
- **Vi visual mode has its own indicator**, `"+ "`.
  It no longer follows `$env.PROMPT_INDICATOR_VI_NORMAL`.
  Helix select mode uses it too.
- `input --reedline` follows `$env.config.prompt`, so its vi normal
indicator changed from `"〉"` to `": "` and its vi insert indicator from
`": "` to `"> "`.

`commandline set-prompt` gained `--vi-visual`.

`config default` reports the default prompt closures, so
`$env.config.prompt = (config default).prompt` restores the default
prompt.

Fixed the reverse-search indicator running into the matched entry:
`(reverse-search: ls)ls -la` is now `(reverse-search: ls) ls -la`.

## Additional notes

Checked against the nushell integration of every project in the README's
"Officially Supported By" list.
Only virtualenv reads one of the variables: `activate.nu` wraps
`$env.PROMPT_COMMAND`, and with nothing seeded the venv prompt loses the
default prompt behind its prefix.
uv ships a copy of the same script.
Both need a fallback to `$env.config.prompt.left`, and venvs created
before that fix keep the old script.
The starship and oh-my-posh init scripts were run against this branch
and against `main` on a pty.
They render the same in emacs mode, in vi mode the only difference is
the new default indicator.

OSC 133/633 emission is untouched, the sequences of a session on this
branch and on `main` are identical.
2026-11-14 14:17:59 +01:00
Martin Kronberger f861a79a00 fix(prompt): don't tint a supplied prompt with the default colors (#18686)
## Description

reedline prints a foreground color in front of the left and the right
prompt, and `NushellPrompt` never overrode it.
Thus every unstyled piece of a custom prompt, like a starship module
with `style = "none"`, came out light green or purple instead of in the
terminal's own foreground.

`NushellPrompt` now answers `Color::Default` for a side that was
supplied, and keeps reedline's colors for a side that falls back to the
built-in prompt.
The two sides are judged separately.

The indicators keep their default colors.
They are nushell's own rather than the prompt generator's, and styling
one means putting the escapes into the indicator value.

## User-facing changes (Release notes)

Fixed unstyled text in a custom prompt being tinted light green (left)
or purple (right).
It now uses the terminal's default foreground, as in other shells.
A prompt that sets its own colors looks the same as before.

## Additional notes

fixes #16384

Based on `main`, since the `PromptState` rewrite it needed is already
there.
It conflicts with #18734 in one hunk, both append tests to
`crates/nu-cli/src/prompt.rs`, so whichever lands second needs that
merge.
2026-11-14 13:58:52 +01:00
eitsupiandmst-mkt 3e2dc65564 feat(cli): map auto-pair closers in history hints with the lexer (#19199)
## Summary

Build on #19146 so that history hints work before auto-paired closers,
using the hooks added in nushell/reedline#1244 (now merged).

`NuHighlighter` implements `Highlighter::hint_closer_offsets` with
Nushell's lexer, telling Reedline which characters of a hint close the
closers after the cursor.

## Why

Auto-pairing turns `(gs` into `(gs|)`. Searching history with the whole
buffer misses `(gstat).branch`. Matching closer characters is not enough
either: a `)` inside a string in the hint does not close the existing
one. Telling them apart depends on Nushell syntax, so it belongs here
rather than in Reedline.

## Design choices

**Reuse the lexer.** `lex_with_delimiter_pairs()` collects matched
brackets and quotes during lexing, including `[]` and `{}` inside
interpolated expressions, without changing the shared lexer or parser
rules. The text before the cursor plus the hint is lexed, so a source
left unfinished by an earlier partial acceptance still maps correctly.

**Decline rather than guess.** Pairs not in
`$env.config.auto_pairs.pairs`, ambiguous mappings, lex errors, and
raw-string boundaries give no mapping, so no hint is shown before the
closers. An unquoted `#` inside interpolation also disables mapping,
which avoids reimplementing comment and raw-string rules.

**Keep the hint closure contract.** `CwdAwareHinter` opts in on the
Reedline side. `ExternalHinter` does not, so its closure still receives
the whole buffer and cursor, and its hint is accepted at the buffer end
as before.

This also updates #19146's string and comment detection for recent lexer
changes: `ParseError::Unclosed` now carries a `Cow`, and an unclosed raw
string is reported as `Unclosed`.

## Tests and dependencies

Unit tests cover nesting, quotes, escapes, misleading closer characters,
interpolated collections, configured pairs, and rejected mappings.

Unix PTY tests drive the actual Reedline editor with `CwdAwareHinter`
and `ExternalHinter`, checking queries, displayed hints, full and
partial acceptance, and submission.

This PR includes #19146's auto-pair implementation.

---------

Co-authored-by: mst-mkt <mail@keito.dev>
2026-11-14 11:47:08 +01:00
Breaker 70da637398 Allow dynamic completers to opt out of caching (#19346)
## Description

Let a custom completer opt out of the shared completion cache by
returning `options: { cache: false }` in its completion envelope:

```nu
def branches [token] {
    { completions: (git branch --format='%(refname:short)' | lines), options: { cache: false } }
}
```

By default, custom completers keep their existing cross-prompt cache,
which matters for expensive sources such as Carapace. A completer that
reads changing state outside Nushell's cache key can opt out. The
opt-out also covers a result merged with file or other fallback
completions. Failed or declining custom completers are not cached, since
either may return a different result on the next prompt. Dynamic
completions supplied by plugin commands are not cached for the same
reason.

The previous revision cleared every custom completion at each new
prompt. This revision removes that behavior and the per-prompt cache
scan.

## User-facing changes (Release notes)

Custom completers can return `options: { cache: false }` to refresh
suggestions on later prompts when their results depend on changing
external state. Existing completers retain their caching behavior by
default.

## Additional notes

Addresses #19297 through the per-completer opt-out proposed in the
issue. The opt-out must be set by the completer author; this does not
automatically refresh every custom completer.

Tests cover parameter, command-wide, and external completers; the
dynamic command completion path; fallback merging; and unchanged default
caching. Local checks: 26 completer unit tests and 237 completion
integration tests passed (2 ignored), `cargo +1.98.0 fmt --all`, and
targeted `nu-cli` Clippy passed. Full workspace `nuclippy` is blocked by
a pre-existing `nu-table` `manual_slice_fill` warning under Rust 1.98;
the repository's pinned Rust 1.97.1 toolchain is unavailable in this
environment.
2026-11-13 11:57:54 -06:00
Darren Schroeder 6f51b1f270 fix: don't lose errors and exit from stream items a command drops (#19467)
## Description

A stream carries a failure as an item, so a command that read that item
and then dropped it also dropped the failure. `last`, `get 2`, `skip 1`
and others returned a normal result with exit code 0. This was the gap
#16738 and #18976 closed for collecting and for `length`, `columns` and
`is-empty`.

`exit` makes it worse. Since #18389 (0.114.0) `exit` travels as an error
instead of ending the process, so the same commands discarded it and the
script kept running. 0.113.1 exits 7 on the commands below, and 0.114.0
carries on with exit code 0.

Commands that read and drop an item now raise its error or pass it
along, and commands that bury an item in a record or list now pass the
error along instead. `;` no longer ignores an error returned as a single
value. A closure is never handed an `exit`, because `catch` can't handle
one and the closure could ignore it. `do --ignore-errors` no longer
ignores `exit`. Items that never ran stay unevaluated, so `first` and
`take` are as lazy as before.

## User-facing changes (Release notes)

- An error in a stream is no longer lost when a command drops that item.
This covers `last`, `get`, cell paths on a stream, `skip`, `skip while`,
`skip until`, `take while`, `take until`, `select`, `drop`, `drop nth`,
`slice`, `every`, `update`, `upsert`, `window`, `lines`, `zip` and `to
text`.
- `enumerate`, `wrap`, `zip`, `chunks`, `chunk-by`, `window` and `split
list` no longer hide a stream error inside the record or list they
build.
- An external now reports an error or `exit` in its input once it
finishes, so `boom | to text | ^cat` raises `boom` and `try` can catch
it. `do --ignore-errors` still ignores the error, but not `exit`.
- A closure that returns an error value now counts as failing in `take
while`, `take until`, `skip while`, `skip until`, `chunk-by`, `split
list` and `where`, where it used to count as `false`.
- `exit` inside a closure always ends the script again, whichever
command consumes the stream, and `do --ignore-errors` no longer ignores
it.
- `;` no longer discards an error returned as a single value, and
`catch` now sees errors from `first` and `last`.

### Breaking Changes
- a closure that fails in `take while`, `take until`, `skip while`,
`skip until`, `chunk-by` or `split list` now raises its error, as
`where` already does. It used to count as `false`, so `[{a: 1} {b: 2}] |
take while {|r| $r.a == 1 }` returned the first row and now reports the
missing column. Use `$r.a?` for optional columns.
- a script that relied on `last`, `skip` or similar to get past an error
now fails. To handle a failed item, use `each {|row| try { $row |
ignore; $row } catch { ... } }`.
- `reverse`, `shuffle`, `sort-by`, `drop` and `last` now raise an error
item instead of keeping it among the rows, so that `try` form has to
come before them.
- `to text` now raises an error instead of writing its debug form into
the text, and `each {|y| $y; 'ok' }` raises an error input instead of
discarding it at the `;`.

## Additional notes

Closes #19463
2026-11-12 14:02:57 -06:00
Darren Schroeder ab6c901127 fix(modules): reloading a module picks up edits and drops what the file no longer exports (#19468)
## Description

Working on a module at the prompt had a few traps, raised on #10995.

`use spam` and `overlay use spam` kept the loaded copy after the file
changed, while `use spam.nu` read it again. Directory modules had it
worst, because `use pkg` read the disk the first time and memory every
time after. By-name imports now read the file again when it, or anything
it imports, changed. With an unchanged file, or a module written at the
prompt, they behave as before.

Reloading also left old definitions behind. A command deleted from the
file kept working through `use`, `hide`, `overlay use --reload` and
`overlay hide` followed by `overlay use`, and a name you didn't import
again kept running the old code. A reload now hides what the new version
no longer exports, and moves every name still showing the old version to
the new one. A command you defined yourself with the same name stays,
and so does one you imported directly from a module this one used to
re-export.

`hide spam` after `use spam.nu *` silently did nothing, and now hides
the module's commands however they were imported.

Changing overlays moved you. `overlay hide` went back to the directory
you activated the overlay from, and bringing a hidden overlay back with
`overlay use <name>` or `overlay new` went to the directory it was
hidden in. `PWD` and `OLDPWD` now stay put unless the module's
`export-env` changes directory.

The first change could have sent more people into an existing trap. An
unclosed delimiter in a file that `use` or `source` loads left the REPL
at the `:::` prompt with nothing you could type to finish the line. The
validator now counts only errors in the line itself as unfinished input.

## User-facing changes (Release notes)

- `use <name>` and `overlay use <name>` now read the module's file again
if it changed, the same as `use <path>`.
- Reloading a module now removes commands, aliases, type aliases,
constants and submodules that were deleted from its file, and moves
names you imported earlier to the new version.
- `hide <module>` now hides a module's commands after `use <module> *`,
as well as after `use <module>`.
- Fixed the REPL getting stuck at the `:::` prompt when `use` or
`source` loaded a file with an unclosed delimiter. You now see the
error.

### Breaking changes

- `overlay hide`, `overlay use` and `overlay new` no longer change the
current directory, unless the module's `export-env` does. `--keep-env
[PWD]` still works but is no longer needed. A script that used a
temporary overlay as a scoped `cd` has to `cd` back itself.
- `use <name>` and `overlay use <name>` now report parse errors in the
module's file, where they used to keep the loaded copy. A hook that runs
`use toolkit` on every `cd` shows them until the file is fixed.


## Additional notes

Related to #10995.

This reverses two choices that existing tests had recorded. #13170 said
`use voice` "will still use the module which is saved in EngineState",
so one assertion in `use_submodules` flipped. Four tests asserted that
changing overlays moves you, so they're renamed with the new expected
value: `overlay_hide_in_export_env_keeps_cd`,
`use_overlay_hide_keeps_cd`, `source_env_overlay_hide_keeps_cd` and
`overlay_reactivate_with_module_name_keeps_pwd`.

By-name imports only check modules from an earlier source unit, so
loading a module tree reads no extra files. Loading a 120-module `export
module x.nu; export use x` tree takes 57.7 ms before and 58.2 ms after
on a debug build. Loading that tree and then running a by-name `use` of
it in a later source unit, which reads its 120 files, takes 77.1 ms
before and 80.6 ms after.

Only a reload removes a module's name. `hide <module>` keeps it on
purpose, so `hide spam; use spam` still works.
2026-11-12 08:08:01 -06:00
Retro 4fc558aa55 fix(menu): honor numbered selectors in custom list menus (#19477)
## Description

Custom list menus could close before asking the source for rows. In Diff
mode, a selector like `!2` could also reach the source as search text.
Pressing Enter could leave the selector on the command line.

Handle selectors across `diff`, `cursor_prefix`, and `full_buffer` list
menus. Keep selectors out of the search text and remove them when a row
is accepted while honoring custom replacement ranges. The Nushell menu
wrapper uses Reedline’s existing visibility API to keep the prompt in
its normal state until the first rows arrive.

Fixes #19151

## User-facing changes (Release notes)

Custom list menus open with the default completion settings and accept
numbered selectors such as `!2`. Enter inserts the selected item and
removes the selector, and an empty first result leaves the normal prompt
visible.

## Additional notes

- Regression tests cover all input and output modes, custom replacement
ranges, and Unicode. Terminal checks covered partial completion on and
off, empty sources, and the built-in history menu.
- On macOS arm64, the workspace suite, 235 doctests, 254
standard-library tests, and the Python 3.13 virtualenv check passed. All
289 CLI tests passed on the final files. Formatting, Clippy, and `typos`
passed.
- Reedline can still accept the previous row when one keybinding sends
an edit and an accept action in the same event.
2026-11-12 06:06:52 -06:00
Darren Schroeder 81e7b29223 Stream output to the terminal when max_last_result_size is set (#19474)
## Description

With `$env.config.max_last_result_size` above `0b`, the REPL read a
stream into `$ans.last` before printing any of it. A stream that never
filled the limit printed nothing until it ended, and an endless stream
never printed at all.

The stream now goes straight to display as it is produced. A capped copy
fills up as items pass through, and `$ans.last` is stored when the
stream ends. List streams and byte streams had the same problem, and
this fixes both.

## User-facing changes (Release notes)

- Streams now print as they are produced when
`$env.config.max_last_result_size` is set, the same as with `0b`.
`$ans.last` still gets the result, up to the limit, once the stream
ends.
- Pressing Ctrl-C partway through a stream no longer loses all of its
output.
- An error partway through a byte stream is now reported when
`max_last_result_size` is set. It used to be hidden.
- If a stream stops before its end, reading `$ans` now warns that the
result may be incomplete. It no longer tells you to raise
`max_last_result_size` when the limit wasn't the cause.

## Additional notes

Closes #19472
2026-11-12 06:06:15 -06:00
INNOCENT EJEH 74ef6cc114 fix(hints): isolate hint closures from terminal input (#19471)
## Description

Fixes #18840.

Hint closures run while Reedline is reading the command line. External
commands in a hint can inherit terminal descriptors and take over the
foreground process group, leaving Reedline with an I/O error during
editing. Stderr and output from earlier statements can also overwrite
the prompt or give the child access to terminal input.

Evaluate each hint on a child stack with `suppress_output()` and
`suppress_stdin()`, reusing the isolation used for completion workers.
External commands detach from the terminal and their uncaptured output
is discarded. `print` still writes to the screen. Pipeline input, the
returned hint, and explicitly captured stderr remain available. `input`,
`input list`, `input listen` and `term query` return an error; an
uncaught error yields no hint. The caller's stack keeps its normal
terminal access.

Unix regression tests cover subprocess isolation with empty and piped
input, stderr isolation, intermediate stdout isolation, explicit stderr
capture with `complete` and `e>|`, and the `input` error. The new stderr
and intermediate-stdout tests fail on `33fdc6c` and pass with this
change.

## User-facing changes (Release notes)

External commands in custom hint closures run detached from the
terminal, and their uncaptured output, including stderr, is discarded.
`print` still writes to the screen. Pipeline input and explicitly
captured output remain available. `input`, `input list`, `input listen`
and `term query` return an error instead of reading from the line
editor.

## Additional notes

Validated locally on macOS:

- `cargo test --locked -p nu-cli`: 574 passed, 2 ignored.
- `cargo nuclippy`
- `cargo fmt --all -- --check`
- `typos`
- Interactive PTY check: 20 type/backspace rounds and 173 hint
callbacks. External commands had no terminal stdin, stderr or
controlling terminal, and intermediate stdout was also isolated. The
probes' uncaptured output stayed off the prompt, the returned hint
remained visible, terminal modes and the shell's foreground process
group stayed intact, and an ordinary foreground command still received
terminal stdin.

The original intermittent I/O error was not reproduced locally; the
tests verify terminal isolation. No local Windows or Linux run was
performed.

AI assistance: the code, regression tests, and local validation were
prepared with Codex at the contributor's request.
2026-11-12 06:05:22 -06:00
Darren Schroeder 6172c35bc6 Fix stale $env in the parser and completer after overlay use inside a block (#19458)
## Description

With `if (which opam | is-not-empty) { overlay use opam }` in
`config.nu`, Tab completion stays on the directory nu started in,
wherever you `cd`, while `$env.PWD`, `pwd` and `ls` are correct.

The parser drops an overlay command's effect when the enclosing block
ends, but the stack keeps it, so the two disagree about which overlays
are active. `cd` and `$env.FOO = ...` write through the stack's list.
`EngineState::get_env_var`, which the parser and the completer rely on,
reads through the parser's list, so it misses those values and finds
older ones below them. `overlay hide` inside a block goes wrong the same
way in reverse.

`merge_env` now remembers the stack's list when it differs from the
parser's, and `get_env_var` and `render_env_vars` read through it. When
the lists agree, which is the normal case, they read the same overlays
as before.

## User-facing changes (Release notes)

- Fixed Tab completion, relative `use`, const path commands and the
`cwd` saved in sqlite history using the startup directory after an
overlay command inside a block, such as `if $x { overlay use spam }`.
- Fixed `$env.NU_LIB_DIRS` and other variables the parser reads being
ignored when set after an overlay command inside a block.
- 
## Additional notes

- related #18742, related #19437
- Left as is: an overlay activated in a block still can't be hidden from
the prompt, and its exports still aren't callable there, because the
parser has dropped it.
- `nu --lsp`, `nu --mcp` and `nu --dap` run the startup files on a stack
they then discard, so they call the new
`EngineState::clear_runtime_overlays` and behave as they do on main.
2026-11-12 06:03:43 -06:00
Martin KronbergerandDarren Schroeder 47ad8aad59 fix(config): reject a keybindings or menus list with an entry it can't read (#19438)
## Description

Follow-up to #19418.
A keybinding or menu with a modifier, keycode, mode, layout, input mode
or output mode that can't be read used to be accepted and then failed at
every prompt.
A fixed copy that a reload appended did not replace it, since `++=` only
adds, thus Tab stayed broken until a restart.

Assigning such a list is now rejected as a whole and the previous list
stays, like for any other config value that can't be read.
The grammar moved from `nu-cli` to `nu-protocol` (`config/key_spec.rs`)
for that, since `nu-protocol` has no `crossterm`, and `nu-cli` only maps
it onto reedline's types.

This also adds `config default`, which returns the default config as a
record.
A config that gets sourced again needs it to start from the defaults,
and it replaces the `^$nu.current-exe -n -c ...` hack in
`doc_config.nu`.

## User-facing changes (Release notes)

- Assigning `$env.config.keybindings` or `$env.config.menus` with an
entry that can't be read is now an error, and the old list is kept.
That covers the `modifier`, `keycode` and `mode` of a keybinding, and
the `layout`, `input_mode` (or `only_buffer_difference`) and
`output_mode` of a menu.
  Before, it was accepted and failed on every prompt.
  In `config.nu`, the lines after the rejected assignment don't run.
- A menu without a `layout`, such as `type: {}`, is rejected on
assignment now.
- New command `config default`, which returns the default config as a
record.
A config that is sourced again adds its `++=` entries each time, and `=`
drops the defaults, so start from the defaults to keep the list stable:

  ```nu
  $env.config.keybindings = (config default).keybindings
  $env.config.keybindings ++= $custom
  ```

## Additional notes

Unit tests in `nu-protocol` cover the grammar and the rejected lists,
and repl tests cover the reload scenario.

Out of scope:

- `event` and the fields of one menu layout (`columns`, `page_size`,
`description_position`) are still read when the prompt is built.
- The error names the first bad entry and not the setting. One error per
bad entry would be a follow-up.
- `nu-tui` still reads keybinding strings with its own looser rules
(`normalize_binding`).

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
2026-11-05 15:48:31 +01:00
Martin Kronberger 674c49c3b0 fix(config)!: make assigning keybindings and menus replace the list (#19418)
## Description

Since #18761 assigning `$env.config.keybindings` or `$env.config.menus`
merges into the current list in the config layer.
That made the two lists behave unlike every other list in nushell: `=`
could not drop a single binding, `menus = []` cleared nothing, and a
binding with a bad keycode errored on every prompt until the whole list
was cleared.
#18828 and #18870 patched the merge (unnamed bindings, then name plus
key, with a warning for atuin's shared names in #18848), but each patch
added a rule on top of the merge.

This PR takes the merge out.
Both lists are stored as written, like any other list:

```nu
$env.config.keybindings = [...]                                              # replaces the list
$env.config.keybindings ++= [...]                                            # appends to it
$env.config.keybindings | where name != x                                    # filters it
$env.config.keybindings | reverse | uniq-by modifier keycode mode | reverse  # drops exact repeats
```

Overlaps are resolved where the list is used, by reedline, with one rule
for both lists: entries are applied in order and the last one wins.

| | spot | free spot | taken spot |
|---|---|---|---|
| keybinding | mode, modifier, keycode | filled | replaced |
| menu | name | appended | replaced in place |

Keys already worked like this in reedline, since `add_binding` is a
`HashMap::insert`.
Menus did not, since the lookup by name takes the first match, so
nushell/reedline#1294 made a later menu replace one of the same name.
A keybinding's `name` is only a label and plays no part in what a key
does.

`SharedKeybindingName` goes, since one name on several keys (atuin) is
no longer ambiguous once nothing merges by name.
The `KeyIdentity` machinery that mirrored reedline's key parsing goes
with it.

For keybindings there is a test where nushell hands the list over:
`create_keybindings` is checked for last-wins, for `event: null`
removing a reedline base binding, and for a later entry covering fewer
modes.
Menus rely on the reedline test for the same rule, since nushell only
passes the list on.

## User-facing changes (Release notes)

### Assigning `$env.config.keybindings` and `$env.config.menus` replaces
the list

Breaking: `$env.config.keybindings = [...]` and `$env.config.menus =
[...]` now replace the whole list, including nushell's default menus and
the keys that open them (Tab and Shift+Tab completion, Ctrl+Space, F1
help, Ctrl+X and Ctrl+Z paging, the Ctrl+R history menu).
If your config assigns either list, or sets `keybindings` or `menus`
inside a `$env.config = {...}` record, switch to `++=` or Tab stops
completing.
Reedline's own bindings (movement, editing) are not part of the list and
stay.

```nu
$env.config.keybindings ++= [{ name: my_binding, modifier: control, keycode: char_t, mode: emacs, event: { send: clearscreen } }]
```

To get the defaults back in a running shell, assign them again from a
clean `nu -n`:

```nu
$env.config.keybindings = (^$nu.current-exe -n -c '$env.config.keybindings | to nuon' | from nuon)
$env.config.menus = (^$nu.current-exe -n -c '$env.config.menus | to nuon' | from nuon)
```

Filtering a list now removes what it drops, and `= []` clears either
list.
When several keybindings bind the same key in the same mode, or several
menus share a name, the last one wins.
A keybinding's `name` is only a label, so sharing one between keys no
longer warns.
To unbind a key that reedline itself binds, add an entry for it with
`event: null`.

## Additional notes

Menus need nushell/reedline#1294, which is in the reedline bump commit
before the menus commit.

The book still describes the merge in `line_editor.md` (the keybindings
section and the menus note), so that needs a follow-up PR to
nushell.github.io.

Related: #18761, #18828, #18870, #18848.
2026-11-04 08:11:43 -06:00
Martin Kronberger 29a4f0397c chore(reedline): bump reedline to 8bc5cd0 (#19416)
## Description

Bumps reedline from `4a3dad3` to `8bc5cd0`, which pulls in reedline
#1266, #1279, #1280, #1281, #1285 to #1292.

Nushell side:
- `Signal::CtrlC` now carries the buffer, so `repl.rs` and `input_.rs`
match `Signal::CtrlC(_)`. Nushell keeps discarding it as before.
- `EditCommand::MoveWordRightEnd` is deprecated in reedline as the same
move as `MoveWordRight`, so `movewordrightend` now builds
`MoveWordRight` and existing bindings keep working.
- New parser and display arms for `capitalizeword` (edit) and
`firsthistory` / `leavehistory` (events).

## User-facing changes (Release notes)

- `PageUp` and `PageDown` without an open menu now jump to the oldest
history entry (the oldest one matching what is typed) and back to the
line being typed. Two new events, `firsthistory` and `leavehistory`,
back them.
- `Alt-c` in emacs mode now capitalizes the whole word under the cursor
(first letter up, the rest down), like `Alt-u` and `Alt-l`, instead of
only the character under the cursor. The new edit command is
`capitalizeword`; `capitalizechar` is still available.
- `Esc` reports when it has nothing to cancel, so `until: [{send: esc}
{send: executehostcommand cmd: ...}]` falls through to the custom action
when no menu is open and nothing is selected.
- `movewordrightend` and `movebigwordrightend` now land behind the word
in emacs and vi insert mode instead of one character short.
`movewordrightend` does the same as `movewordright` and is kept only for
existing bindings.
- `Ctrl+C` during reverse history search (`Ctrl+R`) now clears the line
like it does everywhere else, instead of bringing it back on the next
prompt.
- A multi-line history hint now shows the multiline indicator on each of
its lines, drawn in the hint's style.
- The history file no longer fails to load on filesystems that cannot
lock files (NFS without a lock daemon); it is written without the lock
there.
- A list menu whose completer is a `source` closure or an external
completer now evaluates it once per refresh instead of twice.
2026-11-02 13:15:44 -06:00
Darren Schroeder 7219843497 A status line under the prompt: errors, signatures, types and const previews as you type (#19403)
## Description

The highlighter already parses the line on every keystroke, then keeps
only the colors. This PR uses that parse to draw one line under the
buffer. The line shows the first parse or type error, or, when there is
none, the signature of the command under the cursor with the current
parameter emphasized, the type the pipeline outputs, and the value of a
line built only from const commands.

An error appears as soon as it stops being about the text still being
typed: `let x: int = "a"` shows nothing until a space follows the `"a"`,
and `str substring ` waits for its range. Nothing shows while the
validator calls the line unfinished, as with an open `{`, and no error
or preview shows for a line that `use`s a module not loaded yet: the
highlighter's parse skips loading it, so its names would read as
unknown.



https://github.com/user-attachments/assets/d7e467f0-fdeb-42b4-a93e-20c49f56c9e0



## User-facing changes (Release notes)

- The REPL shows a status line under the line being edited: the first
parse or type error, or the signature of the command under the cursor,
the type the pipeline outputs, and the value of a line built only from
const commands (`"a,b" | split row ","` shows `= [a, b]`). It is erased
when the line runs.
- `$env.config.status_line` controls it: `enable` turns all of it off,
and `errors`, `signature`, `type` and `preview` turn off one part each.
- Ctrl+C now stops a math reduction over a big range, such as
`1..10000000000 | math sum`, with `Operation interrupted`. In a script
or `nu -c`, it also stops a const evaluation such as `const x =
(1..10000000000 | math sum)`.

## Additional notes
2026-11-02 06:34:28 -06:00
Darren Schroeder 4c672e8468 Add older-than and newer-than operators for datetimes (#19397)
## Description

I got tired of filtering by age since it takes `where modified < (date
now) - 2wk` today, and the shorter `where modified < 2wk` fails with a
type error that doesn't say what to write instead. This PR adds two
comparison operators:

- `$date older-than 2wk`: `$date` is before now minus two weeks
- `$date newer-than 2wk`: `$date` is after now minus two weeks
- with a datetime on the right, they work like `<` and `>`: `2020-01-01
older-than 2021-01-01`

Both are strict. `nothing` on either side gives `nothing`, as `<` does,
and a custom value on the left gets the operator through
`CustomValue::operation`. A duration is counted back from the clock when
the comparison runs, so `const`, parameter defaults and match patterns
refuse the duration form, as they refuse `date now`. Datetime against
datetime still works there.

`<`, `<=`, `>` and `>=` between a datetime and a duration now point to
the new operators in their help, and putting the duration on the left of
`older-than` says the datetime goes on the left.

## User-facing changes (Release notes)

- Added the `older-than` and `newer-than` operators for datetimes. `ls |
where modified older-than 2wk` keeps files last changed more than two
weeks ago, and `newer-than 2wk` keeps files changed since then. With a
datetime on the right they work like `<` and `>`: `$date older-than
2024-01-01`. Both are strict and listed in `help operators`.
- Comparing a datetime with a duration using `<`, `<=`, `>` or `>=` now
suggests `older-than` or `newer-than` in the error.
- For plugin authors: `nu_protocol::ast::Comparison` has two new
variants, `OlderThan` and `NewerThan`. A `match` on `Comparison` without
a wildcard arm needs arms for them, and `CustomValue::operation`
receives them when a custom value is on the left.

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-11-01 05:18:10 -06:00
Darren Schroeder 168db974ba Remove deprecations older than six months (#19382)
## Description

This removes everything deprecated in 0.112 or earlier (April 2026 or
before), along with the stubs left from the 2023 removals. It also
removes `ast::Call::positional_nth` and `positional_len`, which were
deprecated in 0.113 and have no in-tree users. Everything else
deprecated in 0.113 or later stays: `watch` with a closure, `str
upcase`/`str downcase`, `ShellError::Return`, `tui label --title`, and
`update cells --columns`.

Commands and flags are deleted outright instead of being turned into
stubs. Most removed names still lead to their replacement through
existing search terms: `filter` suggests `where`, `benchmark` suggests
`timeit`, `fetch` suggests `http get`, and `post` suggests `http post`.

`default $closure` keeps its current behavior. The deprecation warning
promised that closures passed by variable would become lazy, but making
that change would be a new break. So the promise goes away instead: a
closure literal (`default { ... }`) is evaluated lazily, and a closure
passed directly as `$var` is the default value itself. The help text now
says this.

`CustomValue::is_iterable()` is no longer deprecated. Its deprecation
note promised a replacement that was never built, and the SQLite query
builder still depends on it.

## User-facing changes (Release notes)

- Removed `--ignore-errors (-i)` from `get`, `select`, and `reject`. Use
`--optional (-o)`.
- Removed `get --sensitive (-s)`. Cell paths are case-sensitive by
default. Add `!` after a member to make it case-insensitive.
- Removed `filter`. Use `where`, which takes the same closures,
including one stored in a variable.
- Removed the `positional` option from custom completer results. Use
`completion_algorithm: substring` instead. A completer that still
returns `positional: false` now gets prefix matching.
- `default` no longer warns when its closure is passed directly as
`$var`. That closure is used as the default value, while a closure
literal is still evaluated lazily.
- Deleted the `date format` and `let-env` stubs and the removal hints
for `fetch`, `post`, and `benchmark`. All of these were removed in 2023.
`let-env FOO = 1` now fails with "Assignment operations require a
variable", and `date format '%Y'` with "Extra positional argument". Use
`$env.FOO = 1` and `format date`.
- Nushell no longer converts a pre-0.93 `plugin.nu` into
`plugin.msgpackz`. A setup that has only `plugin.nu` starts with no
plugins. Register them again with `plugin add`.

### Breaking changes for plugin authors

- `ShellError::GenericError` is removed. Use
`ShellError::Generic(GenericError)`.
- `PipelineData::metadata()` is removed. Use `metadata_ref()`,
`metadata_mut()`, or `take_metadata()`.
- `EngineState::current_work_dir()` and `StateWorkingSet::get_cwd()` are
removed. Use `EngineState::cwd()` or `cwd_as_string()`.
- `ast::Call::positional_nth()` and `positional_len()` are removed. Use
`positional_iter()`.
- The unused `ShellError::DeprecationWarning` is removed.
- `CustomValue::is_iterable()` is no longer deprecated.

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-10-31 07:58:34 -05:00
Darren Schroeder 62c483dc89 Make closures that call commands faster, and into datetime on RFC 3339 strings (#19394)
## Description

Running a closure-taking command (`each`, `where`, `update`, ...) inside
another closure was slow, because each call copied the engine's whole
parse state (the scope's name tables, the variable list, the span list,
the file list). In #19392 the `update cells` + `match` + `each` form did
that 90,000 times on 30,000 rows, roughly 300k instructions per call,
before running any user code. Those parts of `EngineState` are now
behind `Arc`s (like `decls` and `blocks` already were), so the copy is a
handful of reference-count bumps.

Two more per-call costs showed up in the same profiles:

- Every call to a built-in command rebuilt the command's `Signature` to
check its input and arguments. It now comes from the signature cache the
parser already keeps on `EngineState`.
- `into datetime` (and `format date`, `date humanize`, `date
to-timezone`) parsed every string with `dtparse`. RFC 3339 date-times,
the usual form in data, now go through chrono's RFC 3339 parser first.
Leap seconds still go to `dtparse`, which rejects them, so results don't
change: over 83,581 date-like strings, `into datetime` and `format date`
give the same output as on main.
### Before and after

The issue's 30,000 rows in `$data`, with `let cols = [date created_at
updated_at last_played_at play_history like_history]`:

```nushell
# match: the issue's one-call attempt
$data | update cells {|value|
  match $value {
    [ ..$elements ] => { $elements | each { into datetime } }
    null => { $value }
    _ => { $value | into datetime }
  }
} ...$cols files
# two calls: the issue's fast form
$data | update cells {|| try { into datetime } } ...$cols | update files { into datetime created_at updated_at mod_time }
# recursive: one call
$data | update cells -r {|| try { into datetime } } ...$cols files
# par-each
$data | par-each --keep-order {|row| $row | update cells {|| try { into datetime } } ...$cols | update files { into datetime created_at updated_at mod_time } }
```

`nu -n`, main at e6a17bd21 vs this branch, both `--release`. Time is the
best of 3 `timeit` runs on an idle CPU. Instructions retired are for the
whole process and include ~2.1G for loading the JSON.

| command | main | branch |
| --- | --- | --- |
| match | 2.28 s, 36.6G instructions | 369 ms, 7.1G instructions |
| two calls | 673 ms, 12.4G instructions | 218 ms, 5.2G instructions |
| recursive | 647 ms, 12.2G instructions | 191 ms, 4.8G instructions |
| par-each | 420 ms, 31.8G instructions | 255 ms, 7.9G instructions |


## User-facing changes (Release notes)

- Closures that call `each`, `where`, `update` or another command that
takes a closure run much faster.
- Calls to built-in commands inside loops and closures are faster.
- `into datetime`, `format date`, `date humanize` and `date to-timezone`
read RFC 3339 date-times (`2025-04-18T04:04:32-07:00`) several times
faster.

## Additional notes

closed https://github.com/nushell/nushell/issues/19392
2026-10-31 07:46:51 -05:00
Lucas 9970552848 Fix OSC 7 directory URL escaping (#19358)
Hello

## Description

Use `Url::from_file_path` to encode OSC 7 directory paths. Keep the
shell hostname for local paths, including numeric names. UNC paths now
use the file server as the URL host.

## User-facing changes (Release notes)

Fixed terminal directory tracking for directory names containing `#`,
`?`, `%`, or `;`. UNC paths now report the file server as the host, so
terminals that require a local host may ignore them.

## Additional notes

Fixes #19357.
2026-10-27 10:39:15 -05:00
Darren Schroeder faa166c374 Don't let Tab's partial completion drop suggestions that replace a different span (#19344)
## Description

With `completions.partial` on (the default), Tab inserts the prefix that
every suggestion shares. nushell worked that prefix out itself in
`partial_of`, using only the suggestions with the first suggestion's
span. An extern's subcommands replace the whole `foo re`, while a file
replaces only `re`. So when a file sorted first, it was the shared
prefix on its own. In a directory with `README.md`, `foo re<Tab>` became
`foo README.md` once the background completer answered. With a module of
`git <sub>` externs loaded, `git re<Tab>` became `git README.md`.

When the completer passes no prefix, reedline derives one. Since
nushell/reedline#1261, which main picked up in #19342, reedline lines up
suggestions that replace different spans and keeps only what all of them
share. Any prefix `partial_of` returned was one reedline derives anyway,
so this PR deletes `partial_of` and lets reedline decide.

The stale fallback dropped a group too. After `foo r<Tab>`, Esc,
`e<Tab>`, Tab answers at once from the cached `foo r` answer, narrowed
to `foo re`. The narrowing kept only the suggestions sharing the last
suggestion's span. Those were the subcommands, so reedline inserted `foo
reb` and `README.md` was gone. Now a cached answer that mixes spans
gives no fallback. Until the fresh answer arrives, Tab inserts nothing
and an open menu keeps its last answer, as on the first Tab of a line.

## User-facing changes (Release notes)

Fixed Tab replacing a partly typed subcommand with a file name, such as
`git re<Tab>` becoming `git README.md` in a directory that has a
`README.md`.

## Additional notes
<!--
Optional.

Examples:
- fixes #123
- closes #456
- related #789

Anything else reviewers should know.
Remove this section if not needed.
-->
2026-10-26 08:01:17 -05:00
赤坂理子 b1a32d194f Reset stale REPL interrupts before running a new command (#19337)
## Description

Related to #18989 and follows up on #19163

The REPL resets interrupt signals at the start of each iteration, before
evaluating the prompt
An interrupted prompt can leave the signal set for the transient prompt,
line editor callbacks, and the next command

- Recover interrupted signals after normal prompt evaluation, before
constructing the transient prompt and entering the line editor
- Keep command-boundary recovery before pre-execution hooks for
interruptions from editor callbacks
- Only reset at these recovery points when interrupted, avoiding extra
plugin Reset messages on normal commands
- Keep normal prompt errors visible and retain cancellation of running
commands
- Extend the existing regression test to cover the interrupted prompt
result, transient prompt, custom completion, and a subsequent editor
interrupt followed by a hook and command
- Disable all shell-integration flags in the regression test and explain
why its expressions use `match` to reach signal checks

### Reproduction

- Start an interactive session with a slow prompt closure such as `{
sleep 1min; "prompt" }`
- Press Ctrl-C while the prompt is evaluating
- Try a custom completer that polls interruption signals, or a transient
prompt closure containing `sleep`
- Without prompt-boundary recovery, these callbacks inherit the
interrupt until the next command is submitted
- Enter `match 1 { 1 => 42 }`
- Without command-boundary recovery, the command and its pre-execution
hooks can inherit an interrupt from the prompt or editor
- With both recovery points, the transient prompt, completion, hook, and
new command run normally

The macOS PTY probe compared the previous PR commit `0c3e8f749` with the
updated code
The previous PR binary reported normal and transient prompt interruption
errors and offered no custom completion before Enter
The updated binary reported only the normal prompt interruption, offered
completion before Enter, and rendered the transient prompt
The next hook and command succeeded in both probes, including after a
separate SIGINT while waiting for input

A separate PTY probe kept a background thread job and a frozen external
process registered during prompt interruption and verified cancellation
of a later foreground command

## User-facing changes (Release notes)

Fixed stale prompt interrupts affecting completions, transient prompts,
and the next interactive command with its pre-execution hooks

## Validation

Local checks on macOS aarch64 with Rust 1.97.1 at `2bcf4099e`

| Command | Result |
| --- | --- |
| `cargo test --locked --profile ci -p nu-cli --lib --
command_after_interrupted_prompt_runs_hooks_and_command` | Fails without
prompt-boundary recovery at the transient prompt assertion, passes with
the fix |
| `cargo build --locked --profile ci --bin nu` | Passed |
| `cargo test --locked --profile ci -p nu-cli --no-fail-fast` | 200 unit
tests and 295 integration tests passed, 2 ignored |
| `cargo test --locked --profile ci --test tests -- shell::` | 341
passed, 6 ignored, including all 29 background-job tests |
| `cargo test --locked --profile ci --bin nu -- signals::` | 3 passed |
| `cargo nuclippy` | Passed |
| `cargo check --locked --profile ci --no-default-features --bin nu` |
Passed |
| `cargo fmt --all` and `cargo fmt --all --check` | Passed |
| `typos` 1.51.1 | Passed |
| `git diff --check` | Passed |

Manual PTY checks passed for prompt errors remaining visible, completion
and transient-prompt recovery before Enter, subsequent hook and command
execution, editor-interrupt recovery, background and frozen job
preservation, and foreground cancellation
The regression test emitted no shell-integration OSC or application-mode
reset sequences

## Additional notes

The command-boundary recovery retains a short race for a SIGINT arriving
after Enter but before the reset
This is a trade-off to recover editor interruptions, not a claim that
the race is eliminated

One initial baseline PTY launch in this follow-up timed out after 30
seconds without output, while the rerun and updated-binary probes passed
The earlier validation also recorded one 60-second PTY startup timeout
The causes were not established and the passing reruns do not erase
those observations

This reproduction did not demonstrate actual job deletion, so this PR
does not claim to resolve every scenario in #18989 or close that issue

Windows and Linux runtime validation is deferred to GitHub CI and is not
included in the local results above
2026-10-24 18:54:48 -05:00