From 5af385bc95e4ed6794885635bd81e4b94719d8a5 Mon Sep 17 00:00:00 2001
From: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Date: Sat, 14 Nov 2026 15:59:57 -0600
Subject: [PATCH 01/46] Fix doc statements that contradict Nushell 0.117.0
These passages described behavior that the 0.117.0 binary or source
contradicts. Each was re-checked before editing.
- configuration: assigning a record to $env.config merges; login.nu
loads before the autoload dirs; -l with a script file loads no config
- hooks: display_output and command_not_found run under -c and scripts
- coloring_and_theming: drop bg_* names, which color_config ignores;
every prompt variable accepts a closure
- line_editor: keybindings and menus assignment replaces the list
(#19418); fix Alt+C, add PageUp/PageDown, correct the
`keybindings default` claim
- types: inf/-inf/NaN literals; custom type names work as annotations
- strings, globs, date, =~ engine, null comparisons, multi-line
parameter comments, module path resolution, std/dirs vs std/log,
error chaining from catch, load-env PATH conversion, nu -i -c,
display_output default, tui and mcp defaults, explore config saving,
background job exit warning, alias hoisting, match int/float
equality, reduce closure parameter order
Prettier re-padded the color table in coloring_and_theming.md after the
bg_* rows were removed.
---
book/background_jobs.md | 6 +-
book/coloring_and_theming.md | 255 ++++++++----------
book/configuration.md | 17 +-
book/creating_errors.md | 4 +-
book/custom_commands.md | 2 +-
book/environment.md | 2 +-
book/explore.md | 2 +-
book/hooks.md | 3 +-
book/line_editor.md | 31 ++-
book/loading_data.md | 2 +-
book/mcp.md | 2 +-
book/modules/creating_modules.md | 2 +-
book/modules/using_modules.md | 2 +-
book/moving_around.md | 2 +
book/operators.md | 2 +-
book/pipelines.md | 10 +-
book/sorting.md | 2 +-
book/special_variables.md | 2 +-
book/standard_library.md | 6 +-
book/tui.md | 2 +-
book/types_of_data.md | 4 +-
book/working_with_strings.md | 13 +-
cookbook/direnv.md | 16 +-
cookbook/foreign_shell_scripts.md | 7 +-
lang-guide/chapters/flow_control/match.md | 7 +
lang-guide/chapters/flow_control/try-catch.md | 4 +-
.../chapters/types/basic_types/closure.md | 4 +-
.../types/other_types/01_not_declarable.md | 18 +-
.../types/other_types/custom_value.md | 2 +-
lang-guide/chapters/variable_scope.md | 2 +-
30 files changed, 220 insertions(+), 213 deletions(-)
diff --git a/book/background_jobs.md b/book/background_jobs.md
index 6ea2217a3ad..9f6a00697e0 100644
--- a/book/background_jobs.md
+++ b/book/background_jobs.md
@@ -175,7 +175,11 @@ for spawning independent background processes (see [#15201](https://github.com/n
Additionally, if the user is running an interactive Nushell session and runs
[`exit`](/commands/docs/exit.md) while there are background jobs running,
-the shell will warn about them before prompting the user to confirm `exit`.
+the shell doesn't exit. It prints a `background_jobs_running` warning with the number of
+running jobs and returns to the prompt. Running `exit` again as the next command kills the
+jobs and exits; if you run any other command first, the next `exit` warns again.
+Jobs started with `job spawn --auto-kill` don't count toward the warning and are killed
+on exit without one.
Pressing Ctrl+C at the REPL interrupts only the command running in the foreground.
Background jobs and frozen jobs keep running.
diff --git a/book/coloring_and_theming.md b/book/coloring_and_theming.md
index 920fb9d559b..0e7c0a46443 100644
--- a/book/coloring_and_theming.md
+++ b/book/coloring_and_theming.md
@@ -95,141 +95,124 @@ The color and style-attributes can be declared in multiple alternative formats.
### Normal Colors and Abbreviations
-| code | name |
-| --------- | ------------------------- |
-| `g` | `green` |
-| `gb` | `green_bold` |
-| `gu` | `green_underline` |
-| `gi` | `green_italic` |
-| `gd` | `green_dimmed` |
-| `gr` | `green_reverse` |
-| `bg_g` | `bg_green` |
-| `lg` | `light_green` |
-| `lgb` | `light_green_bold` |
-| `lgu` | `light_green_underline` |
-| `lgi` | `light_green_italic` |
-| `lgd` | `light_green_dimmed` |
-| `lgr` | `light_green_reverse` |
-| `bg_lg` | `bg_light_green` |
-| `r` | `red` |
-| `rb` | `red_bold` |
-| `ru` | `red_underline` |
-| `ri` | `red_italic` |
-| `rd` | `red_dimmed` |
-| `rr` | `red_reverse` |
-| `bg_r` | `bg_red` |
-| `lr` | `light_red` |
-| `lrb` | `light_red_bold` |
-| `lru` | `light_red_underline` |
-| `lri` | `light_red_italic` |
-| `lrd` | `light_red_dimmed` |
-| `lrr` | `light_red_reverse` |
-| `bg_lr` | `bg_light_red` |
-| `u` | `blue` |
-| `ub` | `blue_bold` |
-| `uu` | `blue_underline` |
-| `ui` | `blue_italic` |
-| `ud` | `blue_dimmed` |
-| `ur` | `blue_reverse` |
-| `bg_u` | `bg_blue` |
-| `lu` | `light_blue` |
-| `lub` | `light_blue_bold` |
-| `luu` | `light_blue_underline` |
-| `lui` | `light_blue_italic` |
-| `lud` | `light_blue_dimmed` |
-| `lur` | `light_blue_reverse` |
-| `bg_lu` | `bg_light_blue` |
-| `b` | `black` |
-| `bb` | `black_bold` |
-| `bu` | `black_underline` |
-| `bi` | `black_italic` |
-| `bd` | `black_dimmed` |
-| `br` | `black_reverse` |
-| `bg_b` | `bg_black` |
-| `ligr` | `light_gray` |
-| `ligrb` | `light_gray_bold` |
-| `ligru` | `light_gray_underline` |
-| `ligri` | `light_gray_italic` |
-| `ligrd` | `light_gray_dimmed` |
-| `ligrr` | `light_gray_reverse` |
-| `bg_ligr` | `bg_light_gray` |
-| `y` | `yellow` |
-| `yb` | `yellow_bold` |
-| `yu` | `yellow_underline` |
-| `yi` | `yellow_italic` |
-| `yd` | `yellow_dimmed` |
-| `yr` | `yellow_reverse` |
-| `bg_y` | `bg_yellow` |
-| `ly` | `light_yellow` |
-| `lyb` | `light_yellow_bold` |
-| `lyu` | `light_yellow_underline` |
-| `lyi` | `light_yellow_italic` |
-| `lyd` | `light_yellow_dimmed` |
-| `lyr` | `light_yellow_reverse` |
-| `bg_ly` | `bg_light_yellow` |
-| `p` | `purple` |
-| `pb` | `purple_bold` |
-| `pu` | `purple_underline` |
-| `pi` | `purple_italic` |
-| `pd` | `purple_dimmed` |
-| `pr` | `purple_reverse` |
-| `bg_p` | `bg_purple` |
-| `lp` | `light_purple` |
-| `lpb` | `light_purple_bold` |
-| `lpu` | `light_purple_underline` |
-| `lpi` | `light_purple_italic` |
-| `lpd` | `light_purple_dimmed` |
-| `lpr` | `light_purple_reverse` |
-| `bg_lp` | `bg_light_purple` |
-| `m` | `magenta` |
-| `mb` | `magenta_bold` |
-| `mu` | `magenta_underline` |
-| `mi` | `magenta_italic` |
-| `md` | `magenta_dimmed` |
-| `mr` | `magenta_reverse` |
-| `bg_m` | `bg_magenta` |
-| `lm` | `light_magenta` |
-| `lmb` | `light_magenta_bold` |
-| `lmu` | `light_magenta_underline` |
-| `lmi` | `light_magenta_italic` |
-| `lmd` | `light_magenta_dimmed` |
-| `lmr` | `light_magenta_reverse` |
-| `bg_lm` | `bg_light_magenta` |
-| `c` | `cyan` |
-| `cb` | `cyan_bold` |
-| `cu` | `cyan_underline` |
-| `ci` | `cyan_italic` |
-| `cd` | `cyan_dimmed` |
-| `cr` | `cyan_reverse` |
-| `bg_c` | `bg_cyan` |
-| `lc` | `light_cyan` |
-| `lcb` | `light_cyan_bold` |
-| `lcu` | `light_cyan_underline` |
-| `lci` | `light_cyan_italic` |
-| `lcd` | `light_cyan_dimmed` |
-| `lcr` | `light_cyan_reverse` |
-| `bg_lc` | `bg_light_cyan` |
-| `w` | `white` |
-| `wb` | `white_bold` |
-| `wu` | `white_underline` |
-| `wi` | `white_italic` |
-| `wd` | `white_dimmed` |
-| `wr` | `white_reverse` |
-| `bg_w` | `bg_white` |
-| `dgr` | `dark_gray` |
-| `dgrb` | `dark_gray_bold` |
-| `dgru` | `dark_gray_underline` |
-| `dgri` | `dark_gray_italic` |
-| `dgrd` | `dark_gray_dimmed` |
-| `dgrr` | `dark_gray_reverse` |
-| `bg_dgr` | `bg_dark_gray` |
-| `def` | `default` |
-| `defb` | `default_bold` |
-| `defu` | `default_underline` |
-| `defi` | `default_italic` |
-| `defd` | `default_dimmed` |
-| `defr` | `default_reverse` |
-| `bg_def` | `bg_default` |
+These names set the foreground color. For a background color, use the record format, such as `{ bg: red }`. The `bg_*` names that the [`ansi`](/commands/docs/ansi.md) command accepts, such as `bg_red`, have no effect in `color_config`.
+
+| code | name |
+| ------- | ------------------------- |
+| `g` | `green` |
+| `gb` | `green_bold` |
+| `gu` | `green_underline` |
+| `gi` | `green_italic` |
+| `gd` | `green_dimmed` |
+| `gr` | `green_reverse` |
+| `lg` | `light_green` |
+| `lgb` | `light_green_bold` |
+| `lgu` | `light_green_underline` |
+| `lgi` | `light_green_italic` |
+| `lgd` | `light_green_dimmed` |
+| `lgr` | `light_green_reverse` |
+| `r` | `red` |
+| `rb` | `red_bold` |
+| `ru` | `red_underline` |
+| `ri` | `red_italic` |
+| `rd` | `red_dimmed` |
+| `rr` | `red_reverse` |
+| `lr` | `light_red` |
+| `lrb` | `light_red_bold` |
+| `lru` | `light_red_underline` |
+| `lri` | `light_red_italic` |
+| `lrd` | `light_red_dimmed` |
+| `lrr` | `light_red_reverse` |
+| `u` | `blue` |
+| `ub` | `blue_bold` |
+| `uu` | `blue_underline` |
+| `ui` | `blue_italic` |
+| `ud` | `blue_dimmed` |
+| `ur` | `blue_reverse` |
+| `lu` | `light_blue` |
+| `lub` | `light_blue_bold` |
+| `luu` | `light_blue_underline` |
+| `lui` | `light_blue_italic` |
+| `lud` | `light_blue_dimmed` |
+| `lur` | `light_blue_reverse` |
+| `b` | `black` |
+| `bb` | `black_bold` |
+| `bu` | `black_underline` |
+| `bi` | `black_italic` |
+| `bd` | `black_dimmed` |
+| `br` | `black_reverse` |
+| `ligr` | `light_gray` |
+| `ligrb` | `light_gray_bold` |
+| `ligru` | `light_gray_underline` |
+| `ligri` | `light_gray_italic` |
+| `ligrd` | `light_gray_dimmed` |
+| `ligrr` | `light_gray_reverse` |
+| `y` | `yellow` |
+| `yb` | `yellow_bold` |
+| `yu` | `yellow_underline` |
+| `yi` | `yellow_italic` |
+| `yd` | `yellow_dimmed` |
+| `yr` | `yellow_reverse` |
+| `ly` | `light_yellow` |
+| `lyb` | `light_yellow_bold` |
+| `lyu` | `light_yellow_underline` |
+| `lyi` | `light_yellow_italic` |
+| `lyd` | `light_yellow_dimmed` |
+| `lyr` | `light_yellow_reverse` |
+| `p` | `purple` |
+| `pb` | `purple_bold` |
+| `pu` | `purple_underline` |
+| `pi` | `purple_italic` |
+| `pd` | `purple_dimmed` |
+| `pr` | `purple_reverse` |
+| `lp` | `light_purple` |
+| `lpb` | `light_purple_bold` |
+| `lpu` | `light_purple_underline` |
+| `lpi` | `light_purple_italic` |
+| `lpd` | `light_purple_dimmed` |
+| `lpr` | `light_purple_reverse` |
+| `m` | `magenta` |
+| `mb` | `magenta_bold` |
+| `mu` | `magenta_underline` |
+| `mi` | `magenta_italic` |
+| `md` | `magenta_dimmed` |
+| `mr` | `magenta_reverse` |
+| `lm` | `light_magenta` |
+| `lmb` | `light_magenta_bold` |
+| `lmu` | `light_magenta_underline` |
+| `lmi` | `light_magenta_italic` |
+| `lmd` | `light_magenta_dimmed` |
+| `lmr` | `light_magenta_reverse` |
+| `c` | `cyan` |
+| `cb` | `cyan_bold` |
+| `cu` | `cyan_underline` |
+| `ci` | `cyan_italic` |
+| `cd` | `cyan_dimmed` |
+| `cr` | `cyan_reverse` |
+| `lc` | `light_cyan` |
+| `lcb` | `light_cyan_bold` |
+| `lcu` | `light_cyan_underline` |
+| `lci` | `light_cyan_italic` |
+| `lcd` | `light_cyan_dimmed` |
+| `lcr` | `light_cyan_reverse` |
+| `w` | `white` |
+| `wb` | `white_bold` |
+| `wu` | `white_underline` |
+| `wi` | `white_italic` |
+| `wd` | `white_dimmed` |
+| `wr` | `white_reverse` |
+| `dgr` | `dark_gray` |
+| `dgrb` | `dark_gray_bold` |
+| `dgru` | `dark_gray_underline` |
+| `dgri` | `dark_gray_italic` |
+| `dgrd` | `dark_gray_dimmed` |
+| `dgrr` | `dark_gray_reverse` |
+| `def` | `default` |
+| `defb` | `default_bold` |
+| `defu` | `default_underline` |
+| `defi` | `default_italic` |
+| `defd` | `default_dimmed` |
+| `defr` | `default_reverse` |
@@ -437,7 +420,7 @@ The Nushell prompt is configurable through these environment variables and confi
- `PROMPT_MULTILINE_INDICATOR` = "::: "
- `render_right_prompt_on_last_line`: Bool value to enable or disable the right prompt to be rendered on the last line of the prompt
-Example: For a simple prompt one could do this. Note that `PROMPT_COMMAND` requires a `block` whereas the others require a `string`.
+Example: For a simple prompt one could do this. Each `PROMPT_*` variable takes either a string or a closure that returns one, and Nushell runs the closure every time it draws the prompt.
```nu
$env.PROMPT_COMMAND = { $"(date now | format date '%m/%d/%Y %I:%M:%S%.3f'): (pwd | path basename)" }
diff --git a/book/configuration.md b/book/configuration.md
index 848a3a11ed0..794caef496b 100644
--- a/book/configuration.md
+++ b/book/configuration.md
@@ -72,9 +72,9 @@ Nushell uses multiple, optional configuration files. These files are loaded in t
1. The first file loaded is `env.nu`, which was historically used to override environment variables. However, the current "best-practice" recommendation is to set all environment variables (and other configuration) using `config.nu` and the autoload directories below.
2. `config.nu` is typically used to override default Nushell settings, define (or import) custom commands, or run any other startup tasks.
-3. `*.nu` files in `$nu.vendor-autoload-dirs` are loaded. These directories are intended for vendors' and package managers' startup files.
-4. `*.nu` files in `$nu.user-autoload-dirs` are loaded. These files may be used for any startup tasks and are a good way to modularize the configuration.
-5. `login.nu` runs commands or handles configuration that should only take place when Nushell is running as a login shell.
+3. `login.nu` runs commands or handles configuration that should only take place when Nushell is running as a login shell.
+4. `*.nu` files in `$nu.vendor-autoload-dirs` are loaded. These directories are intended for vendors' and package managers' startup files.
+5. `*.nu` files in `$nu.user-autoload-dirs` are loaded. These files may be used for any startup tasks and are a good way to modularize the configuration.
By default, `env.nu`, `config.nu`, and `login.nu` are read from the `$nu.default-config-dir` directory. For example:
@@ -330,23 +330,24 @@ To avoid overwriting existing settings, it's best to simply assign updated value
```nu
$env.config = {
show_banner: false
+ color_config: { string: red }
}
```
-This would reset any _other_ settings that had been changed, since the entire record would be overwritten.
+Nushell merges a record assigned to `$env.config` into the current settings, so the keys it doesn't name keep their values. A key that holds a list or a free-form record is replaced whole, though. Here `color_config` ends up with only the `string` entry, and every other color setting is dropped. The same happens to `keybindings`, `menus`, `abbreviations`, `explore`, `tui`, `plugins`, `hooks.env_change`, and the `pre_prompt` and `pre_execution` hook lists.
:::
::: tip Right
```nu
$env.config.show_banner = false
+$env.config.color_config.string = 'red'
```
-This changes _only_ the `show_banner` key/value pair, leaving all other keys with their existing values.
+This changes _only_ the `show_banner` and `color_config.string` values, leaving all other keys with their existing values.
:::
-Certain keys are themselves also records. It's okay to overwrite these records, but it's best-practice
-to set all values when doing so. For example:
+Certain keys are themselves also records. Assigning a record to one of them merges it the same way, so you only need to list the values you want to change. For example:
```nu
# In config.nu
@@ -633,7 +634,7 @@ The following stages and their steps _may_ occur during startup, based on the fl
| Normal Shell | `nu` (no flags) | All launch steps **_except_** those marked with **_(login)_** occur. |
| Login Shell | `nu --login/-l` | All launch steps occur. |
| Command-string | `nu --commands ` (or `-c`) | All Launch stages **_except_** those marked with **_(config files)_** or **_(repl)_** occur. However, **_(default_env.nu)_** and **_(plugin)_** do occur, so plugins can be used in the command-string. With `--login/-l`, the **_(env.nu)_**, **_(config.nu)_**, and **_(login)_** steps occur as well. |
-| Script file | `nu ` | Same as with Command-string. |
+| Script file | `nu ` | Same as with Command-string, except that `--login/-l` doesn't add the **_(env.nu)_**, **_(config.nu)_**, and **_(login)_** steps. |
| No config | `nu -n` | **_(config files)_** stages do **_not_** occur, regardless of other flags. |
| No Standard Library | `nu --no-std-lib` | Regardless of other flags, the steps marked **_(stdlib)_** will **_not_** occur. |
| Force config file | `nu --config ` | Forces steps marked with **_(config.nu)_** above to run with the provided config ``, unless `-n` was also specified |
diff --git a/book/creating_errors.md b/book/creating_errors.md
index 72a71b8a430..478535fe8a6 100644
--- a/book/creating_errors.md
+++ b/book/creating_errors.md
@@ -125,7 +125,7 @@ In Nushell 0.113 and earlier, this information was available as a JSON string in
## Chaining Errors
-If you call `error make` inside a `catch` block, the caught error becomes an inner error of the new one, and both are reported:
+`error make` adds an error record that it receives as input to the new error's `inner` list. A `catch` block's input is the caught error, so when `error make` is the first command in the block, the caught error becomes an inner error of the new one, and both are reported:
```nu
try { check-range 10 1 } catch { error make "could not build the range" }
@@ -147,3 +147,5 @@ try { check-range 10 1 } catch { error make "could not build the range" }
# => ╰────
# => help: swap the two arguments
```
+
+After any other statement in the block, such as a `print`, the caught error is no longer the input, and `error make` reports only the new error. To keep the chain, pipe the error in with `$err | error make "..."`, or pass it with `inner`, as in `catch {|err| print 'cleaning up'; error make {msg: 'could not build the range', inner: [$err]} }`.
diff --git a/book/custom_commands.md b/book/custom_commands.md
index 1ce9b0555bb..1724f65e485 100644
--- a/book/custom_commands.md
+++ b/book/custom_commands.md
@@ -1166,7 +1166,7 @@ scope commands
This will show the Help _record_ that Nushell creates.
:::
-The comments following the parameters become their description. Only a single-line comment is valid for parameters.
+The comments following the parameters become their description. A comment can continue on the lines below its parameter. Nushell adds each comment-only line, up to the next parameter, to that parameter's description as a new line.
::: tip Note
A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign.
diff --git a/book/environment.md b/book/environment.md
index ee39de72557..96aeafb84e7 100644
--- a/book/environment.md
+++ b/book/environment.md
@@ -247,7 +247,7 @@ Because `nu` is an external program, Nushell translated the `[ a b c ]` list acc
Running commands with `nu -c` does not load the config file, therefore the env conversion for `FOO` is missing and it is displayed as a plain string -- this way we can verify the translation was successful.
You can also run this step manually by `do $env.ENV_CONVERSIONS.FOO.to_string [a b c]`
-_(Important! The string -> value conversion happens only for variables that already exist when `$env.ENV_CONVERSIONS` is assigned, such as those inherited from the parent process. A variable that you set as a string afterwards stays a string. To convert it, set it before assigning `ENV_CONVERSIONS`, or assign `$env.ENV_CONVERSIONS` to itself again.)_
+_(Important! The string -> value conversion happens only for variables that already exist when `$env.ENV_CONVERSIONS` is assigned, such as those inherited from the parent process. A variable that you set as a string afterwards with `$env.FOO = ...` stays a string. To convert it, set it before assigning `ENV_CONVERSIONS`, or assign `$env.ENV_CONVERSIONS` to itself again. [`load-env`](/commands/docs/load-env.md), [`with-env`](/commands/docs/with-env.md) and `FOO=bar cmd` don't have this limit. They run each string they set through its `from_string` conversion and turn a string `PATH` into a list. Pass `--no-convert` to `load-env` or `with-env` to set the values as given.)_
## Removing Environment Variables
diff --git a/book/explore.md b/book/explore.md
index 06863c5f818..64a045e0dfc 100644
--- a/book/explore.md
+++ b/book/explore.md
@@ -113,7 +113,7 @@ Remember you can combine it with `--peek`.
## Exploring Your Configuration
-[`explore config`](/commands/docs/explore_config.md) opens your current `$env.config` as a tree with an editor pane. Use `Tab` to switch between the tree and the editor, the arrow keys to move and to expand or collapse nodes, and `Enter` to start editing a value. Press `Ctrl+S` to apply an edit. When you quit with `q`, your changes are applied to the running session; `Ctrl+C` quits without saving them.
+[`explore config`](/commands/docs/explore_config.md) opens your current `$env.config` as a tree with an editor pane. Use `Tab` to switch between the tree and the editor, the arrow keys to move and to expand or collapse nodes, and `Enter` to start editing a value. Press `Ctrl+S` to apply an edit to the tree. After an edit, `q` won't quit and shows "Unsaved changes!" until you press `Ctrl+S` again while you aren't editing a value, which stages your changes. When `explore config` exits, every edit you applied to the tree is written to `$env.config` in the running session. That includes quitting with `Ctrl+C`, which skips the check and drops only an edit you haven't applied yet.
```nu
# Browse and edit the running configuration
diff --git a/book/hooks.md b/book/hooks.md
index c632f0c3ec3..0f8d69c2b94 100644
--- a/book/hooks.md
+++ b/book/hooks.md
@@ -1,7 +1,8 @@
# Hooks
Hooks allow you to run a code snippet at some predefined situations.
-They are only available in the interactive mode ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)), they do not work if you run Nushell with a script (`nu script.nu`) or command (`nu -c "print foo"`) argument.
+The `pre_prompt`, `pre_execution` and `env_change` hooks only run in the interactive mode ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)). They do not run if you run Nushell with a script (`nu script.nu`) or command (`nu -c "print foo"`) argument.
+The `display_output` and `command_not_found` hooks work there too. `display_output` formats the value that the script or command returns, and `command_not_found` runs when it calls a command that doesn't exist.
Currently, we support these types of hooks:
diff --git a/book/line_editor.md b/book/line_editor.md
index 9ef8ded2e6c..58ca050badd 100644
--- a/book/line_editor.md
+++ b/book/line_editor.md
@@ -114,7 +114,7 @@ $env.config.cursor_shape.vi_normal = 'block'
## Default Keybindings
-Each of the three edit modes is built from a few shared sets of keybindings plus its own additions. The tables below follow Reedline's [keybinding reference](https://github.com/nushell/reedline/blob/main/KEYBINDINGS.md) for the Reedline version that ships with Nushell. Run [`keybindings default`](/commands/docs/keybindings_default.md) to list the built-in keybindings of every mode.
+Each of the three edit modes is built from a few shared sets of keybindings plus its own additions. The tables below follow Reedline's [keybinding reference](https://github.com/nushell/reedline/blob/main/KEYBINDINGS.md) for the Reedline version that ships with Nushell. Run [`keybindings default`](/commands/docs/keybindings_default.md) to list Reedline's built-in key table for the `emacs`, `vi_normal`, `vi_insert`, `helix_normal` and `helix_insert` modes. It has no rows for `vi_visual` or `helix_select`, and it leaves out the plain-key Vi and Helix commands such as w and d, which Reedline handles outside that table.
Some keys are a _fallback chain_: Reedline tries each step and takes the first one that applies. The tables write those with "otherwise". For example, → accepts a history hint if one is showing, otherwise moves right in an open menu, otherwise moves the cursor right.
@@ -179,6 +179,8 @@ A mode without the editing set rebinds Backspace and Delete↑, Ctrl+P | Move up in an open menu, otherwise move one line up, walking back through the history from the first line |
| ↓, Ctrl+N | Move down in an open menu, otherwise move one line down, walking forward through the history from the last line |
+| PageUp | Move one page up in an open menu, otherwise jump to the oldest history entry |
+| PageDown | Move one page down in an open menu, otherwise leave the history for the line you were typing |
| ← | Move left in an open menu, otherwise move one character left |
| → | Accept a history hint, otherwise move right in an open menu, otherwise move one character right |
| Ctrl+← | Move one word left |
@@ -237,7 +239,7 @@ Emacs mode is the default. It has all four [common sets](#common-keybindings), p
| Ctrl+G | Redo |
| Alt+U | Uppercase the word under the cursor |
| Alt+L | Lowercase the word under the cursor |
-| Alt+C | Capitalize the character under the cursor |
+| Alt+C | Uppercase the first letter of the word under the cursor and lowercase the rest |
### Vi Mode
@@ -561,13 +563,14 @@ $env.config.keybindings ++= [{
After loading this new `config.nu`, your new keybinding (`Ctrl + t`) will open
the completion command.
-Each keybinding requires the next elements:
+Each keybinding has the next elements:
-- name: A unique name for your keybinding. Assigning to `$env.config.keybindings` merges
- the new entries into the existing bindings by name: an entry with the same name and key
- as an existing binding replaces it, while an entry that reuses a name for a different key
- is added as another binding and prints a `Multiple keybindings share a name` warning.
- To clear every keybinding, assign an empty list (`$env.config.keybindings = []`).
+- name: A label for your keybinding. It is optional, and Nushell doesn't use it to match
+ entries. Assigning a list to `$env.config.keybindings` replaces the whole list, including
+ the default bindings that open the menus (such as Tab for the completion menu),
+ so add your bindings with `++=` as in the example above. When two entries bind the same
+ mode, modifier and keycode, the later one wins. `$env.config.keybindings = []` removes
+ every binding in the list, but Reedline's built-in bindings for moving and editing stay.
- modifier: A key modifier for the keybinding. The options are:
- none
- control
@@ -931,13 +934,15 @@ Your terminal environment may not always propagate your key combinations on to N
## Menus
Thanks to Reedline, Nushell has menus that can help you with your day to day
-shell scripting. Next we present the default menus that are always available
+shell scripting. Next we present the default menus that are available
when using Nushell
-Menus are configured in `$env.config.menus`. Assigning to this list merges your
-entries into the default menus by `name`, so an entry named `completion_menu`
-replaces the default completion menu instead of adding a second one, and
-`$env.config.menus = []` does not remove the default menus.
+Menus are configured in `$env.config.menus`. Assigning a list to it replaces every
+menu, including the defaults, so `$env.config.menus = []` removes them all and
+Tab no longer opens a completion menu. To add a menu or change a default
+one, append it with `++=`. When two menus share a `name`, the later one replaces the
+earlier one, so an appended `completion_menu` takes the place of the default
+completion menu.
Each menu sets `input_mode`, which controls the text that the menu searches:
diff --git a/book/loading_data.md b/book/loading_data.md
index 1bc2414d737..a2f69c63dbc 100644
--- a/book/loading_data.md
+++ b/book/loading_data.md
@@ -1,6 +1,6 @@
# Loading Data
-Earlier, we saw how you can use commands like [`ls`](/commands/docs/ls.md), [`ps`](/commands/docs/ps.md), [`date`](/commands/docs/date.md), and [`sys host`](/commands/docs/sys_host.md) to load information about your files, processes, time of day, and the system itself. Each command gives us a table of information that we can explore. There are other ways we can load in a table of data to work with.
+Earlier, we saw how you can use commands like [`ls`](/commands/docs/ls.md), [`ps`](/commands/docs/ps.md), [`date now`](/commands/docs/date_now.md), and [`sys host`](/commands/docs/sys_host.md) to load information about your files, processes, time of day, and the system itself. Each command gives us a table of information that we can explore. There are other ways we can load in a table of data to work with.
## Opening files
diff --git a/book/mcp.md b/book/mcp.md
index bff9f684a84..3a639274a52 100644
--- a/book/mcp.md
+++ b/book/mcp.md
@@ -67,7 +67,7 @@ Every result is also stored in the `$history` list, at the `history_index` given
| Variable | Default | Effect |
| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `NU_MCP_OUTPUT_LIMIT` | `10kb` | Larger results are left out of the response, which has a `note` field in place of `output`: `output truncated, full result in $history.0`. `0b` turns truncation off. |
+| `NU_MCP_OUTPUT_LIMIT` | `10kib` | Larger results are left out of the response, which has a `note` field in place of `output`: `output truncated, full result in $history.0`. `0b` turns truncation off. |
| `NU_MCP_HISTORY_LIMIT` | `100` | How many results `$history` keeps. Older results are dropped. |
| `NU_MCP_PROMOTE_AFTER` | `120sec` | A call that runs longer than this becomes a [background job](./background_jobs.md). The response is an error with the job id, and the result can be collected later with `job recv`. |
diff --git a/book/modules/creating_modules.md b/book/modules/creating_modules.md
index 636f427da42..f0136edcc4c 100644
--- a/book/modules/creating_modules.md
+++ b/book/modules/creating_modules.md
@@ -384,7 +384,7 @@ Running this command changes the directory _locally_ in the module, but the chan
### `export-env` runs only when the `use` call is _evaluated_
::: note
-This scenario is commonly encountered when creating a module that uses `std/log`.
+This scenario is commonly encountered when creating a module that uses `std/dirs`.
:::
Attempting to import a module's environment within another environment may not work as expected. Let's create a new module `go.nu` that creates "shortcuts" to common directories. One of these will be the `$env.NU_MODULES_DIR` defined above in `my-utils`.
diff --git a/book/modules/using_modules.md b/book/modules/using_modules.md
index a87bf198273..b750a401d68 100644
--- a/book/modules/using_modules.md
+++ b/book/modules/using_modules.md
@@ -76,7 +76,7 @@ The path to the module can be:
:::
::: important Important! Importing modules from `$NU_LIB_DIRS` or `$env.NU_LIB_DIRS`
- When importing a module via a relative path, Nushell first searches from the current directory. If a matching module is not found at that location, Nushell then searches each directory in the constant `$NU_LIB_DIRS` list, and then the environment variable version, `$env.NU_LIB_DIRS`. By default, both include the `scripts` directory in your Nushell configuration directory and the `completions` directory in your Nushell data directory. The constant is the recommended place to add your own directories.
+ When importing a module via a relative path, Nushell first searches from the directory of the file that contains the `use` (or `source`) call. For a command typed at the prompt or passed to `nu -c`, that is the current directory. If a matching module is not found at that location, Nushell then searches each directory in the constant `$NU_LIB_DIRS` list, and then the environment variable version, `$env.NU_LIB_DIRS`. By default, both include the `scripts` directory in your Nushell configuration directory and the `completions` directory in your Nushell data directory. The constant is the recommended place to add your own directories.
This allows you to install modules to a location that is easily accessible via a relative path regardless of the current directory.
:::
diff --git a/book/moving_around.md b/book/moving_around.md
index c8ae80279a9..45ed6b2757c 100644
--- a/book/moving_around.md
+++ b/book/moving_around.md
@@ -110,6 +110,8 @@ The quoting techniques above are useful when constructing glob-literals, but you
ls $glob_pattern
```
+ An interpolated string written directly as the argument doesn't need `into glob`. Nushell expands it as a glob, so `ls $"*($current_month)*"` finds the same files. The conversion is needed when the pattern is stored in a variable first, as above, or comes from another command.
+
2. The spread operator combined with the [`glob` command](/commands/docs/glob.html):
The [`glob` command](/commands/docs/glob.html) (note: not the same as `into glob`) produces a [`list`](types_of_data.html#lists) of filenames that match the glob pattern. This list can be expanded and passed to filesystem commands using the [spread operator](operators.html#spread-operator):
diff --git a/book/operators.md b/book/operators.md
index cad2bceca63..0b4ac0d3569 100644
--- a/book/operators.md
+++ b/book/operators.md
@@ -125,7 +125,7 @@ For example:
ls | where name =~ ^nu # returns all files whose names start with "nu"
```
-Both operators use [the Rust regex crate's `is_match()` function](https://docs.rs/regex/latest/regex/struct.Regex.html#method.is_match).
+Both operators use the [`fancy-regex`](https://docs.rs/fancy-regex) crate, which adds look-around and backreferences to the syntax of Rust's `regex` crate. See [Regular Expressions](./regular_expressions.md) for the syntax.
## Case Sensitivity
diff --git a/book/pipelines.md b/book/pipelines.md
index d1aa258502f..c96a824fb42 100644
--- a/book/pipelines.md
+++ b/book/pipelines.md
@@ -404,15 +404,15 @@ Many commands do have piped input/output however, and if it's ever unclear, chec
## Rendering Display Results
-In interactive mode, when a pipeline ends, the [`display_output` hook configuration](https://www.nushell.sh/book/hooks.html#changing-how-output-is-displayed) defines how the result will be displayed.
-The default configuration uses the [`table` command](/commands/docs/table.md) to render structured data as a visual table.
+When a pipeline typed at the prompt ends, or a script or `nu -c` command finishes, the [`display_output` hook configuration](https://www.nushell.sh/book/hooks.html#changing-how-output-is-displayed) defines how the result will be displayed.
+The default hook is `if (term size).columns >= 100 { table -e } else { table }`, which uses the [`table` command](/commands/docs/table.md) to render structured data as a visual table, expanding nested data when the terminal is at least 100 columns wide.
The following example shows how the `display_output` hook can render
- an expanded table with `table -e`
- an unexpanded table with `table`
- an empty closure `{||}` and empty string `''` lead to simple output
-- `null` can be assigned to clear any customization, reverting back to default behavior
+- `null` removes the hook, and Nushell then renders results with a plain `table`, without the default's `-e` on wide terminals
```nu
$env.config.hooks.display_output = { table -e }
@@ -455,7 +455,7 @@ $env.config.hooks.display_output = ''
# => 5
# => 6]
-# clear to default behavior
+# remove the hook: a plain `table`, even on a wide terminal
$env.config.hooks.display_output = null
[1,2,3,[4,5,6]]
# => ╭───┬────────────────╮
@@ -466,6 +466,8 @@ $env.config.hooks.display_output = null
# => ╰───┴────────────────╯
```
+To restore the default, assign its string again: `$env.config.hooks.display_output = 'if (term size).columns >= 100 { table -e } else { table }'`.
+
## Output Result to External Commands
Sometimes you want to output Nushell structured data to an external command for further processing. However, Nushell's default formatting options for structured data may not be what you want.
diff --git a/book/sorting.md b/book/sorting.md
index 1f18b567be4..ba8166b6e1c 100644
--- a/book/sorting.md
+++ b/book/sorting.md
@@ -398,7 +398,7 @@ $incompatible | sort-by -c {|a, b| $a < $b | default ($a != null) }
# => ╰────
```
-Special handling is required for `null` values, since comparison between any value and `null` returns `null`. To instead reject `null` values, try the following:
+Special handling is required for `null` values, since an ordering comparison (`<`, `<=`, `>`, `>=`) between any value and `null` returns `null`. `==` and `!=` still return a `bool`, so `1 == null` is `false`. To instead reject `null` values, try the following:
```nu
let baddata = [8 3.2 null 58 2]
diff --git a/book/special_variables.md b/book/special_variables.md
index e0a067c885f..437c3a15639 100644
--- a/book/special_variables.md
+++ b/book/special_variables.md
@@ -43,7 +43,7 @@ The `$nu` constant is a record containing several useful values:
# => true
```
- Note: When started as an interactive shell, startup config files are processed. When started as a non-interactive shell, no config files are read unless explicitly called via flag.
+ Note: When started as an interactive shell (the REPL), startup config files are processed. When started as a non-interactive shell, no config files are read unless explicitly called via flag. `--interactive (-i)` doesn't change that. `nu -i -c` and `nu -i script.nu` still read no config files, and they exit when they finish.
- `is-login`: Indicates whether or not Nushell was started as a login shell.
- `history-enabled`: History may be disabled via `nu --no-history`, in which case this constant will be `false`.
diff --git a/book/standard_library.md b/book/standard_library.md
index 304017810aa..3272074b5fd 100644
--- a/book/standard_library.md
+++ b/book/standard_library.md
@@ -161,10 +161,12 @@ nu -n -c "$nu.startup-time"
You will not be able to import the library, any of its submodules, nor use any of its commands, when it is disabled in this way. This includes the `banner` and `pwd` commands from `std/prelude`.
-## Using `std/log` in Modules
+## Using `std/dirs` in Modules
::: warning Important!
-`std/log` exports environment variables. To use the `std/log` module in your own module, please see [this caveat](./modules/creating_modules.md#export-env-runs-only-when-the-use-call-is-evaluated) in the "Creating Modules" Chapter.
+`std/dirs` sets up its environment variables in an `export-env` block. If your own module imports it with a top-level `use std/dirs`, that block doesn't run when your module is imported, and `dirs` fails with `Cannot find column 'DIRS_LIST'`. To use the `std/dirs` module in your own module, please see [this caveat](./modules/creating_modules.md#export-env-runs-only-when-the-use-call-is-evaluated) in the "Creating Modules" Chapter.
+
+`std/log` doesn't need this. Its commands fall back to their default formats when its environment variables aren't set.
:::
diff --git a/book/tui.md b/book/tui.md
index 3893d10952a..576268334e3 100644
--- a/book/tui.md
+++ b/book/tui.md
@@ -867,7 +867,7 @@ Colors come from `$env.config.tui`, which has one entry per part of the interfac
| `tab_active` / `tab_inactive` | The tab bar | `{ fg: cyan, attr: bu }` / `{ fg: dark_gray }` |
| `progress` | The filled part of a progress bar | `{ fg: green }` |
| `button` | Button labels | `{ fg: white, bg: blue }` |
-| `surface` / `backdrop` | The fill behind widgets, and behind a `--dialog` (only `bg` is used) | unset (a near-black fill) |
+| `surface` / `backdrop` | The fill behind widgets, and behind a `--dialog` (only `bg` is used) | `{ bg: default }`, the terminal's background |
```nu
$env.config.tui.title_bar = { fg: black, bg: yellow, attr: b }
diff --git a/book/types_of_data.md b/book/types_of_data.md
index 2d5d6723cf6..c56ef5489b4 100644
--- a/book/types_of_data.md
+++ b/book/types_of_data.md
@@ -26,7 +26,7 @@ Each type below lists its _annotation_: the name you write after `:` to declare
| Type | Example |
| ------------------------------------- | --------------------------------------------------------------------- |
| [Integers](#integers) | `-65535` |
-| [Floats (decimals)](#floats-decimals) | `9.9999`, `Infinity` |
+| [Floats (decimals)](#floats-decimals) | `9.9999`, `inf`, `-inf`, `NaN` |
| [Strings](#text-strings) | "hole 18", 'hole 18', \`hole 18\`, hole18, r#'hole18'# |
| [Booleans](#booleans) | `true` |
| [Dates](#dates) | `2000-01-01` |
@@ -439,7 +439,7 @@ $simple_record.c? == null
| | |
| --------------------- | ---------------------------------------------------------------------------------------------------------- |
| **_Description:_** | A [semantic version](https://semver.org) number, such as `1.2.3` or `2.0.0-rc.1` |
-| **_Annotation:_** | N/A - This is a custom value, which `describe` reports as `semver` |
+| **_Annotation:_** | `semver`, a custom value type that `describe` also reports as `semver` |
| **_Literal Syntax:_** | N/A - Convert a string or record with [`into semver`](/commands/docs/into_semver.md) |
| **_See also:_** | [`semver bump`](/commands/docs/semver_bump.md), [`into semver-range`](/commands/docs/into_semver-range.md) |
diff --git a/book/working_with_strings.md b/book/working_with_strings.md
index 0f37e87ea57..df9724e6b0b 100644
--- a/book/working_with_strings.md
+++ b/book/working_with_strings.md
@@ -7,12 +7,12 @@ and much more. Strings are so common that Nushell offers multiple string formats
| Format of string | Example | Escapes | Notes |
| ---------------------------------------------------- | ----------------------- | ------------------------- | ---------------------------------------------------------------------- |
-| [Single-quoted string](#single-quoted-strings) | `'[^\n]+'` | None | Cannot contain single quotes within the string |
+| [Single-quoted string](#single-quoted-strings) | `'[^\n]+'` | None | Inner `'` only in pairs, kept as written: `'a''b'` is `a''b` |
| [Double-quoted string](#double-quoted-strings) | `"The\nEnd"` | C-style backslash escapes | All literal backslashes must be escaped |
| [Raw strings](#raw-strings) | `r#'Raw string'#` | None | May include single quotes |
| [Bare word string](#bare-word-strings) | `ozymandias` | None | Can only contain "word" characters; Cannot be used in command position |
| [Backtick string](#backtick-quoted-strings) | \`[^\n]+\` | None | Bare string that can include whitespace. Cannot contain any backticks |
-| [Single-quoted interpolation](#string-interpolation) | `$'Captain ($name)'` | None | Cannot contain any `'` or unmatched `()` |
+| [Single-quoted interpolation](#string-interpolation) | `$'Captain ($name)'` | None | Inner `'` only in pairs, as above. No unmatched `()` |
| [Double-quoted interpolation](#string-interpolation) | `$"Captain ($name)"` | C-style backslash escapes | All literal backslashes and `()` must be escaped |
## Single-quoted Strings
@@ -30,6 +30,15 @@ end'
Single-quoted strings don't do anything to the text they're given, making them ideal for holding a wide range of text data.
+There is no escape for `'` inside a single-quoted string. Inner single quotes work only in pairs, and only when the word ends with `'`. Nushell keeps them as written, so `''` is not read as one quote the way it is in SQL:
+
+```nu
+'it''s'
+# => it''s
+```
+
+For text with a lone `'`, such as `don't`, use a double-quoted string, a backtick string, or a [raw string](#raw-strings).
+
## Double-quoted Strings
For more complex strings, Nushell also offers double-quoted strings. These strings use the `"` character to surround text. They also support the ability to escape characters inside the text using the `\` character.
diff --git a/cookbook/direnv.md b/cookbook/direnv.md
index 19145259550..cb1020af83a 100644
--- a/cookbook/direnv.md
+++ b/cookbook/direnv.md
@@ -17,18 +17,15 @@ From [direnv.net](https://direnv.net):
In Nushell, it's possible to run direnv each time the prompt displays (using a [`pre_prompt` hook](/book/hooks.html)). However, it's more efficient to update only when the directory is changed using an `env_change` hook along with:
- [`from json`](/commands/docs/from_json.md) to convert the direnv output to structured data
-- [`load-env`](/commands/docs/load-env.md)
-- An `env-conversion` helper for the `PATH` from the [Standard Library](/book/standard_library.md)
+- [`load-env`](/commands/docs/load-env.md), which also turns the `PATH` string that direnv exports into a list
::: note
-The direnv configuration below requires Nushell 0.104 or later.
+The direnv configuration below requires Nushell 0.117 or later.
:::
```nu
-use std/config *
-
# Initialize the PWD hook as an empty list if it doesn't exist
$env.config.hooks.env_change.PWD = $env.config.hooks.env_change.PWD? | default []
@@ -38,14 +35,7 @@ $env.config.hooks.env_change.PWD ++= [{||
return
}
- direnv export json
- | from json
- | default {}
- | update cells {
- # If direnv changes the PATH, it will become a string and we need to re-convert it to a list
- do (env-conversions).path.from_string $in
- } PATH
- | load-env
+ direnv export json | from json | default {} | load-env
}]
```
diff --git a/cookbook/foreign_shell_scripts.md b/cookbook/foreign_shell_scripts.md
index 35810c80ac7..7cbad5325ba 100644
--- a/cookbook/foreign_shell_scripts.md
+++ b/cookbook/foreign_shell_scripts.md
@@ -140,9 +140,10 @@ A caveat for this approach is that it requires all changed environment variables
not to include newline characters, as the UNIX `env` output is not cleanly
parseable in that case.
-Also beware that directly passing the output of `capture-foreign-env` to
-`load-env` can result in changed variables like `PATH` to become strings again,
-even if they have been converted to a list before.
+Before Nushell 0.117.0, passing the output of `capture-foreign-env` directly to
+`load-env` turned changed variables like `PATH` back into strings. Since 0.117.0,
+`load-env` turns a string `PATH` into a list and applies `$env.ENV_CONVERSIONS`
+to the other variables it sets.
:::
### Detailed Explanation of `capture-foreign-env`
diff --git a/lang-guide/chapters/flow_control/match.md b/lang-guide/chapters/flow_control/match.md
index 0ade5ee11c2..0f0bbf2b601 100644
--- a/lang-guide/chapters/flow_control/match.md
+++ b/lang-guide/chapters/flow_control/match.md
@@ -98,6 +98,13 @@ List and record patterns can be nested, and a pattern can be followed by an `if`
# => string
```
+ Ints and floats are the exception. They compare by numeric value, so the float `1.0` matches the pattern `1`:
+
+ ```nu
+ match 1.0 { 1 => 'int pattern', 1.0 => 'float pattern' }
+ # => int pattern
+ ```
+
1. A list pattern without `..` must have exactly as many items as the list:
```nu
diff --git a/lang-guide/chapters/flow_control/try-catch.md b/lang-guide/chapters/flow_control/try-catch.md
index abc3900e1fa..193d8e234af 100644
--- a/lang-guide/chapters/flow_control/try-catch.md
+++ b/lang-guide/chapters/flow_control/try-catch.md
@@ -70,7 +70,7 @@ try { error make {msg: "disk full", help: "free some space"} } catch { $in.detai
# => 1
```
-1. Errors raised inside `catch` propagate normally. When `catch` raises a new error with `error make`, the original error is attached to it and printed after it:
+1. Errors raised inside `catch` propagate normally. `error make` attaches an error record it receives as input to the new error, and the input of `catch` is the original error. So when `error make` is the first command in `catch`, the original error is attached to the new one and printed after it:
```nu
try { error make {msg: a} } catch {|e| error make {msg: b} }
@@ -90,6 +90,8 @@ try { error make {msg: "disk full", help: "free some space"} } catch { $in.detai
# => ╰────
```
+ After any other statement, the original error is no longer the input. Pipe it in (`$e | error make {msg: b}`) or pass it as `inner` to keep it attached: `catch {|e| print "logging"; error make {msg: b, inner: [$e]} }`.
+
To log an error and re-raise it unchanged, return `$e.raw`: `catch {|e| print "logging"; $e.raw }`.
1. `finally` runs after the block succeeds, after `catch`, when an uncaught error is about to propagate, and when `break`, `continue`, `return` or `exit` leaves the `try` (only `exit --abort` skips it). It receives a value as its parameter and as `$in`:
diff --git a/lang-guide/chapters/types/basic_types/closure.md b/lang-guide/chapters/types/basic_types/closure.md
index 0ecf4ae6ac8..b7c382f5a35 100644
--- a/lang-guide/chapters/types/basic_types/closure.md
+++ b/lang-guide/chapters/types/basic_types/closure.md
@@ -204,9 +204,9 @@ The `sort-by` command sorts a list or table. The closure determines and returns
# => ╰───┴────────╯
```
-The `reduce` command processes a list to accumulate a single result. The closure defines how to combine the current item with the (intermediate) accumulated value.
+The `reduce` command processes a list to accumulate a single result. The closure defines how to combine the current item with the (intermediate) accumulated value. It receives the current item first and the accumulated value second.
```nu
-[1 2 3 4] | reduce {|accumulator, current_value| $accumulator + $current_value }
+[1 2 3 4] | reduce {|current_value, accumulator| $accumulator + $current_value }
# => 10
```
diff --git a/lang-guide/chapters/types/other_types/01_not_declarable.md b/lang-guide/chapters/types/other_types/01_not_declarable.md
index 0e610e96fad..c0bcff1d909 100644
--- a/lang-guide/chapters/types/other_types/01_not_declarable.md
+++ b/lang-guide/chapters/types/other_types/01_not_declarable.md
@@ -2,18 +2,14 @@
The following are valid Nushell data types which cannot be declared by the user. They are used by Nushell internally or by plugins or commands compiled in Nushell like Polars and SQLite database.
-Besides `error` values and blocks (see their pages), this group includes [custom values](custom_value.md) such as `semver` and `semver-range` (from `into semver` and `into semver-range`), `matrix` (from `into matrix`), `SQLiteDatabase` (from `open` on a SQLite file or `stor open`), and Polars objects such as `polars_dataframe`. `describe` reports their names, but a name like `semver` cannot be used as a type annotation:
+Besides `error` values and blocks (see their pages), this group includes [custom values](custom_value.md) such as `semver` and `semver-range` (from `into semver` and `into semver-range`), `matrix` (from `into matrix`), `SQLiteDatabase` (from `open` on a SQLite file or `stor open`), and Polars objects such as `polars_dataframe`. `describe` reports their names. Since Nushell 0.117.0, such a name also works as a type annotation when a command in scope declares that type in its signature. The built-in types above always qualify, and a plugin's types, such as `polars_dataframe`, do once the plugin is added:
```nu
-let v: semver = ("1.2.3" | into semver)
-# => Error: nu::parser::unknown_type
-# =>
-# => × Unknown type.
-# => ╭─[repl_entry #1:1:8]
-# => 1 │ let v: semver = ("1.2.3" | into semver)
-# => · ───┬──
-# => · ╰── unknown type
-# => ╰────
+def bump-minor [v: semver]: nothing -> semver { $v | semver bump minor }
+bump-minor ("1.2.3" | into semver)
+# => 1.3.0
```
-Leave such a variable or parameter unannotated, or annotate it as `any`.
+The parser checks the argument, so `bump-minor "1.2.3"` fails with `expected semver`. Convert the string with `into semver` first.
+
+A name that no command in scope declares, such as `polars_dataframe` without the Polars plugin, is an `unknown type` error. Leave such a variable or parameter unannotated, or annotate it as `any`.
diff --git a/lang-guide/chapters/types/other_types/custom_value.md b/lang-guide/chapters/types/other_types/custom_value.md
index 38ea5115d87..bfc7e61a514 100644
--- a/lang-guide/chapters/types/other_types/custom_value.md
+++ b/lang-guide/chapters/types/other_types/custom_value.md
@@ -4,7 +4,7 @@
| | |
| --- | --- |
| **_Description:_** | An opaque data type that is only used internally in Nushell by built-in commands or plugins.
-| **_Annotation:_** | None
+| **_Annotation:_** | The type name reported by `describe`, such as `semver`, when a command in scope declares it (see [Types which are not declarable](./01_not_declarable.md))
| **_Literal syntax:_** | None
| **_Casts:_** | None
diff --git a/lang-guide/chapters/variable_scope.md b/lang-guide/chapters/variable_scope.md
index 76616a4dfec..90226ea51a6 100644
--- a/lang-guide/chapters/variable_scope.md
+++ b/lang-guide/chapters/variable_scope.md
@@ -85,7 +85,7 @@ g
# => 1
```
-`def` and `alias` definitions are scoped like variables: a command defined inside a block, closure or other command is not visible outside it. Unlike variables, definitions are available in their whole block, even before the line that defines them:
+`def` and `alias` definitions are scoped like variables: a command defined inside a block, closure or other command is not visible outside it. An `alias` can only be used after its definition, but a `def` is available in its whole block, even before the line that defines it:
```nu
print (greet); def greet [] { 'defined later' }
From 2fbe7a35607acf0edf31e0ffc1504cc4a877655f Mon Sep 17 00:00:00 2001
From: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Date: Sat, 14 Nov 2026 16:24:34 -0600
Subject: [PATCH 02/46] Document type, string, and operator features that had
no docs
Covers the rows rated `none` in the coverage checklist for data types,
literals, operators, redirection, and Nushell's exit status:
- quotes inside one word, nested interpolation, bare-word interpolation
- inf/-inf/NaN, inclusive ranges, range bound and construction errors
- list and record separators, parenthesized expressions in literals,
combined cell-path modifiers, interpolated globs
- subtyping and which values a type annotation accepts
- unary minus, every redirection spelling including the append forms,
where redirections are allowed, and nu's exit status after an error
Examples were run with a 0.117.1-dev build and checked against 0.117.0.
---
book/moving_around.md | 2 +
book/navigating_structured_data.md | 2 +
book/operators.md | 21 ++++
book/stdout_stderr_exit_codes.md | 102 ++++++++++++++++++
book/types_of_data.md | 4 +-
book/working_with_strings.md | 77 ++++++++++++-
lang-guide/chapters/operators.md | 1 +
lang-guide/chapters/strings_and_text.md | 12 +++
.../chapters/types/basic_types/cellpath.md | 27 +++++
.../chapters/types/basic_types/float.md | 29 ++++-
lang-guide/chapters/types/basic_types/glob.md | 13 +++
lang-guide/chapters/types/basic_types/list.md | 39 +++++++
.../chapters/types/basic_types/range.md | 56 ++++++++++
.../chapters/types/basic_types/record.md | 41 +++++++
lang-guide/chapters/types/type_signatures.md | 53 +++++++++
15 files changed, 476 insertions(+), 3 deletions(-)
diff --git a/book/moving_around.md b/book/moving_around.md
index 45ed6b2757c..14d83722e6a 100644
--- a/book/moving_around.md
+++ b/book/moving_around.md
@@ -112,6 +112,8 @@ The quoting techniques above are useful when constructing glob-literals, but you
An interpolated string written directly as the argument doesn't need `into glob`. Nushell expands it as a glob, so `ls $"*($current_month)*"` finds the same files. The conversion is needed when the pattern is stored in a variable first, as above, or comes from another command.
+ This only works when the interpolated string has at least one `( )` part. `ls $"*.txt"` has nothing to interpolate, so it is a plain string, and `ls` looks for a file literally named `*.txt`. A [bare word with `( )`](working_with_strings.md#interpolation-in-bare-words) expands as well: `ls *($current_month)*` finds the same files as the examples above.
+
2. The spread operator combined with the [`glob` command](/commands/docs/glob.html):
The [`glob` command](/commands/docs/glob.html) (note: not the same as `into glob`) produces a [`list`](types_of_data.html#lists) of filenames that match the glob pattern. This list can be expanded and passed to filesystem commands using the [spread operator](operators.html#spread-operator):
diff --git a/book/navigating_structured_data.md b/book/navigating_structured_data.md
index 37b54589b9c..50611f9ce34 100644
--- a/book/navigating_structured_data.md
+++ b/book/navigating_structured_data.md
@@ -311,6 +311,8 @@ $person | get --ignore-case name
(Environment variables are an exception: `$env.path` and `$env.PATH` both work.)
+A member can also be both case-insensitive and [optional](#the-optional-operator). Add both modifiers, in either order: `$person.age?!` returns `null` instead of failing.
+
## Handling Missing Data
### The Optional Operator
diff --git a/book/operators.md b/book/operators.md
index 0b4ac0d3569..2f6a712c19b 100644
--- a/book/operators.md
+++ b/book/operators.md
@@ -67,6 +67,27 @@ Presented in descending order of precedence, the article details the operations
# => 9
```
+## Negation
+
+A `-` written directly in front of a variable or a parenthesized expression negates it. This works for numbers, durations and file sizes:
+
+```nu
+let x = 5
+-$x
+# => -5
+-(1 + $x)
+# => -6
+let d = 2sec
+-$d
+# => -2sec
+```
+
+The `-` has to touch the value. `- $x`, with a space, is a parse error ("expected operator"). Negating any other type, such as a string or a bool, is a parse error with the hint "Only numbers, durations and filesizes can be negated." When the parser can't know the type, as with a variable declared `any`, the error comes when the line runs instead.
+
+Negation binds more tightly than every binary operator, `**` included, so `-$x ** 2` is `25`. Write `-($x ** 2)` to get `-25`.
+
+In a command call, Nushell reads a word that starts with `-` as a flag. `echo -$x` fails with "The `echo` command doesn't have flag `-$`", so put the negation in parentheses: `echo (-$x)`. An external command gets `-$x` as the literal text `-$x`, so use `^echo (-$x)` there too.
+
## Types
Not all operations make sense for all data types.
diff --git a/book/stdout_stderr_exit_codes.md b/book/stdout_stderr_exit_codes.md
index 350e3bb0c89..74fa1023764 100644
--- a/book/stdout_stderr_exit_codes.md
+++ b/book/stdout_stderr_exit_codes.md
@@ -55,6 +55,27 @@ try { ^false | lines } catch {|err| $err.exit_code }
This pipeline behavior is an opt-out experimental option named `pipefail`. To turn it off, start Nushell with `nu --experimental-options '[pipefail=false]'`.
:::
+### Nushell's own exit status
+
+When a script (`nu script.nu`) or a command string (`nu -c '...'`) stops at an error that nothing catches, Nushell prints the error and exits with a non-zero status. The status tells the calling program what failed:
+
+- `1` for an error from Nushell itself, such as a parse error, a failing built-in command, or [`error make`](/commands/docs/error_make.md).
+- The external command's own exit code when an external failed. A script that stops at an external that exited with `42` exits with `42`.
+- `256 - N` when an external was killed by signal `N`. This only happens on Unix-like systems. Inside Nushell, [`complete`](/commands/docs/complete.md) and the `exit_code` field of a `catch` error report the signal as `-N`, and the operating system keeps only the low 8 bits of that, so SIGTERM (15) becomes `241`. Bash reports `128 + N` (`143` for SIGTERM) in the same situation.
+
+```nu
+nu -c 'error make {msg: boom}' | complete | get exit_code
+# => 1
+nu -c 'nu -c "exit 42"' | complete | get exit_code
+# => 42
+sh -c 'kill -TERM $$' | complete | get exit_code
+# => -15
+nu -c 'sh -c "kill -TERM $$"' | complete | get exit_code
+# => 241
+```
+
+To set the status yourself, end the script with [`exit`](/commands/docs/exit.md).
+
## Using the [`complete`](/commands/docs/complete.md) command
The [`complete`](/commands/docs/complete.md) command allows you to run an external to completion, and gather the stdout, stderr, and exit code together in one record.
@@ -112,6 +133,29 @@ cat unknown.txt o> out.log e> err.log
cat unknown.txt o+e> log.log
```
+The `>` forms replace the file's contents. To add to the end of the file instead, use `>>`. It creates the file if it doesn't exist yet:
+
+```nu
+nu -c 'print one' o> out.log
+nu -c 'print two' o>> out.log
+open out.log
+# => one
+# => two
+```
+
+The combined forms can name the streams in either order, so `e+o>` and `err+out>` do the same as `o+e>`. This table lists every redirection operator, including the [pipe redirections](#pipe-redirections) described below:
+
+| Operators | Effect |
+| ------------------------------------------------- | ------------------------------------------------ |
+| `o>`, `out>` | Write stdout to a file, replacing its contents |
+| `o>>`, `out>>` | Append stdout to a file |
+| `e>`, `err>` | Write stderr to a file, replacing its contents |
+| `e>>`, `err>>` | Append stderr to a file |
+| `o+e>`, `out+err>`, `e+o>`, `err+out>` | Write both streams to one file |
+| `o+e>>`, `out+err>>`, `e+o>>`, `err+out>>` | Append both streams to one file |
+| `e>\|`, `err>\|` | Pipe stderr to the next command |
+| `o+e>\|`, `out+err>\|`, `e+o>\|`, `err+out>\|` | Pipe both streams to the next command |
+
Also, any expression can be used for the file path, as long as it is a string value:
```nu
use std
@@ -159,6 +203,23 @@ nu -c 'print output; print -e error' o+e>| str uppercase
# => ERROR
```
+There is no pipe redirection for stdout alone, since a plain `|` already does that job. `o>|` and `out>|` are parse errors:
+
+```nu
+nu -c 'print hello' o>| str uppercase
+# => Error: nu::parser::parse_mismatch
+# =>
+# => × Parse mismatch: expected `|`. Redirecting stdout to a pipe is the same as
+# => │ normal piping..
+# => ╭─[repl_entry #1:1:21]
+# => 1 │ nu -c 'print hello' o>| str uppercase
+# => · ─┬─
+# => · ╰── expected `|`. Redirecting stdout to a pipe is the same as normal piping.
+# => ╰────
+# => help: Check the syntax around this position — a typo, missing delimiter, or
+# => wrong separator is common.
+```
+
::: note
Because a failing external makes the whole pipeline fail (see [Exit Code](#exit-code)), the redirected output of a command that exits with an error can be lost. For example, `cat unknown.txt e>| str uppercase` prints nothing, because `cat` exits with code 1. Use [`complete`](#using-the-complete-command) when you need both the output and the exit code of a failing command.
:::
@@ -170,6 +231,47 @@ Unlike file redirections, pipe redirections do not apply to all commands inside
# => TWO
```
+## Where redirections are allowed
+
+A redirection belongs to the command in front of it. One with no command, such as `ls | o> out.txt`, is an error:
+
+```nu
+ls | o> out.txt
+# => Error: nu::parser::unexpected_redirection
+# =>
+# => × Unexpected redirection.
+# => ╭─[repl_entry #1:1:6]
+# => 1 │ ls | o> out.txt
+# => · ─┬
+# => · ╰── redirecting nothing
+# => ╰────
+```
+
+The keywords that define or load code can't be redirected: `def`, `extern`, `module`, `use`, `hide`, the `overlay` subcommands, `plugin use`, `source`, `source-env` and `run`, along with the `export` forms of these. `for` is in the same group. Each one fails with "Redirection can not be used with" followed by the keyword:
+
+```nu
+for i in 1..2 { ^echo $i } o> loop.txt
+# => Error: nu::parser::error
+# =>
+# => × Redirection can not be used with for.
+# => ╭─[repl_entry #1:1:28]
+# => 1 │ for i in 1..2 { ^echo $i } o> loop.txt
+# => · ─┬
+# => · ╰── not allowed here
+# => ╰────
+```
+
+Two other keywords reject a redirection with a different error. `type T = int o> t.txt` is "Extra tokens in code", and `alias l = ls o> x.txt` is "Can't create alias to expression".
+
+To redirect what a loop prints, run it inside [`do`](/commands/docs/do.md) and redirect the `do` call. A file redirection applies to every external command inside it:
+
+```nu
+do { for i in 1..2 { ^echo $i } } o> loop.txt
+open loop.txt
+# => 1
+# => 2
+```
+
## Discarding Output
The [`ignore`](/commands/docs/ignore.md) command discards the output of the previous command. By default, it consumes stdout and lets the stderr of an external command through to the screen. Use `--stderr` to consume stderr instead, or both flags to silence the command completely:
diff --git a/book/types_of_data.md b/book/types_of_data.md
index c56ef5489b4..49e3bded1f8 100644
--- a/book/types_of_data.md
+++ b/book/types_of_data.md
@@ -81,6 +81,7 @@ The `/` operator always returns a float, even when both operands are integers an
| **_Description:_** | Numbers with some fractional component |
| **_Annotation:_** | `float` |
| **_Literal Syntax:_** | A decimal numeric value including a decimal place. E.g., `1.5`, `2.0`, `-15.333` |
+| | `inf`, `-inf` and `NaN` (also `nan`) for infinity and "not a number" |
| **_See also:_** | [Language Reference - Float](/lang-guide/chapters/types/basic_types/float.md) |
Simple Example:
@@ -216,6 +217,7 @@ See the [Language Reference](/lang-guide/chapters/types/basic_types/filesize.htm
| **_Annotation:_** | `range` |
| **_Literal Syntax:_** | `..`. E.g., `1..10`. |
| | `....`. E.g., `2..4..20` |
+| | `..<` excludes the end value (`0..<5`), and `..=` is an explicit spelling of `..` (`0..=4`) |
| **_See also:_** | [Language Guide - Range](/lang-guide/chapters/types/basic_types/range.md) |
Simple example:
@@ -232,7 +234,7 @@ Simple example:
```
::: tip
-You can also easily create lists of characters with a form similar to ranges with the command [`seq char`](/commands/docs/seq_char.html) as well as with dates using the [`seq date`](/commands/docs/seq_date.html) command.
+The values of a range must be numbers, so `("a")..("z")` is an error. To make a list of characters, use the [`seq char`](/commands/docs/seq_char.html) command, and for dates use [`seq date`](/commands/docs/seq_date.html).
:::
### Cell Paths
diff --git a/book/working_with_strings.md b/book/working_with_strings.md
index df9724e6b0b..9d0e6350cb6 100644
--- a/book/working_with_strings.md
+++ b/book/working_with_strings.md
@@ -30,7 +30,7 @@ end'
Single-quoted strings don't do anything to the text they're given, making them ideal for holding a wide range of text data.
-There is no escape for `'` inside a single-quoted string. Inner single quotes work only in pairs, and only when the word ends with `'`. Nushell keeps them as written, so `''` is not read as one quote the way it is in SQL:
+There is no escape for `'` inside a single-quoted string. Inner single quotes work only in pairs, and only when the word ends with `'` (see [Quotes inside a quoted word](#quotes-inside-a-quoted-word)). Nushell keeps them as written, so `''` is not read as one quote the way it is in SQL:
```nu
'it''s'
@@ -94,6 +94,35 @@ r###'r##'This is an example of a raw string.'##'###
# => r##'This is an example of a raw string.'##
```
+## Quotes inside a quoted word
+
+Nushell splits a line into words at whitespace outside of quotes. When a word starts with `'` or `"`, the string runs from that quote to the last quote of the same kind in the word, and any quotes of that kind in between are part of the string. That's why `'it''s'` keeps both quotes, and why inner double quotes can go unescaped as long as the word has no spaces outside them:
+
+```nu
+"[{a: "b"}]"
+# => [{a: "b"}]
+```
+
+Text after the last quote is an error:
+
+```nu
+'a'b
+# => Error: nu::parser::extra_token_after_closing_delimiter
+# =>
+# => × Invalid characters after closing delimiter
+# => ╭─[repl_entry #1:1:4]
+# => 1 │ 'a'b
+# => · ┬
+# => · ╰── invalid characters
+# => ╰────
+# => help: Remove these characters, or check that a delimiter closed too early
+# => above.
+```
+
+A space outside the inner quotes ends the word, so `"a "b c" d"` fails the same way at the `b`, and so does JSON with a space in a value, such as `"{"k": "a b"}"`. Escape the inner quotes instead (`"a \"b c\" d"`), or use the other kind of quote or a raw string: `'{"k": "a b"}'` works.
+
+The rule also catches words that look like operators. `'a'..'z'` is not a range of letters. It is the single string `a'..'z`.
+
## Bare Word Strings
Like other shell languages (but unlike most other programming languages) strings consisting of a single 'word' can also be written without any quotes:
@@ -253,6 +282,32 @@ $"2 + 2 is (2 + 2) \(you guessed it!)"
# => 2 + 2 is 4 (you guessed it!)
```
+The code inside `( )` is ordinary Nushell code, not part of the surrounding string. Quotes inside it don't end the interpolated string, and you write them without escapes, the same way you would outside a string. That includes another interpolated string:
+
+```nu
+$"(["x" "y"] | str join ", ")"
+# => x, y
+$"a ($"b (1 + 1)")"
+# => a b 2
+```
+
+A `)` inside a quoted string within the parentheses doesn't close them either: `$"a (")") c"` is `a ) c`. Escaping a quote inside the parentheses is an error, because `\"` isn't valid Nushell code outside a string:
+
+```nu
+$"a (\"b\") c"
+# => Error: nu::parser::unclosed_delimiter
+# =>
+# => × Unclosed delimiter.
+# => ╭─[repl_entry #1:1:14]
+# => 1 │ $"a (\"b\") c"
+# => · ┬ ┬
+# => · │ ╰── expected `)` here
+# => · ╰── unclosed — opens here (need `)`)
+# => ╰────
+# => help: Add a matching `)` to close this delimiter, or check that an earlier
+# => closer closed the wrong block.
+```
+
Interpolated strings can be evaluated at parse time, but if they include values whose formatting depends
on your configuration and your `config.nu` hasn't been loaded yet, they will use the default configuration.
So if you have something like this in your `config.nu`, `x` will be `"2.0 kB"` even if your config says to use
@@ -262,6 +317,26 @@ So if you have something like this in your `config.nu`, `x` will be `"2.0 kB"` e
const x = $"(2kb)"
```
+### Interpolation in bare words
+
+A [bare word](#bare-word-strings) that contains `(` is interpolated without the `$"..."`. This is handy for file names and other arguments built from a variable:
+
+```nu
+let n = 3
+echo file($n).txt
+# => file3.txt
+[v($n) ($n)-beta] | to nuon
+# => ["v3", "3-beta"]
+```
+
+It follows the rules for bare words:
+
+- It works where Nushell expects a value, such as a command argument, a list item or a record value. At the start of a pipeline or after `let x =`, a word like `v($n)` is a command name, so Nushell tries to run an external command called `v3`. A word that starts with `(`, like `($n)-beta`, works in both places.
+- There are no escapes. As in single-quoted interpolation, `v\($n)` is `v\3`.
+- It can't be attached to a quoted string. `"v"($n)` is the "Invalid characters after closing delimiter" error from [above](#quotes-inside-a-quoted-word).
+- The variable needs parentheses. Nushell reads all of `$n-beta` as one variable name and rejects it with "expected valid variable name".
+- In a command argument that takes a glob, such as for `ls` or `rm`, the result is a glob pattern: `ls ($n)*.txt` lists the files whose names start with `3` and end in `.txt`. See [Converting Strings to Globs](moving_around.md#converting-strings-to-globs).
+
## Splitting Strings
The [`split row`](/commands/docs/split_row.md) command creates a list from a string based on a delimiter.
diff --git a/lang-guide/chapters/operators.md b/lang-guide/chapters/operators.md
index 29c2a6658f3..1f77c49e7e7 100644
--- a/lang-guide/chapters/operators.md
+++ b/lang-guide/chapters/operators.md
@@ -12,6 +12,7 @@ For a full list with precedence values, run `help operators`. See also [Operator
- `mod` - Modulo (floor semantics: the result has the sign of the divisor)
- `**` - Pow
- `++` - Concatenates two lists, two strings, or two binary values
+- `-` directly before a variable or a parenthesized expression (`-$x`, `-(1 + $x)`) - Negation of a number, duration or file size. There is no space after the `-`, and negation binds more tightly than `**`. See [Negation](/book/operators.md#negation) in the Book.
```nu
10 / 4
diff --git a/lang-guide/chapters/strings_and_text.md b/lang-guide/chapters/strings_and_text.md
index a8e11180619..335b3246623 100644
--- a/lang-guide/chapters/strings_and_text.md
+++ b/lang-guide/chapters/strings_and_text.md
@@ -155,3 +155,15 @@ The key to always remember is that double quotes recognize and interpret escapes
It doesn't work because it sees `\P` and `\s` as escapes that are not recognized. Use single quotes or a raw string instead: `'C:\Program Files\somedir'` or `r#'C:\Program Files\somedir'#`.
## Bare word
+
+A bare word is a string written without quotes, such as `hello` or `./my-file.txt`. See [Bare Word Strings](/book/working_with_strings.md#bare-word-strings) in the Book for where Nushell reads one as a string and where it reads it as a command name.
+
+A bare word that contains `(` is an interpolated string. Each `( )` part is evaluated and joined with the text around it. Backslashes are kept as written, as in `$'...'`:
+
+```nu
+let n = 3
+echo file($n).txt
+# => file3.txt
+```
+
+In command position the word is still a command name, so `v($n)` on its own runs an external command named `v3`. A word that starts with a quote is not bare, and `"v"($n)` is a parse error. See [Interpolation in bare words](/book/working_with_strings.md#interpolation-in-bare-words) for the details.
diff --git a/lang-guide/chapters/types/basic_types/cellpath.md b/lang-guide/chapters/types/basic_types/cellpath.md
index 55d6933c546..0672ce35a6d 100644
--- a/lang-guide/chapters/types/basic_types/cellpath.md
+++ b/lang-guide/chapters/types/basic_types/cellpath.md
@@ -63,6 +63,33 @@ let data = [
# => 1
```
+ One member can have both modifiers, in either order. `?!` and `!?` mean the same thing, and Nushell displays the combination as `!?`. Repeating a modifier is a parse error: `{a: 1}.a??` fails with "expected . or !", and `.a!!` with "expected . or ?".
+
+ ```nu
+ {Name: 1}.name?!
+ # => 1
+ {Name: 1}.age!? | describe
+ # => nothing
+ ```
+
+- Negative indexes:
+
+ A row index counts from the start, and there is no negative form for counting from the end. `$list.-1` is a parse error:
+
+ ```nu
+ [1 2 3].-1
+ # => Error: nu::parser::error
+ # =>
+ # => × Invalid literal
+ # => ╭─[repl_entry #1:1:9]
+ # => 1 │ [1 2 3].-1
+ # => · ─┬
+ # => · ╰── negative index is not supported in cell path
+ # => ╰────
+ ```
+
+ A negative int passed to `get` fails at runtime with "can't convert negative number to cell path". Use [`last`](/commands/docs/last.md) to get items from the end of a list.
+
## Additional Language Notes
1. Ordering
diff --git a/lang-guide/chapters/types/basic_types/float.md b/lang-guide/chapters/types/basic_types/float.md
index ab5e3f6f906..ffedf9396e4 100644
--- a/lang-guide/chapters/types/basic_types/float.md
+++ b/lang-guide/chapters/types/basic_types/float.md
@@ -28,4 +28,31 @@
- `into int` truncates the fractional part. Use `math round`, `math floor` or `math ceil` to round instead.
-
+## Infinity and NaN
+
+The words `inf` and `NaN` are float literals for infinity and "not a number". Write `-inf` for negative infinity. `nan` is accepted as another spelling of `NaN`, and Nushell prints it as `NaN`. No other spelling is a float. `Nan`, `Inf` and `infinity` are bare-word strings:
+
+```nu
+[inf -inf nan NaN Nan Inf infinity] | to nuon
+# => [inf, -inf, NaN, NaN, "Nan", "Inf", "infinity"]
+```
+
+[`into float`](/commands/docs/into_float.md) is more lenient with text. `'infinity' | into float` returns `inf`.
+
+These values also come out of float arithmetic. A literal too large for a float becomes `inf` (`1e400` is `inf`), and `inf - inf` is `NaN`. Division by zero is an error, even for floats, so `1.0 / 0` and `0.0 / 0.0` fail with `nu::shell::division_by_zero` instead of returning `inf` or `NaN`.
+
+Comparisons follow IEEE-754. `inf == inf` is `true`, and `NaN` is not equal to anything, itself included:
+
+```nu
+NaN == NaN
+# => false
+NaN in [NaN]
+# => false
+```
+
+Other places where they behave differently from ordinary floats:
+
+- [`sort`](/commands/docs/sort.md) puts `NaN` after every other number: `[3 NaN 1 inf -inf] | sort` is `[-inf, 1, 3, inf, NaN]`.
+- [`to nuon`](/commands/docs/to_nuon.md) writes `inf`, `-inf` and `NaN`, which `from nuon` reads back as floats. JSON has no such values, so [`to json`](/commands/docs/to_json.md) writes each of them as `null`.
+- Converting to an int doesn't fail. `inf | into int` is the largest int, `9223372036854775807`, and `NaN | into int` is `0`. `math floor` and `math ceil` do the same, while `math round` rejects them with "cannot round non-finite number".
+- A range can't start at `inf`, `-inf` or `NaN`. See [Range](range.md#range-errors).
diff --git a/lang-guide/chapters/types/basic_types/glob.md b/lang-guide/chapters/types/basic_types/glob.md
index eb95a90d145..19ed61b860c 100644
--- a/lang-guide/chapters/types/basic_types/glob.md
+++ b/lang-guide/chapters/types/basic_types/glob.md
@@ -29,6 +29,17 @@
open '*.txt' # it's quoted, opens a file named `*.txt`
```
+ - It will interpret an interpolated string as a glob when the string has at least one `( )` part. This holds for `$"..."`, `$'...'` and [bare-word interpolation](/book/working_with_strings.md#interpolation-in-bare-words). An interpolated string with nothing to interpolate is a plain string:
+
+ ```nu
+ let prefix = "a"
+ ls $"($prefix)*.txt" # lists the files that start with `a` and end in `.txt`
+ ls ($prefix)*.txt # the same
+ ls $"a*.txt" # no `( )`, so it looks for a file named `a*.txt`
+ ```
+
+ The glob comes from writing the interpolation as the argument. If you store it in a variable first, the variable holds a string, so use `into glob` or a `glob` annotation.
+
1. There is no literal syntax for a glob. As seen above, it is usually created as a string and then interpreted by the calling command as a glob.
Example
@@ -74,6 +85,8 @@
^cat *.txt | lines
```
+ For an interpolated argument, only a bare word that doesn't start with `(` is expanded. `^echo *($prefix)*` passes the matching file names, while `^echo $"*($prefix)*"` and `^echo ($prefix)*` pass the text as written.
+
1. As with most other types, globs can be saved in a variable, passed to custom commands and returned from custom commands.
1. You can use `into glob` and `into string` to convert values between `glob` and `string`.
diff --git a/lang-guide/chapters/types/basic_types/list.md b/lang-guide/chapters/types/basic_types/list.md
index d42b30aa969..bf7787c921c 100644
--- a/lang-guide/chapters/types/basic_types/list.md
+++ b/lang-guide/chapters/types/basic_types/list.md
@@ -51,6 +51,45 @@ List syntax is very similar to that of arrays in JSON. However, commas are _not_
# => ╰───┴─────╯
```
+Extra commas are ignored, so a trailing comma (`[1, 2,]`) or a doubled one (`[1,,2]`) still gives `[1, 2]`. A semicolon is not a separator:
+
+```nu
+[1; 2]
+# => Error: nu::parser::error
+# =>
+# => × Unexpected semicolon in list
+# => ╭─[repl_entry #1:1:3]
+# => 1 │ [1; 2]
+# => · ┬
+# => · ╰── not a valid list separator
+# => ╰────
+# => help: Use commas or whitespace to separate list items.
+```
+
+### Expressions in a list literal
+
+Because whitespace separates the items, a list literal doesn't evaluate operators or pipelines. Each word is its own item, so `[1 + 1]` is a list of three values:
+
+```nu
+[1 + 1]
+# => ╭───┬───╮
+# => │ 0 │ 1 │
+# => │ 1 │ + │
+# => │ 2 │ 1 │
+# => ╰───┴───╯
+```
+
+Put an expression in parentheses to make it one item:
+
+```nu
+[(1 + 1)]
+# => ╭───┬───╮
+# => │ 0 │ 2 │
+# => ╰───┴───╯
+```
+
+Variables and cell paths (`$x`, `$row.name`) work without parentheses. The same rule applies to [record literals](record.md#expressions-in-a-record-literal).
+
## Additional Language Notes
1. A list is like a vector or array list in other languages.
diff --git a/lang-guide/chapters/types/basic_types/range.md b/lang-guide/chapters/types/basic_types/range.md
index 6801ebdfbb5..02da5f89f30 100644
--- a/lang-guide/chapters/types/basic_types/range.md
+++ b/lang-guide/chapters/types/basic_types/range.md
@@ -27,6 +27,15 @@
# => ╰───┴───╯
```
+ `..=` spells the inclusive form out, as Rust does. `1..=5` is the same range as `1..5`. The `=` goes only on the last `..`, so `1..3..=9` and `..=3` are ranges, but `1..=3..9` is not. Nushell reads that word as the name of an external command.
+
+ ```nu
+ (1..=5) == (1..5)
+ # => true
+ 1..3..=9 | each {} | to nuon
+ # => [1, 3, 5, 7, 9]
+ ```
+
1. In many programming languages, the _step_ (or interval) is specified. Nushell's range is inspired by more functional languages, where the second value is literally the second value that should be generated. The step is then automatically calculated as the distance between the first and second values.
Example - Values from 1 to 10, striding with 2 (only odds):
@@ -73,6 +82,30 @@
Note: Parentheses (subexpressions) are not required in this example; they are simply used for readability.
+ If any of the values is a float, the whole range is a float range. `1..2.5` starts at `1.0`:
+
+ ```nu
+ 1..2.5 | each {} | to nuon
+ # => [1.0, 2.0]
+ ```
+
+1. The start, second and end values must be numbers. A range of strings or dates is a parse error:
+
+ ```nu
+ ("a")..("z")
+ # => Error: nu::parser::operator_unsupported_type
+ # =>
+ # => × The '..' operator does not work on values of type 'string'.
+ # => ╭─[repl_entry #1:1:1]
+ # => 1 │ ("a")..("z")
+ # => · ──┬───┬
+ # => · │ ╰── does not support 'string'
+ # => · ╰── string
+ # => ╰────
+ ```
+
+ Without the parentheses, `'a'..'z'` isn't a range at all. A quoted word runs to its last quote, so it is the single string `a'..'z` (see [Quotes inside a quoted word](/book/working_with_strings.md#quotes-inside-a-quoted-word)). For a sequence of letters, use [`seq char`](/commands/docs/seq_char.md), and for dates use [`seq date`](/commands/docs/seq_date.md).
+
1. When no second value is given, the step is `1` (or `-1` when counting down). The exception is a float range whose start and end are less than `1` apart. Its step is based on the order of magnitude of the difference:
```nu
@@ -134,3 +167,26 @@
```
A range stays a `range` when it is assigned to a variable or passed through `collect`. Most filter commands, such as `each`, `take` and `append`, produce a list from it.
+
+## Range errors
+
+Some ranges parse but can't produce any values. Nushell reports them when the range is evaluated, not when it is parsed, so a bad range inside an `if` branch that never runs causes no error. Each one fails with the same error, which underlines either the value at fault or the whole range:
+
+```nu
+1..1..5
+# => Error: nu::shell::range_to_countable
+# =>
+# => × Can't convert range to countable values
+# => ╭─[repl_entry #1:1:4]
+# => 1 │ 1..1..5
+# => · ┬
+# => · ╰── can't convert to countable values
+# => ╰────
+```
+
+These ranges fail:
+
+- The second value equals the start, as in `1..1..5`. The step would be zero.
+- The second value is on the other side of the start from the end, as in `1..2..-5` or `5..1..10`. Counting would never reach the end.
+- A float range has equal start and end and no second value, as in `1.0..1.0` or `1..1.0`. An int range with equal bounds is fine: `1..1` yields `[1]`.
+- A float range starts at `inf`, `-inf` or `NaN` (`inf..5`), has a second value that isn't finite (`1..inf..5`), or ends at `NaN` (`1..2..NaN`). An end of `inf` is allowed and makes an endless range, like `1..`.
diff --git a/lang-guide/chapters/types/basic_types/record.md b/lang-guide/chapters/types/basic_types/record.md
index fe18d13540a..6e93ba22d7f 100644
--- a/lang-guide/chapters/types/basic_types/record.md
+++ b/lang-guide/chapters/types/basic_types/record.md
@@ -62,6 +62,47 @@ Record syntax is very similar to objects in JSON. However, commas are _not_ requ
# => ╰──────┴─────╯
```
+As in lists, extra commas are ignored: `{a: 1,, b: 2,}` is `{a: 1, b: 2}`.
+
+## Expressions in a record literal
+
+A field's value is a single word, just like a [list item](list.md#expressions-in-a-list-literal). In `{a: 1 + 1}`, the value of `a` is `1`, and Nushell then reads `+` as the next key:
+
+```nu
+{a: 1 + 1}
+# => Error: nu::parser::error
+# =>
+# => × Expected `:` after record key
+# => ╭─[repl_entry #1:1:9]
+# => 1 │ {a: 1 + 1}
+# => · ┬
+# => · ╰── expected `:`, found `1`
+# => ╰────
+# => help: Record fields look like `key: value`. A missing colon often causes
+# => this field to be parsed as a block or closure.
+```
+
+Wrap the expression in parentheses:
+
+```nu
+{a: (1 + 1)}
+# => ╭───┬───╮
+# => │ a │ 2 │
+# => ╰───┴───╯
+```
+
+## No field shorthand
+
+JavaScript lets you write `{a}` for `{a: a}`. Nushell has no such shorthand, and every field needs a key and a colon. Braces holding only a variable, such as `{$a}`, are a closure that returns `$a`:
+
+```nu
+let a = 1
+{$a} | describe
+# => closure
+```
+
+When the braces also hold a real field, the missing colon is an error. `{a: 1, b}` and `{a: 1, $b}` both fail with "Incomplete record field". Write the key out instead: `{a: $a, b: $b}`.
+
## Common commands that can be used with `record`
Since the record data type is foundational to Nushell's structured nature, many commands use records as inputs or as parameters. See the list of commands for tables as many of those also take records.
diff --git a/lang-guide/chapters/types/type_signatures.md b/lang-guide/chapters/types/type_signatures.md
index 1162a39e98f..e8008d00c84 100644
--- a/lang-guide/chapters/types/type_signatures.md
+++ b/lang-guide/chapters/types/type_signatures.md
@@ -65,6 +65,59 @@ There are 3 forms of valid type signatures in Nu:
Any of these can be given a name with a [type alias](#type-aliases).
+## Which values a type accepts
+
+An annotation accepts values of its own type and of its subtypes. These are the subtype rules:
+
+- `any` accepts every value.
+- `number` accepts `int` and `float` values.
+- `glob` accepts a `string`, but `string` doesn't accept a `glob`. Convert it with `into string` first.
+- `cell-path` accepts a `string` or an `int`, which is why `get $key` works with a plain string or int variable.
+- `list` accepts any list whose item type `T` accepts, so a `list` can be passed where a `list` is expected. A plain `list` accepts every list.
+- `record` accepts any record with a field `a` that `T` accepts. The record may have other fields too. A plain `record` accepts every record.
+- `table` follows the same rule for columns. A table is also accepted as a `list>` with the same columns, and the other way around.
+- `oneof` accepts whatever `A` or `B` accepts.
+
+For example, a command that needs a `name` field takes any record that has one:
+
+```nu
+def name-of [r: record] { $r.name }
+name-of {name: "nu", stars: 30}
+# => nu
+```
+
+A record without that field is rejected when the call is parsed:
+
+```nu
+def name-of [r: record] { $r.name }; name-of {title: "nu"}
+# => Error: nu::parser::type_mismatch
+# =>
+# => × Type mismatch.
+# => ╭─[repl_entry #1:1:60]
+# => 1 │ def name-of [r: record] { $r.name }; name-of {title: "nu"}
+# => · ──────┬──────
+# => · ╰── expected record, found record
+# => ╰────
+```
+
+The parser can only reject a value whose type it knows can't fit. When the known type is wider than the annotation, as with a variable declared `any` or `number`, the parser lets it through and the value itself is checked when the command runs. A `number` that holds `2` can be passed to an `int` parameter, but one that holds `1.5` fails:
+
+```nu
+def double [x: int] { $x * 2 }; let y: number = 1.5; double $y
+# => Error: nu::shell::cant_convert
+# =>
+# => × Can't convert to int.
+# => ╭─[repl_entry #1:1:61]
+# => 1 │ def double [x: int] { $x * 2 }; let y: number = 1.5; double $y
+# => · ─┬
+# => · ╰── can't convert float to int
+# => ╰────
+```
+
+`glob` to `string` is different. A `glob` is never a `string`, so passing a `glob` variable to a `string` parameter is a parse error ("expected string, found glob").
+
+Custom values, such as a `semver` from `into semver` or a value from a plugin, also pass the parser when the parameter is a `list`, `record` or `table`, and are checked when the command runs. A `semver` doesn't fit any of these, so `def f [r: record] { $r }; f ('1.2.3' | into semver)` fails at runtime with "can't convert semver to record".
+
## Type aliases
`type Name = ` gives a type signature a name. The name can then be used wherever a type signature can: parameters, flags, rest parameters, closure parameters, input/output types, `let`/`mut`/`const` annotations, inside other types, and on the right-hand side of another `type`:
From d6cf32c08555cf43768f0765a7f76a04592dc735 Mon Sep 17 00:00:00 2001
From: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Date: Sat, 14 Nov 2026 16:31:47 -0600
Subject: [PATCH 03/46] Document environment and startup features that had no
docs
Covers the rows rated `none` in the coverage checklist for environment
variables, the nu executable, and startup:
- special_variables: COLUMNS/LINES, proxy variables and NO_PROXY,
LC_ALL/LC_TIME/LANG, NU_BACKTRACE, NU_EXPERIMENTAL_OPTIONS,
NU_VENDOR_AUTOLOAD_DIR, NUSHELL_SHELLS and friends, PATHEXT, PWD,
SSH_CLIENT, TERM_PROGRAM, XDG_CACHE_HOME
- environment: the automatic PWD, FILE_PWD, and CURRENT_FILE variables
and the error when you try to set or hide them
- configuration: $env.config validation errors, flag syntax for nu,
starting the REPL without a terminal, errors and broken symlinks in
startup files, and experimental options
Windows-only PATHEXT behavior and the build-time vendor autoload
setting were written from the 0.117.0 source; the rest was run.
---
book/configuration.md | 195 ++++++++++++++++++++++++++++++++++++++
book/environment.md | 28 +++++-
book/special_variables.md | 132 +++++++++++++++++++++++++-
3 files changed, 351 insertions(+), 4 deletions(-)
diff --git a/book/configuration.md b/book/configuration.md
index 794caef496b..048b6a268b9 100644
--- a/book/configuration.md
+++ b/book/configuration.md
@@ -363,6 +363,70 @@ $env.config.history = {
The history settings `file_format`, `max_size`, `isolation`, and `path` are read once, when the REPL starts. Set them in `config.nu`; changing them afterwards (for example, at the prompt) raises a `nu::shell::config_option_locked_after_startup` error.
:::
+#### Errors in settings
+
+Nushell checks every value you assign to `$env.config`. When something is wrong, the assignment raises a `nu::shell::invalid_config` error that lists each problem with its own code:
+
+- `nu::shell::unknown_config_option` for a key Nushell doesn't know, often a typo.
+- `nu::shell::invalid_value` for a value outside the accepted set. The label lists the values it accepts.
+- `nu::shell::type_mismatch` for a value of the wrong type.
+- `nu::shell::missing_required_column` for a record without a key it needs, such as `table.trim` without `methodology`.
+
+Other errors can appear in the list too. For example, a keybinding without an `event` gives `nu::shell::column_not_found`. The history lock error above is reported the same way.
+
+A setting with an error keeps its old value, and the other settings in the same assignment still change:
+
+```nu
+$env.config.completions = { case_sensitive: true, algorithm: "fast", partal: false }
+# => Error: nu::shell::invalid_config
+# =>
+# => × Encountered 2 error(s) when updating config
+# =>
+# => Error: nu::shell::invalid_value
+# =>
+# => × Invalid value for $env.config.completions.algorithm
+# => ╭─[repl_entry #1:1:62]
+# => 1 │ $env.config.completions = { case_sensitive: true, algorithm: "fast", partal: false }
+# => · ───┬──
+# => · ╰── expected 'prefix' or 'fuzzy' or 'substring', but got 'fast'
+# => ╰────
+# =>
+# => Error: nu::shell::unknown_config_option
+# =>
+# => × Unknown config option: $env.config.completions.partal
+# => ╭─[repl_entry #1:1:78]
+# => 1 │ $env.config.completions = { case_sensitive: true, algorithm: "fast", partal: false }
+# => · ──┬──
+# => · ╰── remove this
+# => ╰────
+$env.config.completions.case_sensitive
+# => true
+```
+
+The error stops the rest of the script, or the rest of `config.nu`, like any other error, unless you catch it with [`try`](/commands/docs/try.md). See [Problems with startup files](#problems-with-startup-files) for how startup continues after an error in `config.nu`.
+
+A common mistake is leaving out the colons in a record. `{ mode light }` is a closure, not a record, and the error says so:
+
+```nu
+$env.config.table = { mode light }
+# => Error: nu::shell::invalid_config
+# =>
+# => × Encountered 1 error(s) when updating config
+# =>
+# => Error: nu::shell::type_mismatch
+# =>
+# => × Type mismatch at $env.config.table
+# => ╭─[repl_entry #1:1:21]
+# => 1 │ $env.config.table = { mode light }
+# => · ───────┬──────
+# => · ╰── expected record, but got closure
+# => ╰────
+# => help: If you meant a record, use `key: value` fields (colon required). A
+# => missing `:` makes `{ … }` parse as a closure/block.
+```
+
+A few combinations only produce a warning (`nu::shell::incompatible_options`), and the value is still set. For example, setting `history.isolation = true` in `config.nu` while history uses the plain-text format warns that isolation needs SQLite history.
+
### Remove Welcome Message
:::note
@@ -433,6 +497,12 @@ The variables that affect Nushell file locations are:
- `$env.XDG_DATA_DIRS` _(Unix Platforms Only)_: If this environment variable is set, it is used to populate the `$nu.vendor-autoload-dirs` directories. Following the XDG convention that earlier entries take precedence, the directories are processed in _reverse_ order: the first directory in `XDG_DATA_DIRS` is read last, giving it the ability to override definitions from the others.
+- `$env.XDG_CACHE_HOME`: If this environment variable is set to an absolute path, Nushell sets the `$nu.cache-dir` constant to `($env.XDG_CACHE_HOME)/nushell`. Otherwise `$nu.cache-dir` is the `nushell` directory under the platform's cache directory, such as `~/Library/Caches/nushell` on macOS, `~/.cache/nushell` on Linux, or `%LOCALAPPDATA%\nushell` on Windows. A relative or empty value is ignored. Nushell doesn't store anything in this directory or create it. It is a standard place for your scripts and plugins to keep data they can rebuild.
+
+- `$env.NU_VENDOR_AUTOLOAD_DIR`: If this environment variable is set to an absolute path, Nushell adds that directory to the end of `$nu.vendor-autoload-dirs`, after the `$nu.data-dir` one, so its files load last among the vendor files and can override the others. Unlike the other entries, the path is used as given, without `nushell/vendor/autoload` appended. A relative path is ignored, and a directory already in the list isn't added twice.
+
+ Packagers can also set `NU_VENDOR_AUTOLOAD_DIR` when they build Nushell. The value is compiled into `nu` and placed just before the `$nu.data-dir` entry. The build-time and runtime values can be used together.
+
::: warning
The `XDG_*` variables are **not** Nushell-specific and should not be set to a directory with only Nushell files. Instead, set the environment variable to the directory _above_ the one with the `nushell` directory.
@@ -755,3 +825,128 @@ The following stages and their steps _may_ occur during startup, based on the fl
- ❌ Does not enter the REPL
- ❌ Does not source the files in `vendor-autoload-dirs`
- ❌ Does not source the files in `user-autoload-dirs`
+
+### Passing flags to `nu`
+
+`nu` reads its flags in the usual Unix styles:
+
+- A long flag takes its value after a space or after `=`, as in `--table-mode light` or `--table-mode=light`.
+- A short flag works the same way, as in `-m light` or `-m=light`. Writing the value right after the letter, as in `-mlight`, is an error.
+- Short flags can share one `-`, so `-nl` means `-n -l`. Only the last letter of such a group can be a flag that takes a value. `nu -nc 'ls'` works, and `nu -cn 'ls'` is an error:
+
+ ```nu
+ nu -cn 'ls'
+ # => Error: nu::shell::error
+ # =>
+ # => × `-c` expects a value
+ # => help: Move `-c` to the end, then pass a value like `-c ` or
+ # => `-c=`.
+ ```
+
+- A value after `=` on a flag that doesn't take one, as in `-n=1`, is an error, and so is an empty value, as in `-c=`. A `-` on its own is an error too.
+
+When a flag is unknown, `nu` suggests a flag with a similar name if it finds one:
+
+```nu
+nu --no-config
+# => Error: nu::shell::error
+# =>
+# => × Unknown flag '--no-config'
+# => help: Did you mean '--no-config-file'?
+```
+
+Flags that accept a fixed set of values, such as `--table-mode`, `--error-style`, `--log-level`, and `--experimental-options`, check the value the same way. A misspelled value gets a suggestion, so `--table-mode rouned` suggests `rounded`, and a value that is not close to any valid one gets the list of valid values. Any of these errors stops `nu` with exit status 1 before it runs anything.
+
+### Starting the REPL without a terminal
+
+The REPL needs a terminal to read from. When `nu` would start the REPL, because neither `-c` nor a script file was given, and its standard input isn't a terminal, it prints an error and exits with status 1:
+
+```nu
+"ls" | nu
+# => Error: × Nushell launched as a REPL, but STDIN is not a TTY; either launch in a
+# => │ valid terminal or provide arguments to invoke a script!
+```
+
+The same happens when a program starts Nushell as a login shell with no command and no terminal. The check comes right before the line editor starts, after `env.nu`, `config.nu`, the autoload files, and any `--execute` commands have run, so their output appears before the error. `--stdin` doesn't change this. To run Nushell code from another program, pass it with `-c` or in a script file, and add `--stdin` if that code should read the piped input as `$in`.
+
+### Problems with startup files
+
+In the REPL, an error in `env.nu`, `config.nu`, `login.nu`, or an autoload file is printed, and startup goes on with the next file. A runtime error stops the rest of that file, but changes made before the error stay in effect. Commands that the file defines with `def` are available even when their definitions come after the error, because Nushell defines them when it parses the file. A parse error means none of the file runs.
+
+With `-c` or a script file, the configuration files Nushell loads are strict. If one fails, `nu` stops before running the command or script and exits with that file's exit status, which is 1 for a Nushell error or the external command's own status. This covers the files given with `--env-config` and `--config`, and the default `env.nu` and `config.nu` that `-l` loads together with `-c`. `login.nu` is the exception. When it fails under `nu -l -c`, Nushell prints the error and still runs the command.
+
+A path given with `--config` or `--env-config` that doesn't exist is an error:
+
+```nu
+nu --config missing.nu -c 'ls'
+# => Error: File not found: missing.nu (config.nu)
+# => help: Check the path passed to --config / --env-config, or create the file under your config directory.
+```
+
+With `-c` or a script file, `nu` then exits with status 1. The REPL prints the same error, with the full path, and starts without that file.
+
+If Nushell itself panics while it loads the startup files for the REPL, it prints `A panic occurred while reading configuration files, using default configuration.`, resets `$env.config` to the defaults, and starts the REPL.
+
+#### Broken symlinks
+
+If you keep your configuration in another place, such as a dotfiles repository, and link to it, a broken link doesn't stop Nushell from starting. When the configuration directory, `env.nu`, `config.nu`, or `login.nu` is a symbolic link whose target doesn't exist, Nushell skips that file, keeps the built-in defaults, and prints a warning in the form `Warning: config.nu is a broken symlink ( -> ); using built-in defaults.` For a broken configuration directory, the warning reads `config directory is a broken symlink`, and both `env.nu` and `config.nu` are skipped. Nushell never removes or replaces the link, and on first launch it doesn't create a configuration directory or default files in its place. A `--config` or `--env-config` path that is a broken link counts as a missing file and gets the `File not found` error above.
+
+### Experimental options
+
+Nushell ships some features as experimental options. An `opt-in` option is off until you turn it on, and an `opt-out` option is on until you turn it off. [`debug experimental-options`](/commands/docs/debug_experimental-options.md) lists them with their current state and a description:
+
+```nu
+debug experimental-options | select identifier enabled status
+# => ╭───┬─────────────────────────────┬─────────┬────────────────────╮
+# => │ # │ identifier │ enabled │ status │
+# => ├───┼─────────────────────────────┼─────────┼────────────────────┤
+# => │ 0 │ example │ false │ deprecated-discard │
+# => │ 1 │ dc-glob │ false │ opt-in │
+# => │ 2 │ reorder-cell-paths │ true │ opt-out │
+# => │ 3 │ pipefail │ true │ opt-out │
+# => │ 4 │ enforce-runtime-annotations │ true │ opt-out │
+# => │ 5 │ native-clip │ false │ opt-in │
+# => │ 6 │ cell-path-types │ false │ opt-in │
+# => ╰───┴─────────────────────────────┴─────────┴────────────────────╯
+```
+
+You can set them when Nushell starts, with the `--experimental-options` flag or the `NU_EXPERIMENTAL_OPTIONS` environment variable. Each entry is an option name, which turns the option on, or `name=true` or `name=false`. A bare `all` turns on every option that isn't deprecated. The variable also accepts `all=false`, which turns all of them off, but the flag accepts only a bare `all`. The variable holds a comma-separated list:
+
+```nu
+NU_EXPERIMENTAL_OPTIONS='native-clip,pipefail=false' nu
+```
+
+Nushell reads `NU_EXPERIMENTAL_OPTIONS` once, before any configuration file, so it has to be in the environment that starts `nu`. Setting it in `config.nu` has no effect on that session. When both are given, the flag is applied after the variable, so the flag wins for an option that both name.
+
+Problems in the variable are warnings, not errors. Nushell reports an unknown name or a value other than `true` or `false`, skips that entry, and starts anyway:
+
+```nu
+NU_EXPERIMENTAL_OPTIONS='native-clp,pipefail=nope' nu
+# => Warning: nu::experimental_option::unknown
+# =>
+# => ⚠ Unknown experimental option `native-clp`
+# => ╭────
+# => 1 │ NU_EXPERIMENTAL_OPTIONS=native-clp,pipefail=nope
+# => · ──────────
+# => ╰────
+# => help: Known experimental options are: example, dc-glob, reorder-cell-paths,
+# => pipefail, enforce-runtime-annotations, native-clip, cell-path-types
+# =>
+# => Warning: nu::experimental_option::invalid_assignment
+# =>
+# => ⚠ Invalid assignment for `pipefail`, expected `true` or `false`, got `nope`
+# => ╭────
+# => 1 │ NU_EXPERIMENTAL_OPTIONS=native-clp,pipefail=nope
+# => · ─────────────
+# => ╰────
+```
+
+Naming a deprecated option also prints a warning. For a `deprecated-discard` option, the warning says it will be removed. For a `deprecated-default` option, it says the behavior is now the default and that you can remove the option.
+
+The variable follows the same rule as your configuration files. Nushell ignores it, while still applying `--experimental-options`, in these cases:
+
+- with `-n` or `--no-config-file`
+- with `-c`, unless `-l`, `--config`, or `--env-config` is also given
+- with a script file, unless `--config` or `--env-config` is also given, since `-l` doesn't load configuration files for a script
+
+The REPL always reads it, unless `-n` is given.
diff --git a/book/environment.md b/book/environment.md
index 96aeafb84e7..b1130bb1271 100644
--- a/book/environment.md
+++ b/book/environment.md
@@ -158,7 +158,33 @@ See also: [Changing the Environment in a Custom Command](./custom_commands.html#
## Changing the Directory
-A common task in a shell is to change the directory using the [`cd`](/commands/docs/cd.md) command. In Nushell, calling [`cd`](/commands/docs/cd.md) is equivalent to setting the `PWD` environment variable. Therefore, it follows the same rules as other environment variables (for example, scoping).
+A common task in a shell is to change the directory using the [`cd`](/commands/docs/cd.md) command. In Nushell, [`cd`](/commands/docs/cd.md) works by changing the `PWD` environment variable. Therefore, it follows the same rules as other environment variables (for example, scoping). You can't assign `PWD` yourself, though. Use `cd` instead.
+
+## Automatic variables
+
+Nushell sets three environment variables itself:
+
+- `PWD` holds the current directory. [`cd`](/commands/docs/cd.md) changes it.
+- `FILE_PWD` holds the directory of the script, module, or sourced file that is running.
+- `CURRENT_FILE` holds the full path of that file.
+
+Nushell rejects every attempt to set or hide one of them, whether through `$env.PWD = ...`, [`load-env`](/commands/docs/load-env.md), [`with-env`](/commands/docs/with-env.md), a `PWD=... cmd` prefix, or [`hide-env`](/commands/docs/hide-env.md). The check ignores case, so `$env.pwd = ...` fails as well:
+
+```nu
+$env.PWD = '/tmp'
+# => Error: nu::compile::automatic_env_var_set_manually
+# =>
+# => × 'PWD' cannot be changed manually.
+# => ╭─[repl_entry #1:1:1]
+# => 1 │ $env.PWD = '/tmp'
+# => · ────┬───
+# => · ╰── cannot change 'PWD' manually
+# => ╰────
+# => help: The environment variable 'PWD' is set automatically by Nushell and
+# => cannot be changed manually.
+```
+
+An assignment like this one fails before anything runs, with a `nu::compile` error. The commands fail when they run, with `nu::shell::automatic_env_var_set_manually`. To get the file's path or directory as a constant at parse time, use [`path self`](/commands/docs/path_self.md).
## Single-use Environment Variables
diff --git a/book/special_variables.md b/book/special_variables.md
index 437c3a15639..c01f2c39195 100644
--- a/book/special_variables.md
+++ b/book/special_variables.md
@@ -64,6 +64,12 @@ There are also several environment variables that Nushell uses for specific purp
The amount of time in milliseconds that the previous command took to run.
+### `$env.COLUMNS` and `$env.LINES`
+
+On Unix, Nushell asks the terminal for its size. When there is no terminal at all, as in a cron job or a CI runner with no controlling terminal, it reads the width from `COLUMNS` and the height from `LINES` instead. Both must be set to whole numbers greater than zero, or Nushell falls back to 80 columns by 24 rows. The width decides where [`table`](/commands/docs/table.md), [`grid`](/commands/docs/grid.md), and `help` output wrap. The height decides when `$env.config.footer_mode = "auto"` shows a table footer. [`term size`](/commands/docs/term_size.md) reports both values.
+
+A terminal that is attached always wins, even when the output is redirected to a file or a pipe. Nushell reads `COLUMNS` and `LINES` from the environment it was started with, so set them before starting `nu`. Assigning `$env.COLUMNS` inside Nushell has no effect. Windows doesn't use these variables.
+
### `$env.config`
`$env.config` is the main configuration record used in Nushell. Settings are documented in `config nu --doc`.
@@ -72,6 +78,7 @@ The amount of time in milliseconds that the previous command took to run.
Inside a script, module, or sourced-file, this variable holds the fully-qualified filename. Note that this
information is also available as a constant through the [`path self`](/commands/docs/path_self.md) command.
+Nushell sets it, so it can't be assigned or hidden. See [Automatic variables](./environment.md#automatic-variables).
### `$env.ENV_CONVERSIONS`
@@ -86,6 +93,28 @@ the file resides. Note that this value is also available as a constant, using [`
const this_dir = path self | path dirname
```
+Like `CURRENT_FILE`, it can't be assigned or hidden.
+
+### `$env.HTTP_PROXY` and other proxy variables
+
+The [`http`](/commands/docs/http.md) commands send their requests through a proxy when `HTTP_PROXY`, `HTTPS_PROXY`, or `ALL_PROXY` is set. Nushell takes the first of the three that is set, in that order, and uses it for every request, whether the URL starts with `http://` or `https://`. So with both `HTTP_PROXY` and `HTTPS_PROXY` set, HTTPS requests also go through `HTTP_PROXY`. Like every name in `$env`, these ignore case, so `http_proxy` and `HTTP_PROXY` are the same variable.
+
+The value is the proxy's URL, such as `http://proxy.example.com:8080`. The scheme can be `http`, `https`, `socks4`, `socks4a`, `socks5`, `socks`, or `socks5h`, and a value without one is treated as `http`. A user name and password in the URL (`http://user:password@proxy.example.com:8080`) are sent to the proxy. If Nushell can't use the value as a proxy URL, for example `ftp://proxy.example.com`, it ignores it and connects directly.
+
+`NO_PROXY` lists hosts that skip the proxy, separated by commas. Each entry is one of:
+
+- an exact host name or IP address, such as `localhost` or `127.0.0.1`
+- a domain suffix starting with `.` or `*`, such as `.example.com` or `*.example.com`
+- a prefix ending with `.` or `*`, such as `10.0.` or `192.168.*`
+- `*`, which matches every host
+
+Entries match the host name only. An entry with a port, such as `localhost:8080`, never matches.
+
+Nushell reads these variables from `$env` each time an `http` command runs, so setting them in `config.nu`, at the prompt, or for a single command with [`with-env`](/commands/docs/with-env.md) works. Two cases behave differently:
+
+- Hiding an inherited proxy variable with `hide-env` doesn't turn the proxy off. With no proxy variable in `$env`, the HTTP library falls back to the environment Nushell was started with. To skip an inherited proxy, set `$env.NO_PROXY = "*"` and leave the proxy variable alone.
+- The shared client that `--pool` uses is created on the first `--pool` request and keeps that proxy for the rest of the session. It ignores `NO_PROXY` until you rebuild it with [`http pool`](/commands/docs/http_pool.md).
+
### `$env.LAST_EXIT_CODE`
The exit code of the last command, usually used for external commands — Equivalent to `$?` from POSIX. If several external commands in a pipeline fail, it holds the exit code of the rightmost one that failed (see [Pipelines - Failing External Commands in a Pipeline](./pipelines.md#failing-external-commands-in-a-pipeline)). Note that this information is also made available to the `catch` block in a `try` expression for external commands. For instance:
@@ -104,6 +133,69 @@ try {
# => 2
```
+### `$env.LC_ALL`, `$env.LC_TIME`, and `$env.LANG`
+
+These standard locale variables set the language and the local formats for dates. Nushell uses the first one that is set, in the order `LC_ALL`, `LC_TIME`, `LANG`, and drops an encoding suffix such as `.UTF-8`. When none is set, it uses the operating system's locale. A locale Nushell doesn't know falls back to `en_US`.
+
+[`format date`](/commands/docs/format_date.md) uses the locale for day and month names and for the `%x`, `%X`, `%c`, and `%r` formats. It reads the variables from `$env`, so `with-env` or an assignment changes the result. On a system with an `en_US` locale:
+
+```nu
+let d = 2026-03-01T14:30:00
+$d | format date "%A %d %B %Y, %X"
+# => Sunday 01 March 2026, 02:30:00 PM
+with-env { LC_TIME: de_DE.UTF-8 } { $d | format date "%A %d %B %Y, %X" }
+# => Sonntag 01 März 2026, 14:30:00
+```
+
+The `datetime_format` settings in `$env.config`, which control how Nushell displays dates, work differently. They read the locale from the environment Nushell was started with, so changing `$env.LC_TIME` inside Nushell doesn't change how dates are shown. Set the variable before starting `nu`:
+
+```nu
+LC_TIME=de_DE nu -n -c '$env.config.datetime_format.normal = "%A %d %B %Y"; 2026-03-01T14:30:00'
+# => Sonntag 01 März 2026
+```
+
+### `$env.NU_BACKTRACE`
+
+When `NU_BACKTRACE` is set, an error report also shows the calls that led to the error. Each custom command or closure call that the error passed through, including a closure run with [`do`](/commands/docs/do.md), adds a `chained_error` entry labeled "error happened when running this", starting with the outermost call. The original error comes last:
+
+```nu
+NU_BACKTRACE=1 nu -n -c 'def inner [] { error make {msg: boom} }; def outer [] { inner }; outer'
+# => Error: chained_error
+# =>
+# => × oops
+# => ╭─[source:1:66]
+# => 1 │ def inner [] { error make {msg: boom} }; def outer [] { inner }; outer
+# => · ──┬──
+# => · ╰── error happened when running this
+# => ╰────
+# =>
+# => Error: chained_error
+# =>
+# => × oops
+# => ╭─[source:1:57]
+# => 1 │ def inner [] { error make {msg: boom} }; def outer [] { inner }; outer
+# => · ──┬──
+# => · ╰── error happened when running this
+# => ╰────
+# =>
+# => Error:
+# => × boom
+# => ╭─[source:1:27]
+# => 1 │ def inner [] { error make {msg: boom} }; def outer [] { inner }; outer
+# => · ───────────
+# => ╰────
+```
+
+Without `NU_BACKTRACE`, the same command prints only the `boom` error. An error from a stream, such as one raised inside [`each`](/commands/docs/each.md), also gets a label at each call the stream passed through.
+
+Any value turns it on, including `0` and `false`. Nushell checks its global environment, which takes in your changes after each startup file and after each line you run at the prompt. So you can set `NU_BACKTRACE` before starting `nu`, in `config.nu`, or at the prompt, where it applies from the next line on. Setting it inside a script or a `nu -c` command doesn't affect that same script or command.
+
+The chain also changes what [`try`](/commands/docs/try.md) catches. With `NU_BACKTRACE` set, `$e.msg` in a `catch` closure is `oops`, the message of the outer entry, instead of the original message.
+
+### `$env.NU_EXPERIMENTAL_OPTIONS`
+
+A comma-separated list of experimental options to turn on or off when Nushell starts, such as `native-clip,pipefail=false`. Nushell reads it once, before any configuration file, so it has to be in the environment that starts `nu`. It is ignored with `-n`, and for `nu -c` and scripts unless they also load configuration files. See [Configuration - Experimental options](./configuration.md#experimental-options).
+
### `$env.NU_LIB_DIRS`
::: tip
@@ -155,22 +247,38 @@ A list of directories which will be searched when registering plugins with `plug
- [Plugin Search Path](./plugins.md#plugin-search-path)
+### `$env.NU_VENDOR_AUTOLOAD_DIR`
+
+Adds a directory to `$nu.vendor-autoload-dirs`. Packagers can also set it when building Nushell. See [Configuration - Startup Variables](./configuration.md#startup-variables).
+
### `$env.NU_VERSION`
The current Nushell version. The same as `(version).version`, but, as an environment variable, it is exported to and can be read by child processes.
+### `$env.NUSHELL_SHELLS`, `$env.NUSHELL_CURRENT_SHELL`, and `$env.NUSHELL_LAST_SHELL`
+
+Leftovers from the built-in `shells` and `enter` commands of older Nushell versions. Nothing in Nushell reads them, but they can show up in `$env`. When you change directories at the prompt by typing just a path (auto-cd), the REPL writes the new directory into the `NUSHELL_SHELLS` list, at the index in `NUSHELL_CURRENT_SHELL` (`0` when it isn't set), and sets `NUSHELL_LAST_SHELL`. [`cd`](/commands/docs/cd.md) doesn't touch them. To keep a list of directories and move between them, use the [`dirs` module](./directory_stack.md).
+
### `$env.PATH`
The search path for executing other applications. It is initially inherited from the parent process as a string, but converted to a Nushell `list` at startup for easy access.
It is converted back to a string before running a child-process.
+### `$env.PATHEXT`
+
+On Windows, `PATHEXT` lists the file extensions that count as programs, separated by `;`, such as `.COM;.EXE;.BAT;.CMD`. Nushell uses it in two places:
+
+- To run an external command, Nushell looks the name up with the `PATHEXT` it inherited when it started, so `foo` finds `foo.exe` or `foo.bat` on the path. Changing `$env.PATHEXT` inside Nushell doesn't affect this lookup. When the file it finds ends in an extension other than `.COM`, `.EXE`, `.BAT`, `.CMD`, or `.PS1`, Nushell runs it through `cmd.exe /D /C`, so a file association you made with `assoc` and `ftype` applies. For example, after you associate `.nu` files with `nu.exe` and add `.NU` to `PATHEXT` before starting Nushell, typing `myscript` runs `myscript.nu`. A `.PS1` file runs with `powershell.exe -File` instead.
+- [`which`](/commands/docs/which.md) reads `$env.PATHEXT`, so it follows changes you make inside Nushell, including with `with-env`. After `hide-env PATHEXT`, `which` doesn't fall back to the inherited value.
+
+Other platforms ignore `PATHEXT`.
+
### `$env.PROCESS_PATH`
-When _executing a script_, this variable represents the name and relative path of the script. Unlike the two variables
-above, it is not present when sourcing a file or importing a module.
+When _executing a script_, this variable represents the name and relative path of the script. Unlike `CURRENT_FILE` and `FILE_PWD`, it is not present when sourcing a file or importing a module.
-Note: Also unlike the two variables above, the exact path (including symlinks) that was used to _invoke_ the file is returned.
+Note: Also unlike `CURRENT_FILE` and `FILE_PWD`, the exact path (including symlinks) that was used to _invoke_ the file is returned.
### `$env.PROMPT_*` and `$env.TRANSIENT_PROMPT_*`
@@ -179,11 +287,29 @@ A number of variables are available for configuring the Nushell prompt that appe
- [Configuration - Prompt Configuration](./configuration.md#prompt-configuration)
- `config nu --doc`
+### `$env.PWD`
+
+The current directory, as an absolute path. [`cd`](/commands/docs/cd.md) changes it, and the change follows the same scoping rules as other environment variables. Nushell sets `PWD`, `FILE_PWD`, and `CURRENT_FILE` itself, so assigning or hiding them is an error. See [Automatic variables](./environment.md#automatic-variables).
+
### `$env.SHLVL`
`SHLVL` is incremented by most shells when entering a new subshell. It can be used to determine the number of nested shells. For instance,
if `$env.SHLVL == 2` then typing `exit` should return you to a parent shell.
+### `$env.SSH_CLIENT`
+
+SSH servers set `SSH_CLIENT` in the session they start. When it is set, the file names in `ls` output are not clickable links. Normally, with `$env.config.shell_integration.osc8` on, as it is by default, Nushell writes each name as an OSC 8 hyperlink to the local path, which the terminal can open. Over SSH, those paths are on the remote machine, so Nushell leaves the links out.
+
+Nushell reads `SSH_CLIENT` from the environment it was started with, so assigning or hiding `$env.SSH_CLIENT` inside Nushell changes nothing. It checks only `SSH_CLIENT`, not `SSH_CONNECTION` or `SSH_TTY`.
+
+### `$env.TERM_PROGRAM`
+
+Many terminals set `TERM_PROGRAM` to their own name. Nushell looks for one value, `vscode`, which the terminal in Visual Studio Code sets. In that terminal, with `$env.config.shell_integration.osc633` on, as it is by default, the REPL marks the prompt, the command line, and each command's start and end with VS Code's OSC 633 escape sequences instead of the standard OSC 133 ones. It also sends VS Code the current directory and the text of each command it runs. With any other value, or with `osc633` turned off, the REPL sends OSC 133 marks when `$env.config.shell_integration.osc133` is on.
+
+### `$env.XDG_CACHE_HOME`
+
+Can be used to optionally override the `$nu.cache-dir` location. See [Configuration - Startup Variables](./configuration.md#startup-variables).
+
### `$env.XDG_CONFIG_HOME`
Can be used to optionally override the `$nu.default-config-dir` location. See [Configuration - Startup Variables](./configuration.md#startup-variables).
From 3414a2ef0f0c7cb3fde7c1ef45f44dfb1e0f9f7b Mon Sep 17 00:00:00 2001
From: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Date: Sat, 14 Nov 2026 16:32:39 -0600
Subject: [PATCH 04/46] Document tooling and plugin features that had no docs
Covers the rows rated `none` in the coverage checklist for the language
server, the debug adapter, explore, and plugins:
- new page book/language_server.md: starting `nu --lsp`, what it loads,
editor setup for VS Code and Neovim, what the client must send, and
each capability with its limits (diagnostics, completion, hover,
signature help, definition, highlight, references, rename, symbols,
inlay hints, semantic tokens)
- debugging: DAP pause and the nuDapVisualize request
- explore: the :table and :expand commands and the binary (hex) viewer
- plugins: the installed_plugins column of `version` and the JavaScript
example plugin; contributor book: serve_plugin_io and
create_plugin_signature
- dataframes: cloud storage URLs and where polars reads credentials
LSP and DAP behavior was checked with scripted clients against a
0.117.1-dev build and the 0.117.0 source. Cloud reads need credentials
and were not run.
---
.vuepress/configs/sidebar/en.ts | 1 +
book/dataframes.md | 26 ++++
book/debugging.md | 4 +
book/explore.md | 28 ++++
book/language_server.md | 228 ++++++++++++++++++++++++++++++++
book/plugins.md | 25 ++++
contributor-book/plugins.md | 2 +
7 files changed, 314 insertions(+)
create mode 100644 book/language_server.md
diff --git a/.vuepress/configs/sidebar/en.ts b/.vuepress/configs/sidebar/en.ts
index 820b09f5679..fec7effc5cb 100644
--- a/.vuepress/configs/sidebar/en.ts
+++ b/.vuepress/configs/sidebar/en.ts
@@ -65,6 +65,7 @@ export const sidebarEn: SidebarConfig = {
'/book/sorting.md',
'/book/testing.md',
'/book/debugging.md',
+ '/book/language_server.md',
'/book/style_guide.md',
],
},
diff --git a/book/dataframes.md b/book/dataframes.md
index d3fe8a975e3..0473cf0912b 100644
--- a/book/dataframes.md
+++ b/book/dataframes.md
@@ -258,6 +258,32 @@ If you want to see all the dataframe commands that are available you
can use `scope commands | where category =~ dataframe`
:::
+### Cloud Storage
+
+`polars open` and `polars save` also accept a URL in cloud storage in place of a file path:
+
+```nu
+# Read a Parquet file from Amazon S3 as a lazy dataframe
+polars open s3://my-bucket/sales.parquet
+
+# Write a dataframe to Azure Blob Storage
+$df | polars save az://my-container/sales.parquet
+```
+
+The URL's scheme picks the provider, and each provider has its own way of finding credentials:
+
+| Schemes | Provider | Where the credentials come from |
+| ---------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `s3://`, `s3a://` | Amazon S3 | The AWS SDK's default chain: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN`, then the shared config and credentials files (with `AWS_PROFILE`), web identity, ECS, and EC2 instance metadata. Other `AWS_` variables, such as `AWS_REGION`, are read too. |
+| `az://`, `azure://`, `abfs://`, `abfss://`, `adl://` | Azure | Variables whose names start with `AZURE_`, such as `AZURE_STORAGE_ACCOUNT_NAME`, `AZURE_STORAGE_ACCOUNT_KEY`, `AZURE_STORAGE_SAS_TOKEN`, or `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, and `AZURE_TENANT_ID`. |
+| `gs://`, `gcs://` | Google Cloud Storage | `SERVICE_ACCOUNT`, the path to a service account key file, and variables whose names start with `GOOGLE_`, such as `GOOGLE_SERVICE_ACCOUNT` (which wins over `SERVICE_ACCOUNT`) and `GOOGLE_APPLICATION_CREDENTIALS`. |
+
+When no AWS credentials turn up, the command fails with `Could not fetch AWS credentials`, followed by each place the SDK looked. Other schemes, such as `https://` and `file://`, fail with `Could not determine a supported cloud type from path`.
+
+The plugin reads these variables from its own environment, which it gets from `$env` when Nushell starts it. If you set or change them while the plugin is running, run `plugin stop polars`, and the next `polars` command starts the plugin with the new values. Stopping the plugin also drops the dataframes it holds.
+
+Not every format works with cloud storage. `polars open` reads CSV, TSV, Parquet, Arrow, and NDJSON files from a cloud URL, always as a lazy dataframe, so `--eager` fails with `Cloud URLs are not supported with --eager`. JSON and Avro files can't be read from the cloud. `polars save` writes Parquet, Arrow, NDJSON, and CSV files to the cloud, but not Avro.
+
## Basic Aggregations
Let's start with basic aggregations on the dataframe. Let's sum all the columns
diff --git a/book/debugging.md b/book/debugging.md
index 89686df2f21..458dded6883 100644
--- a/book/debugging.md
+++ b/book/debugging.md
@@ -62,6 +62,8 @@ The **Runtime errors** exception filter, which is on by default, pauses the scri
While the script is paused, you can continue, step over a line, step into a command call or a pipeline stage, or step out of the current command. The call stack shows the command and closure calls that led to the current line.
+To stop a script that is running, use the editor's **Pause** command. The script stops at the next step it reaches, as if a breakpoint were there. While a long-running command such as [`sleep`](/commands/docs/sleep.md) or an external program is working, the script isn't at a step, so it pauses when that command finishes.
+
## Inspecting Values
When the script pauses, the editor's variables view shows:
@@ -74,6 +76,8 @@ When the script pauses, the editor's variables view shows:
Nested records, lists, and tables load one level at a time as you expand them, so a large value doesn't slow anything down until you look inside it. Streams are described, not read, so looking at one doesn't consume it.
+To see a whole value at once, a client can send the debugger's own `nuDapVisualize` request, which the VS Code extension's **Visualize** action uses. Its arguments name a value from the variables view, either with the value's `variablesReference` or, for a value that doesn't expand, with the `containerReference` of the scope or value that holds it and its `name`. The response has the value as JSON in `value`, its Nushell type in `type`, and `truncated`. Lists and records stop at 1000 items, nesting stops at 8 levels, and binary data, sent as a hex string in a `$nuBinary` object, stops at 64 KiB. When any of these limits cuts the value, `truncated` is `true`. Filesizes, durations, and dates come back as strings, such as `"2.0 kB"`, `"1500000000ns"`, and `"2026-01-02T03:04:05+00:00"`. Use references from the current pause. One that the current pause doesn't have gets the error `no value for that reference (stale after resume?)`.
+
Watch expressions, the debug console, and hovering over a variable evaluate Nushell expressions using the paused values. They run against a copy of the script's state, so they can't change the script's variables.
Output from [`print`](/commands/docs/print.md) and from external commands goes to the editor's debug console. The script has no terminal, so external commands get no standard input.
diff --git a/book/explore.md b/book/explore.md
index 64a045e0dfc..1e96d1d53fc 100644
--- a/book/explore.md
+++ b/book/explore.md
@@ -65,8 +65,36 @@ Press `/` to search forward or `?` to search backward. Results are highlighted a
| `:help` | Show the help page |
| `:try` | Open an interactive REPL on the current data |
| `:nu ` | Run a Nushell command on the current data |
+| `:table` | Open the current value in a new table view |
+| `:expand`, `:e` | Show the current value with all nested data expanded |
| `:q` | Exit `explore` |
+`:table` and `:expand` work on the current value, which is the selected cell in cursor mode and the whole table you are looking at in view mode. Both open a new view on top of the current one, and `Esc` goes back to it.
+
+`:table` shows the value as a table that you can move around in, even when it is a plain value such as a string. `:expand`, which the `e` key also runs, draws the value as text, the way [`table --expand`](/commands/docs/table.md) does. Every nested list and record is drawn in full inside its cell, in the style set by `$env.config.table.mode`.
+
+## Viewing Binary Data
+
+When the input is binary data, `explore` shows a hex dump instead of a table. Each line has the offset of its first byte, the next sixteen bytes in hex, and the same bytes as characters:
+
+```nu
+0x[48 65 6c 6c 6f 2c 20 4e 75 21 00 09 0a 7f c3 a9] | explore
+# => 00000000 │ 4865 6c6c 6f2c 204e 7521 0009 0a7f c3a9 │ Hello, Nu!0__•××
+```
+
+In the character column, a printable ASCII character stands for itself, `0` is a null byte, `_` is whitespace other than a space (such as a tab or a newline), `•` is any other ASCII control character, and `×` is a byte outside ASCII.
+
+A byte stream also opens in the hex view, even when it holds text. That includes the output of an external command and a text file read with [`open`](/commands/docs/open.md):
+
+```nu
+^echo hi there | explore
+# => 00000000 │ 6869 2074 6865 7265 0a │ hi there_
+```
+
+To see the text, convert it first, for example with [`lines`](/commands/docs/lines.md) or [`decode`](/commands/docs/decode.md). `explore` reads the whole stream into memory before it shows anything.
+
+The hex view is simpler than the table view. You can scroll with the arrow keys, but there is no cursor mode, searching finds nothing, and `--peek` returns nothing. `q` and `Esc` don't exit. Type `:q` or press `Ctrl+C` instead.
+
## Config
`explore`'s colors are configured in `$env.config.explore`. Each value takes the same forms as [`color_config`](coloring_and_theming.md): a color name, a `#RRGGBB` hex code, or a `{fg, bg, attr}` record. For example:
diff --git a/book/language_server.md b/book/language_server.md
new file mode 100644
index 00000000000..09f4473c1d3
--- /dev/null
+++ b/book/language_server.md
@@ -0,0 +1,228 @@
+# Language server
+
+Running `nu --lsp` starts Nushell's built-in [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) (LSP) server. An editor that speaks LSP uses it to underline errors as you type, complete commands and paths, show a command's help when you hover over it, jump to definitions, and rename a variable or custom command across files. The server runs Nushell's own parser on your code, so the errors it reports are the ones `nu` would report before running the script.
+
+The language server is part of the default build (the `lsp` [Cargo feature](./installation.md)). To step through a script while it runs, use the debugger instead (see [Debugging Scripts](./debugging.md)).
+
+## Starting the server
+
+You don't run the server by hand. The editor starts `nu --lsp` and talks to it over the process's standard input and output. No other arguments are needed.
+
+Before it answers the editor, the server loads the same startup files as an interactive session: the plugin registry, `env.nu`, `config.nu`, and the autoload directories. Custom commands, aliases, and modules defined there, and the commands of registered plugins, are all known to the server. It completes them, shows their help, and doesn't treat calls to them as external commands. Add `-n` (`--no-config-file`) to the arguments to start from the defaults instead. The other startup flags, such as `--config`, `--env-config`, `--plugin-config`, and `--plugins`, work with `--lsp` too.
+
+While the startup files run, [`$nu.is-lsp`](./special_variables.md#nu) is `true`. [`print`](/commands/docs/print.md) writes to stderr in this mode, but the output of an external command still goes to stdout, in between the protocol messages that the editor reads from there. Skip such commands when the language server starts:
+
+```nu
+# in config.nu
+if not $nu.is-lsp {
+ ^echo "hello from config.nu"
+}
+```
+
+The server parses each file with the file's own directory as the current directory. Relative paths in `use` and `source`, and file path completions, start from where the file is, not from where the editor was started.
+
+## Editor setup
+
+### VS Code
+
+The [Nushell extension for VS Code](https://marketplace.visualstudio.com/items?itemName=TheNuProjectContributors.vscode-nushell-lang) starts `nu --lsp` for `.nu` files.
+
+### Neovim
+
+Neovim 0.11 and later can start the server with the built-in LSP client. Neovim sets the `nu` filetype for `.nu` files:
+
+```lua
+vim.lsp.config('nushell', {
+ cmd = { 'nu', '--lsp' },
+ filetypes = { 'nu' },
+ root_markers = { '.git' },
+})
+vim.lsp.enable('nushell')
+```
+
+`root_markers` decides the workspace folder. Neovim looks upward from the file for one of the listed names and sends that directory to the server as the workspace folder. When nothing matches, no folder is sent, and find references and rename only see the current file.
+
+### Other editors
+
+Any editor with an LSP client can use the server. Configure it to run `nu` with the argument `--lsp` for `.nu` files, and check that it sends a workspace folder, as described in the next section.
+
+## What the editor sends
+
+The server uses standard LSP over stdin and stdout: JSON-RPC messages, each preceded by a `Content-Length` header. Editors with an LSP client handle the details, but a few of them matter when a feature doesn't work:
+
+- The server reads the project directories from the `workspaceFolders` field of the `initialize` request. It ignores `rootUri` and `rootPath`, so a client that only sends those gets no workspace-wide search. Later `workspace/didChangeWorkspaceFolders` notifications add and remove folders. A file belongs to a folder when the file's URI starts with the folder's URI.
+- The editor sends `textDocument/didOpen`, `didChange`, and `didClose` for the files you edit. The server asks for incremental changes, so each `didChange` carries only the edited range. The server works from the text it was sent, including unsaved edits.
+- The server reports the progress of workspace-wide searches with `$/progress` notifications, and sends warnings as `window/logMessage` notifications.
+- The server registers no trigger characters for completion or signature help. Most editors ask for completions while you type a word, but whether signature help appears without you asking for it depends on the editor.
+
+An `initialize` request with one workspace folder looks like this:
+
+```json
+{
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "processId": null,
+ "capabilities": {},
+ "workspaceFolders": [
+ { "uri": "file:///home/me/project", "name": "project" }
+ ]
+ }
+}
+```
+
+The response lists the features below in `capabilities`, and its `serverInfo` gives the name `Nushell` and the version of `nu`.
+
+## Features
+
+| Feature | LSP method |
+| ------------------ | -------------------------------------------------------- |
+| Diagnostics | `textDocument/publishDiagnostics` (sent by the server) |
+| Completion | `textDocument/completion` |
+| Hover | `textDocument/hover` |
+| Signature help | `textDocument/signatureHelp` |
+| Go to definition | `textDocument/definition` |
+| Document highlight | `textDocument/documentHighlight` |
+| Find references | `textDocument/references` |
+| Rename | `textDocument/prepareRename`, then `textDocument/rename` |
+| Document symbols | `textDocument/documentSymbol` |
+| Workspace symbols | `workspace/symbol` |
+| Inlay hints | `textDocument/inlayHint` |
+| Semantic tokens | `textDocument/semanticTokens/full` |
+
+The server has no formatting or code actions.
+
+### Diagnostics
+
+Each time a file is opened or changed, the server parses it and sends the problems it found in a `textDocument/publishDiagnostics` notification. Parse errors become errors, and parse warnings, such as a call to a deprecated command, become warnings. These are the problems `nu` finds before it runs a script: syntax errors, unknown flags, missing arguments, variables that don't exist, and the type mismatches the parser can detect. Errors that only happen while a script runs aren't reported. In this file:
+
+```nu
+ls --al
+$greting
+```
+
+the server reports two errors, ``The `ls` command doesn't have flag `al`.`` on `--al` and `Variable not found.` on `$greting`.
+
+A diagnostic has only the short message, without the help text and labels that `nu` prints. A problem inside a file that this one imports with `use` or `source` is reported on this file, at its end.
+
+### Completion
+
+Completions come from the same engine as Tab completion in the REPL. They include commands, flags, file and directory paths, module names after `use`, variables, the fields of a record in a cell path, and operators. [Custom completions](./custom_completions.md) and the external completer set in `config.nu` (`$env.config.completions.external.completer`) apply as well.
+
+Each item has a kind, which most editors show as an icon:
+
+| Suggestion | Completion item kind |
+| -------------------------------------- | -------------------- |
+| Built-in command | Function |
+| Custom command or plugin command | Method |
+| Keyword, such as `let` or `def` | Keyword |
+| Alias | Reference |
+| External command | Interface |
+| Flag | Field |
+| File | File |
+| Directory | Folder |
+| Module | Module |
+| Variable | Variable |
+| Cell path member | Property |
+| Operator | Operator |
+| String value, such as a flag's choices | Value |
+
+Choosing a command inserts a snippet with a placeholder for each positional parameter. An optional parameter's placeholder ends in `?`, a rest parameter's starts with `...`, and a block parameter gets braces. The item's documentation is the command's help. Completing `str jo` returns (some fields left out):
+
+```json
+{
+ "label": "str join",
+ "labelDetails": { "description": "built-in" },
+ "kind": 3,
+ "detail": "Concatenate multiple strings into a single string, with an optional separator between each.",
+ "insertTextFormat": 2,
+ "textEdit": {
+ "range": {
+ "start": { "line": 1, "character": 0 },
+ "end": { "line": 1, "character": 6 }
+ },
+ "newText": "str join ${1:separator?}"
+ }
+}
+```
+
+### Hover
+
+What hovering shows depends on what is under the cursor:
+
+- A command: its help as Markdown, with the description, usage, flags, parameters, input and output types, and examples. This covers built-in, custom, and plugin commands.
+- A variable: its type, and its value if it is a constant. For other variables, hover says whether the variable is `mutable` or `immutable`.
+- A cell path such as `$person.name`: the type of that field, and its value when the variable is a constant.
+- A module name: the module's documentation comments.
+- An external command: its manual page, from `man`. On Windows, the server runs PowerShell's `help` instead.
+- Any other expression, such as a literal: its type.
+
+### Signature help
+
+With the cursor among a command's arguments, signature help shows the command's usage line, such as `str join {flags} (separator)`, and describes each parameter. Positional parameters come first, in order, and the flags follow them. The active parameter is the positional parameter the cursor is on, counted by the positional arguments before it.
+
+### Go to definition
+
+Go to definition jumps to:
+
+- the body of a custom command
+- the declaration of a variable, including command parameters and closure parameters
+- the definition of a module
+- the value of a field, for a cell path into a constant
+
+For a module that is a whole file, as in `overlay use lib.nu`, the definition is the start of that file. The definition can be in another file that the current one imports with `use` or `source`, whether or not that file is open in the editor. Built-in commands, plugin commands, and external commands have no definition to go to. Neither do commands from the [standard library](./standard_library.md), which is built into `nu`. For a standard library command, the server logs a warning and returns nothing.
+
+### Document highlight
+
+Document highlight marks every place in the current file where the variable, command, or module under the cursor appears, including its definition.
+
+### Find references
+
+Find references lists every place where the variable, command, or module under the cursor appears, including its definition. The request's `includeDeclaration` setting is ignored.
+
+When the file is in a workspace folder, the server searches every `.nu` file under that folder, at any depth, along with the files open in the editor. It parses only the files whose text contains the name, and reports its progress as it goes (`Finding references ...`). The search has a five-second budget. When that runs out, the server stops, logs `Workspace-wide search took too long!`, and returns the references it found so far.
+
+When the file isn't in a workspace folder, only the current file is searched.
+
+Results from other files are best-effort. A use of a command in a file that imports it with a different path can be missed, and so can the name in that file's `use` statement.
+
+### Rename
+
+Renaming takes two requests. `textDocument/prepareRename` checks what is under the cursor and starts a search for every occurrence, and `textDocument/rename` turns what that search found into edits.
+
+Only variables, custom commands, and modules defined in your code can be renamed. On a built-in command, or anything else without a definition, preparation fails with `Definition not found. Not allowed to rename built-ins.` On a literal or another expression, it fails with `Rename only works for variable/command.`
+
+The search covers the same files as find references, and reports progress as `Preparing rename ...`. It has no time limit, but any other message from the editor stops it, such as a hover request or the `didChange` that a keystroke sends. The server then logs `Workspace-wide search took too long!` and ends the progress report with `interrupted.` A rename request that arrives before the search finishes is refused with `Please wait for renaming preparation to complete.` and stops the search too. A rename after a stopped search only edits what the search found before it stopped, which can be nothing at all. Start the rename again to search every file.
+
+Without a workspace folder, only the current file is edited. When the command is defined in another file, its definition keeps the old name. Because cross-file results are best-effort, check the edits before you save them.
+
+### Symbols
+
+Document symbols list the custom commands, variables, and modules defined in a file, as a flat list with the commands first. Editors use them for an outline view and for jumping to a symbol.
+
+Workspace symbols search the symbols of the files open in the editor and of the files they import with `use` or `source`, matching the query fuzzily. The query is case-insensitive unless it has an uppercase letter. Files in the workspace folder that aren't open or imported aren't searched.
+
+### Inlay hints
+
+Inlay hints are short labels that the editor draws inside the code without changing it. The server adds:
+
+- the type after the name in a `let`, `mut`, or `const` declaration and after a `for` loop variable, unless the code already has a type annotation, as in `let count: int = 0`,
+- the type after the variable in an assignment, such as `$count += 1`,
+- the parameter name before each positional argument of a custom command defined in your code, with the parameter's type and description as a tooltip.
+
+Lists, records, and tables are shown as `list`, `record`, and `table`, without their element types. Parameter names aren't shown for built-in or plugin commands, for flags, or for a rest parameter. After a spread argument (`...$args`), no more parameter names are shown. For this file:
+
+```nu
+def greet [name: string] { $"hello ($name)" }
+let names = [Ada Grace]
+$names | each {|n| greet $n }
+```
+
+an editor shows `: list` after `names`, and `name:` before `$n`.
+
+The server computes the hints when the file is opened or changed and always returns the hints for the whole file, whatever range the editor asks for.
+
+### Semantic tokens
+
+Most editors color Nushell code with a syntax grammar that only sees the text. Such a grammar can't know which multi-word names, such as `str join`, are a single command, so it may color the second word as an argument. Semantic tokens cover that one case. The server marks each call to a command whose name has more than one word, such as `str join`, a custom command named `git sync`, or `assert equal` from the standard library, with the token type `function`. Calls to commands whose names start with `export` or `overlay` aren't marked, and neither is anything else, so the grammar still colors the rest of the file. Only full-document requests are supported.
diff --git a/book/plugins.md b/book/plugins.md
index 8e92ab89fb8..844fdb091b9 100644
--- a/book/plugins.md
+++ b/book/plugins.md
@@ -241,6 +241,15 @@ All of the commands from installed plugins are available in the current scope:
scope commands | where type == "plugin"
```
+[`version`](/commands/docs/version.md) also names the plugins, in its `installed_plugins` column. It is a single string with each plugin's name and version, separated by commas:
+
+```nu
+version | get installed_plugins
+# => polars 0.117.0, query 0.117.0
+```
+
+The column lists the plugins loaded into the current session, running or not. A plugin you have only registered with `plugin add` appears after `plugin use` or a restart, and one you remove with `plugin rm` stays until the session ends. A plugin that didn't report a version is listed by its name alone.
+
### Plugin Lifecycle
Plugins stay running while they are in use, and are automatically stopped by default after a period of time of inactivity. This behavior is managed by the [plugin garbage collector](#plugin-garbage-collector). To manually stop a plugin, call `plugin stop` with its name:
@@ -321,6 +330,22 @@ Nu's main repo contains example plugins that are useful for learning how the plu
- [Rust](https://github.com/nushell/nushell/tree/main/crates/nu_plugin_example)
- [Python](https://github.com/nushell/nushell/blob/main/crates/nu_plugin_python)
- [Nu](https://github.com/nushell/nushell/tree/main/crates/nu_plugin_nu_example)
+- [JavaScript (Node.js)](https://github.com/nushell/nushell/tree/main/crates/nu_plugin_javascript)
+
+The JavaScript example is a single file, `nu_plugin_node_example.js`, that speaks the JSON encoding of the protocol. Its one command, `node_example`, ignores its arguments and returns a 10-row table. The file hard-codes the Nushell version it works with in the `NUSHELL_VERSION` constant, `'0.103.1'` as shipped. During the handshake, the plugin exits unless that constant equals the version of `nu` exactly, and `nu` itself refuses a plugin that reports an incompatible version. Before you add the plugin, set the constant to your version, the value of `(version).version`. Then register the file with Node.js as the interpreter, giving `--shell` the full path to `node`:
+
+```nu
+plugin add --shell (which node | get path.0) ./nu_plugin_node_example.js
+plugin use node_example
+node_example 2 "3" | first 3
+# => ╭───┬─────┬─────┬───────╮
+# => │ # │ one │ two │ three │
+# => ├───┼─────┼─────┼───────┤
+# => │ 0 │ 0 │ 0 │ 0 │
+# => │ 1 │ 1 │ 2 │ 3 │
+# => │ 2 │ 2 │ 4 │ 6 │
+# => ╰───┴─────┴─────┴───────╯
+```
### Debugging
diff --git a/contributor-book/plugins.md b/contributor-book/plugins.md
index 5540936b546..bccdb5bc48e 100644
--- a/contributor-book/plugins.md
+++ b/contributor-book/plugins.md
@@ -141,6 +141,8 @@ fn main() {
In `main()`, we just call a single function `serve_plugin`. This will do the work of calling into our plugin, handling the JSON serialization/deserialization, and sending values and errors back to Nu for us. To start it up, we pass it something that implements the `Plugin` trait and something that implements the `PluginEncoder` trait. We're given a choice of serialization formats that Nu supports. Ordinarily plugins written in Rust should use `MsgPackSerializer` as it is considerably faster, but here we select JSON to demonstrate how the communication protocol works further on in this tutorial.
+`serve_plugin` reads the arguments that Nushell starts the plugin with (`--stdio`, or `--local-socket` and a socket name), tells Nushell which encoding the plugin uses, and then hands the connection to `serve_plugin_io`, which runs the protocol over any reader and writer. If two of the plugin's commands return the same `name()`, `serve_plugin_io` prints a warning to stderr when the plugin starts, and the command that comes later in `commands()` replaces the earlier one. When Nushell asks for the plugin's signatures during `plugin add`, `create_plugin_signature` builds each command's signature from its `signature()`, `description()`, `extra_description()`, `search_terms()`, and `examples()` methods. `nu-plugin` exports both functions, but they are hidden from its API documentation and aren't a public API. They exist for `nu-plugin-test-support`. In your own plugin, call `serve_plugin`, and test it with [`nu-plugin-test-support`](#testing-plugins).
+
Above `main()` is the implementation of the `SimplePluginCommand` trait for the `len` command that our plugin will expose, which is represented by the `Len` type. We use `SimplePluginCommand` rather than `PluginCommand` in order to simplify our implementation and avoid [handling streams](#using-streams-in-plugins). Let's take a look at how we implement this trait:
```rust
From d1073adb29fb37d38f00d335b42860a21c45d9d1 Mon Sep 17 00:00:00 2001
From: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Date: Sat, 14 Nov 2026 16:35:42 -0600
Subject: [PATCH 05/46] Document definition and control flow features that had
no docs
Covers the rows rated `none` in the coverage checklist for custom
commands, modules, scripts, and control flow:
- defining a command twice in one block, duplicate parameter and flag
names, and user-defined attributes
- what a module body may contain, and how a submodule named `mod` is
merged into its parent
- `nu script.nu --help`
- `else`, `catch`, and `finally` must stay on the line of the closing
brace; type annotations on the `for` variable
- `catch` and `finally` with a closure in a variable, `try` collecting
the block's output, and re-raising a caught error with `raw`
Parse errors were captured from a REPL. The code that decides each
behavior is unchanged between 0.117.0 and the build used for testing.
---
book/control_flow.md | 49 +++++++-
book/creating_errors.md | 57 ++++++++++
book/custom_commands.md | 106 ++++++++++++++++++
book/modules/creating_modules.md | 43 +++++++
book/scripts.md | 58 ++++++++++
lang-guide/chapters/custom_commands.md | 11 ++
lang-guide/chapters/flow_control/if-else.md | 2 +
lang-guide/chapters/flow_control/try-catch.md | 50 ++++++++-
8 files changed, 374 insertions(+), 2 deletions(-)
diff --git a/book/control_flow.md b/book/control_flow.md
index 5664791cb8f..1a9ab028959 100644
--- a/book/control_flow.md
+++ b/book/control_flow.md
@@ -63,6 +63,41 @@ if $x > 0 { 'positive' } else if $x == 0 { 'zero' } else { "negative" }
When the first condition is `true` (`$x` is greater than zero) it will return `'positive'`, when the first condition is `false` and the next condition is `true` (`$x` equals zero) it will return `'zero'`, otherwise it will return `'negative'` (when `$x` is less than zero).
+::: warning
+`else` has to start on the same line as the `}` before it. A newline ends the `if` command, so Nushell runs the `if` by itself and then tries to run `else` as a separate command. The parser doesn't catch this. The script fails when it reaches the `else`, whichever branch the condition picked:
+
+```nu
+# size.nu
+def describe-size [n: int] {
+ if $n > 100 {
+ "big"
+ }
+ else {
+ "small"
+ }
+}
+
+describe-size 5
+```
+
+```nu
+nu size.nu
+# => Error: nu::shell::external_command
+# =>
+# => × External command failed
+# => ╭─[/home/me/size.nu:5:5]
+# => 4 │ }
+# => 5 │ else {
+# => · ──┬─
+# => · ╰── Command `else` not found
+# => 6 │ "small"
+# => ╰────
+# => help: Did you mean `if`?
+```
+
+Write `} else {` on one line. The same rule applies to `else if` and to the `catch` and `finally` parts of [`try`](#try). Inside parentheses a newline doesn't end the command, so wrapping the whole `if` in `( )` also lets `else` start a new line (see [Multi-line pipelines](pipelines.md#multi-line-pipelines)).
+:::
+
### `match`
[`match`](/commands/docs/match.html) executes one of several conditional branches based on the value given to match. You can also do some [pattern matching](/cookbook/pattern_matching.html) to unpack values in composite types like lists and records.
@@ -268,6 +303,14 @@ for x in [1 2 3] { $x * $x | print }
# => 9
```
+The loop variable can have a type annotation, as in `for x: int in $numbers`. Nushell checks that the annotation names a real type, but it doesn't check the items against it, and it doesn't convert them. The variable gets the type of the items instead, so this loop runs without an error:
+
+```nu
+for x: string in [1 2] { print ($x | describe) }
+# => int
+# => int
+```
+
#### Expression Command Alternatives
- [`each`](/commands/docs/each.html)
@@ -373,7 +416,7 @@ try { 1 / 0 } catch { 'An error happened!' } | $in ++ ' And now I am resuming.'
# => An error happened! And now I am resuming.
```
-It will not execute the `catch` block if an error did not occur.
+It will not execute the `catch` block if an error did not occur. As with [`else`](#if), `catch` and `finally` have to start on the same line as the `}` before them.
The `catch` closure can take a parameter, which receives a record describing the error:
@@ -382,6 +425,8 @@ try { 1 / 0 } catch {|err| $err.msg }
# => Division by zero.
```
+Instead of writing the closure after `catch`, you can give it a closure stored in a variable or passed in as a parameter, as in `try { ... } catch $handler`. `finally` only takes a closure written in place. See [the Language Guide](/lang-guide/chapters/flow_control/try-catch.md#language-notes) for both.
+
`try` also works for external commands:
```nu
@@ -453,6 +498,8 @@ try { 1 / 0 } finally { print 'cleaning up' }
# => ╰────
```
+With a `catch` or a `finally`, `try` collects the whole output of its block before it returns. An error in any item of a stream is therefore still caught, but the output doesn't stream on to the next command while the block runs. See [the Language Guide](/lang-guide/chapters/flow_control/try-catch.md#language-notes) for an example.
+
## Other
### `return`
diff --git a/book/creating_errors.md b/book/creating_errors.md
index 478535fe8a6..fd635c0aadf 100644
--- a/book/creating_errors.md
+++ b/book/creating_errors.md
@@ -149,3 +149,60 @@ try { check-range 10 1 } catch { error make "could not build the range" }
```
After any other statement in the block, such as a `print`, the caught error is no longer the input, and `error make` reports only the new error. To keep the chain, pipe the error in with `$err | error make "..."`, or pass it with `inner`, as in `catch {|err| print 'cleaning up'; error make {msg: 'could not build the range', inner: [$err]} }`.
+
+## Re-raising a caught error
+
+Sometimes a `catch` block only needs to log an error and then let it continue. The `raw` field of the error record holds the original error itself, and returning it from `catch` raises that error again, unchanged:
+
+```nu
+try { check-range 10 1 } catch {|err| print "logging the error"; $err.raw }
+# => logging the error
+# => Error: nu::shell::error
+# =>
+# => × invalid range
+# => ╭─[repl_entry #2:1:19]
+# => 1 │ try { check-range 10 1 } catch {|err| print "logging the error"; $err.raw }
+# => · ─┬ ┬
+# => · │ ╰── is greater than the upper bound
+# => · ╰── lower bound
+# => ╰────
+# => help: swap the two arguments
+```
+
+Reading `$err.raw` raises the error right away, so it can't be stored or inspected. That means `error make {msg: "new message", raw: $err.raw}` also re-raises the original error, before `error make` even runs.
+
+`error make` treats a `raw` field the same way. When the record it receives has one, `error make` raises the error stored there and ignores the other fields. The record in `$err` has a `raw` field, so `error make $err` re-raises the caught error, and so does a copy with a changed message:
+
+```nu
+try { check-range 10 1 } catch {|err| error make ($err | update msg "could not build the range") }
+# => Error: nu::shell::error
+# =>
+# => × invalid range
+# => ╭─[repl_entry #3:1:19]
+# => 1 │ try { check-range 10 1 } catch {|err| error make ($err | update msg "could not build the range") }
+# => · ─┬ ┬
+# => · │ ╰── is greater than the upper bound
+# => · ╰── lower bound
+# => ╰────
+# => help: swap the two arguments
+```
+
+To raise a new error based on the caught one, start from `$err.details` instead. It has the `msg`, `labels`, `code`, `url`, `help` and `inner` fields, but no `raw`:
+
+```nu
+try { check-range 10 1 } catch {|err| let details = $err.details | update msg "could not build the range"; error make $details }
+# => Error: nu::shell::error
+# =>
+# => × could not build the range
+# => ╭─[repl_entry #4:1:19]
+# => 1 │ try { check-range 10 1 } catch {|err| let details = $err.details | update msg "could not build the range"; error make $details }
+# => · ─┬ ┬
+# => · │ ╰── is greater than the upper bound
+# => · ╰── lower bound
+# => ╰────
+# => help: swap the two arguments
+```
+
+The new error keeps the original labels and help. Because `error make` isn't the first command in the block, the caught error isn't also attached as an inner error (see [Chaining Errors](#chaining-errors)).
+
+A `raw` field has to hold an error. Any other value, such as `raw: 5`, fails with `Can't convert to ShellError`, and `raw: null` is ignored.
diff --git a/book/custom_commands.md b/book/custom_commands.md
index 1724f65e485..7d28c9a190e 100644
--- a/book/custom_commands.md
+++ b/book/custom_commands.md
@@ -383,6 +383,41 @@ def greet [] { "hi" }
`%` is handy inside a command that shadows a built-in, because the body can call the original without recursing into itself. See [Aliases](aliases.md#replacing-existing-commands-using-aliases) for a complete example that replaces `ls`.
:::
+### Defining a command more than once
+
+A block can define each command name only once. A second `def` (or [`extern`](externs.md)) with the same name in the same block is a parse error, so nothing in the block runs:
+
+```nu
+def greet [] { "hi" }; def greet [] { "hello" }
+# => Error: nu::parser::duplicate_command_def
+# =>
+# => × Duplicate command definition within a block.
+# => ╭─[repl_entry #1:1:28]
+# => 1 │ def greet [] { "hi" }; def greet [] { "hello" }
+# => · ──┬──
+# => · ╰── defined more than once
+# => ╰────
+```
+
+A script file and a module are each a single block, so neither can define the same name twice. At the REPL, each entry is a new block, and entering a new `def greet` at the prompt replaces the earlier one:
+
+```nu
+def greet [] { "hi" }
+def greet [] { "hello" }
+greet
+# => hello
+```
+
+A `def` inside a nested block, such as a `do` closure or another command's body, shadows the outer command only within that block:
+
+```nu
+def greet [] { "hi" }
+do { def greet [] { "hello" }; greet }
+# => hello
+greet
+# => hi
+```
+
## Parameters
### Multiple parameters
@@ -792,6 +827,33 @@ def greet [
}
```
+Because `--all-caps` creates `$all_caps`, it would collide with a parameter named `all_caps`. Parameters and flags share one set of variable names, and each short flag needs its own letter. Nushell rejects a repeated name when it parses the definition:
+
+```nu
+def greet [--all-caps, all_caps] { $all_caps }
+# => Error: nu::parser::duplicate_parameter
+# =>
+# => × Duplicate parameter or flag.
+# => ╭─[repl_entry #1:1:24]
+# => 1 │ def greet [--all-caps, all_caps] { $all_caps }
+# => · ─────┬──── ────┬───
+# => · │ ╰── `all_caps` uses a name that is already taken
+# => · ╰── first used here
+# => ╰────
+# => help: Each parameter and flag needs its own name, and each short flag its own letter. A long flag's
+# => variable replaces `-` with `_`, so `--foo-bar` and `foo_bar` clash.
+```
+
+The same error covers two parameters with one name, a rest parameter that reuses a name, and two flags with the same short letter, such as `--verbose (-v)` and `--version (-v)`. A flag with only a short form, like `-v`, creates the variable `$v`, so it also collides with a parameter named `v`.
+
+The one name you can repeat is `_`. Use it for positional arguments the command doesn't need:
+
+```nu
+def third [_, _, value] { $value }
+third a b c
+# => c
+```
+
#### Flags with a `null` Value
When a flag is given `null` as its value, what happens depends on the flag's type:
@@ -1340,6 +1402,50 @@ applies only to `extern`. It lets an external command return data instead of tex
To see other attributes available for use within nushell, check the [command reference](/commands/docs/attr.html)
or run `help attr` from the nushell REPL.
+### Defining your own attributes
+
+An attribute such as `@owner` calls a command named `attr owner` while Nushell parses the definition, and stores the value that command returns. To create your own attribute, define an alias whose name starts with `attr ` and points to a built-in command that can run at parse time. [`echo`](/commands/docs/echo.md) is the usual choice, since it returns its arguments as they are:
+
+```nu
+alias "attr owner" = echo
+alias "attr tags" = echo
+alias "attr slow" = echo
+
+@owner "platform-team"
+@tags web api
+@slow
+@category "deploy"
+def deploy [] { "deploying" }
+
+@slow
+def rebuild [] { "rebuilding" }
+
+scope commands | where name == deploy | get 0.attributes
+# => ╭───┬───────┬────────────────╮
+# => │ # │ name │ value │
+# => ├───┼───────┼────────────────┤
+# => │ 0 │ owner │ platform-team │
+# => │ 1 │ tags │ [list 2 items] │
+# => │ 2 │ slow │ │
+# => ╰───┴───────┴────────────────╯
+```
+
+Nushell doesn't act on custom attributes. It stores them in the `attributes` column of [`scope commands`](/commands/docs/scope_commands.md), one row per attribute, with its name and value. Several arguments, as in `@tags web api`, give a list, and an attribute without arguments, like `@slow`, stores an empty string. Using the same attribute twice adds two rows. The built-in `@example`, `@search-terms`, `@category` and `@complete` attributes are applied to the command and aren't listed.
+
+A script can read the attributes back to find the commands it cares about:
+
+```nu
+scope commands | where {|cmd| "slow" in $cmd.attributes.name } | get name
+# => ╭───┬─────────╮
+# => │ 0 │ deploy │
+# => │ 1 │ rebuild │
+# => ╰───┴─────────╯
+```
+
+To share attributes, export the aliases from a module (`export alias "attr owner" = echo`) and import them with `use ownership.nu *`, or by name with `use ownership.nu ["attr owner"]`. A plain `use ownership.nu` puts the module name in front of the alias, so `@owner` can't find it. The standard library's `@test`, `@ignore` and other [testing attributes](./standard_library.md#importing-submodules) are aliases of `echo` exported this way.
+
+The command behind an attribute has to be one that can run at parse time. An attribute backed by a custom command, such as `def "attr owner" [x] { $x }`, fails with a `Not a const command` error. An attribute also has to come right before a `def` or `extern`. Anywhere else, it is a `nu::parser::attribute_requires_definition` error.
+
## Changing the Environment in a Custom Command
Normally, environment variable definitions and changes are [_scoped_ within a block](./environment.html#scoping). This means that changes to those variables are lost when they go out of scope at the end of the block, including the block of a custom command.
diff --git a/book/modules/creating_modules.md b/book/modules/creating_modules.md
index f0136edcc4c..9777c08544e 100644
--- a/book/modules/creating_modules.md
+++ b/book/modules/creating_modules.md
@@ -381,6 +381,31 @@ Running this command changes the directory _locally_ in the module, but the chan
## Caveats
+### A module can only contain definitions
+
+The top level of a module, whether it is a file or a `module { }` block, can only contain definitions: `def`, `extern`, `alias`, `const`, `type`, `use` and `module`, any of these with `export` in front, `export-env` blocks, and attributes on a `def` or `extern`. Any other statement, such as `let` or `print`, is a parse error:
+
+```nu
+module greetings {
+ let default_name = "world"
+ export def hello [] { $"Hello, ($default_name)!" }
+}
+# => Error: nu::parser::expected_keyword
+# =>
+# => × Expected keyword.
+# => ╭─[repl_entry #1:2:5]
+# => 1 │ module greetings {
+# => 2 │ let default_name = "world"
+# => · ─┬─
+# => · ╰── expected def, const, extern, alias, type, use, module, export or export-env keyword
+# => 3 │ export def hello [] { $"Hello, ($default_name)!" }
+# => ╰────
+```
+
+For a module file, the error appears when you import it with `use`. A pipeline such as `ls | length` is rejected too, with `Parse mismatch: expected not a pipeline`. The rule covers only the module's top level, not the bodies of its commands.
+
+Use `const` for a value that the module's commands share. Changing `let` to `const` in the example above makes it work. Code that should run when the module is imported belongs in an [`export-env`](#environment-variables) block.
+
### `export-env` runs only when the `use` call is _evaluated_
::: note
@@ -491,6 +516,24 @@ module spam { export module spam { } }
# => help: Module spam can't export module named the same as the module. Either change the module name, or export `mod` module.
```
+The `mod` in the help text is a submodule name with special handling. Whatever a submodule named `mod` exports is merged into its parent. Its commands (including `main`), aliases, known externals, type aliases and submodules become members of the parent module, as if the parent had exported them itself:
+
+```nu
+module spam {
+ export module mod {
+ export def main [] { "spam!" }
+ export def eggs [] { "eggs" }
+ }
+}
+use spam
+spam
+# => spam!
+spam eggs
+# => eggs
+```
+
+With any other submodule name, `use spam` would import neither command (see [Submodules](#submodules)). Constants that `mod` exports are dropped instead of merged. A `main` in `mod` also keeps the name `mod`, so `spam mod` runs it too. If the parent exports a `main` of its own as well, the second one is a `nu::parser::module_double_main` error.
+
::: note
A `.nu` file _may_ have the same name as its module directory (e.g., `spam/spam.nu`), and Nushell will import it. Still, prefer a different name: if the parent module and the same-named submodule both export a `main`, the two definitions resolve to the same command name and the parent's `main` silently wins.
:::
diff --git a/book/scripts.md b/book/scripts.md
index f4cad852a8f..8fd8365eb60 100644
--- a/book/scripts.md
+++ b/book/scripts.md
@@ -78,6 +78,64 @@ nu add_ten.nu 100
# => 110
```
+### Help for a script
+
+Run a script with `--help` (or `-h`) to see the help for its `main` command, shown under the script's file name. As with any [documented command](custom_commands.md#documenting-your-command), the comment directly above `def main` becomes the description and a comment after each parameter describes it. The help also lists the [subcommands](#subcommands) of `main`:
+
+```nu
+# welcome.nu
+
+# Welcome someone by name
+#
+# Prints a short greeting.
+def main [
+ name: string # Who to welcome
+ --shout (-s) # Print the greeting in capitals
+] {
+ let text = $"Welcome, ($name)!"
+ if $shout { $text | str uppercase } else { $text }
+}
+
+# Say goodbye instead
+def "main bye" [name: string] {
+ $"Goodbye, ($name)!"
+}
+```
+
+```nu
+nu welcome.nu --help
+# => Welcome someone by name
+# =>
+# => Prints a short greeting.
+# =>
+# => Usage:
+# => > welcome.nu {flags}
+# =>
+# => Subcommands:
+# => welcome.nu bye (custom) - Say goodbye instead
+# =>
+# => Flags:
+# => -h, --help: Display the help message for this command
+# => -s, --shout: Print the greeting in capitals
+# =>
+# => Command Type:
+# => > custom
+# =>
+# => Parameters:
+# => name : Who to welcome
+# =>
+# => Input/output types:
+# => ╭───┬───────┬────────╮
+# => │ # │ input │ output │
+# => ├───┼───────┼────────┤
+# => │ 0 │ any │ any │
+# => ╰───┴───────┴────────╯
+```
+
+`nu welcome.nu bye --help` shows the help for the subcommand. The blank line after `# welcome.nu` keeps that comment out of the description, because only the comment lines directly above `def main` count.
+
+Nushell runs the rest of the script before it calls `main`, so code outside any command, such as a top-level `print`, still runs before the help appears. A script without a `main` command has no help to show. It ignores `--help` like any other argument and runs as usual.
+
## Argument Type Interpretation
By default, arguments provided to a script are interpreted with the type `Type::Any`, implying that they are not constrained to a specific data type and can be dynamically interpreted as fitting any of the available data types during script execution.
diff --git a/lang-guide/chapters/custom_commands.md b/lang-guide/chapters/custom_commands.md
index 9f795f2c355..f50eb109e3b 100644
--- a/lang-guide/chapters/custom_commands.md
+++ b/lang-guide/chapters/custom_commands.md
@@ -11,6 +11,7 @@ def []: ->