diff --git a/.vuepress/config.js b/.vuepress/config.js index aabdb72aa70..1114600ff09 100755 --- a/.vuepress/config.js +++ b/.vuepress/config.js @@ -2,6 +2,7 @@ import path from 'path'; import { defineUserConfig } from '@vuepress/cli'; import { gitPlugin } from '@vuepress/plugin-git'; import { feedPlugin } from 'vuepress-plugin-feed2'; +import { shikiPlugin } from '@vuepress/plugin-shiki'; import { defaultTheme } from '@vuepress/theme-default'; import { sitemapPlugin } from 'vuepress-plugin-sitemap2'; import { docsearchPlugin } from '@vuepress/plugin-docsearch'; @@ -139,6 +140,21 @@ export default defineUserConfig({ gitPlugin(), backToTopPlugin(), mediumZoomPlugin(), + shikiPlugin({ + theme: 'dark-plus', + langs: [ + 'nushell', + 'rust', + 'bash', + 'shell', + 'sh', + 'toml', + 'json', + 'python', + 'cpp', + 'powershell', + ], + }), docsearchPlugin({ appId: 'GHCTOYCW6T', indexName: 'nushell', @@ -162,7 +178,7 @@ export default defineUserConfig({ : a.frontmatter.date, b.data.git?.createdTime ? new Date(b.data.git?.createdTime) - : b.frontmatter.date + : b.frontmatter.date, ); }, }), @@ -173,7 +189,7 @@ export default defineUserConfig({ onPrepared: async (app) => { await app.writeTemp( 'pages.js', - `export default ${JSON.stringify(app.pages.map(({ data }) => data))}` + `export default ${JSON.stringify(app.pages.map(({ data }) => data))}`, ); }, }); diff --git a/README.md b/README.md index 33fad2a1463..689a0243f1a 100644 --- a/README.md +++ b/README.md @@ -34,13 +34,13 @@ Nushell is available as [downloadable binaries](https://github.com/nushell/nushe #### macOS / Linux: -```console +```shell $ brew install nushell ``` #### Windows: -```console +```shell $ winget install nushell ``` diff --git a/book/3rdpartyprompts.md b/book/3rdpartyprompts.md index bd9eec51fc4..5e6f9784fd6 100644 --- a/book/3rdpartyprompts.md +++ b/book/3rdpartyprompts.md @@ -21,9 +21,9 @@ If you like [oh-my-posh](https://ohmyposh.dev/), you can use oh-my-posh with Nus 3. Generate the .oh-my-posh.nu file. By default it will be generated to your home directory. You can use `--config` to specify a theme, other wise, oh-my-posh comes with a default theme. 4. Initialize oh-my-posh prompt by adding in ~/.config/nushell/config.nu(or the path output by `$nu.config-path`) to source ~/.oh-my-posh.nu. -```shell +```nu # Generate the .oh-my-posh.nu file -> oh-my-posh init nu --config ~/.poshthemes/M365Princess.omp.json +> oh-my-posh init nu --config ~/.poshthemes/M365Princess.omp.json # Initialize oh-my-posh.nu at shell startup by adding this line in your config.nu file > source ~/.oh-my-posh.nu @@ -35,7 +35,7 @@ For MacOS users: 2. Download and install a [nerd font](https://github.com/ryanoasis/nerd-fonts). 3. Set the PROMPT_COMMAND in the file output by `$nu.config-path`, here is a code snippet: -```shell +```nu let posh_dir = (brew --prefix oh-my-posh | str trim) let posh_theme = $'($posh_dir)/share/oh-my-posh/themes/' # Change the theme names to: zash/space/robbyrussel/powerline/powerlevel10k_lean/ @@ -58,7 +58,7 @@ $env.PROMPT_INDICATOR = $"(ansi y)$> (ansi reset)" Here's an example config section for Starship: -``` +```nu $env.STARSHIP_SHELL = "nu" def create_left_prompt [] { diff --git a/book/aliases.md b/book/aliases.md index 1f952074cbc..f504b0bb300 100644 --- a/book/aliases.md +++ b/book/aliases.md @@ -4,19 +4,19 @@ Aliases in Nushell offer a way of doing a simple replacement of command calls (b For example, let's create an alias called `ll` which will expand to `ls -l`. -``` +```nu > alias ll = ls -l ``` We can now call this alias: -``` +```nu > ll ``` Once we do, it's as if we typed `ls -l`. This also allows us to pass in flags or positional parameters. For example, we can now also write: -``` +```nu > ll -a ``` @@ -31,7 +31,7 @@ Your useable aliases can be seen in `scope aliases` and `help aliases`. To make your aliases persistent they must be added to your _config.nu_ file by running `config nu` to open an editor and inserting them, and then restarting nushell. e.g. with the above `ll` alias, you can add `alias ll = ls -l` anywhere in _config.nu_ -```nushell +```nu $env.config = { # main configuration } @@ -46,7 +46,7 @@ alias ll = ls -l Note that `alias uuidgen = uuidgen | tr A-F a-f` (to make uuidgen on mac behave like linux) won't work. The solution is to define a command without parameters that calls the system program `uuidgen` via `^`. -``` +```nu def uuidgen [] { ^uuidgen | tr A-F a-f } ``` @@ -54,7 +54,7 @@ See more in the [custom commands](custom_commands.md) section of this book. Or a more idiomatic example with nushell internal commands -``` +```nu def lsg [] { ls | sort-by type name -i | grid -c | str trim } ``` diff --git a/book/cheat_sheet.md b/book/cheat_sheet.md index 0808c963c6b..def5666f897 100644 --- a/book/cheat_sheet.md +++ b/book/cheat_sheet.md @@ -2,7 +2,7 @@ ## Data types -```shell +```nu > "12" | into int ``` @@ -10,7 +10,7 @@ --- -```shell +```nu > date now | date to-timezone "Europe/London" ``` @@ -18,7 +18,7 @@ --- -```shell +```nu > {'name': 'nu', 'stars': 5, 'language': 'Python'} | upsert language 'Rust' ``` @@ -26,7 +26,7 @@ --- -```shell +```nu > [one two three] | to yaml ``` @@ -34,7 +34,7 @@ --- -```shell +```nu > [[framework, language]; [Django, Python] [Lavarel, PHP]] ``` @@ -42,7 +42,7 @@ --- -```shell +```nu > [{name: 'Robert' age: 34 position: 'Designer'} {name: 'Margaret' age: 30 position: 'Software Developer'} {name: 'Natalie' age: 50 position: 'Accountant'} @@ -53,7 +53,7 @@ ## Strings -```shell +```nu > let name = "Alice" > $"greetings, ($name)!" ``` @@ -62,7 +62,7 @@ --- -```shell +```nu > let string_list = "one,two,three" | split row "," $string_list @@ -77,7 +77,7 @@ --- -```shell +```nu "Hello, world!" | str contains "o, w" ``` @@ -85,7 +85,7 @@ --- -```shell +```nu let str_list = [zero one two] $str_list | str join ',' ``` @@ -94,7 +94,7 @@ --- -```shell +```nu > 'Hello World!' | str substring 4..8 ``` @@ -102,7 +102,7 @@ --- -```shell +```nu > 'Nushell 0.80' | parse '{shell} {version}' ╭───┬─────────┬─────────╮ @@ -114,13 +114,13 @@ > **parses the string to columns** -```shell +```nu > "acronym,long\nAPL,A Programming Language" | from csv ``` > **parses comma separated values (csv)** -```shell +```nu > $'(ansi purple_bold)This text is a bold purple!(ansi reset)' ``` @@ -128,7 +128,7 @@ ## Lists -```shell +```nu > [foo bar baz] | insert 1 'beeze' ╭───┬───────╮ @@ -143,7 +143,7 @@ --- -```shell +```nu > [1, 2, 3, 4] | update 1 10 ``` @@ -151,7 +151,7 @@ --- -```shell +```nu > let numbers = [1, 2, 3, 4, 5] > $numbers | prepend 0 ``` @@ -160,7 +160,7 @@ --- -```shell +```nu > let numbers = [1, 2, 3, 4, 5] > $numbers | append 6 ``` @@ -169,7 +169,7 @@ --- -```shell +```nu > let flowers = [cammomile marigold rose forget-me-not] > let flowers = ($flowers | first 2) > $flowers @@ -179,7 +179,7 @@ --- -```shell +```nu > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] > $planets | each { |it| $"($it) is a planet of solar system" } ``` @@ -188,7 +188,7 @@ --- -```shell +```nu > $planets | enumerate | each { |it| $"($it.index + 1) - ($it.item)" } ``` @@ -196,7 +196,7 @@ --- -```shell +```nu > let scores = [3 8 4] > $"total = ($scores | reduce { |it, acc| $acc + $it })" ``` @@ -206,7 +206,7 @@ --- -```shell +```nu > $"total = ($scores | reduce --fold 1 { |it, acc| $acc * $it })" ``` @@ -214,7 +214,7 @@ --- -```shell +```nu > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] > $planets.2 > Earth @@ -224,7 +224,7 @@ --- -```shell +```nu > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] > $planets | any {|it| $it | str starts-with "E" } > true @@ -234,7 +234,7 @@ --- -```shell +```nu > let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond ╭───┬────╮ │ 0 │ -1 │ @@ -246,7 +246,7 @@ ## Tables -```shell +```nu > ls | sort-by size ``` @@ -254,7 +254,7 @@ --- -```shell +```nu > ls | sort-by size | first 5 ``` @@ -262,7 +262,7 @@ --- -```shell +```nu > let $a = [[first_column second_column third_column]; [foo bar snooze]] > let $b = [[first_column second_column third_column]; [hex seeze feeze]] > $a | append $b @@ -279,7 +279,7 @@ --- -```shell +```nu > let teams_scores = [[team score plays]; ['Boston Celtics' 311 3] ['Golden State Warriors', 245 2]] > $teams_scores | drop column @@ -295,7 +295,7 @@ ## Files & Filesystem -```shell +```nu > start file.txt ``` @@ -303,7 +303,7 @@ --- -```shell +```nu > 'lorem ipsum ' | save file.txt ``` @@ -311,7 +311,7 @@ --- -```shell +```nu > 'dolor sit amet' | save --append file.txt ``` @@ -319,7 +319,7 @@ --- -```shell +```nu > { a: 1, b: 2 } | save file.json ``` @@ -327,7 +327,7 @@ --- -```shell +```nu > glob **/*.{rs,toml} --depth 2 ``` @@ -335,7 +335,7 @@ --- -```shell +```nu > watch . --glob=**/*.rs {|| cargo test } ``` @@ -345,7 +345,7 @@ ## Custom Commands -```shell +```nu def greet [name: string] { $"hello ($name­)" } @@ -355,7 +355,7 @@ --- -```shell +```nu def greet [name = "nushell"] { $"hello ($name­)" } @@ -365,7 +365,7 @@ --- -```shell +```nu def greet [ name: string --age: int @@ -380,7 +380,7 @@ --- -```shell +```nu def greet [ name: string --age (-a): int @@ -399,7 +399,7 @@ --- -```shell +```nu def greet [...name: string] { print "­hello all:" for $n in $name { @@ -414,7 +414,7 @@ ## Variables & Subexpressions -```shell +```nu > let val = 42 > print $val 42 @@ -424,7 +424,7 @@ --- -```shell +```nu > let val = 42 > do { let val = 101; $val } 101 @@ -436,7 +436,7 @@ --- -```shell +```nu > mut val = 42 > $val += 27 > $val @@ -447,7 +447,7 @@ --- -```shell +```nu > mut x = 0 > [1 2 3] | each { $x += 1 } ``` @@ -455,7 +455,7 @@ > **closures and nested defs cannot capture mutable variables from their enviro­nment. > This expression results in error.** -```shell +```nu > const plugin = 'path/­to/­plugin' > register $plugin ``` @@ -464,7 +464,7 @@ --- -```shell +```nu > let files = (ls) > $files.na­me?.0? ``` @@ -473,7 +473,7 @@ --- -```shell +```nu > let big_files = (ls | where size > 10kb) > $big_files ``` @@ -484,7 +484,7 @@ ## Modules -```shell +```nu > module greetings { export def hello [name: string] { $"hello ($name­)!" @@ -503,7 +503,7 @@ --- -```shell +```nu # greeti­ngs.nu export-env { $env.M­YNAME = "­Arthur, King of the Briton­s" @@ -523,7 +523,7 @@ --- -```shell +```nu # greeti­ngs.nu export def hello [name: string] { $"hello ($name­)!" diff --git a/book/coloring_and_theming.md b/book/coloring_and_theming.md index c8417a23f3b..c3ae96faa11 100644 --- a/book/coloring_and_theming.md +++ b/book/coloring_and_theming.md @@ -12,7 +12,7 @@ Many parts of Nushell's interface can have their color customized. All of these Table borders are controlled by the `$env.config.table.mode` setting in `config.nu`. Here is an example: -```shell +```nu > $env.config = { table: { mode: rounded @@ -268,7 +268,7 @@ This is the current list of primitives. Not all of these are configurable. The c Here's a small example of changing some of these values. -```shell +```nu > let config = { color_config: { separator: purple @@ -293,7 +293,7 @@ Here's a small example of changing some of these values. Here's another small example using multiple color syntaxes with some comments. -```shell +```nu > let config = { color_config: { separator: "#88b719" # this sets only the foreground color like PR #486 @@ -347,7 +347,7 @@ Here's the current list of flat shapes. Here's a small example of how to apply color to these items. Anything not specified will receive the default color. -```shell +```nu > $env.config = { color_config: { shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b} @@ -371,19 +371,19 @@ The Nushell prompt is configurable through these environment variables and confi Example: For a simple prompt one could do this. Note that `PROMPT_COMMAND` requires a `block` whereas the others require a `string`. -```shell +```nu > $env.PROMPT_COMMAND = { build-string (date now | date format '%m/%d/%Y %I:%M:%S%.3f') ': ' (pwd | path basename) } ``` If you don't like the default `PROMPT_INDICATOR` you could change it like this. -```shell +```nu > $env.PROMPT_INDICATOR = "> " ``` If you're using `starship`, you'll most likely want to show the right prompt on the last line of the prompt, just like zsh or fish. You could modify the `config.nu` file, just set `render_right_prompt_on_last_line` to true: -``` +```nu config { render_right_prompt_on_last_line = true ... @@ -400,13 +400,13 @@ Each of the `PROMPT_*` variables has a corresponding `TRANSIENT_PROMPT_*` variab For example, if you want to make past prompts show up without a left prompt entirely and leave only the indicator, you can use: -```shell +```nu > $env.TRANSIENT_PROMPT_COMMAND = "" ``` If you want to go back to the normal left prompt, you'll have to unset `TRANSIENT_PROMPT_COMMAND`: -```shell +```nu > hide-env TRANSIENT_PROMPT_COMMAND ``` @@ -430,7 +430,7 @@ Theming combines all the coloring above. Here's a quick example of one we put to The key to making theming work is to make sure you specify all themes and colors you're going to use in the `config.nu` file _before_ you declare the `let config = ` line. -```shell +```nu # let's define some colors let base00 = "#181818" # Default Background @@ -516,7 +516,7 @@ if you want to go full-tilt on theming, you'll want to theme all the items I men Nushell's default config file contains a light theme definition, if you are working on a light background terminal, you can apply the light theme easily. -```shell +```nu # in $nu.config-path $env.config = { ... @@ -527,7 +527,7 @@ $env.config = { You can just change it to light theme by replacing `$dark_theme` to `$light_theme` -```shell +```nu # in $nu.config-path $env.config = { ... @@ -540,7 +540,7 @@ $env.config = { It's often desired to have the minimum amount of decorations when using a screen reader. In those cases, it's possible to disable borders and other decorations for both table and errors with the following options: -```shell +```nu # in $nu.config-path $env.config = { ... diff --git a/book/command_signature.md b/book/command_signature.md index c296d740836..9d99ef73fe6 100644 --- a/book/command_signature.md +++ b/book/command_signature.md @@ -2,18 +2,18 @@ nu commands contain a signature section, take [`str distance`](/commands/docs/str_distance.md) as example, the signature is like this: -``` +```nu Signatures(Cell paths are supported): | str distance -> ``` The first type name before `|` describes the type of input pipeline. The command name is followed by the required argument type(s) for the command. The output type is `int` and given after `->`. - + `(Cell paths are supported)` indicates that you can provide cell paths for `str distance` to apply an operation at the given cell path(s) in a nested structure or table, and replace the column or field with the result, like: `ls | str distance 'nushell' 'name'` Here is another one example, [`str join`](/commands/docs/str_join.md): -``` +```nu Signatures: list | str join -> ``` diff --git a/book/configuration.md b/book/configuration.md index a7cba2db451..99e3ffca525 100644 --- a/book/configuration.md +++ b/book/configuration.md @@ -9,7 +9,7 @@ Nushell uses a configuration system that loads and runs two Nushell script files You can check where Nushell is reading these config files from by calling `$nu.env-path` and `$nu.config-path`. -``` +```nu > $nu.env-path /Users/FirstNameLastName/Library/Application Support/nushell/env.nu ``` @@ -24,7 +24,7 @@ You can browse the default files for default values of environment variables and Nushell's main settings are kept in the `config` environment variable as a record. This record can be created using: -``` +```nu $env.config = { ... } @@ -32,7 +32,7 @@ $env.config = { You can also shadow `$env.config` and update it: -``` +```nu $env.config = ($env.config | upsert ) ``` @@ -42,7 +42,7 @@ By convention, this variable is defined in the `config.nu` file. You can set environment variables for the duration of a Nushell session using the `$env. = ` structure inside the `env.nu` file. For example: -``` +```nu $env.FOO = 'BAR' ``` @@ -96,7 +96,7 @@ This will print out `$env. = ` lines, one for each environment variabl Next, on some distros you'll also need to ensure Nu is in the /etc/shells list: -``` +```sh > cat /etc/shells # /etc/shells: valid login shells /bin/sh @@ -124,7 +124,7 @@ Some tools (e.g. Emacs) rely on an [`open`](/commands/docs/open.md) command to o As Nushell has its own [`open`](/commands/docs/open.md) command which has different semantics and shadows `/usr/bin/open`, these tools will error out when trying to use it. One way to work around this is to define a custom command for Nushell's [`open`](/commands/docs/open.md) and create an alias for the system's [`open`](/commands/docs/open.md) in your `config.nu` file like this: -``` +```nu def nuopen [arg, --raw (-r)] { if $raw { open -r $arg } else { open $arg } } alias open = ^open ``` @@ -136,7 +136,7 @@ For more about escape and `^` see the [chapter about escapes](escaping.md). In Nushell, [the PATH environment variable]() (Path on Windows) is a list of paths. To append a new path to it, you can use `$env. = ` and [`append`](/commands/docs/append.html) in `env.nu`: -``` +```nu $env.PATH = ($env.PATH | split row (char esep) | append '/some/path') ``` @@ -148,7 +148,7 @@ Note the `split row (char esep)` step. We need to add it because in `env.nu`, th [Homebrew](https://brew.sh/) is a popular package manager that often requires PATH configuration. To add it to your Nushell PATH: -``` +```nu # macOS ARM64 (Apple Silicon) $env.PATH = ($env.PATH | split row (char esep) | prepend '/opt/homebrew/bin') diff --git a/book/creating_errors.md b/book/creating_errors.md index 0c1d80b1947..1f63dbe1e17 100644 --- a/book/creating_errors.md +++ b/book/creating_errors.md @@ -9,19 +9,19 @@ You can use the [`error make`](/commands/docs/error_make.md) command to create y First, you can take the span of where the argument is coming from: -``` +```nu let span = (metadata $x).span; ``` Next, you can create an error using the [`error make`](/commands/docs/error_make.md) command. This command takes in a record that describes the error to create: -``` +```nu error make {msg: "this is fishy", label: {text: "fish right here", start: $span.start, end: $span.end } } ``` Together with your custom command, it might look like this: -``` +```nu def my-command [x] { let span = (metadata $x).span; error make { @@ -37,7 +37,7 @@ def my-command [x] { When called with a value, we'll now see an error message returned: -``` +```nu > my-command 100 Error: diff --git a/book/custom_commands.md b/book/custom_commands.md index 61c49b11a15..d1af49b8dce 100644 --- a/book/custom_commands.md +++ b/book/custom_commands.md @@ -6,7 +6,7 @@ This is where custom commands come in. An example definition of a custom command: -```nushell +```nu def greet [name] { ['hello' $name] } @@ -20,7 +20,7 @@ In this definition, we define the `greet` command, which takes a single paramete To run the above, we can call it like we would call built-in commands: -``` +```nu > greet "world" ``` @@ -36,7 +36,7 @@ As we do, we also get output just as we would with built-in commands: ::: tip If you want to generate a single string, you can use the string interpolation syntax to embed $name in it: -```nushell +```nu def greet [name] { $"hello ($name)" } @@ -57,7 +57,7 @@ _Note: It's common practice in Nushell to separate the words of the command with You can also define subcommands to commands using a space. For example, if we wanted to add a new subcommand to [`str`](/commands/docs/str.md), we can create it by naming our subcommand to start with "str ". For example: -```nushell +```nu def "str mycommand" [] { "hello" } @@ -65,13 +65,13 @@ def "str mycommand" [] { Now we can call our custom command as if it were a built-in subcommand of [`str`](/commands/docs/str.md): -``` +```nu > str mycommand ``` Of course, commands with spaces in their names are defined in the same way: -```nushell +```nu def "custom command" [] { "this is a custom command with a space in the name!" } @@ -81,7 +81,7 @@ def "custom command" [] { When defining custom commands, you can name and optionally set the type for each parameter. For example, you can write the above as: -```nushell +```nu def greet [name: string] { $"hello ($name)" } @@ -91,7 +91,7 @@ The types of parameters are optional. Nushell supports leaving them off and trea For example, let's say you wanted to take in an `int` instead: -```nushell +```nu def greet [name: int] { $"hello ($name)" } @@ -140,7 +140,7 @@ The currently accepted types are (as of version 0.65.0): To make a parameter optional and directly provide a default value for it you can provide a default value in the command definition. -```nushell +```nu def greet [name = "nushell"] { $"hello ($name)" } @@ -148,7 +148,7 @@ def greet [name = "nushell"] { You can call this command either without the parameter or with a value to override the default value: -``` +```nu > greet hello nushell > greet world @@ -157,7 +157,7 @@ hello world You can also combine a default value with a [type requirement](#parameter-types): -``` +```nu def congratulate [age: int = 18] { $"Happy birthday! You are ($age) years old now!" } @@ -169,7 +169,7 @@ If you want to check if an optional parameter is present or not and not just rel By default, positional parameters are required. If a positional parameter is not passed, we will encounter an error: -``` +```nu × Missing required positional argument. ╭─[entry #23:1:1] 1 │ greet @@ -181,7 +181,7 @@ By default, positional parameters are required. If a positional parameter is not We can instead mark a positional parameter as optional by putting a question mark (`?`) after its name. For example: -```nushell +```nu def greet [name?: string] { $"hello ($name)" } @@ -193,7 +193,7 @@ Making a positional parameter optional does not change its name when accessed in When an optional parameter is not passed, its value in the command body is equal to `null`. We can use this to act on the case where a parameter was not passed: -```nushell +```nu def greet [name?: string] { if ($name == null) { "hello, I don't know your name!" @@ -215,7 +215,7 @@ In addition to passing positional parameters, you can also pass named parameters For example: -```nushell +```nu def greet [ name: string --age: int @@ -228,19 +228,19 @@ In the `greet` definition above, we define the `name` positional parameter as we You can call the above using: -``` +```nu > greet world --age 10 ``` Or: -``` +```nu > greet --age 10 world ``` Or even leave the flag off altogether: -``` +```nu > greet world ``` @@ -248,7 +248,7 @@ Flags can also be defined to have a shorthand version. This allows you to pass a Let's extend the previous example to use a shorthand flag for the `age` value: -```nushell +```nu def greet [ name: string --age (-a): int @@ -261,13 +261,13 @@ _Note:_ Flags are named by their longhand name, so the above example would need Now, we can call this updated definition using the shorthand flag: -``` +```nu > greet -a 10 hello ``` Flags can also be used as basic switches. This means that their presence or absence is taken as an argument for the definition. Extending the previous example: -```nushell +```nu def greet [ name: string --age (-a): int @@ -283,19 +283,19 @@ def greet [ And the definition can be either called as: -``` +```nu > greet -a 10 --twice hello ``` Or just without the switch flag: -``` +```nu > greet -a 10 hello ``` -Flags can contain dashes. They can be accessed by replacing the dash with an underscore: +Flags can contain dashes. They can be accessed by replacing the dash with an underscore: -```nushell +```nu def greet [ name: string --age (-a): int @@ -313,7 +313,7 @@ def greet [ There may be cases when you want to define a command which takes any number of positional arguments. We can do this with a rest parameter, using the following `...` syntax: -```nushell +```nu def greet [...name: string] { print "hello all:" for $n in $name { @@ -328,7 +328,7 @@ We could call the above definition of the `greet` command with any number of arg Rest parameters can be used together with positional parameters: -``` +```nu def greet [vip: string, ...name: string] { print $"hello to our VIP ($vip)" print "and hello to everybody else:" @@ -348,7 +348,7 @@ In order to best help users of your custom commands, you can also document them Taking our previous example: -```nushell +```nu def greet [ name: string --age (-a): int @@ -359,7 +359,7 @@ def greet [ Once defined, we can run `help greet` to get the help information for the command: -``` +```nu Usage: > greet {flags} @@ -375,7 +375,7 @@ You can see the parameter and flag that we defined, as well as the `-h` help fla To improve this help, we can add descriptions to our definition that will show up in the help: -```nushell +```nu # A greeting command that can greet the caller def greet [ name: string # The name of the person to greet @@ -411,13 +411,13 @@ Flags: Custom commands stream their output just like built-in commands. For example, let's say we wanted to refactor this pipeline: -```nushell +```nu > ls | get name ``` Let's move [`ls`](/commands/docs/ls.md) into a command that we've written: -```nushell +```nu def my-ls [] { ls } ``` @@ -440,7 +440,7 @@ Custom commands can also take input from the pipeline, just like other commands. Let's make our own command that doubles every value it receives as input: -```nushell +```nu def double [] { each { |it| 2 * $it } } @@ -448,7 +448,7 @@ def double [] { Now, if we call the above command later in a pipeline, we can see what it does with the input: -``` +```nu > [1 2 3] | double ───┬───── 0 │ 2 @@ -459,7 +459,7 @@ Now, if we call the above command later in a pipeline, we can see what it does w We can also store the input for later use using the `$in` variable: -```nushell +```nu def nullify [...cols] { let start = $in $cols | reduce --fold $start { |col, df| diff --git a/book/custom_completions.md b/book/custom_completions.md index ee8ebe77151..79dbc6e8d17 100644 --- a/book/custom_completions.md +++ b/book/custom_completions.md @@ -8,7 +8,7 @@ There are two parts to a custom command: the command that handles a completion a Let's look at an example: -``` +```nu > def animals [] { ["cat", "dog", "eel" ] } > def my-command [animal: string@animals] { print $animal } >| my-command @@ -27,7 +27,7 @@ You may prefer to keep your custom completions away from the public API for your Let's take the example above and put it into a module: -``` +```nu module commands { def animals [] { ["cat", "dog", "eel" ] @@ -49,7 +49,7 @@ It is possible to pass the context to the custom completion command. This is use Let's apply this concept to the previous example: -``` +```nu module commands { def animals [] { ["cat", "dog", "eel" ] @@ -74,7 +74,7 @@ module commands { Here, the command `animal-names` returns the appropriate list of names. This is because `$context` is a string with where the value is the command that has been typed until now. -``` +```nu >| my-command cat dog eel >| my-command dog @@ -91,7 +91,7 @@ A powerful combination is adding custom completions to [known `extern` commands] If you look closely at the examples in the default config, you'll see this: -``` +```nu export extern "git push" [ remote?: string@"nu-complete git remotes", # the name of the remote refspec?: string@"nu-complete git branches" # the branch / refspec @@ -105,7 +105,7 @@ Custom completions will serve the same role in this example as in the previous e As an alternative to returning a list of strings, a completion function can also return a list of records with a `value` and `description` field. -``` +```nu def my_commits [] { [ { value: "5c2464", description: "Add .gitignore" }, diff --git a/book/dataframes.md b/book/dataframes.md index 6af196a548a..8fb12814be5 100644 --- a/book/dataframes.md +++ b/book/dataframes.md @@ -48,7 +48,7 @@ Feel free to download it if you want to follow these tests. The dataset has 5 columns and 5,429,252 rows. We can check that by using the `dfr ls` command: -```shell +```nu ❯ let df = (dfr open .\Data7602DescendingYearOrder.csv) ❯ dfr ls @@ -61,7 +61,7 @@ The dataset has 5 columns and 5,429,252 rows. We can check that by using the We can have a look at the first lines of the file using [`first`](/commands/docs/first.md): -```shell +```nu ❯ $df | dfr first ╭───┬──────────┬─────────┬──────┬───────────┬──────────╮ │ # │ anzsic06 │ Area │ year │ geo_count │ ec_count │ @@ -72,7 +72,7 @@ We can have a look at the first lines of the file using [`first`](/commands/docs ...and finally, we can get an idea of the inferred data types: -```shell +```nu ❯ $df | dfr dtypes ╭───┬───────────┬───────╮ │ # │ column │ dtype │ @@ -90,7 +90,7 @@ We can have a look at the first lines of the file using [`first`](/commands/docs Let's start by comparing loading times between the various methods. First, we will load the data using Nushell's [`open`](/commands/docs/open.md) command: -```shell +```nu ❯ timeit {open .\Data7602DescendingYearOrder.csv} 30sec 479ms 614us 400ns ``` @@ -108,7 +108,7 @@ df = pd.read_csv("Data7602DescendingYearOrder.csv") And the benchmark for it is: -```shell +```nu ❯ timeit {python load.py} 2sec 91ms 872us 900ns ``` @@ -118,7 +118,7 @@ That is a great improvement, from 30 seconds to 2 seconds. Nicely done, Pandas! Probably we can load the data a bit faster. This time we will use Nushell's `dfr open` command: -```shell +```nu ❯ timeit {dfr open .\Data7602DescendingYearOrder.csv} 601ms 700us 700ns ``` @@ -138,7 +138,7 @@ use a large amount of memory. This may affect the performance of your system while this is being executed. ::: -```shell +```nu ❯ timeit { open .\Data7602DescendingYearOrder.csv | group-by year @@ -164,7 +164,7 @@ print(res) And the result from the benchmark is: -```shell +```nu ❯ timeit {python .\load.py} 1sec 966ms 954us 800ns @@ -176,7 +176,7 @@ To finish the comparison, let's try Nushell dataframes. We are going to put all the operations in one `nu` file, to make sure we are doing similar operations: -```shell +```nu let df = (dfr open Data7602DescendingYearOrder.csv) let res = ($df | dfr group-by year | dfr agg (dfr col geo_count | dfr sum)) $res @@ -184,7 +184,7 @@ $res and the benchmark with dataframes is: -```shell +```nu ❯ timeit {source load.nu} 557ms 658us 500ns @@ -206,7 +206,7 @@ CSV file that will become our sample dataframe that we will be using along with the examples. In your favorite file editor paste the next lines to create out sample csv file. -```csv +``` int_1,int_2,float_1,float_2,first,second,third,word 1,11,0.1,1.0,a,b,c,first 2,12,0.2,1.0,a,b,c,second @@ -226,7 +226,7 @@ the file will be called `test_small.csv`. Now, to read that file as a dataframe use the `dfr open` command like this: -```shell +```nu ❯ let df = (dfr open test_small.csv) ``` @@ -240,7 +240,7 @@ files. To see all the dataframes that are stored in memory you can use -```shell +```nu ❯ dfr ls ╭───┬──────┬─────────┬──────╮ │ # │ name │ columns │ rows │ @@ -255,7 +255,7 @@ information about them. And if you want to see a preview of the loaded dataframe you can send the dataframe variable to the stream -```shell +```nu ❯ $df ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ @@ -286,7 +286,7 @@ can use `$nu.scope.commands | where category =~ dataframe` Let's start with basic aggregations on the dataframe. Let's sum all the columns that exist in `df` by using the `aggregate` command -```shell +```nu ❯ $df | dfr sum ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬──────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ @@ -299,7 +299,7 @@ As you can see, the aggregate function computes the sum for those columns where a sum makes sense. If you want to filter out the text column, you can select the columns you want by using the [`dfr select`](/commands/docs/dfr_select.md) command -```shell +```nu ❯ $df | dfr sum | dfr select int_1 int_2 float_1 float_2 ╭───┬───────┬───────┬─────────┬─────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ @@ -311,7 +311,7 @@ the columns you want by using the [`dfr select`](/commands/docs/dfr_select.md) c You can even store the result from this aggregation as you would store any other Nushell variable -```shell +```nu ❯ let res = ($df | dfr sum | dfr select int_1 int_2 float_1 float_2) ``` @@ -322,7 +322,7 @@ executed command. Note the space between ( and !!. And now we have two dataframes stored in memory -```shell +```nu ❯ dfr ls ╭───┬──────┬─────────┬──────╮ │ # │ name │ columns │ rows │ @@ -355,7 +355,7 @@ int_1,int_2,float_1,float_2,first We use the `dfr open` command to create the new variable -```shell +```nu ❯ let df_a = (dfr open test_small_a.csv) ``` @@ -363,7 +363,7 @@ Now, with the second dataframe loaded in memory we can join them using the column called `int_1` from the left dataframe and the column `int_1` from the right dataframe -```shell +```nu ❯ $df | dfr join $df_a int_1 int_1 ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────┬─────────┬───────────┬───────────┬─────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ int_2_x │ float_1_x │ float_2_x │ first_x │ @@ -384,7 +384,7 @@ as long as they have the same type. For example: -``` +```nu ❯ $df | dfr join $df_a [int_1 first] [int_1 first] ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────┬─────────┬───────────┬───────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ int_2_x │ float_1_x │ float_2_x │ @@ -410,7 +410,7 @@ operations with the same group condition. To create a `GroupBy` object you only need to use the [`dfr_group-by`](/commands/docs/dfr_group-by.md) command -```shell +```nu ❯ let group = ($df | dfr group-by first) ❯ $group ╭─────────────┬──────────────────────────────────────────────╮ @@ -422,7 +422,7 @@ When printing the `GroupBy` object we can see that it is in the background a lazy operation waiting to be completed by adding an aggregation. Using the `GroupBy` we can create aggregations on a column -```shell +```nu ❯ $group | dfr agg (dfr col int_1 | dfr sum) ╭───┬───────┬───────╮ │ # │ first │ int_1 │ @@ -435,7 +435,7 @@ lazy operation waiting to be completed by adding an aggregation. Using the or we can define multiple aggregations on the same or different columns -```shell +```nu ❯ $group | dfr agg [ ∙ (dfr col int_1 | dfr n-unique) ∙ (dfr col int_2 | dfr min) @@ -460,7 +460,7 @@ It is also possible to construct dataframes from basic Nushell primitives, such as integers, decimals, or strings. Let's create a small dataframe using the command `dfr into-df`. -```shell +```nu ❯ let a = ([[a b]; [1 2] [3 4] [5 6]] | dfr into-df) ❯ $a ``` @@ -473,7 +473,7 @@ a dataframe. This will change in the future, as the dataframe feature matures We can append columns to a dataframe in order to create a new variable. As an example, let's append two columns to our mini dataframe `$a` -```shell +```nu ❯ let a2 = ($a | dfr with-column $a.a --name a2 | dfr with-column $a.a --name a3) ❯ $a2 ╭───┬───┬───┬────┬────╮ @@ -489,7 +489,7 @@ Nushell's powerful piping syntax allows us to create new dataframes by taking data from other dataframes and appending it to them. Now, if you list your dataframes you will see in total four dataframes -```shell +```nu ❯ dfr ls ╭───┬───────┬─────────┬──────╮ │ # │ name │ columns │ rows │ @@ -524,7 +524,7 @@ types, such as float, int or string. Let's start our exploration with Series by creating one using the `dfr into-df` command: -```shell +```nu ❯ let new = ([9 8 4] | dfr into-df) ❯ $new ╭───┬───╮ @@ -543,7 +543,7 @@ Series have their own basic operations defined, and they can be used to create other Series. Let's create a new Series by doing some arithmetic on the previously created column. -```shell +```nu ❯ let new_2 = ($new * 3 + 10) ❯ $new_2 ╭───┬────╮ @@ -565,7 +565,7 @@ use `$nu.scope.vars` Let's rename our previous Series so it has a memorable name -```shell +```nu ❯ let new_2 = ($new_2 | dfr rename "0" memorable) ❯ $new_2 ╭───┬───────────╮ @@ -580,7 +580,7 @@ Let's rename our previous Series so it has a memorable name We can also do basic operations with two Series as long as they have the same data type -```shell +```nu ❯ $new - $new_2 ╭───┬─────────────────╮ │ # │ sub_0_memorable │ @@ -593,7 +593,7 @@ data type And we can add them to previously defined dataframes -```shell +```nu ❯ let new_df = ($a | dfr with-column $new --name new_col) ❯ $new_df ╭───┬───┬───┬─────────╮ @@ -608,7 +608,7 @@ And we can add them to previously defined dataframes The Series stored in a Dataframe can also be used directly, for example, we can multiply columns `a` and `b` to create a new Series -```shell +```nu ❯ $new_df.a * $new_df.b ╭───┬─────────╮ │ # │ mul_a_b │ @@ -621,7 +621,7 @@ we can multiply columns `a` and `b` to create a new Series and we can start piping things in order to create new columns and dataframes -```shell +```nu ❯ let $new_df = ($new_df | dfr with-column ($new_df.a * $new_df.b / $new_df.new_col) --name my_sum) ❯ $new_df ╭───┬───┬───┬─────────┬────────╮ @@ -641,7 +641,7 @@ Series have another key use in when working with `DataFrames`, and it is the fac that we can build boolean masks out of them. Let's start by creating a simple mask using the equality operator -```shell +```nu ❯ let mask = ($new == 8) ❯ $mask ╭───┬───────╮ @@ -655,7 +655,7 @@ mask using the equality operator and with this mask we can now filter a dataframe, like this -```shell +```nu ❯ $new_df | dfr filter-with $mask ╭───┬───┬───┬─────────┬────────╮ │ # │ a │ b │ new_col │ my_sum │ @@ -668,7 +668,7 @@ Now we have a new dataframe with only the values where the mask was true. The masks can also be created from Nushell lists, for example: -```shell +```nu ❯ let mask1 = ([true true false] | dfr into-df) ❯ $new_df | dfr filter-with $mask1 ╭───┬───┬───┬─────────┬────────╮ @@ -681,7 +681,7 @@ The masks can also be created from Nushell lists, for example: To create complex masks, we have the `AND` -```shell +```nu ❯ $mask and $mask1 ╭───┬─────────╮ │ # │ and_0_0 │ @@ -694,7 +694,7 @@ To create complex masks, we have the `AND` and `OR` operations -```shell +```nu ❯ $mask or $mask1 ╭───┬────────╮ │ # │ or_0_0 │ @@ -708,7 +708,7 @@ and `OR` operations We can also create a mask by checking if some values exist in other Series. Using the first dataframe that we created we can do something like this -```shell +```nu ❯ let mask3 = ($df | dfr col first | dfr is-in [b c]) ❯ $mask3 ╭──────────┬─────────────────────────────────────────────────────────────────────────────────────────────────╮ @@ -726,7 +726,7 @@ Using the first dataframe that we created we can do something like this and this new mask can be used to filter the dataframe -```shell +```nu ❯ $df | dfr filter-with $mask3 ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ @@ -749,7 +749,7 @@ the value is equal to `a` This is example is not updated to recent Nushell versions. ::: -```shell +```nu ❯ $df | dfr get first | dfr set new --mask ($df.first =~ a) ╭───┬────────╮ │ # │ string │ @@ -774,7 +774,7 @@ list of indices. For example, let's say that we want to get rows 1, 4, and 6 from our original dataframe. With that in mind, we can use the next command to extract that information -```shell +```nu ❯ let indices = ([1 4 6] | dfr into-df) ❯ $df | dfr take $indices ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ @@ -791,7 +791,7 @@ Let's say that we want to extract all rows for the first duplicated element for column `first`. In order to do that, we can use the command `dfr arg-unique` as shown in the next example -```shell +```nu ❯ let indices = ($df | dfr get first | dfr arg-unique) ❯ $df | dfr take $indices ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ @@ -811,7 +811,7 @@ can sort the dataframe by the column `word` The same result could be accomplished using the command [`sort`](/commands/docs/sort.md) ::: -```shell +```nu ❯ let indices = ($df | dfr get word | dfr arg-sort) ❯ $df | dfr take $indices ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ @@ -833,7 +833,7 @@ The same result could be accomplished using the command [`sort`](/commands/docs/ And finally, we can create new Series by setting a new value in the marked indices. Have a look at the next command -```shell +```nu ❯ let indices = ([0 2] | dfr into-df); ❯ $df | dfr get int_1 | dfr set-with-idx 123 --indices $indices ╭───┬───────╮ @@ -863,7 +863,7 @@ command calculates a count of the unique values that exist in a Series. For example, we can use it to count how many occurrences we have in the column `first` -```shell +```nu ❯ $df | dfr get first | dfr value-counts ╭───┬───────┬────────╮ │ # │ first │ counts │ @@ -880,7 +880,7 @@ queries. Continuing with our exploration of `Series`, the next thing that we can do is to only get the unique unique values from a series, like this -```shell +```nu ❯ $df | dfr get first | dfr unique ╭───┬───────╮ │ # │ first │ @@ -895,7 +895,7 @@ Or we can get a mask that we can use to filter out the rows where data is unique or duplicated. For example, we can select the rows for unique values in column `word` -```shell +```nu ❯ $df | dfr filter-with ($df | dfr get word | dfr is-unique) ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬───────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ @@ -907,7 +907,7 @@ in column `word` Or all the duplicated ones -```shell +```nu ❯ $df | dfr filter-with ($df | dfr get word | dfr is-duplicated) ╭───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────────╮ │ # │ int_1 │ int_2 │ float_1 │ float_2 │ first │ second │ third │ word │ @@ -933,7 +933,7 @@ operations. Let's create a small example of a lazy dataframe -```shell +```nu ❯ let a = ([[a b]; [1 a] [2 b] [3 c] [4 d]] | dfr into-lazy) ❯ $a ╭────────────────┬─────────────────────────────────────────────────────────╮ @@ -948,7 +948,7 @@ As you can see, the resulting dataframe is not yet evaluated, it stays as a set of instructions that can be done on the data. If you were to collect that dataframe you would get the next result -```shell +```nu ❯ $a | dfr collect ╭───┬───┬───╮ │ # │ a │ b │ @@ -970,14 +970,14 @@ dataframes. To find all lazy dataframe operations you can use -```shell +```nu $nu.scope.commands | where category =~ lazyframe ``` With your lazy frame defined we can start chaining operations on it. For example this -```shell +```nu ❯ $a | ∙ dfr reverse | ∙ dfr with-column [ @@ -1005,7 +1005,7 @@ frame. When put together they create the whole set of instructions used by the lazy commands to query the data. To list all the commands that generate an expression you can use -```shell +```nu $nu.scope.commands | where category =~ expression ``` @@ -1014,20 +1014,20 @@ will be multiplied by 2 and then it will be aliased to the name `double_a`. In some cases the use of the `dfr col` command can be inferred. For example, using the `dfr select` command we can use only a string -```shell +```nu > $a | dfr select a | dfr collect ``` or the `dfr col` command -```shell +```nu > $a | dfr select (dfr col a) | dfr collect ``` Let's try something more complicated and create aggregations from a lazy dataframe -```shell +```nu ❯ let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | dfr into-lazy ) ❯ $a | ∙ dfr group-by name | @@ -1046,7 +1046,7 @@ dataframe And we could join on a lazy dataframe that hasn't being collected. Let's join the resulting group by to the original lazy frame -```shell +```nu ❯ let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | dfr into-lazy ) ❯ let group = ($a ∙ | dfr group-by name diff --git a/book/environment.md b/book/environment.md index 3f350bb718f..e116f7a1f48 100644 --- a/book/environment.md +++ b/book/environment.md @@ -4,7 +4,7 @@ A common task in a shell is to control the environment that external application You can see the current environment variables in the $env variable: -``` +```nu ~> $env | table -e ╭──────────────────────────────────┬───────────────────────────────────────────╮ │ │ ╭──────┬────────────────────────────────╮ │ @@ -37,13 +37,13 @@ There are several ways to set an environment variable: Using the `$env.VAR = "val"` is the most straightforward method -``` +```nu > $env.FOO = 'BAR' ``` So, if you want to extend the Windows `Path` variable, for example, you could do that as follows. -``` +```nu $env.Path = ($env.Path | prepend 'C:\path\you\want\to\add') ``` @@ -54,7 +54,7 @@ If you want to give it the lowest priority instead, you can use the [`append`](/ If you have more than one environment variable you'd like to set, you can use [`load-env`](/commands/docs/load-env.md) to create a table of name/value pairs and load multiple variables at the same time: -``` +```nu > load-env { "BOB": "FOO", "JAY": "BAR" } ``` @@ -75,7 +75,7 @@ See [Modules](modules.md) for details. Individual environment variables are fields of a record that is stored in the `$env` variable and can be read with `$env.VARIABLE`: -``` +```nu > $env.FOO BAR ``` @@ -86,7 +86,7 @@ When you set an environment variable, it will be available only in the current s Here is a small example to demonstrate the environment scoping: -``` +```nu > $env.FOO = "BAR" > do { $env.FOO = "BAZ" @@ -107,14 +107,14 @@ Therefore, it follows the same rules as other environment variables (for example A common shorthand to set an environment variable once is available, inspired by Bash and others: -``` +```nu > FOO=BAR $env.FOO BAR ``` You can also use [`with-env`](/commands/docs/with-env.html) to do the same thing more explicitly: -``` +```nu > with-env { FOO: BAR } { $env.FOO } BAR ``` @@ -127,7 +127,7 @@ You can also set environment variables at startup so they are available for the To do this, set an environment variable inside [the Nu configuration file](configuration.md). For example: -``` +```nu # In config.nu $env.FOO = 'BAR' ``` @@ -137,7 +137,7 @@ $env.FOO = 'BAR' Due to the scoping rules, any environment variables defined inside a custom command will only exist inside the command's scope. However, a command defined as [`def-env`](/commands/docs/def-env.html) instead of [`def`](/commands/docs/def.html) (it applies also to [`export def`](/commands/docs/export_def.md), see [Modules](modules.md)) will preserve the environment on the caller's side: -``` +```nu > def-env foo [] { $env.FOO = 'BAR' } @@ -159,7 +159,7 @@ The conversion of value -> string is set by the `to_string` field of `ENV_CONVER Let's illustrate the conversions with an example. Put the following in your config.nu: -``` +```nu $env.ENV_CONVERSIONS = { # ... you might have Path and PATH already there, add: FOO : { @@ -171,7 +171,7 @@ $env.ENV_CONVERSIONS = { Now, within a Nushell instance: -``` +```nu > with-env { FOO : 'a-b-c' } { nu } # runs Nushell with FOO env. var. set to 'a-b-c' > $env.FOO @@ -183,13 +183,13 @@ Now, within a Nushell instance: You can see the `$env.FOO` is now a list in a new Nushell instance with the updated config. You can also test the conversion manually by -``` +```nu > do $env.ENV_CONVERSIONS.FOO.from_string 'a-b-c' ``` Now, to test the conversion list -> string, run: -``` +```nu > nu -c '$env.FOO' a-b-c ``` @@ -204,7 +204,7 @@ _(Important! The environment conversion string -> value happens **after** the en You can remove an environment variable only if it was set in the current scope via [`hide-env`](/commands/docs/hide_env.html): -``` +```nu > $env.FOO = 'BAR' ... > hide-env FOO @@ -212,7 +212,7 @@ You can remove an environment variable only if it was set in the current scope v The hiding is also scoped which both allows you to remove an environment variable temporarily and prevents you from modifying a parent environment from within a child scope: -``` +```nu > $env.FOO = 'BAR' > do { hide-env FOO diff --git a/book/escaping.md b/book/escaping.md index d215371ca63..0b819c70ae1 100644 --- a/book/escaping.md +++ b/book/escaping.md @@ -4,13 +4,13 @@ Nu provides a set of commands that you can use across different OSes ("internal" Nu internal command: -``` +```nu > ls ``` Escape to external command: -``` +```nu > ^ls ``` diff --git a/book/externs.md b/book/externs.md index 45bba9d5086..0f8f245e386 100644 --- a/book/externs.md +++ b/book/externs.md @@ -4,7 +4,7 @@ Calling external commands is a fundamental part of using Nushell as a shell (and This is where `extern` comes in. The `extern` keyword allows you to write a full signature for the command that lives outside of Nushell so that you get all the benefits above. If you take a look at the default config, you'll notice that there are a few extern calls in there. Here's one of them: -``` +```nu export extern "git push" [ remote?: string@"nu-complete git remotes", # the name of the remote refspec?: string@"nu-complete git branches" # the branch / refspec @@ -39,7 +39,7 @@ This is where `extern` comes in. The `extern` keyword allows you to write a full You'll notice this gives you all the same descriptive syntax that internal commands do, letting you describe flags, short flags, positional parameters, types, and more. ::: warning Note -A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign. +A Nushell comment that continues on the same line for argument documentation purposes requires a space before the ` #` pound sign. ::: ## Types and custom completions @@ -52,7 +52,7 @@ Both the type (or shape) of the argument and the custom completion tell Nushell Positional parameters can be made optional with a `?` (as seen above) the remaining parameters can be matched with `...` before the parameter name, which will return a list of arguments. -``` +```nu export extern "git add" [ ...pathspecs: glob # … diff --git a/book/hooks.md b/book/hooks.md index 7223d837f21..fae1da3bc7d 100644 --- a/book/hooks.md +++ b/book/hooks.md @@ -27,7 +27,7 @@ The steps to evaluate one line in the REPL mode are as follows: To enable hooks, define them in your [config](configuration.md): -``` +```nu $env.config = { # ...other config... @@ -46,7 +46,7 @@ When you change a directory, the `PWD` environment variable changes and the chan Instead of defining just a single hook per trigger, it is possible to define a **list of hooks** which will run in sequence: -``` +```nu $env.config = { ...other config... @@ -71,7 +71,7 @@ $env.config = { Also, it might be more practical to update the existing config with new hooks, instead of defining the whole config from scratch: -``` +```nu $env.config = ($env.config | upsert hooks { pre_prompt: ... pre_execution: ... @@ -87,7 +87,7 @@ One feature of the hooks is that they preserve the environment. Environment variables defined inside the hook **block** will be preserved in a similar way as [`def-env`](environment.md#defining-environment-from-custom-commands). You can test it with the following example: -``` +```nu > $env.config = ($env.config | upsert hooks { pre_prompt: { $env.SPAM = "eggs" } }) @@ -102,7 +102,7 @@ The hook blocks otherwise follow the general scoping rules, i.e., commands, alia One thing you might be tempted to do is to activate an environment whenever you enter a directory: -``` +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: [ @@ -121,7 +121,7 @@ In this case, you could easily rewrite it as `load-env (if $after == ... { ... } To deal with the above problem, we introduce another way to define a hook -- **a record**: -``` +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: [ @@ -149,7 +149,7 @@ To be able to define commands or aliases, it is possible to define the `code` fi You can think of it as if you typed the string into the REPL and hit Enter. So, the hook from the previous section can be also written as -``` +```nu > $env.config = ($env.config | upsert hooks { pre_prompt: '$env.SPAM = "eggs"' }) @@ -160,7 +160,7 @@ eggs This feature can be used, for example, to conditionally bring in definitions based on the current directory: -``` +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: [ @@ -179,7 +179,7 @@ $env.config = ($env.config | upsert hooks { When defining a hook as a string, the `$before` and `$after` variables are set to the previous and current environment variable value, respectively, similarly to the previous examples: -``` +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: { @@ -195,7 +195,7 @@ $env.config = ($env.config | upsert hooks { An example for PWD env change hook: -``` +```nu $env.config = ($env.config | upsert hooks.env_change.PWD {|config| let val = ($config | get -i hooks.env_change.PWD) @@ -213,7 +213,7 @@ $env.config = ($env.config | upsert hooks.env_change.PWD {|config| This one looks for `test-env.nu` in a directory -``` +```nu $env.config = ($env.config | upsert hooks.env_change.PWD { [ { @@ -244,7 +244,7 @@ The output of external commands is not filtered through `display_output`. This hook can display the output in a separate window, perhaps as rich HTML text. Here is the basic idea of how to do that: -``` +```nu $env.config = ($env.config | upsert hooks { display_output: { to html --partial --no-color | save --raw /tmp/nu-output.html } }) @@ -261,7 +261,7 @@ to send the HTML output to a desired window. The following hook uses the `pkgfile` command, to find which packages commands belong to in _Arch Linux_. -``` +```nu $env.config = { ...other config... diff --git a/book/how_nushell_code_gets_run.md b/book/how_nushell_code_gets_run.md index 81e01da87af..5ca7a130dc1 100644 --- a/book/how_nushell_code_gets_run.md +++ b/book/how_nushell_code_gets_run.md @@ -6,20 +6,20 @@ First, let's give a few example which you might intuitively try but which do not 1. Sourcing a dynamic path -``` +```nu source $"($my_path)/common.nu" ``` 2. Write to a file and source it in a single script -``` +```nu "def abc [] { 1 + 2 }" | save output.nu source "output.nu" ``` 3. Change a directory and source a path within (even though the file exists) -``` +```nu if ('spam/foo.nu' | path exists) { cd spam source-env foo.nu @@ -34,7 +34,7 @@ The underlying reason why all of the above examples won't work is a strict separ Let's start with a simple "hello world" Nushell program: -``` +```nu # hello.nu print "Hello world!" @@ -143,7 +143,7 @@ _Note: The following examples use [`source`](/commands/docs/source.md), but simi ### 1. Sourcing a dynamic path -``` +```nu source $"($my_path)/common.nu" ``` @@ -160,7 +160,7 @@ You can see the process is similar to the `eval` functionality we talked about e To give another perspective, here is why it is helpful to _think of Nushell as a compiled language_. Instead of -``` +```nu let my_path = 'foo' source $"($my_path)/common.nu" ``` @@ -176,7 +176,7 @@ std::string my_path("foo"); or Rust -```rust! +```rust let my_path = "foo"; use format!("{}::common", my_path); ``` @@ -185,7 +185,7 @@ If you've ever written a simple program in any of these languages, you can see t ### 2. Write to a file and source it in a single script -``` +```nu "def abc [] { 1 + 2 }" | save output.nu source "output.nu" ``` @@ -205,7 +205,7 @@ We're asking Nushell to read `output.nu` before it even exists. All the source c (We assume the `spam/foo.nu` file exists.) -``` +```nu if ('spam/foo.nu' | path exists) { cd spam source-env foo.nu @@ -218,13 +218,13 @@ This one is similar to the previous example. `cd spam` changes the directory _du [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) is what happens when you run `nu` without any file. You launch an interactive prompt. By -``` +```nu > some code... ``` we denote a REPL entry followed by pressing Enter. For example -``` +```nu > print "Hello world!" Hello world! @@ -249,14 +249,14 @@ In other words, each REPL invocation is its own separate parse-evaluation sequen To give an example, we showed that -``` +```nu cd spam source-env foo.nu ``` does not work because the directory will be changed _after_ [`source-env`](/commands/docs/source-env.md) attempts to read the file. Running these commands as separate REPL entries, however, works: -``` +```nu > cd spam > source-env foo.nu @@ -281,14 +281,14 @@ While it is impossible to add parsing into the evaluation, we can add _a little One pattern that this unlocks is being able to [`source`](/commands/docs/source.md)/[`use`](/commands/docs/use.md)/etc. a path from a "variable". We've seen that -``` +```nu let some_path = 'foo/common.nu' source $some_path ``` does not work, but we can do the following: -``` +```nu const some_path = 'foo/common.nu' source $some_path ``` @@ -306,7 +306,7 @@ This still does not violate our rule of not having an eval function, because an Also, note the \* in steps 1.1.1. and 1.2.1. The evaluation happening during parsing is very restricted and limited to only a small subset of what is normally allowed during a regular evaluation. For example, the following is not allowed: -``` +```nu const foo_contents = (open foo.nu) ``` diff --git a/book/line_editor.md b/book/line_editor.md index bd755e3bad1..8e67c1079e5 100644 --- a/book/line_editor.md +++ b/book/line_editor.md @@ -16,7 +16,7 @@ mode. For example: -```bash +```nu $env.config = { ... edit_mode: emacs @@ -125,7 +125,7 @@ As mentioned before, Reedline manages and stores all the commands that are edited and sent to Nushell. To configure the max number of records that Reedline should store you will need to adjust this value in your config file: -```bash +```nu $env.config = { ... max_history_size: 1000 @@ -138,7 +138,7 @@ Reedline should store you will need to adjust this value in your config file: Reedline prompt is also highly customizable. In order to construct your perfect prompt, you could define the next environment variables in your config file: -```bash +```nu # Use nushell functions to define your right and left prompt def create_left_prompt [] { let path_segment = ($env.PWD) @@ -166,7 +166,7 @@ functions. You can use simple strings to define them. You can also customize the prompt indicator for the line editor by modifying the next env variables. -```bash +```nu $env.PROMPT_INDICATOR = "〉" $env.PROMPT_INDICATOR_VI_INSERT = ": " $env.PROMPT_INDICATOR_VI_NORMAL = "〉" @@ -187,7 +187,7 @@ For example, let's say that you would like to map the completion menu to the `Ctrl + t` keybinding (default is `tab`). You can add the next entry to your config file. -```bash +```nu $env.config = { ... @@ -249,7 +249,7 @@ The event section of the keybinding entry is where the actions to be performed are defined. In this field you can use either a record or a list of records. Something like this -```bash +```nu ... event: { send: Enter } ... @@ -257,7 +257,7 @@ Something like this or -```bash +```nu ... event: [ { edit: Clear } @@ -272,7 +272,7 @@ single event is sent to the engine. The next keybinding is an example of a series of events sent to the engine. It first clears the prompt, inserts a string and then enters that value -```bash +```nu $env.config = { ... @@ -303,7 +303,7 @@ For that reason there is the `executehostcommand` type of event. The next example does the same as the previous one in a simpler way, sending a single event to the engine -```bash +```nu $env.config = { ... @@ -333,13 +333,13 @@ are all the `EditCommands` that can be processed by the engine. To find all the available options for `send` you can use -```bash +```nu keybindings list | where type == events ``` And the syntax for `send` events is the next one -```bash +```nu ... event: { send: } ... @@ -354,7 +354,7 @@ There are two exceptions to this rule: the `Menu` and `ExecuteHostCommand`. Those two events require an extra field to be complete. The `Menu` needs the name of the menu to be activated (completion_menu or history_menu) -```bash +```nu ... event: { send: menu @@ -366,7 +366,7 @@ name of the menu to be activated (completion_menu or history_menu) and the `ExecuteHostCommand` requires a valid command that will be sent to the engine -```bash +```nu ... event: { send: executehostcommand @@ -389,13 +389,13 @@ The `edit` type is the simplification of the `Edit([])` event. The `event` type simplifies defining complex editing events for the keybindings. To list the available options you can use the next command -```bash +```nu keybindings list | where type == edits ``` The usual syntax for an `edit` is the next one -```bash +```nu ... event: { edit: } ... @@ -406,7 +406,7 @@ Since those edits require an extra value to be fully defined. For example, if we would like to insert a string where the prompt is located, then you will have to use -```bash +```nu ... event: { edit: insertstring @@ -417,7 +417,7 @@ have to use or say you want to move right until the first `S` -```bash +```nu ... event: { edit: moverightuntil @@ -448,7 +448,7 @@ one is successful, the event processing is stopped. The next keybinding represents this case. -```bash +```nu $env.config = { ... @@ -485,7 +485,7 @@ meaning that the `until` event will stop as soon as it reaches the command. For example, the next keybinding will always send a `down` because that event is always successful -```bash +```nu $env.config = { ... @@ -515,7 +515,7 @@ If you want to remove a certain default keybinding without replacing it with a d e.g. to disable screen clearing with `Ctrl + l` for all edit modes -```bash +```nu $env.config = { ... @@ -560,7 +560,7 @@ the line the available command examples. The help menu can be configured by modifying the next parameters -```bash +```nu $env.config = { ... @@ -601,7 +601,7 @@ menu as well. The completion menu by default is accessed by pressing `tab` and it can be configured by modifying these values from the config object: -```bash +```nu $env.config = { ... @@ -639,7 +639,7 @@ chronological order, making it extremely easy to select a previous command. The history menu can be configured by modifying these values from the config object: -```bash +```nu $env.config = { ... @@ -678,7 +678,7 @@ are looking for. Once the menu is activated, anything that you type will be replaced by the selected command from your history. for example, say that you have already typed this -```bash +```nu let a = () ``` @@ -686,7 +686,7 @@ you can place the cursor inside the `()` and activate the menu. You can filter the history by typing key words and as soon as you select an entry, the typed words will be replaced -```bash +```nu let a = (ls | where size > 10MiB) ``` @@ -695,7 +695,7 @@ let a = (ls | where size > 10MiB) Another nice feature of the menu is the ability to quick select something from it. Say you have activated your menu and it looks like this -```bash +```nu > 0: ls | where size > 10MiB 1: ls | where size > 20MiB @@ -737,7 +737,7 @@ true). With that in mind, the desired menu would look like this -```bash +```nu $env.config = { ... @@ -776,7 +776,7 @@ are using it to create records that will be used to populate the menu. The required structure for the record is the next one -```bash +```nu { value: # The value that will be inserted in the buffer description: # Optional. Description that will be display with the selected value @@ -813,7 +813,7 @@ In case you want to change the default way both menus are activated, you can change that by defining new keybindings. For example, the next two keybindings assign the completion and history menu to `Ctrl+t` and `Ctrl+y` respectively -```bash +```nu $env.config = { ... diff --git a/book/loading_data.md b/book/loading_data.md index 1f02d7dd67b..f2ea6e20ea6 100644 --- a/book/loading_data.md +++ b/book/loading_data.md @@ -12,7 +12,7 @@ In a similar way to [`ls`](/commands/docs/ls.md), opening a file type that Nu un If we wanted to check the version of the project we were looking at, we can use the [`get`](/commands/docs/get.md) command. -``` +```nu > open editors/vscode/package.json | get version 1.0.0 ``` @@ -43,7 +43,7 @@ You can thus simply extend the set of supported file types of `open` by creating But what happens if you load a text file that isn't one of these? Let's try it: -``` +```nu > open README.md ``` @@ -57,7 +57,7 @@ Nushell Object Notation (NUON) aims to be for Nushell what JavaScript Object Not That is, NUON code is a valid Nushell code that describes some data structure. For example, this is a valid NUON (example from the [default configuration file](https://github.com/nushell/nushell/blob/main/crates/nu-utils/src/sample_config/default_config.nu)): -``` +```nu { menus: [ # Configuration for default nushell menus @@ -97,7 +97,7 @@ An important part of working with data coming from outside Nu is that it's not a Let's imagine that we're given this data file: -``` +```nu > open people.txt Octavia | Butler | Writer Bob | Ross | Painter @@ -108,7 +108,7 @@ Each bit of data we want is separated by the pipe ('|') symbol, and each person The first thing we want to do when bringing in the file is to work with it a line at a time: -``` +```nu > open people.txt | lines ───┬────────────────────────────── 0 │ Octavia | Butler | Writer @@ -119,7 +119,7 @@ The first thing we want to do when bringing in the file is to work with it a lin We can see that we're working with the lines because we're back into a list. Our next step is to see if we can split up the rows into something a little more useful. For that, we'll use the [`split`](/commands/docs/split.md) command. [`split`](/commands/docs/split.md), as the name implies, gives us a way to split a delimited string. We will use [`split`](/commands/docs/split.md)'s `column` subcommand to split the contents across multiple columns. We tell it what the delimiter is, and it does the rest: -``` +```nu > open people.txt | lines | split column "|" ───┬──────────┬───────────┬─────────── # │ column1 │ column2 │ column3 @@ -132,7 +132,7 @@ We can see that we're working with the lines because we're back into a list. Our That _almost_ looks correct. It looks like there's an extra space there. Let's [`trim`](/commands/docs/str_trim.md) that extra space: -``` +```nu > open people.txt | lines | split column "|" | str trim ───┬─────────┬─────────┬────────── # │ column1 │ column2 │ column3 @@ -145,7 +145,7 @@ That _almost_ looks correct. It looks like there's an extra space there. Let's [ Not bad. The [`split`](/commands/docs/split.md) command gives us data we can use. It also goes ahead and gives us default column names: -``` +```nu > open people.txt | lines | split column "|" | str trim | get column1 ───┬───────── 0 │ Octavia @@ -156,7 +156,7 @@ Not bad. The [`split`](/commands/docs/split.md) command gives us data we can use We can also name our columns instead of using the default names: -``` +```nu > open people.txt | lines | split column "|" first_name last_name job | str trim ───┬────────────┬───────────┬────────── # │ first_name │ last_name │ job @@ -169,7 +169,7 @@ We can also name our columns instead of using the default names: Now that our data is in a table, we can use all the commands we've used on tables before: -``` +```nu > open people.txt | lines | split column "|" first_name last_name job | str trim | sort-by first_name ───┬────────────┬───────────┬────────── # │ first_name │ last_name │ job @@ -188,7 +188,7 @@ There are other commands you can use to work with strings: There is also a set of helper commands we can call if we know the data has a structure that Nu should be able to understand. For example, let's open a Rust lock file: -``` +```nu > open Cargo.lock # This file is automatically @generated by Cargo. # It is not intended for manual editing. @@ -207,7 +207,7 @@ The [`from`](/commands/docs/from.md) command can be used for each of the structu While it's helpful to be able to open a file and immediately work with a table of its data, this is not always what you want to do. To get to the underlying text, the [`open`](/commands/docs/open.md) command can take an optional `--raw` flag: -``` +```nu > open Cargo.toml --raw [package] name = "nu" version = "0.1.3" @@ -220,19 +220,19 @@ license = "MIT" SQLite databases are automatically detected by [`open`](/commands/docs/open.md), no matter what their file extension is. You can open a whole database: -``` +```nu > open foo.db ``` Or [`get`](/commands/docs/get.md) a specific table: -``` +```nu > open foo.db | get some_table ``` Or run any SQL query you like: -``` +```nu > open foo.db | query db "select * from some_table" ``` diff --git a/book/metadata.md b/book/metadata.md index a3c52a5cf18..24f711cdeb6 100644 --- a/book/metadata.md +++ b/book/metadata.md @@ -2,7 +2,7 @@ In using Nu, you may have come across times where you felt like there was something extra going on behind the scenes. For example, let's say that you try to open a file that Nu supports only to forget and try to convert again: -``` +```nu > open Cargo.toml | from toml error: Expected a string from pipeline - shell:1:18 @@ -19,7 +19,7 @@ Values that flow through a pipeline in Nu often have a set of additional informa Let's run the [`open`](/commands/docs/open.md) command again, but this time, we'll look at the tags it gives back: -``` +```nu > metadata (open Cargo.toml) ╭──────┬───────────────────╮ │ span │ {record 2 fields} │ @@ -28,7 +28,7 @@ Let's run the [`open`](/commands/docs/open.md) command again, but this time, we' Currently, we track only the span of where values come from. Let's take a closer look at that: -``` +```nu > metadata (open Cargo.toml) | get span ╭───────┬────────╮ │ start │ 212970 │ diff --git a/book/modules.md b/book/modules.md index e4badc291ce..a9ea53a4aef 100644 --- a/book/modules.md +++ b/book/modules.md @@ -32,7 +32,7 @@ _\*These definitions can also be defined as `main` (see below)._ The simplest (and probably least useful) way to define a module is an "inline" module can be defined like this: -```nushell +```nu module greetings { export def hello [name: string] { $"hello ($name)!" @@ -56,7 +56,7 @@ First, we create a module (put `hello` and `hi` commands into a "bag" called `gr A .nu file can be a module. Just take the contents of the module block from the example above and save it to a file `greetings.nu`. The module name is automatically inferred as the stem of the file ("greetings"). -```nushell +```nu # greetings.nu export def hello [name: string] { @@ -70,7 +70,7 @@ export def hi [where: string] { then -```nushell +```nu > use greetings.nu hello > hello @@ -78,7 +78,7 @@ then The result should be similar as in the previous section. -> **Note** +> **Note** > that the `use greetings.nu hello` call here first implicitly creates the `greetings` module, > then takes `hello` from it. You could also write it as `module greetings.nu`, `use greetings hello`. > Using `module` can be useful if you're not interested in any definitions from the module but want to, @@ -90,7 +90,7 @@ Finally, a directory can be imported as a module. The only condition is that it _In the following examples, `/` is used at the end to denote that we're importing a directory but it is not required._ -```nushell +```nu # greetings/mod.nu export def hello [name: string] { @@ -104,7 +104,7 @@ export def hi [where: string] { then -```nushell +```nu > use greetings/ hello > hello @@ -123,25 +123,25 @@ The import pattern has the following structure `use head members...` where `head Using our `greetings` example: -``` +```nu use greetings ``` imports all symbols prefixed with the `greetings` namespace (can call `greetings hello` and `greetings hi`). -``` +```nu use greetings hello ``` will import the `hello` command directly without any prefix. -``` +```nu use greetings [hello, hi] ``` imports multiple definitions<> directly without any prefix. -``` +```nu use greetings * ``` @@ -151,7 +151,7 @@ will import all names directly without any prefix. Exporting a command called `main` from a module defines a command named as the module. Let's extend our `greetings` example: -```nushell +```nu # greetings.nu export def hello [name: string] { @@ -169,7 +169,7 @@ export def main [] { then -``` +```nu > use greetings.nu > greetings @@ -197,12 +197,12 @@ Submodules are modules inside modules. They are automatically created when you c The difference is that `export module some-module` _only_ adds the module as a submodule, while `export use some-module` _also_ re-exports the submodule's definitions. Since definitions of submodules are available when importing from a module, `export use some-module` is typically redundant, unless you want to re-export its definitions without the namespace prefix. -> **Note** +> **Note** > `module` without `export` defines only a local module, it does not export a submodule. Let's illustrate this with an example. Assume three files: -```nushell +```nu # greetings.nu export def hello [name: string] { @@ -218,7 +218,7 @@ export def main [] { } ``` -```nushell +```nu # animals.nu export def dog [] { @@ -230,7 +230,7 @@ export def cat [] { } ``` -```nushell +```nu # voice.nu export use greetings.nu * @@ -241,7 +241,7 @@ export module animals.nu Then: -``` +```nu > use voice.nu > voice animals dog @@ -267,7 +267,7 @@ As you can see, defining the submodule structure also shapes the command line AP Modules can also define an environment using [`export-env`](/commands/docs/export-env.md): -``` +```nu # greetings.nu export-env { @@ -281,7 +281,7 @@ export def hello [] { When [`use`](/commands/docs/use.md) is evaluated, it will run the code inside the [`export-env`](/commands/docs/export-env.md) block and merge its environment into the current scope: -``` +```nu > use greetings.nu > $env.MYNAME @@ -294,7 +294,7 @@ hello Arthur, King of the Britons! ::: tip You can put a complex code defining your environment without polluting the namespace of the module, for example: -```nushell +```nu def tmp [] { "tmp" } def other [] { "other" } @@ -318,7 +318,7 @@ Like any programming language, Nushell is also a product of a tradeoff and there If you also want to keep your variables in separate modules and export their environment, you could try to [`export use`](/commands/docs/export_use.md) it: -```nushell +```nu # purpose.nu export-env { $env.MYPURPOSE = "to build an empire." @@ -331,7 +331,7 @@ export def greeting_purpose [] { and then use it -```nushell +```nu > use purpose.nu > purpose greeting_purpose @@ -339,7 +339,7 @@ and then use it However, this won't work, because the code inside the module is not _evaluated_, only _parsed_ (only the `export-env` block is evaluated when you call `use purpose.nu`). To export the environment of `greetings.nu`, you need to add it to the `export-env` module: -```nushell +```nu # purpose.nu export-env { use greetings.nu @@ -353,7 +353,7 @@ export def greeting_purpose [] { then -``` +```nu > use purpose.nu > purpose greeting_purpose @@ -377,7 +377,7 @@ This section describes some useful patterns using modules. Anything defined in a module without the [`export`](/commands/docs/export.md) keyword will work only in the module's scope. -```nushell +```nu # greetings.nu use tools/utils.nu generate-prefix # visible only locally (we assume the file exists) @@ -397,7 +397,7 @@ def greetings-helper [greeting: string, subject: string] { then -```nushell +```nu > use greetings.nu * @@ -416,7 +416,7 @@ hi there! Since directories can be imported as submodules and submodules can naturally form subcommands it is easy to build even complex command line applications with a simple file structure. -> **Warning** +> **Warning** > Work In Progress ### Dumping files into directory @@ -429,7 +429,7 @@ A common pattern in traditional shells is dumping and auto-sourcing files from a Now you've set up a directory where you can put your completion files. For example: -``` +```nu # git.nu export extern main [ @@ -463,7 +463,7 @@ We use it in our official virtualenv integration https://github.com/pypa/virtual Another example could be our unofficial Conda module: https://github.com/nushell/nu_scripts/blob/f86a060c10f132407694e9ba0f536bfe3ee51efc/modules/virtual_environments/conda.nu -> **Warning** +> **Warning** > Work In Progress ## Hiding @@ -471,7 +471,7 @@ Another example could be our unofficial Conda module: https://github.com/nushell Any custom command or alias, imported from a module or not, can be "hidden", restoring the previous definition. We do this with the [`hide`](/commands/docs/hide.md) command: -``` +```nu > def foo [] { "foo" } > foo @@ -503,5 +503,5 @@ It can be one of the following: - Hides all of the module's exports, without the prefix -> **Note** +> **Note** > `hide` is not a supported keyword at the root of the module (unlike `def` etc.) diff --git a/book/operators.md b/book/operators.md index e54042e4905..84cde6ae5ba 100644 --- a/book/operators.md +++ b/book/operators.md @@ -43,7 +43,7 @@ Operations are evaluated in the following order (from highest precedence to lowe - Parentheses (`()`) - Exponentiation/Power (`**`) -- Multiply (`*`), Divide (`/`), Integer/Floor Division (`//`), and Modulo (`mod`) +- Multiply (`*`), Divide (`/`), Integer/Floor Division (`//`), and Modulo (`mod`) - Add (`+`) and Subtract (`-`) - Bit shifting (`bit-shl`, `bit-shr`) - Comparison operations (`==`, `!=`, `<`, `>`, `<=`, `>=`), membership tests (`in`, `not-in`, `starts-with`, `ends-with`), regex matching (`=~`, `!~`), and list appending (`++`) @@ -64,7 +64,7 @@ Operations are evaluated in the following order (from highest precedence to lowe Not all operations make sense for all data types. If you attempt to perform an operation on non-compatible data types, you will be met with an error message that should explain what went wrong: -``` +```nu > "spam" - 1 Error: nu::parser::unsupported_operation (link) @@ -90,7 +90,7 @@ The `=~` and `!~` operators provide a convenient way to evaluate [regular expres For example: -```bash +```nu foobarbaz =~ bar # returns true foobarbaz !~ bar # returns false ls | where name =~ ^nu # returns all files whose names start with "nu" @@ -104,19 +104,19 @@ Operators are usually case-sensitive when operating on strings. There are a few 1. In the regular expression operators, specify the `(?i)` case-insensitive mode modifier: -```bash +```nu "FOO" =~ "foo" # returns false "FOO" =~ "(?i)foo" # returns true ``` 2. Use the [`str contains`](/commands/docs/str_contains.md) command's `--insensitive` flag: -```bash +```nu "FOO" | str contains --insensitive "foo" ``` 3. Convert strings to lowercase with [`str downcase`](/commands/docs/str_downcase.md) before comparing: -```bash +```nu ("FOO" | str downcase) == ("Foo" | str downcase) ``` diff --git a/book/overlays.md b/book/overlays.md index 2913ba0a4b0..3c32e81faa9 100644 --- a/book/overlays.md +++ b/book/overlays.md @@ -13,7 +13,7 @@ You should see the default overlay listed there. To create a new overlay, you first need a module: -``` +```nu > module spam { export def foo [] { "foo" @@ -37,7 +37,7 @@ We'll use this module throughout the chapter, so whenever you see `overlay use s To create the overlay, call [`overlay use`](/commands/docs/overlay_use.md): -``` +```nu > overlay use spam > foo @@ -67,7 +67,7 @@ In the following sections, the `>` prompt will be preceded by the name of the la If you don't need the overlay definitions anymore, call [`overlay hide`](/commands/docs/overlay_remove.md): -``` +```nu (spam)> overlay hide spam (zero)> foo @@ -82,7 +82,7 @@ Error: Can't run executable... The overlays are also scoped. Any added overlays are removed at the end of the scope: -``` +```nu (zero)> do { overlay use spam; foo } # overlay is active only inside the block foo @@ -98,7 +98,7 @@ The last way to remove an overlay is to call [`overlay hide`](/commands/docs/ove Any new definition (command, alias, environment variable) is recorded into the last active overlay: -``` +```nu (zero)> overlay use spam (spam)> def eggs [] { "eggs" } @@ -107,7 +107,7 @@ Any new definition (command, alias, environment variable) is recorded into the l Now, the `eggs` command belongs to the `spam` overlay. If we remove the overlay, we can't call it anymore: -``` +```nu (spam)> overlay hide spam (zero)> eggs @@ -116,7 +116,7 @@ Error: Can't run executable... But we can bring it back! -``` +```nu (zero)> overlay use spam (spam)> eggs @@ -130,7 +130,7 @@ This can let you repeatedly swap between different contexts. Sometimes, after adding an overlay, you might not want custom definitions to be added into it. The solution can be to create a new empty overlay that would be used just for recording the custom changes: -``` +```nu (zero)> overlay use spam (spam)> module scratchpad { } @@ -144,7 +144,7 @@ The `eggs` command is added into `scratchpad` while keeping `spam` intact. To make it less verbose, you can use the [`overlay new`](/commands/docs/overlay_new.md) command: -``` +```nu (zero)> overlay use spam (spam)> overlay new scratchpad @@ -160,7 +160,7 @@ The [`overlay use`](/commands/docs/overlay_use.md) command would take all comman However, you might want to keep them as subcommands behind the module's name. That's what `--prefix` is for: -``` +```nu (zero)> module spam { export def foo [] { "foo" } } @@ -177,7 +177,7 @@ Note that this does not apply for environment variables. You can change the name of the added overlay with the `as` keyword: -``` +```nu (zero)> module spam { export def foo [] { "foo" } } (zero)> overlay use spam as eggs @@ -196,7 +196,7 @@ This can be useful if you have a generic script name, such as virtualenv's `acti Sometimes, you might want to remove an overlay, but keep all the custom definitions you added without having to redefine them in the next active overlay: -``` +```nu (zero)> overlay use spam (spam)> def eggs [] { "eggs" } @@ -211,7 +211,7 @@ The `--keep-custom` flag does exactly that. One can also keep a list of environment variables that were defined inside an overlay, but remove the rest, using the `--keep-env` flag: -``` +```nu (zero)> module spam { export def foo [] { "foo" } export-env { $env.FOO = "foo" } @@ -234,7 +234,7 @@ The overlays are arranged as a stack. If multiple overlays contain the same definition, say `foo`, the one from the last active one would take precedence. To bring an overlay to the top of the stack, you can call [`overlay use`](/commands/docs/overlay_use.md) again: -``` +```nu (zero)> def foo [] { "foo-in-zero" } (zero)> overlay use spam diff --git a/book/parallelism.md b/book/parallelism.md index 4bce8c377d1..181c2d711c1 100644 --- a/book/parallelism.md +++ b/book/parallelism.md @@ -12,7 +12,7 @@ Like [`each`](/commands/docs/each.md), [`par-each`](/commands/docs/par-each.md) Let's say you wanted to count the number of files in each sub-directory of the current directory. Using [`each`](/commands/docs/each.md), you could write this as: -``` +```nu > ls | where type == dir | each { |it| { name: $it.name, len: (ls $it.name | length) } } @@ -24,7 +24,7 @@ On your machine, the times may vary. For this machine, it took 21 milliseconds f Now, since this operation can be run in parallel, let's convert the above to parallel by changing [`each`](/commands/docs/each.md) to [`par-each`](/commands/docs/par-each.md): -``` +```nu > ls | where type == dir | par-each { |it| { name: $it.name, len: (ls $it.name | length) } } @@ -34,7 +34,7 @@ On this machine, it now runs in 6ms. That's quite a difference! As a side note: Because [environment variables are scoped](environment.md#scoping), you can use [`par-each`](/commands/docs/par-each.md) to work in multiple directories in parallel (notice the [`cd`](/commands/docs/cd.md) command): -``` +```nu > ls | where type == dir | par-each { |it| { name: $it.name, len: (cd $it.name; ls | length) } } diff --git a/book/pipelines.md b/book/pipelines.md index aa2eab2c98b..97f26f13ffe 100644 --- a/book/pipelines.md +++ b/book/pipelines.md @@ -6,7 +6,7 @@ One of the core designs of Nu is the pipeline, a design idea that traces its roo A pipeline is composed of three parts: the input, the filter, and the output. -``` +```nu > open "Cargo.toml" | inc package.version --minor | save "Cargo_new.toml" ``` @@ -18,7 +18,7 @@ The last command, `save "Cargo_new.toml"`, is an output (sometimes called a "sin The `$in` variable will collect the pipeline into a value for you, allowing you to access the whole stream as a parameter: -```nushell +```nu > [1 2 3] | $in.1 * $in.2 6 ``` @@ -27,7 +27,7 @@ The `$in` variable will collect the pipeline into a value for you, allowing you If a pipeline is getting a bit long for one line, you can enclose it within `(` and `)` to create a subexpression: -```nushell +```nu ( "01/22/2021" | parse "{month}/{day}/{year}" | @@ -41,7 +41,7 @@ Also see [Subexpressions](https://www.nushell.sh/book/variables_and_subexpressio Take this example: -``` +```nu > line1; line2 | line3 ``` @@ -72,13 +72,13 @@ You may have wondered how we see a table if [`ls`](/commands/docs/ls.md) is an i In effect, the command: -``` +```nu > ls ``` And the pipeline: -``` +```nu > ls | table ``` @@ -98,7 +98,7 @@ Are one and the same. 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. For example, you want to find a file named "tutor" under "/usr/share/vim/runtime" and check its ownership -``` +```nu > ls /usr/share/nvim/runtime/ ╭────┬───────────────────────────────────────┬──────┬─────────┬───────────────╮ │ # │ name │ type │ size │ modified │ @@ -117,14 +117,14 @@ For example, you want to find a file named "tutor" under "/usr/share/vim/runtime You decided to use `grep` and [pipe](https://www.nushell.sh/book/pipelines.html) the result to external `^ls` -``` +```nu > ls /usr/share/nvim/runtime/ | get name | ^grep tutor | ^ls -la $in ls: cannot access ''$'\342\224\202'' 32 '$'\342\224\202'' /usr/share/nvim/runtime/tutor '$'\342\224\202\n': No such file or directory ``` What's wrong? Nushell renders lists and tables (by adding a border with characters like `╭`,`─`,`┬`,`╮`) before piping them as text to external commands. If that's not the behavior you want, you must explicitly convert the data to a string before piping it to an external. For example, you can do so with [`to text`](/commands/docs/to_text.md): -``` +```nu > ls /usr/share/nvim/runtime/ | get name | to text | ^grep tutor | tr -d '\n' | ^ls -la $in total 24 drwxr-xr-x@ 5 pengs admin 160 14 Nov 13:12 . @@ -135,6 +135,6 @@ drwxr-xr-x@ 4 pengs admin 128 14 Nov 13:42 en (Actually, for this simple usage you can just use [`find`](/commands/docs/find.md)) -``` +```nu > ls /usr/share/nvim/runtime/ | get name | find tutor | ^ls -al $in ``` diff --git a/book/plugins.md b/book/plugins.md index fd32657a51d..10e896fc034 100644 --- a/book/plugins.md +++ b/book/plugins.md @@ -12,13 +12,13 @@ Please note that the plugin name needs to start with `nu_plugin_`, Nu uses the n Linux+macOS: -``` +```nu > register ./my_plugins/nu_plugin_cool ``` Windows: -``` +```nu > register .\my_plugins\nu_plugin_cool.exe ``` @@ -31,7 +31,7 @@ When [`register`](/commands/docs/register.md) is called: Once registered, the plugin is available as part of your set of commands: -``` +```nu > help commands | where command_type == "plugin" ``` diff --git a/book/scripts.md b/book/scripts.md index b1762b2a7fd..5a55cdd62dd 100644 --- a/book/scripts.md +++ b/book/scripts.md @@ -2,19 +2,19 @@ In Nushell, you can write and run scripts in the Nushell language. To run a script, you can pass it as an argument to the `nu` commandline application: -``` +```nu > nu myscript.nu ``` This will run the script to completion in a new instance of Nu. You can also run scripts inside the _current_ instance of Nu using [`source`](/commands/docs/source.md): -``` +```nu > source myscript.nu ``` Let's look at an example script file: -``` +```nu # myscript.nu def greet [name] { ["hello" $name] @@ -27,7 +27,7 @@ A script file defines the definitions for custom commands as well as the main sc In the above, first `greet` is defined by the Nushell interpreter. This allows us to later call this definition. We could have written the above as: -``` +```nu greet "world" def greet [name] { @@ -47,7 +47,7 @@ After the definitions run, we start at the top of the script file and run each g To better understand how Nushell sees lines of code, let's take a look at an example script: -``` +```nu a b; c | d ``` @@ -60,7 +60,7 @@ Script files can optionally contain a special "main" command. `main` will be run For example: -```bash +```nu # myscript.nu def main [x: int] { @@ -68,7 +68,7 @@ def main [x: int] { } ``` -``` +```nu > nu myscript.nu 100 110 ``` @@ -77,22 +77,22 @@ def main [x: int] { On Linux and macOS you can optionally use a [shebang]() to tell the OS that a file should be interpreted by Nu. For example, with the following in a file named `myscript`: -``` +```nu #!/usr/bin/env nu "Hello World!" ``` -``` +```nu > ./myscript Hello World! ``` For script to have access to standard input, `nu` should be invoked with `--stdin` flag: -``` +```nu #!/usr/bin/env -S nu --stdin echo $"stdin: ($in)" ``` -``` +```nu > echo "Hello World!" | ./myscript stdin: Hello World! ``` diff --git a/book/shells_in_shells.md b/book/shells_in_shells.md index af952973e88..25a38462fd6 100644 --- a/book/shells_in_shells.md +++ b/book/shells_in_shells.md @@ -6,7 +6,7 @@ While it's common to work in one directory, it can be handy to work in multiple To get started, let's enter a directory: -``` +```nu /home/jonathant/Source/nushell(main)> enter ../book /home/jonathant/Source/book(main)> ls ────┬────────────────────┬──────┬────────┬───────────── @@ -20,7 +20,7 @@ To get started, let's enter a directory: Entering is similar to changing directories (as we saw with the [`cd`](/commands/docs/cd.md) command). This allows you to jump into a directory to work in it. Instead of changing the directory, we now are in two directories. To see this more clearly, we can use the [`shells`](/commands/docs/shells.md) command to list the current directories we have active: -``` +```nu /home/jonathan/Source/book(main)> shells ───┬────────┬────────────┬───────────────────────── # │ active │ name │ path @@ -36,7 +36,7 @@ The [`shells`](/commands/docs/shells.md) command shows us there are three shells We can jump between these shells with the [`n`](/commands/docs/n.md), [`p`](/commands/docs/p.md) and [`g`](/commands/docs/g.md) shortcuts, short for "next", "previous" and "goto": -``` +```nu /home/jonathant/Source/book(main)> n /home/jonathant/Source/nushell(main)> p /home/jonathant/Source/book(main)> g 2 diff --git a/book/stdout_stderr_exit_codes.md b/book/stdout_stderr_exit_codes.md index 27927aa2d6b..a77a0d803a7 100644 --- a/book/stdout_stderr_exit_codes.md +++ b/book/stdout_stderr_exit_codes.md @@ -8,7 +8,7 @@ The first of these important streams is stdout. Stdout is the way that most external apps will send data into the pipeline or to the screen. Data sent by an external app to its stdout is received by Nushell by default if it's part of a pipeline: -``` +```nu > external | str join ``` @@ -22,7 +22,7 @@ Another common stream that external applications often use to print error messag You can force Nushell to do a redirection by using `do { ... } | complete`. For example, if we wanted to call the external above and redirect its stderr, we would write: -``` +```nu > do { external } | complete ``` @@ -32,7 +32,7 @@ Finally, external commands have an "exit code". These codes help give a hint to Nushell tracks the last exit code of the recently completed external in one of two ways. The first way is with the `LAST_EXIT_CODE` environment variable. -``` +```nu > do { external } > $env.LAST_EXIT_CODE ``` @@ -45,7 +45,7 @@ The [`complete`](/commands/docs/complete.md) command allows you to run an extern If we try to run the external `cat` on a file that doesn't exist, we can see what [`complete`](/commands/docs/complete.md) does with the streams, including the redirected stderr: -``` +```nu > do { cat unknown.txt } | complete ╭───────────┬─────────────────────────────────────────────╮ │ stdout │ │ @@ -68,7 +68,7 @@ The [standard library](/book/standard_library.md) has commands to write out mess The log level for output can be set with the `NU_LOG_LEVEL` environment variable: -``` +```nu NU_LOG_LEVEL=DEBUG nu std_log.nu ``` @@ -76,13 +76,13 @@ NU_LOG_LEVEL=DEBUG nu std_log.nu If you want to redirect output to file, you can just type something like this: -``` +```nu cat unknown.txt out> out.log err> err.log ``` If you want to redirect both stdout and stderr to the same file, just type something like this: -``` +```nu cat unknown.txt out+err> log.log ``` @@ -96,7 +96,7 @@ Nushell attempts to convert to text using UTF-8. If at any time the conversion f If you want more control over the decoding of the byte stream, you can use the [`decode`](/commands/docs/decode.md) command. The [`decode`](/commands/docs/decode.md) command can be inserted into the pipeline after the external, or other raw stream-creating command, and will handle decoding the bytes based on the argument you give decode. For example, you could decode shift-jis text this way: -``` +```nu > 0x[8a 4c] | decode shift-jis 貝 ``` diff --git a/book/style_guide.md b/book/style_guide.md index f23fea44623..87a12c6745a 100644 --- a/book/style_guide.md +++ b/book/style_guide.md @@ -24,13 +24,13 @@ treat something like `\n` like the new line character and not a literal slash fo Correct: -```nushell +```nu 'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' ``` Incorrect: -```nushell +```nu # - too many spaces after "|": 2 instead of 1 'Hello, Nushell! This is a gradient.' | ansi gradient --fgstart '0x40c9ff' --fgend '0xe81cff' ``` @@ -67,7 +67,7 @@ Rules: Correct: -```nushell +```nu [[status]; [UP] [UP]] | all {|el| $el.status == UP } [1 2 3 4] | reduce {|it, acc| $it + $acc } [1 2 3 4] | reduce {|it acc| $it + $acc } @@ -80,7 +80,7 @@ Correct: Incorrect: -```nushell +```nu # too many spaces before "|el|": no space is allowed [[status]; [UP] [UP]] | all { |el| $el.status == UP } @@ -129,7 +129,7 @@ Rules: Correct: -```nushell +```nu [[status]; [UP] [UP]] | all {|el| $el.status == UP } @@ -152,8 +152,8 @@ let selectedProfile = (for it in ($credentials | transpose name credentials) { Incorrect: -```nushell -# too many spaces before "|el|": no space is allowed (like in one-line format) +```nu +# too many spaces before "|el|": no space is allowed (like in one-line format) [[status]; [UP] [UP]] | all { |el| # too few "\n" before "}": one "\n" is required $el.status == UP} @@ -165,7 +165,7 @@ Incorrect: { # too many "\n" before "x": one-line format required as no nested lists or record exist - x: 1, + x: 1, y: 2 } diff --git a/book/testing.md b/book/testing.md index d7ed25a9523..49de01ab63e 100644 --- a/book/testing.md +++ b/book/testing.md @@ -6,7 +6,7 @@ The [standard library](standard_library.md) has a unit testing framework to ensu Have a file, called `test_math.nu`: -```nushell +```nu use std assert #[test] @@ -27,7 +27,7 @@ def test_failing [] { Run the tests: -``` +```nu ❯ use std testing run-tests ❯ run-tests INF|2023-04-12T10:42:29.099|Running tests in test_math @@ -58,7 +58,7 @@ Error: The foundation for every assertion is the `std assert` command. If the condition is not true, it makes an error. For example: -``` +```nu ❯ std assert (1 == 2) Error: × Assertion failed. @@ -71,7 +71,7 @@ Error: Optionally, a message can be set to show the intention of the assert command, what went wrong or what was expected: -```nushell +```nu ❯ std assert ($a == 19) $"The lockout code is wrong, received: ($a)" Error: × The lockout code is wrong, received: 13 @@ -86,7 +86,7 @@ There are many assert commands, which behave exactly as the base one with the pr For example this is not so helpful without additional message: -``` +```nu ❯ std assert ($b | str contains $a) Error: × Assertion failed. @@ -99,7 +99,7 @@ Error: While with using `assert str contains`: -``` +```nu ❯ std assert str contains $b $a Error: × Assertion failed. @@ -112,7 +112,7 @@ Error: In general for base `assert` command it is encouraged to always provide the additional message to show what went wrong. If you cannot use any built-in assert command, you can create a custom one with passing the label for [`error make`](/commands/docs/error_make.md) for the `assert` command: -``` +```nu def "assert even" [number: int] { std assert ($number mod 2 == 0) --error-label { start: (metadata $number).span.start, @@ -124,7 +124,7 @@ def "assert even" [number: int] { Then you'll have your detailed custom error message: -``` +```nu ❯ let $a = 13 ❯ assert even $a Error: @@ -157,7 +157,7 @@ The standard library itself is tested with this framework, so you can find many The unit testing framework uses the `log` commands from the standard library to display information, so you can set `NU_LOG_LEVEL` if you want more or less details: -``` +```nu ❯ std run-tests ❯ NU_LOG_LEVEL=DEBUG std run-tests ❯ NU_LOG_LEVEL=WARNING std run-tests diff --git a/book/thinking_in_nu.md b/book/thinking_in_nu.md index 2bcdb452f02..8d2f8f401d0 100644 --- a/book/thinking_in_nu.md +++ b/book/thinking_in_nu.md @@ -8,7 +8,7 @@ So what does it mean to think in Nushell? Here are some common topics that come Nushell is both a programming language and a shell and because of this has its own way of working with files, directories, websites, and more. We've modeled this to work closely with what you may be familiar with other shells. Pipelines work by attaching two commands together: -``` +```nu > ls | length ``` @@ -22,7 +22,7 @@ While it does have these amenities, Nushell isn't bash. The bash way of working, In Nushell, we use the `>` as the greater-than operator. This fits better with the language aspect of Nushell. Instead, you pipe to a command that has the job of saving content: -``` +```nu > "hello" | save output.txt ``` @@ -34,7 +34,7 @@ An important part of Nushell's design and specifically where it differs from man For example, the following doesn't make sense in Nushell, and will fail to execute if run as a script: -``` +```nu "def abc [] { 1 + 2 }" | save output.nu source "output.nu" abc @@ -44,7 +44,7 @@ The [`source`](/commands/docs/source.md) command will grow the source that is co Another common issue is trying to dynamically create the filename to source from: -``` +```nu > source $"($my_path)/common.nu" ``` @@ -62,7 +62,7 @@ You might wonder why Nushell uses immutable variables. Early on in Nushell's dev Just because Nushell variables are immutable doesn't mean things don't change. Nushell makes heavy use of the technique of "shadowing". Shadowing means creating a new variable with the same name as a previously declared variable. For example, say you had an `$x` in scope, and you wanted a new `$x` that was one greater: -``` +```nu let x = $x + 1 ``` @@ -70,13 +70,13 @@ This new `x` is visible to any code that follows this line. Careful use of shado Loop counters are another common pattern for mutable variables and are built into most iterating commands, for example you can get both each item and an index of each item using [`each`](/commands/docs/each.md): -``` +```nu > ls | enumerate | each { |it| $"Number ($it.index) is size ($it.item.size)" } ``` You can also use the [`reduce`](/commands/docs/reduce.md) command to work in the same way you might mutate a variable in a loop. For example, if you wanted to find the largest string in a list of strings, you might do: -``` +```nu > [one, two, three, four, five, six] | reduce {|curr, max| if ($curr | str length) > ($max | str length) { $curr @@ -96,7 +96,7 @@ In Nushell, blocks control their own environment. Changes to the environment are In practice, this lets you write some concise code for working with subdirectories, for example, if you wanted to build each sub-project in the current directory, you could run: -``` +```nu > ls | each { |it| cd $it.name make @@ -107,6 +107,6 @@ The [`cd`](/commands/docs/cd.md) command changes the `PWD` environment variables Having the environment scoped like this makes commands more predictable, easier to read, and when the time comes, easier to debug. Nushell also provides helper commands like [`def-env`](/commands/docs/def-env.md), [`load-env`](/commands/docs/load-env.md), as convenient ways of doing batches of updates to the environment. -*There is one exception here, where [`def-env`](/commands/docs/def-env.md) allows you to create a command that participates in the caller's environment.* +_There is one exception here, where [`def-env`](/commands/docs/def-env.md) allows you to create a command that participates in the caller's environment._ **Thinking in Nushell:** - The coding best practice of no global mutable variables extends to the environment in Nushell. Using the built-in helper commands will let you more easily work with the environment in Nushell. Taking advantage of the fact that environments are scoped to blocks can also help you write more concise scripts and interact with external commands without adding things into a global environment you don't need. diff --git a/book/types_of_data.md b/book/types_of_data.md index 2ff4b66408b..dac08ba1744 100644 --- a/book/types_of_data.md +++ b/book/types_of_data.md @@ -8,7 +8,7 @@ Like many programming languages, Nu models data using a set of simple, and struc The [`describe`](/commands/docs/describe.md) command returns the type of a data value: -```sh +```nu > 42 | describe ``` @@ -37,7 +37,7 @@ The [`describe`](/commands/docs/describe.md) command returns the type of a data Examples of integers (i.e. "round numbers") include 1, 0, -5, and 100. You can parse a string into an integer with the [`into int`](/commands/docs/into_int.md) command -```sh +```nu > "-5" | into int ``` @@ -46,7 +46,7 @@ You can parse a string into an integer with the [`into int`](/commands/docs/into Decimal numbers are numbers with some fractional component. Examples include 1.5, 2.0, and 15.333. You can cast a string into a Decimal with the [`into decimal`](/commands/docs/into_decimal.md) command -```sh +```nu > "1.2" | into decimal ``` @@ -71,7 +71,7 @@ See [Working with strings](working_with_strings.md) and [Handling Strings](https There are just two boolean values: `true` and `false`. Rather than writing the values directly, they often result from a comparison: -```sh +```nu > let mybool = 2 > 1 > $mybool true @@ -110,14 +110,14 @@ Durations represent a length of time. This chart shows all durations currently s You can make fractional durations: -```sh +```nu > 3.14day 3day 3hr 21min ``` And you can do calculations with durations: -```sh +```nu > 30day / 1sec # How many seconds in 30 days? 2592000 ``` @@ -144,7 +144,7 @@ The full list of filesize units are: As with durations, you can make fractional file sizes, and do calculations: -```sh +```nu > 1Gb / 1b 1000000000 > 1Gib / 1b @@ -177,7 +177,7 @@ Binary data, like the data from an image file, is a group of raw bytes. You can write binary as a literal using any of the `0x[...]`, `0b[...]`, or `0o[...]` forms: -```sh +```nu > 0x[1F FF] # Hexadecimal > 0b[1 1010] # Binary > 0o[377] # Octal @@ -193,7 +193,7 @@ Structured data builds from the simple data. For example, instead of a single in Records hold key-value pairs, which associate string keys with various data values. Record syntax is very similar to objects in JSON. However, commas are _not_ required to separate values if Nushell can easily distinguish them! -```sh +```nu > {name: sam rank: 10} ╭──────┬─────╮ │ name │ sam │ @@ -208,7 +208,7 @@ A record is identical to a single row of a table (see below). You can think of a This means that any command that operates on a table's rows _also_ operates on records. For instance, [`insert`](/commands/docs/insert.md), which adds data to each of a table's rows, can be used with records: -```sh +```nu > {x:3 y:1} | insert z 0 ╭───┬───╮ │ x │ 3 │ @@ -221,7 +221,7 @@ This means that any command that operates on a table's rows _also_ operates on r You can iterate over records by first transposing it into a table: -```sh +```nu > {name: sam, rank: 10} | transpose key value ╭───┬──────┬───────╮ │ # │ key │ value │ @@ -233,14 +233,14 @@ You can iterate over records by first transposing it into a table: Accessing records' data is done by placing a `.` before a string, which is usually a bare string: -```sh +```nu > {x:12 y:4}.x 12 ``` However, if a record has a key name that can't be expressed as a bare string, or resembles an integer (see lists, below), you'll need to use more explicit string syntax, like so: -```sh +```nu > {"1":true " ":false}." " false ``` @@ -249,7 +249,7 @@ false Lists are ordered sequences of data values. List syntax is very similar to arrays in JSON. However, commas are _not_ required to separate values if Nushell can easily distinguish them! -```sh +```nu > [sam fred george] ╭───┬────────╮ │ 0 │ sam │ @@ -261,7 +261,7 @@ Lists are ordered sequences of data values. List syntax is very similar to array :::tip Lists are equivalent to the individual columns of tables. You can think of a list as essentially being a "one-column table" (with no column name). Thus, any command which operates on a column _also_ operates on a list. For instance, [`where`](/commands/docs/where.md) can be used with lists: -```sh +```nu > [bell book candle] | where ($it =~ 'b') ╭───┬──────╮ │ 0 │ bell │ @@ -273,14 +273,14 @@ Lists are equivalent to the individual columns of tables. You can think of a lis Accessing lists' data is done by placing a `.` before a bare integer: -```sh +```nu > [a b c].1 b ``` To get a sub-list from a list, you can use the [`range`](/commands/docs/range.md) command: -```sh +```nu > [a b c d e f] | range 1..3 ╭───┬───╮ │ 0 │ b │ @@ -295,7 +295,7 @@ The table is a core data structure in Nushell. As you run commands, you'll see t We can create our own tables similarly to how we create a list. Because tables also contain columns and not just values, we pass in the name of the column values: -```sh +```nu > [[column1, column2]; [Value1, Value2] [Value3, Value4]] ╭───┬─────────┬─────────╮ │ # │ column1 │ column2 │ @@ -307,7 +307,7 @@ We can create our own tables similarly to how we create a list. Because tables a You can also create a table as a list of records, JSON-style: -```sh +```nu > [{name: sam, rank: 10}, {name: bob, rank: 7}] ╭───┬──────┬──────╮ │ # │ name │ rank │ @@ -320,7 +320,7 @@ You can also create a table as a list of records, JSON-style: :::tip Internally, tables are simply **lists of records**. This means that any command which extracts or isolates a specific row of a table will produce a record. For example, `get 0`, when used on a list, extracts the first value. But when used on a table (a list of records), it extracts a record: -```sh +```nu > [{x:12, y:5}, {x:3, y:6}] | get 0 ╭───┬────╮ │ x │ 12 │ @@ -330,7 +330,7 @@ Internally, tables are simply **lists of records**. This means that any command This is true regardless of which table syntax you use: -```sh +```nu [[x,y];[12,5],[3,6]] | get 0 ╭───┬────╮ │ x │ 12 │ @@ -350,7 +350,7 @@ You can access individual rows by number to obtain records: Moreover, you can also access entire columns of a table by name, to obtain lists: -```sh +```nu > [{x:12 y:5} {x:4 y:7} {x:2 y:2}].x ╭───┬────╮ │ 0 │ 12 │ @@ -361,7 +361,7 @@ Moreover, you can also access entire columns of a table by name, to obtain lists Of course, these resulting lists don't have the column names of the table. To remove columns from a table while leaving it as a table, you'll commonly use the [`select`](/commands/docs/select.md) command with column names: -```sh +```nu > [{x:0 y:5 z:1} {x:4 y:7 z:3} {x:2 y:2 z:0}] | select y z ╭───┬───┬───╮ │ # │ y │ z │ @@ -374,7 +374,7 @@ Of course, these resulting lists don't have the column names of the table. To re To remove rows from a table, you'll commonly use the [`select`](/commands/docs/select.md) command with row numbers, as you would with a list: -```sh +```nu > [{x:0 y:5 z:1} {x:4 y:7 z:3} {x:2 y:2 z:0}] | select 1 2 ╭───┬───┬───┬───╮ │ # │ x │ y │ z │ @@ -388,7 +388,7 @@ To remove rows from a table, you'll commonly use the [`select`](/commands/docs/s By default, cell path access will fail if it can't access the requested row or column. To suppress these errors, you can add `?` to a cell path member to mark it as _optional_: -```sh +```nu > [{foo: 123}, {}].foo? ╭───┬─────╮ │ 0 │ 123 │ @@ -439,7 +439,7 @@ Finally, there is `null` (also known as `$nothing`) which is the language's "not You can place `null` at the end of a pipeline to replace the pipeline's output with it, and thus print nothing: -```sh +```nu git checkout featurebranch | null ``` @@ -447,7 +447,7 @@ git checkout featurebranch | null `null` is not the same as the absence of a value! It is possible for a table to be produced that has holes in some of its rows. Attempting to access this value will not produce `null`, but instead cause an error: -```sh +```nu > [{a:1 b:2} {b:1}] ╭───┬────┬───╮ │ # │ a │ b │ diff --git a/book/variables_and_subexpressions.md b/book/variables_and_subexpressions.md index a447f4101d5..67d65dbccd8 100644 --- a/book/variables_and_subexpressions.md +++ b/book/variables_and_subexpressions.md @@ -12,7 +12,7 @@ The simpler of the two evaluation expressions is the variable. During evaluation An immutable variable cannot change its value after declaration. They are declared using the `let` keyword, -``` +```nu > let val = 42 > print $val 42 @@ -20,7 +20,7 @@ An immutable variable cannot change its value after declaration. They are declar However, they can be 'shadowed'. Shadowing means that they are redeclared and their initial value cannot be used anymore within the same scope. -``` +```nu > let val = 42 # declare a variable > do { let val = 101; $val } # in an inner scope, shadow the variable 101 @@ -32,7 +32,7 @@ However, they can be 'shadowed'. Shadowing means that they are redeclared and th A mutable variable is allowed to change its value by assignment. These are declared using the `mut` keyword. -``` +```nu > mut val = 42 > $val += 27 > $val @@ -61,7 +61,7 @@ There are a couple of assignment operators used with mutable variables Closures and nested `def`s cannot capture mutable variables from their environment. For example -``` +```nu # naive method to count number of elements in a list mut x = 0 @@ -98,13 +98,13 @@ It is common for some scripts to declare variables that start with `$`. This is A variable path works by reaching inside of the contents of a variable, navigating columns inside of it, to reach a final value. Let's say instead of `4`, we had assigned a table value: -``` +```nu > let my_value = [[name]; [testuser]] ``` We can use a variable path to evaluate the variable `$my_value` and get the value from the `name` column in a single step: -``` +```nu > $my_value.name.0 testuser ``` @@ -133,7 +133,7 @@ The parentheses contain a pipeline that will run to completion, and the resultin Subexpressions can also be pipelines and not just single commands. If we wanted to get a table of files larger than ten kilobytes, we could use a subexpression to run a pipeline and assign its result to a variable: -``` +```nu > let big_files = (ls | where size > 10kb) > $big_files ───┬────────────┬──────┬──────────┬────────────── @@ -148,13 +148,13 @@ Subexpressions can also be pipelines and not just single commands. If we wanted Subexpressions also support paths. For example, let's say we wanted to get a list of the filenames in the current directory. One way to do this is to use a pipeline: -``` +```nu > ls | get name ``` We can do a very similar action in a single step using a subexpression path: -``` +```nu > (ls).name ``` @@ -164,13 +164,13 @@ It depends on the needs of the code and your particular style which form works b Nushell supports accessing columns in a subexpression using a simple short-hand. You may have already used this functionality before. If, for example, we wanted to only see rows from [`ls`](/commands/docs/ls.md) where the entry is at least ten kilobytes we could write: -``` +```nu > ls | where size > 10kb ``` The `where size > 10kb` is a command with two parts: the command name [`where`](/commands/docs/where.md) and the short-hand expression `size > 10kb`. We say short-hand because `size` here is the shortened version of writing `$it.size`. This could also be written in any of the following ways: -``` +```nu > ls | where $it.size > 10kb > ls | where ($it.size > 10kb) > ls | where {|$x| $x.size > 10kb } diff --git a/book/working_with_lists.md b/book/working_with_lists.md index 2c995802bc0..82440b57a43 100644 --- a/book/working_with_lists.md +++ b/book/working_with_lists.md @@ -10,14 +10,14 @@ For example, `[foo bar baz]` or `[foo, bar, baz]`. You can [`update`](/commands/docs/update.md) and [`insert`](/commands/docs/insert.md) values into lists as they flow through the pipeline, for example let's insert the value `10` into the middle of a list: -```bash +```nu > [1, 2, 3, 4] | insert 2 10 # [1, 2, 10, 3, 4] ``` We can also use [`update`](/commands/docs/update.md) to replace the 2nd element with the value `10`. -```bash +```nu > [1, 2, 3, 4] | update 1 10 # [1, 10, 3, 4] ``` @@ -28,7 +28,7 @@ In addition to [`insert`](/commands/docs/insert.md) and [`update`](/commands/doc For example: -```bash +```nu let colors = [yellow green] let colors = ($colors | prepend red) let colors = ($colors | append purple) @@ -39,7 +39,7 @@ $colors # [black red yellow green purple blue] In case you want to remove items from list, there are many ways. [`skip`](/commands/docs/skip.md) allows you skip first rows from input, while [`drop`](/commands/docs/drop.md) allows you to skip specific numbered rows from end of list. -```bash +```nu let colors = [red yellow green purple] let colors = ($colors | skip 1) let colors = ($colors | drop 2) @@ -48,7 +48,7 @@ $colors # [yellow] We also have [`last`](/commands/docs/last.md) and [`first`](/commands/docs/first.md) which allow you to [`take`](/commands/docs/take.md) from the end or beginning of the list, respectively. -```bash +```nu let colors = [red yellow green purple black magenta] let colors = ($colors | last 3) $colors # [purple black magenta] @@ -56,7 +56,7 @@ $colors # [purple black magenta] And from the beginning of a list, -```bash +```nu let colors = [yellow green purple] let colors = ($colors | first 2) $colors # [yellow green] @@ -68,7 +68,7 @@ To iterate over the items in a list, use the [`each`](/commands/docs/each.md) co of Nu code that specifies what to do to each item. The block parameter (e.g. `|it|` in `{ |it| print $it }`) is the current list item, but the [`enumerate`](/commands/docs/enumerate.md) filter can be used to provide `index` and `item` values if needed. For example: -```bash +```nu let names = [Mark Tami Amanda Jeremy] $names | each { |it| $"Hello, ($it)!" } # Outputs "Hello, Mark!" and three more similar lines. @@ -81,7 +81,7 @@ The [`where`](/commands/docs/where.md) command can be used to create a subset of The following example gets all the colors whose names end in "e". -```bash +```nu let colors = [red orange yellow green blue purple] $colors | where ($it | str ends-with 'e') # The block passed to `where` must evaluate to a boolean. @@ -90,7 +90,7 @@ $colors | where ($it | str ends-with 'e') In this example, we keep only values higher than `7`. -```bash +```nu let scores = [7 10 8 6 7] $scores | where $it > 7 # [10 8] ``` @@ -101,7 +101,7 @@ It uses a block which takes 2 parameters: the current item (conventionally named To change `it` to have `index` and `item` values, use the [`enumerate`](/commands/docs/enumerate.md) filter. For example: -```bash +```nu let scores = [3 8 4] $"total = ($scores | reduce { |it, acc| $acc + $it })" # total = 15 @@ -118,14 +118,14 @@ To access a list item at a given index, use the `$name.index` form where `$name` For example, the second element in the list below can be accessed with `$names.1`. -```bash +```nu let names = [Mark Tami Amanda Jeremy] $names.1 # gives Tami ``` If the index is in some variable `$index` we can use the `get` command to extract the item from the list. -```bash +```nu let names = [Mark Tami Amanda Jeremy] let index = 1 $names | get $index # gives Tami @@ -137,7 +137,7 @@ For example, `[red green blue] | length` outputs `3`. The [`is-empty`](/commands/docs/is-empty.md) command determines whether a string, list, or table is empty. It can be used with lists as follows: -```bash +```nu let colors = [red green blue] $colors | is-empty # false @@ -147,7 +147,7 @@ $colors | is-empty # true The `in` and `not-in` operators are used to test whether a value is in a list. For example: -```bash +```nu let colors = [red green blue] 'blue' in $colors # true 'yellow' in $colors # false @@ -158,7 +158,7 @@ The [`any`](/commands/docs/any.md) command determines if any item in a list matches a given condition. For example: -```bash +```nu # Do any color names end with "e"? $colors | any {|it| $it | str ends-with "e" } # true @@ -176,7 +176,7 @@ The [`all`](/commands/docs/all.md) command determines if every item in a list matches a given condition. For example: -```bash +```nu # Do all color names end with "e"? $colors | all {|it| $it | str ends-with "e" } # false @@ -197,7 +197,7 @@ by adding items in nested lists to the top-level list. This can be called multiple times to flatten lists nested at any depth. For example: -```bash +```nu [1 [2 3] 4 [5 6]] | flatten # [1 2 3 4 5 6] [[1 2] [3 [4 5 [6 7 8]]]] | flatten | flatten | flatten # [1 2 3 4 5 6 7 8] @@ -206,7 +206,7 @@ For example: The [`wrap`](/commands/docs/wrap.md) command converts a list to a table. Each list value will be converted to a separate row with a single column: -```bash +```nu let zones = [UTC CET Europe/Moscow Asia/Yekaterinburg] # Show world clock for selected time zones diff --git a/book/working_with_strings.md b/book/working_with_strings.md index c2b76209212..003142aa900 100644 --- a/book/working_with_strings.md +++ b/book/working_with_strings.md @@ -19,7 +19,7 @@ matches your needs. The simplest string in Nushell is the single-quoted string. This string uses the `'` character to surround some text. Here's the text for hello world as a single-quoted string: -```sh +```nu > 'hello world' hello world > 'The @@ -34,7 +34,7 @@ Single-quoted strings don't do anything to the text they're given, making them i Single-quoted strings, due to not supporting any escapes, cannot contain any single-quote characters themselves. As an alternative, backtick strings using the ` character also exist: -```sh +```nu > `no man's land` no man's land > `no man's @@ -51,7 +51,7 @@ For more complex strings, Nushell also offers double-quoted strings. These strin For example, we could write the text hello followed by a new line and then world, using escape characters and a double-quoted string: -```sh +```nu > "hello\nworld" hello world @@ -76,7 +76,7 @@ Nushell currently supports the following escape characters: Like other shell languages (but unlike most other programming languages) strings consisting of a single 'word' can also be written without any quotes: -```sh +```nu > print hello hello > [hello] | describe @@ -85,7 +85,7 @@ list But be careful - if you use a bare word plainly on the command line (that is, not inside a data structure or used as a command parameter) or inside round brackets `(` `)`, it will be interpreted as an external command: -``` +```nu > hello Error: nu::shell::external_command @@ -100,7 +100,7 @@ Error: nu::shell::external_command Also, many bare words have special meaning in nu, and so will not be interpreted as a string: -``` +```nu > true | describe bool > [true] | describe @@ -125,7 +125,7 @@ So, while bare strings are useful for informal command line usage, when programm You can place the `^` sigil in front of any string (including a variable) to have Nushell execute the string as if it was an external command: -```sh +```nu ^'C:\Program Files\exiftool.exe' > let foo = 'C:\Program Files\exiftool.exe' @@ -138,31 +138,30 @@ You can also use the [`run-external`](/commands/docs/run-external.md) command fo There are various ways to pre, or append strings. If you want to add something to the beginning of each string closures are a good option: -```sh +```nu ['foo', 'bar'] | each {|s| '~/' ++ $s} # ~/foo, ~/bar ['foo', 'bar'] | each {|s| '~/' + $s} # ~/foo, ~/bar ``` You can also use a regex to replace the beginning or end of a string: -```sh +```nu ['foo', 'bar'] | str replace -r '^' '~/'# ~/foo, ~/bar ['foo', 'bar'] | str replace -r '$' '~/'# foo~/, bar~/ ``` If you want to get one string out of the end then `str join` is your friend: -```sh +```nu "hello" | append "world!" | str join " " # hello world! ``` You can also use reduce: -```sh +```nu 1..10 | reduce -f "" {|it, acc| $acc + ($it | into string) + " + "} # 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + ``` - Though in the cases of strings, especially if you don't have to operate on the strings, it's usually easier and more correct (notice the extra + at the end in the example above) to use `str join`. Finally you could also use string interpolation, but that is complex enough that it is covered in it's own subsection below. @@ -175,7 +174,7 @@ String interpolation uses `$" "` and `$' '` as ways to wrap interpolated text. For example, let's say we have a variable called `$name` and we want to greet the name of the person contained in this variable: -```sh +```nu > let name = "Alice" > $"greetings, ($name)" greetings, Alice @@ -187,7 +186,7 @@ String interpolation has both a single-quoted, `$' '`, and a double-quoted, `$" As of version 0.61, interpolated strings support escaping parentheses, so that the `(` and `)` characters may be used in a string without Nushell trying to evaluate what appears between them: -```sh +```nu > $"2 + 2 is (2 + 2) \(you guessed it!)" 2 + 2 is 4 (you guessed it!) ``` @@ -196,7 +195,7 @@ As of version 0.61, interpolated strings support escaping parentheses, so that t The [`split row`](/commands/docs/split_row.md) command creates a list from a string based on a delimiter. -```sh +```nu > "red,green,blue" | split row "," ╭───┬───────╮ │ 0 │ red │ @@ -207,7 +206,7 @@ The [`split row`](/commands/docs/split_row.md) command creates a list from a str The [`split column`](/commands/docs/split_column.md) command will create a table from a string based on a delimiter. This applies generic column names to the table. -```sh +```nu > "red,green,blue" | split column "," ╭───┬─────────┬─────────┬─────────╮ │ # │ column1 │ column2 │ column3 │ @@ -218,7 +217,7 @@ The [`split column`](/commands/docs/split_column.md) command will create a table Finally, the [`split chars`](/commands/docs/split_chars.md) command will split a string into a list of characters. -```sh +```nu > 'aeiou' | split chars ╭───┬───╮ │ 0 │ a │ @@ -235,7 +234,7 @@ Many string functions are subcommands of the [`str`](/commands/docs/str.md) comm For example, you can look if a string contains a particular substring using [`str contains`](/commands/docs/str_contains.md): -```sh +```nu > "hello world" | str contains "o wo" true ``` @@ -246,7 +245,7 @@ true You can trim the sides of a string with the [`str trim`](/commands/docs/str_trim.md) command. By default, the [`str trim`](/commands/docs/str_trim.md) commands trims whitespace from both sides of the string. For example: -```sh +```nu > ' My string ' | str trim My string ``` @@ -257,7 +256,7 @@ To trim a specific character, use `--char ` or `-c ` to sp Here's an example of all the options in action: -```sh +```nu > '=== Nu shell ===' | str trim -r -c '=' === Nu shell ``` @@ -266,7 +265,7 @@ Here's an example of all the options in action: Substrings are slices of a string. They have a startpoint and an endpoint. Here's an example of using a substring: -```sh +```nu > 'Hello World!' | str index-of 'o' 4 > 'Hello World!' | str index-of 'r' @@ -279,7 +278,7 @@ o Wo With the [`fill`](/commands/docs/fill.md) command you can add padding to a string. Padding adds characters to string until it's a certain length. For example: -```sh +```nu > '1234' | fill -a right -c '0' -w 10 0000001234 > '1234' | fill -a left -c '0' -w 10 | str length @@ -290,7 +289,7 @@ With the [`fill`](/commands/docs/fill.md) command you can add padding to a strin This can be done easily with the [`str reverse`](/commands/docs/str_reverse.md) command. -```sh +```nu > 'Nushell' | str reverse llehsuN > ['Nushell' 'is' 'cool'] | str reverse @@ -305,7 +304,7 @@ llehsuN With the [`parse`](/commands/docs/parse.md) command you can parse a string into columns. For example: -```sh +```nu > 'Nushell 0.80' | parse '{shell} {version}' ╭───┬─────────┬─────────╮ │ # │ shell │ version │ @@ -322,7 +321,7 @@ With the [`parse`](/commands/docs/parse.md) command you can parse a string into If a string is known to contain comma-separated, tab-separated or multi-space-separated data, you can use [`from csv`](/commands/docs/from_csv.md), [`from tsv`](/commands/docs/from_tsv.md) or [`from ssv`](/commands/docs/from_ssv.md): -```sh +```nu > "acronym,long\nAPL,A Programming Language" | from csv ╭───┬─────────┬────────────────────────╮ │ # │ acronym │ long │ @@ -350,7 +349,7 @@ In addition to the standard `==` and `!=` operators, a few operators exist for s Those familiar with Bash and Perl will recognise the regex comparison operators: -```sh +```nu > 'APL' =~ '^\w{0,3}$' true > 'FORTRAN' !~ '^\w{0,3}$' @@ -359,7 +358,7 @@ true Two other operators exist for simpler comparisons: -```sh +```nu > 'JavaScript' starts-with 'Java' true > 'OCaml' ends-with 'Caml' @@ -383,7 +382,7 @@ There are multiple ways to convert strings to and from other types. You can color strings with the [`ansi`](/commands/docs/ansi.md) command. For example: -```sh +```nu > $'(ansi purple_bold)This text is a bold purple!(ansi reset)' ``` diff --git a/book/working_with_tables.md b/book/working_with_tables.md index cbfbbd38fa3..5596c0966d9 100644 --- a/book/working_with_tables.md +++ b/book/working_with_tables.md @@ -4,7 +4,7 @@ One of the common ways of seeing data in Nu is through a table. Nu comes with a To start off, let's get a table that we can use: -``` +```nu > ls ───┬───────────────┬──────┬─────────┬──────────── # │ name │ type │ size │ modified @@ -23,7 +23,7 @@ To start off, let's get a table that we can use: We can sort a table by calling the [`sort-by`](/commands/docs/sort-by.md) command and telling it which columns we want to use in the sort. Let's say we wanted to sort our table by the size of the file: -``` +```nu > ls | sort-by size ───┬───────────────┬──────┬─────────┬──────────── # │ name │ type │ size │ modified @@ -44,7 +44,7 @@ We can sort a table by any column that can be compared. For example, we could al We can select data from a table by choosing to select specific columns or specific rows. Let's [`select`](/commands/docs/select.md) a few columns from our table to use: -``` +```nu > ls | select name size ───┬───────────────┬───────── # │ name │ size @@ -61,7 +61,7 @@ We can select data from a table by choosing to select specific columns or specif This helps to create a table that's more focused on what we need. Next, let's say we want to only look at the 5 smallest files in this directory: -``` +```nu > ls | sort-by size | first 5 ───┬──────────────┬──────┬────────┬──────────── # │ name │ type │ size │ modified @@ -78,7 +78,7 @@ You'll notice we first sort the table by size to get to the smallest file, and t You can also [`skip`](/commands/docs/skip.md) rows that you don't want. Let's skip the first two of the 5 rows we returned above: -``` +```nu > ls | sort-by size | first 5 | skip 2 ───┬───────────┬──────┬────────┬──────────── # │ name │ type │ size │ modified @@ -93,7 +93,7 @@ We've narrowed it to three rows we care about. Let's look at a few other commands for selecting data. You may have wondered why the rows of the table are numbers. This acts as a handy way to get to a single row. Let's sort our table by the file name and then pick one of the rows with the [`select`](/commands/docs/select.md) command using its row number: -``` +```nu > ls | sort-by name ───┬───────────────┬──────┬─────────┬──────────── # │ name │ type │ size │ modified @@ -119,7 +119,7 @@ Let's look at a few other commands for selecting data. You may have wondered why So far, we've worked with tables by trimming the table down to only what we need. Sometimes we may want to go a step further and only look at the values in the cells themselves rather than taking a whole column. Let's say, for example, we wanted to only get a list of the names of the files. For this, we use the [`get`](/commands/docs/get.md) command: -``` +```nu > ls | get name ───┬─────────────── 0 │ files.rs @@ -136,7 +136,7 @@ We now have the values for each of the filenames. This might look like the [`select`](/commands/docs/select.md) command we saw earlier, so let's put that here as well to compare the two: -``` +```nu > ls | select name ───┬─────────────── # │ name @@ -182,7 +182,7 @@ $first | append $second If the column names are not identical then additionally columns and values will be created as necessary: -```sh +```nu let first = [[a b]; [1 2]] let second = [[a b]; [3 4]] let second = [[a c]; [3 4]] @@ -198,7 +198,7 @@ $first | append $second | append $third You can also use the `++` operator as an inline replacement for `append`: -```sh +```nu $first ++ $second ++ $third ───┬───┬────┬──── # │ a │ b │ c @@ -243,7 +243,7 @@ We could join all three tables together like this: Or we could use the [`reduce`](/commands/docs/reduce.md) command to dynamically merge all tables: -``` +```nu > [$first $second $third] | reduce {|it, acc| $acc | merge $it } ───┬───┬───┬───┬───┬───┬─── # │ a │ b │ c │ d │ e │ f @@ -256,7 +256,7 @@ Or we could use the [`reduce`](/commands/docs/reduce.md) command to dynamically We can use the [`insert`](/commands/docs/insert.md) command to add a new column to the table. Let's look at an example: -``` +```nu > open rustfmt.toml ─────────┬────── edition │ 2018 @@ -265,7 +265,7 @@ We can use the [`insert`](/commands/docs/insert.md) command to add a new column Let's add a column called "next_edition" with the value 2021: -``` +```nu > open rustfmt.toml | insert next_edition 2021 ──────────────┬────── edition │ 2018 @@ -275,7 +275,7 @@ Let's add a column called "next_edition" with the value 2021: This visual may be slightly confusing, because it looks like what we've just done is add a row. In this case, remember: rows have numbers, columns have names. If it still is confusing, note that appending one more row will make the table render as expected: -``` +```nu > open rustfmt.toml | insert next_edition 2021 | append {edition: 2021 next_edition: 2024} ───┬─────────┬────────────── # │ edition │ next_edition @@ -288,7 +288,7 @@ This visual may be slightly confusing, because it looks like what we've just don Notice that if we open the original file, the contents have stayed the same: -``` +```nu > open rustfmt.toml ─────────┬────── edition │ 2018 @@ -297,7 +297,7 @@ Notice that if we open the original file, the contents have stayed the same: Changes in Nu are functional changes, meaning that they work on values themselves rather than trying to cause a permanent change. This lets us do many different types of work in our pipeline until we're ready to write out the result with any changes we'd like if we choose to. Here we could write out the result using the [`save`](/commands/docs/save.md) command: -``` +```nu > open rustfmt.toml | insert next_edition 2021 | save rustfmt2.toml > open rustfmt2.toml ──────────────┬────── @@ -310,7 +310,7 @@ Changes in Nu are functional changes, meaning that they work on values themselve In a similar way to the [`insert`](/commands/docs/insert.md) command, we can also use the [`update`](/commands/docs/update.md) command to change the contents of a column to a new value. To see it in action let's open the same file: -``` +```nu > open rustfmt.toml ─────────┬────── edition │ 2018 @@ -319,7 +319,7 @@ In a similar way to the [`insert`](/commands/docs/insert.md) command, we can als And now, let's update the edition to point at the next edition we hope to support: -``` +```nu > open rustfmt.toml | update edition 2021 ─────────┬────── edition │ 2021 @@ -332,7 +332,7 @@ You can also use the [`upsert`](/commands/docs/upsert.md) command to insert or u You can use [`move`](/commands/docs/move.md) to move columns in the table. For example, if we wanted to move the "name" column from [`ls`](/commands/docs/ls.md) after the "size" column, we could do: -``` +```nu > ls | move name --after size ╭────┬──────┬─────────┬───────────────────┬──────────────╮ │ # │ type │ size │ name │ modified │ @@ -349,7 +349,7 @@ You can use [`move`](/commands/docs/move.md) to move columns in the table. For e You can also [`rename`](/commands/docs/rename.md) columns in a table by passing it through the rename command. If we wanted to run [`ls`](/commands/docs/ls.md) and rename the columns, we can use this example: -``` +```nu > ls | rename filename filetype filesize date ╭────┬───────────────────┬──────────┬──────────┬──────────────╮ │ # │ filename │ filetype │ filesize │ date │ @@ -366,7 +366,7 @@ You can also [`rename`](/commands/docs/rename.md) columns in a table by passing You can also [`reject`](/commands/docs/reject.md) columns in a table by passing it through the reject command. If we wanted to run [`ls`](/commands/docs/ls.md) and delete the columns, we can use this example: -``` +```nu > ls -l / |reject readonly num_links inode created accessed modified ╭────┬────────┬─────────┬─────────┬───────────┬──────┬───────┬────────╮ │ # │ name │ type │ target │ mode │ uid │ group │ size │ diff --git a/contributor-book/plugins.md b/contributor-book/plugins.md index 975ed550661..dc0c00b8dee 100644 --- a/contributor-book/plugins.md +++ b/contributor-book/plugins.md @@ -282,7 +282,7 @@ This signature tells Nu everything it needs to pass data in and out of the plugi Now let's try simulating an invocation. Above we tested the plugin within Nu by executing the command `"hello" | len` and we got the response `5`. Of course this hides all of the typed data handling that makes Nu so powerful. -```sh +```nu $ echo '{"CallInfo":{"name":"len","call":{"head":{"start":100953,"end":100957},"positional":[],"named":[]},"input":{"Value":{"String":{"val":"hello","span":{"start":100953,"end":100957}}}}}}' | target/release/nu_plugin_len json{"Value":{"Int":{"val":5,"span":{"start":100953,"end":100957}}}} ``` diff --git a/cookbook/README.md b/cookbook/README.md index 4718258cbba..14cf3e073aa 100644 --- a/cookbook/README.md +++ b/cookbook/README.md @@ -10,7 +10,7 @@ where you will find interesting scripts written for Nushell. And if you are looking for cool oneliners like this one -```shell +```nu > (http get https://api.chucknorris.io/jokes/random).value ``` diff --git a/cookbook/direnv.md b/cookbook/direnv.md index 763e243fa28..e19510c6bf4 100644 --- a/cookbook/direnv.md +++ b/cookbook/direnv.md @@ -13,7 +13,7 @@ Configuring direnv to work with nushell requires nushell version 0.66 or later. To make direnv work with nushell the way it does with other shells, we can use the "hooks" functionality: -```shell +```nu $env.config = { hooks: { pre_prompt: [{ || diff --git a/cookbook/files.md b/cookbook/files.md index 70289a04d35..ca011bb20bc 100644 --- a/cookbook/files.md +++ b/cookbook/files.md @@ -11,7 +11,7 @@ Use `help inc` to get more information. Read the file's initial contents -```shell +```nu > open Cargo.toml | get package.version ``` @@ -23,7 +23,7 @@ Make the edit to the version number and save it. _Note: running this command should work but it will reorder the toml file alphabetically by section._ -```shell +```nu > open Cargo.toml | upsert package.version { |p| $p | get package.version | inc --patch } | save Cargo.toml ``` @@ -32,7 +32,7 @@ _none_ View the changes we made to the file. -```shell +```nu > open Cargo.toml | get package.version ``` @@ -57,7 +57,7 @@ Fugazi:In On The Kill Taker:1993 You can parse it into a table. -```shell +```nu > open bands.txt | lines | split column ":" Band Album Year | skip 1 | sort-by Year ``` @@ -77,13 +77,13 @@ Output You can alternatively do this using `parse`. -```shell +```nu open bands.txt | lines | parse "{Band}:{Album}:{Year}" | skip 1 | sort-by Year ``` Or, you can utilize the `headers` command to use the first row as a header row. The only difference would be the headers would match the case of the text file. So, in this case, the headers would be lowercase. -```shell +```nu > open bands.txt | lines | split column ":" | headers | sort-by year ``` @@ -93,7 +93,7 @@ Or, you can utilize the `headers` command to use the first row as a header row. Suppose you would like to check the number of lines the string "Value" appears per file in the nushell project, then sort those files by largest line count. -```shell +```nu > rg -c Value | lines | split column ":" file line_count | into int line_count | sort-by line_count | reverse ``` diff --git a/cookbook/git.md b/cookbook/git.md index 39539b01df1..ed2fc2f07d1 100644 --- a/cookbook/git.md +++ b/cookbook/git.md @@ -10,7 +10,7 @@ Nu can help with common `Git` tasks like removing all local branches which have **Warning**: This command will hard delete the merged branches from your machine. You may want to check the branches selected for deletion by omitting the last git command. -```shell +```nu > git branch --merged | lines | where ($it != "* master" and $it != "* main") | each {|br| git branch -D ($br | str trim) } | str trim ``` @@ -24,7 +24,7 @@ Output Parse formatted commit messages (more details in the parsing git log section) -```shell +```nu > git log --pretty=%h»¦«%aN»¦«%s»¦«%aD | lines | split column "»¦«" sha1 committer desc merged_at | first 10 ``` @@ -54,7 +54,7 @@ Output _Note: the `histogram` command is not yet ported to the latest version_ -```shell +```nu > git log --pretty=%h»¦«%aN»¦«%s»¦«%aD | lines | split column "»¦«" sha1 committer desc merged_at | histogram committer merger | sort-by merger | reverse ``` diff --git a/cookbook/help.md b/cookbook/help.md index f95555418a1..9487b694d5f 100644 --- a/cookbook/help.md +++ b/cookbook/help.md @@ -8,7 +8,7 @@ The `help` command is a good way to become familiar with all that Nu has to offe ### How to see all supported commands: -```shell +```nu > help commands ``` @@ -18,7 +18,7 @@ The `help` command is a good way to become familiar with all that Nu has to offe To find more specific information on a command, use `help `. This works for regular commands (i.e. `http`) and subcommands (i.e. `http get`): -```shell +```nu > help http get ``` diff --git a/cookbook/http.md b/cookbook/http.md index fb986d7243b..85ac9e4fe93 100644 --- a/cookbook/http.md +++ b/cookbook/http.md @@ -6,7 +6,7 @@ title: HTTP ### Fetching JSON from a url -```shell +```nu > http get https://jsonplaceholder.typicode.com/posts | first 5 ``` @@ -62,7 +62,7 @@ An example JSON file, `urls.json`, with the following contents: } ``` -```shell +```nu > open urls.json | get urls | each { |u| http get $u } ``` @@ -93,7 +93,7 @@ Output If you specify the `--raw` flag, you'll see 3 separate json objects, one in each row. -```shell +```nu > open urls.json | get urls | each { |u| http get $u -r } ``` @@ -131,7 +131,7 @@ Output To combine these responses together into a valid JSON array, you can turn the table into json. -```shell +```nu > open urls.json | get urls | each { |u| http get $u } | to json ``` @@ -174,7 +174,7 @@ Making a `post` request to an endpoint with a JSON payload. To make long request } ``` -```shell +```nu > open payload.json | get my_payload | to json | post https://jsonplaceholder.typicode.com/posts $in ``` @@ -192,7 +192,7 @@ Output We can put this all together into a pipeline where we read data, manipulate it, and then send it back to the API. Lets `fetch` a post, `increment` the id, and `post` it back to the endpoint. In this particular example, the test endpoint gives back an arbitrary response which we can't actually mutate. -```shell +```nu > open urls.json | get urls | first | http get $in | upsert id {|item| $item.id | inc} | to json | post https://jsonplaceholder.typicode.com/posts $in ``` diff --git a/cookbook/parsing.md b/cookbook/parsing.md index 798d3991ec8..1d019ee83e0 100644 --- a/cookbook/parsing.md +++ b/cookbook/parsing.md @@ -8,7 +8,7 @@ Nu offers the ability to do some basic parsing. How to parse an arbitrary pattern from a string of text into a multi-column table. -```shell +```nu > cargo search shells --limit 10 | lines | parse "{crate_name} = {version} #{description}" | str trim ``` diff --git a/cookbook/parsing_git_log.md b/cookbook/parsing_git_log.md index 923b1aab67c..3f1308736ed 100644 --- a/cookbook/parsing_git_log.md +++ b/cookbook/parsing_git_log.md @@ -8,13 +8,13 @@ title: Parsing Git Log This `git log` command is interesting but you can't do a lot with it like this. -```shell +```nu > git log ``` Let's make it more parsable -```shell +```nu > git log --pretty="%h|%s|%aN|%aE|%aD" -n 25 ``` @@ -22,7 +22,7 @@ This will work but I've been burnt by this in the past when a pipe `|` gets inje So, let's try again with something that most likely won't show up in commits, `»¦«`. Also, since we're not using a pipe now we don't have to use quotes around the pretty format string. Notice that the output is just a bunch of strings. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 ``` @@ -38,7 +38,7 @@ Ahh, much better. Now that we have the raw data, let's try to parse it with nu. First we need to get it in lines or rows. Notice that the output is now in a table format. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 | lines ``` @@ -61,7 +61,7 @@ That's more like nushell, but it would be nice to have some columns. We used the delimiter `»¦«` specifically so we can create columns so let's use it like this. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 | lines | split column "»¦«" ``` @@ -89,7 +89,7 @@ Yay, for columns! But wait, it would really be nice if those columns had somethi Let's try adding the columns names to `split column` like this. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 | lines | split column "»¦«" commit subject name email date ``` @@ -117,7 +117,7 @@ Ahhh, that looks much better. Hmmm, that date string is a string. If it were a date vs a string it could be used for sorting by date. The way we do that is we have to convert the datetime to a real datetime and update the column. Try this. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} ``` @@ -145,7 +145,7 @@ Now this looks more nu-ish If we want to revert back to a date string we can do something like this with the `nth` command and the `get` command. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 5 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | select 3 | get date | date format | get 0 ``` @@ -156,7 +156,7 @@ Mon, 28 Feb 2022 18:31:53 -0500 Cool! Now that we have a real datetime we can do some interesting things with it like `group-by` or `sort-by` or `where`. Let's try `sort-by` first -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | sort-by date ``` @@ -228,7 +228,7 @@ Let's try `sort-by` first That's neat but what if I want it sorted in the opposite order? Try the `reverse` command and notice the newest commits are at the top. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | sort-by date | reverse ``` @@ -300,7 +300,7 @@ That's neat but what if I want it sorted in the opposite order? Try the `reverse Now let's try `group-by` and see what happens. This is a tiny bit tricky because dates are tricky. When you use `group-by` on dates you have to remember to use the `group-by date` subcommand so it's `group-by date date_column_name`. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime | date format '%Y-%m-%d'} | group-by date ``` @@ -316,7 +316,7 @@ Now let's try `group-by` and see what happens. This is a tiny bit tricky because This would look better if we transpose the data and name the columns -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime | date format '%Y-%m-%d'} | group-by date | transpose date count ``` @@ -334,7 +334,7 @@ This would look better if we transpose the data and name the columns How about `where` now? Show only the records that are less than a year old. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | where ($it.date > ((date now) - 365day)) ``` @@ -407,7 +407,7 @@ How about `where` now? Show only the records that are less than a year old. Or even show me all the commits in the last 7 days. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD -n 25 | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | where ($it.date > ((date now) - 7day)) ``` @@ -479,7 +479,7 @@ Or even show me all the commits in the last 7 days. Now, with the 365 day slice of data, let's `group-by` name where the commits are less than a year old. This table has a lot of columns so it's unreadable. However, if we `group-by` name and `transpose` the table things will look much cleaner. `Pivot` takes rows and turns them into columns or turns columns into rows. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | where ($it.date > ((date now) - 365day)) | group-by name | transpose ``` @@ -516,14 +516,14 @@ error: Unknown column Here's one tip for dealing with this error. We have a `do` command that has an `--ignore_errors` parameter. This is how you'd use it in the above example, if it were giving errors. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD | lines | do -i { split column "»¦«" commit subject name email date } | upsert date {|d| $d.date | into datetime} | where ($it.date > ((date now) - 365day)) | group-by name | transpose ``` Now, back to parsing. What if we throw in the `sort-by` and `reverse` commands for good measure? Also, while we're in there, let's get rid of the `[table 21 rows]` thing too. We do that by using the `length` command on each row of column1. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | where ($it.date > ((date now) - 365day)) | group-by name | transpose | upsert column1 {|c| $c.column1 | length} | sort-by column1 | reverse ``` @@ -549,7 +549,7 @@ What if we throw in the `sort-by` and `reverse` commands for good measure? Also, This is still a lot of data so let's just look at the top 10 and use the `rename` command to name the columns. We could've also provided the column names with the `transpose` command. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | group-by name | transpose | upsert column1 {|c| $c.column1 | length} | sort-by column1 | rename name commits | reverse | first 10 ``` @@ -574,7 +574,7 @@ And there you have it. The top 10 committers and we learned a little bit of pars Here's one last little known command. Perhaps you don't want your table numbered starting with 0. Here's a way to change that with the `table` command. -```shell +```nu > git log --pretty=%h»¦«%s»¦«%aN»¦«%aE»¦«%aD | lines | split column "»¦«" commit subject name email date | upsert date {|d| $d.date | into datetime} | group-by name | transpose | upsert column1 {|c| $c.column1 | length} | sort-by column1 | rename name commits | reverse | first 10 | table -n 1 ``` diff --git a/cookbook/pattern_matching.md b/cookbook/pattern_matching.md index 7dafcfa17ba..4197a1ff2d8 100644 --- a/cookbook/pattern_matching.md +++ b/cookbook/pattern_matching.md @@ -8,7 +8,7 @@ title: Pattern Matching Like many other languages, nu offers a [`match`](https://www.nushell.sh/commands/docs/match.html#frontmatter-title-for-core) keyword. Usually this is used as a slightly more ergonomic version of `if-else` statements if you have many branches -```shell +```nu > [black red yellow green purple blue indigo] | each {|c| match $c { "black" => "classy" @@ -30,7 +30,7 @@ Like many other languages, nu offers a [`match`](https://www.nushell.sh/commands The equivalent in `if-else` statements would be: -```shell +```nu > [black red yellow green purple blue] | each {|c| if ($c == "black") { "classy" @@ -45,7 +45,7 @@ The equivalent in `if-else` statements would be: } ``` -As you can see you can also use command expressions in match statements (in this case used with `|`). Also notice the `_` case at the end, this is called the default arm and is used in case none of the other patterns match. Note also that in the case that cases overlap the first matching pattern will be used (just like with `if-else` statements): +As you can see you can also use command expressions in match statements (in this case used with `|`). Also notice the `_` case at the end, this is called the default arm and is used in case none of the other patterns match. Note also that in the case that cases overlap the first matching pattern will be used (just like with `if-else` statements): ```nu [yellow green] | each {|c| @@ -64,7 +64,7 @@ As you can see you can also use command expressions in match statements (in this You can use the [`describe`](https://www.nushell.sh/commands/docs/describe.html) command to get more info about the types of values. For example: -```sh +```nu {one: 1 two: 2} | describe record diff --git a/cookbook/polars_v_pandas_v_nushell.md b/cookbook/polars_v_pandas_v_nushell.md index 96d432a15a2..0619d169501 100644 --- a/cookbook/polars_v_pandas_v_nushell.md +++ b/cookbook/polars_v_pandas_v_nushell.md @@ -8,11 +8,11 @@ A dataframe example based on https://studioterabyte.nl/en/blog/polars-vs-pandas ## 1. Opening the file and show the shape of the DataFrame -```console +```nu > let df = (dfr open NYCTaxi.csv) ``` -```console +```nu > $df | shape ╭───┬─────────┬─────────╮ │ # │ rows │ columns │ @@ -25,7 +25,7 @@ A dataframe example based on https://studioterabyte.nl/en/blog/polars-vs-pandas ## 2. Opening the file and show the first 5 rows -```console +```nu > $df | first 5 ╭───┬───────────┬───────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬──────────────┬──────────────╮ │ # │ id │ vendor_id │ pickup_dateti │ dropoff_datet │ passenger_cou │ pickup_longit │ pickup_latitu │ dropoff_longi │ dropoff_latit │ store_and_fw │ trip_duratio │ @@ -49,7 +49,7 @@ A dataframe example based on https://studioterabyte.nl/en/blog/polars-vs-pandas ## 3. Opening the file and get the length of all strings in the "id" column -```console +```nu > let ids = ($df | first 5 | get id | str-lengths) > $df | first 5 | append $ids | rename id_x vendor_id_length ╭───┬───────────┬───────────┬──────────────┬──────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────╮ @@ -71,8 +71,10 @@ A dataframe example based on https://studioterabyte.nl/en/blog/polars-vs-pandas │ │ │ │ ime │ time │ ount │ itude │ tude │ gitude │ itude │ wd_flag │ on │ ength │ ╰───┴───────────┴───────────┴──────────────┴──────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────┴─────────────╯ ``` + Here's an alternate approach using `with-column` -```console + +```nu > $df | first 5 | with-column ($df | first 5 | get id | str-lengths) --name vendor_id_length ╭───┬───────────┬───────────┬──────────────┬──────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────┬─────────────╮ │ # │ id │ vendor_id │ pickup_datet │ dropoff_date │ passenger_c │ pickup_long │ pickup_lati │ dropoff_lon │ dropoff_lat │ store_and_f │ trip_durati │ vendor_id_l │ @@ -96,7 +98,7 @@ Here's an alternate approach using `with-column` ## 4. Opening the file and apply a function to the "trip_duration" to divide the number by 60 to go from the second value to a minute value -```console +```nu > $df | first 5 | with-column ((col trip_duration) / 60.0) ╭───┬───────────┬───────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬──────────────┬──────────────╮ │ # │ id │ vendor_id │ pickup_dateti │ dropoff_datet │ passenger_cou │ pickup_longit │ pickup_latitu │ dropoff_longi │ dropoff_latit │ store_and_fw │ trip_duratio │ @@ -117,9 +119,10 @@ Here's an alternate approach using `with-column` │ │ │ │ me │ ime │ nt │ ude │ de │ tude │ ude │ d_flag │ n │ ╰───┴───────────┴───────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴──────────────┴──────────────╯ ``` + ## 5. Opening the file and filtering out all rows with a trip duration shorther than 500 seconds -```console +```nu > $df | filter-with ((col trip_duration) >= 500) | first 5 ╭───┬───────────┬───────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬───────────────┬──────────────┬──────────────╮ │ # │ id │ vendor_id │ pickup_dateti │ dropoff_datet │ passenger_cou │ pickup_longit │ pickup_latitu │ dropoff_longi │ dropoff_latit │ store_and_fw │ trip_duratio │ @@ -140,9 +143,10 @@ Here's an alternate approach using `with-column` │ │ │ │ me │ ime │ nt │ ude │ de │ tude │ ude │ d_flag │ n │ ╰───┴───────────┴───────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴───────────────┴──────────────┴──────────────╯ ``` + ## 6. Opening the file, filtering out all the rows with a "Y" store_and_fwd_flag value, group by ID and calculate the mean duration time -```console +```nu > $df | filter-with ((col store_and_fwd_flag) == "N") | group-by id | agg (col trip_duration | mean) | sort-by id | first 5 ╭───┬───────────┬───────────────╮ │ # │ id │ trip_duration │ @@ -155,4 +159,4 @@ Here's an alternate approach using `with-column` ├───┼───────────┼───────────────┤ │ # │ id │ trip_duration │ ╰───┴───────────┴───────────────╯ -``` \ No newline at end of file +``` diff --git a/cookbook/setup.md b/cookbook/setup.md index 509fcda68db..3a1538f7da1 100644 --- a/cookbook/setup.md +++ b/cookbook/setup.md @@ -15,7 +15,7 @@ In order to configure your path in nushell you'll need to modify your `PATH` env Alternately, if you want to append a folder to your `PATH` environment variable you can do that too using the `append` or `prepend` command like this: -```shell +```nu $env.PATH = ($env.PATH | split row (char esep) | append "some/other/path") ``` @@ -23,7 +23,7 @@ For more detailed instructions, see the documentation about [environment variabl ### How to list your environment variables -```shell +```nu > $env ``` @@ -45,7 +45,7 @@ Output or for a more detailed view, use our new `env` command. -```shell +```nu > env ``` @@ -97,13 +97,13 @@ You should now be able to run `config nu` or `config env` and edit those files e ### How to get a single environment variable's value -```shell +```nu > $env.APPDATA ``` or -```shell +```nu > env | where name == APPDATA ``` diff --git a/cookbook/system.md b/cookbook/system.md index f9e2889830d..6de6d6de887 100644 --- a/cookbook/system.md +++ b/cookbook/system.md @@ -8,7 +8,7 @@ Nu offers many commands that help interface with the filesystem and control your ### View all files in the current directory -```shell +```nu > ls | where type == file ``` @@ -40,7 +40,7 @@ Output ### View all directories in the current directory -```shell +```nu > ls | where type == dir ``` @@ -69,7 +69,7 @@ Output ### Find processes sorted by greatest cpu utilization. -```shell +```nu > ps | where cpu > 0 | sort-by cpu | reverse ``` @@ -91,7 +91,7 @@ Output Sometimes a process doesn't shut down correctly. Using `ps` it's fairly easy to find the pid of this process: -```shell +```nu > ps | where name == Notepad2.exe ``` @@ -107,7 +107,7 @@ Output This process can be sent the kill signal in a one-liner: -```shell +```nu > ps | where name == Notepad2.exe | get pid.0 | kill $in ``` diff --git a/de/book/3rdpartyprompts.md b/de/book/3rdpartyprompts.md index 543cc150572..acafab58c49 100644 --- a/de/book/3rdpartyprompts.md +++ b/de/book/3rdpartyprompts.md @@ -21,7 +21,7 @@ Wenn [oh-my-posh](https://ohmyposh.dev/) verwendet werden soll, kann dies in wen 2. Herunterladen und installieren einer [nerd font](https://github.com/ryanoasis/nerd-fonts). 3. Die Umgebungsvariable `PROMPT_COMMAND` durch hinzufügen der folgenden Zeile in `~/.config/nushell/config.nu` setzen. Den Style `M365Princess.omp.json` kann man entsprechend der [Demo](https://ohmyposh.dev/docs/themes) beliebig ändern . -```shell +```nu > $env.PROMPT_COMMAND = { oh-my-posh --config ~/.poshthemes/M365Princess.omp.json } ``` diff --git a/de/book/coloring_and_theming.md b/de/book/coloring_and_theming.md index 8ea61aeb508..4d3c28ca01c 100644 --- a/de/book/coloring_and_theming.md +++ b/de/book/coloring_and_theming.md @@ -16,7 +16,7 @@ Ein Hashtag in der Konfigurationsdatei kommentiert den danach folgenden Text aus Tabellen Rahmen werden mit der Einstellung `table_mode` in der `config.nu` konfiguriert. Hier ein Beispiel: -```shell +```nu > $env.config = { table_mode: rounded } @@ -272,7 +272,7 @@ Hier die aktuelle Liste von Primitiven Typen. Nicht alle davon sind konfigurierb Hier ein kleines Beispiel, wie diese Werte angewendet werden können. -```shell +```nu > let config = { color_config: { separator: purple @@ -297,7 +297,7 @@ Hier ein kleines Beispiel, wie diese Werte angewendet werden können. Hier ein anderes Beispiel, welches mehrere Farben Schreibweisen sowie Kommentare verwendet. -```shell +```nu > let config = { color_config: { separator: "#88b719" # Dies setzt nur die Vordergrundsfarbe wie in PR #486 @@ -351,7 +351,7 @@ Hier die aktuelle Formen Liste. Hier ein kleines Beispiel wie Farben auf diese Teile angewendet werden. Was nicht spezifiziert wird, erhält die Standardfarbe. -```shell +```nu > $env.config = { color_config: { shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b} @@ -374,13 +374,13 @@ Der Nushell Prompt ist konfigurierbar mit diesen Umgebungsvariablen: Beispiel: Für einen einfachen Prompt wäre folgendes mögllich. Hinweis `PROMPT_COMMAND` benötigt einen `block` wogegen die anderen einen `string` erwarten. -```shell +```nu > $env.PROMPT_COMMAND = { build-string (date now | date format '%m/%d/%Y %I:%M:%S%.3f') ': ' (pwd | path basename) } ``` Soll der standard `PROMPT_INDICATOR` geändert werden, sieht das so aus. -```shell +```nu > $env.PROMPT_INDICATOR = "> " ``` @@ -414,7 +414,7 @@ Dies ist nur ein Ausschnitt der `base16` Themes, welche im Internet weit verbrei Entscheidend damit Theming funktioniert ist, dass alle Farben und Themen in der `config.nu` definiert werden _bevor_ die `let config =` Zeile definiert wird. -```shell +```nu # Definition von einigen Farben let base00 = "#181818" # Standard Hinergrund diff --git a/de/book/working_with_strings.md b/de/book/working_with_strings.md index a05f73b4541..681cc486835 100644 --- a/de/book/working_with_strings.md +++ b/de/book/working_with_strings.md @@ -10,7 +10,7 @@ ihnen zu arbeiten. Der Anwendungsfall entscheidet, welches am besten passt. Der einfachste Text in Nushell ist der in einfachen Anführungszeichen. Er wird mit dem `'` Zeichen umgeben. Hier der Text als Hallo Welt. -```sh +```nu > 'Hallo Welt' Hallo Welt ``` @@ -29,7 +29,7 @@ Zum Beispiel kann das Hallo Welt von vorhin geschrieben werden als, Hallo gefolgt von einen `\n` um eine neue Linie zu erzeugen, dann Welt. Das ganze in doppelten Anführungszeichen. -```sh +```nu > "Hallo\nWelt" Hallo Welt @@ -63,7 +63,7 @@ Die Text Interpolation wird mit `$" "` und `$" "` gebildet. Soll zum Beispiel eine Person per Namen gegrüsst werden, deren Namen in einer Variablen steht, dann sieht das so aus: -```sh +```nu > let name = "Alice" > $"greetings, ($name)" greetings, Alice @@ -80,7 +80,7 @@ Seit Version 0.61 unterstützt Nushell Escape Zeichen für Klammern. So können die Zeichen `(` und `)` in einem Text verwendet werden, ohne dass Nushell auswerten will, was sich dazwischen befindet. -```sh +```nu > $"2 + 2 is (2 + 2) \(you guessed it!)" 2 + 2 is 4 (you guessed it!) ``` @@ -107,7 +107,7 @@ Mit `help str` wirden alle Sub-Befehle ausgegeben. Zum Beispiel kann geprüft werden, ob sich ein Zeichen in einem Text befindet mit `str contains`: -```sh +```nu > "Hallo Welt" | str contains "W" true ``` @@ -118,7 +118,7 @@ Die Seiten eines Textes werden mit dem [`str trim`](/commands/docs/str_trim.md) geschnitten. Standardmässig schneidet der [`str trim`](/commands/docs/str_trim.md) Befehl Leerraum von beiden Seiten des Textes. Zum Beispiel: -```sh +```nu > ' My string ' | str trim My string ``` @@ -129,7 +129,7 @@ auf der geschnitten werden soll. Um ein spezifisches Zeichen weg zu schneiden, wird `--char ` verwendet. Hier ein Beispiel mit dieser Option: -```sh +```nu > '=== Nu shell ===' | str trim -r -c '=' === Nu shell ``` @@ -139,7 +139,7 @@ Hier ein Beispiel mit dieser Option: Subtexte sind Stücke von Texten. Sie haben einen Start- und einen Endpunkt. Hier ein Beispiel eines Substrings: -```sh +```nu > 'Hallo Welt!' | str index-of 'o' 4 > 'Hallo Welt!' | str index-of 'l' @@ -154,7 +154,7 @@ Mit den Befehlen `[str lpad`](/commands/docs/str_lpad.md) und [`str rpad`](/comm können Texte der angegeben Ausrichtung nach erweitert werden. Dieses Padding erweitert den Text bis zur angegebenen Länge, zum Beispiel: -```sh +```nu > '1234' | str lpad -l 10 -c '0' 0000001234 > '1234' | str rpad -l 10 -c '0' | str length @@ -165,7 +165,7 @@ Dieses Padding erweitert den Text bis zur angegebenen Länge, zum Beispiel: Dies kann mit dem [`str reverse`](/commands/docs/str_reverse.md) Befehl ganz einfach erreicht werden. -```sh +```nu > 'Nushell' | str reverse llehsuN > ['Nushell' 'is' 'cool'] | str reverse @@ -181,7 +181,7 @@ llehsuN Mit dem [`parse`](/commands/docs/parse.md) Befehl können Texte in Spalten geparst werden. Zum Beispiel: -```sh +```nu > 'Nushell is the best' | parse '{shell} is {type}' ╭───┬─────────┬──────────╮ │ # │ shell │ type │ @@ -215,7 +215,7 @@ Es gibt verschiedenste Wege Texte in und von anderen Typen zu konvertieren. Texte können eingefärbt werden mit dem [`ansi`](/commands/docs/ansi.md) Befehl Zum Beispiel: -```sh +```nu > $'(ansi purple_bold)This text is a bold purple!(ansi reset)' ``` diff --git a/package-lock.json b/package-lock.json index be09a395405..d7cec037c40 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,15 +7,19 @@ "": { "name": "nushell.github.io", "version": "0.0.0", + "hasInstallScript": true, "license": "MIT", "devDependencies": { "@vuepress/plugin-back-to-top": "2.0.0-beta.67", "@vuepress/plugin-docsearch": "2.0.0-beta.67", "@vuepress/plugin-git": "2.0.0-beta.67", "@vuepress/plugin-medium-zoom": "2.0.0-beta.67", + "@vuepress/plugin-shiki": "^2.0.0-beta.67", "@vuepress/theme-default": "2.0.0-beta.67", "lefthook": "^1.4.10", + "patch-package": "^8.0.0", "prettier": "^3.0.3", + "shiki": "^0.14.4", "vuepress": "2.0.0-beta.67", "vuepress-plugin-feed2": "2.0.0-beta.237", "vuepress-plugin-sitemap2": "2.0.0-beta.237" @@ -1276,6 +1280,16 @@ "prismjs": "^1.29.0" } }, + "node_modules/@vuepress/plugin-shiki": { + "version": "2.0.0-beta.67", + "resolved": "https://registry.npmmirror.com/@vuepress/plugin-shiki/-/plugin-shiki-2.0.0-beta.67.tgz", + "integrity": "sha512-YqEAmNQ638nBdrFiAOvwfTh5wbs7LcNjMIeMhdg3N8h+OaQKRzz7v61G7yk44rbwkXR647Pzj01t8SJeAi49yA==", + "dev": true, + "dependencies": { + "@vuepress/core": "2.0.0-beta.67", + "shiki": "^0.14.3" + } + }, "node_modules/@vuepress/plugin-theme-data": { "version": "2.0.0-beta.67", "resolved": "https://registry.npmmirror.com/@vuepress/plugin-theme-data/-/plugin-theme-data-2.0.0-beta.67.tgz", @@ -1602,6 +1616,12 @@ "dev": true, "peer": true }, + "node_modules/@yarnpkg/lockfile": { + "version": "1.1.0", + "resolved": "https://registry.npmmirror.com/@yarnpkg/lockfile/-/lockfile-1.1.0.tgz", + "integrity": "sha512-GpSwvyXOcOOlV70vbnzjj4fW5xW/FdUF6nQEt1ENy7m4ZCczi1+/buVUPAqmGfqznsORNFzUMjctTIp8a9tuCQ==", + "dev": true + }, "node_modules/acorn": { "version": "8.10.0", "resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.10.0.tgz", @@ -1679,6 +1699,24 @@ "node": ">=12" } }, + "node_modules/ansi-sequence-parser": { + "version": "1.1.1", + "resolved": "https://registry.npmmirror.com/ansi-sequence-parser/-/ansi-sequence-parser-1.1.1.tgz", + "integrity": "sha512-vJXt3yiaUL4UU546s3rPXlsry/RnM730G1+HkpKE012AN0sx1eOrxSu95oKDIonskeLTijMgqWZ3uDEe3NFvyg==", + "dev": true + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmmirror.com/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/anymatch": { "version": "3.1.3", "resolved": "https://registry.npmmirror.com/anymatch/-/anymatch-3.1.3.tgz", @@ -1707,6 +1745,15 @@ "sprintf-js": "~1.0.2" } }, + "node_modules/at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } + }, "node_modules/autoprefixer": { "version": "10.4.15", "resolved": "https://registry.npmmirror.com/autoprefixer/-/autoprefixer-10.4.15.tgz", @@ -1730,6 +1777,12 @@ "postcss": "^8.1.0" } }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, "node_modules/base64-js": { "version": "1.5.1", "resolved": "https://registry.npmmirror.com/base64-js/-/base64-js-1.5.1.tgz", @@ -1762,6 +1815,16 @@ "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", "dev": true }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, "node_modules/braces": { "version": "3.0.2", "resolved": "https://registry.npmmirror.com/braces/-/braces-3.0.2.tgz", @@ -1896,6 +1959,15 @@ "node": ">=6.0" } }, + "node_modules/ci-info": { + "version": "3.8.0", + "resolved": "https://registry.npmmirror.com/ci-info/-/ci-info-3.8.0.tgz", + "integrity": "sha512-eXTggHWSooYhq49F2opQhuHWgzucfF2YgODK4e1566GQs5BIfP30B0oenwBJHfWxAs2fyPB1s7Mg949zLf61Yw==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/cli-cursor": { "version": "4.0.0", "resolved": "https://registry.npmmirror.com/cli-cursor/-/cli-cursor-4.0.0.tgz", @@ -1917,6 +1989,24 @@ "node": ">=6" } }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmmirror.com/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmmirror.com/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, "node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmmirror.com/commander/-/commander-2.20.3.tgz", @@ -1924,6 +2014,12 @@ "dev": true, "peer": true }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmmirror.com/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, "node_modules/connect-history-api-fallback": { "version": "2.0.0", "resolved": "https://registry.npmmirror.com/connect-history-api-fallback/-/connect-history-api-fallback-2.0.0.tgz", @@ -2330,6 +2426,15 @@ "node": ">=8" } }, + "node_modules/find-yarn-workspace-root": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/find-yarn-workspace-root/-/find-yarn-workspace-root-2.0.0.tgz", + "integrity": "sha512-1IMnbjt4KzsQfnhnzNd8wUEgXZ44IzZaZmnLYx7D5FZlaHt2gW20Cri8Q+E/t5tIj4+epTBub+2Zxu/vNILzqQ==", + "dev": true, + "dependencies": { + "micromatch": "^4.0.2" + } + }, "node_modules/fraction.js": { "version": "4.3.6", "resolved": "https://registry.npmmirror.com/fraction.js/-/fraction.js-4.3.6.tgz", @@ -2353,6 +2458,12 @@ "node": ">=14.14" } }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmmirror.com/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", + "dev": true + }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.2.tgz", @@ -2376,6 +2487,23 @@ "node": ">=16" } }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmmirror.com/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + } + }, "node_modules/glob-parent": { "version": "5.1.2", "resolved": "https://registry.npmmirror.com/glob-parent/-/glob-parent-5.1.2.tgz", @@ -2437,7 +2565,6 @@ "resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz", "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -2499,6 +2626,16 @@ "integrity": "sha512-lj9cnmB/kVS0QHsJnYKD1uo3o39nrbKxszjnqS9Fr6NB7bZzW45U6WSGBPKXDL/CvDKqDNPA4r3DoDQ8GTxo2A==", "dev": true }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmmirror.com/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dev": true, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmmirror.com/inherits/-/inherits-2.0.4.tgz", @@ -2517,6 +2654,18 @@ "node": ">=8" } }, + "node_modules/is-docker": { + "version": "2.2.1", + "resolved": "https://registry.npmmirror.com/is-docker/-/is-docker-2.2.1.tgz", + "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "dev": true, + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmmirror.com/is-extendable/-/is-extendable-0.1.1.tgz", @@ -2583,6 +2732,18 @@ "node": ">=12" } }, + "node_modules/is-wsl": { + "version": "2.2.0", + "resolved": "https://registry.npmmirror.com/is-wsl/-/is-wsl-2.2.0.tgz", + "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "dev": true, + "dependencies": { + "is-docker": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmmirror.com/isexe/-/isexe-2.0.0.tgz", @@ -2631,6 +2792,21 @@ "dev": true, "peer": true }, + "node_modules/json-stable-stringify": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/json-stable-stringify/-/json-stable-stringify-1.0.2.tgz", + "integrity": "sha512-eunSSaEnxV12z+Z73y/j5N37/In40GK4GmsSy+tEHJMxknvqnA7/djeYtAgW0GsWHUfg+847WJjKaEylk2y09g==", + "dev": true, + "dependencies": { + "jsonify": "^0.0.1" + } + }, + "node_modules/jsonc-parser": { + "version": "3.2.0", + "resolved": "https://registry.npmmirror.com/jsonc-parser/-/jsonc-parser-3.2.0.tgz", + "integrity": "sha512-gfFQZrcTc8CnKXp6Y4/CBT3fTc0OVuDofpre4aEeEpSBPV5X5v4+Vmx+8snU7RLPrNHPKSgLxGo9YuQzz20o+w==", + "dev": true + }, "node_modules/jsonfile": { "version": "6.1.0", "resolved": "https://registry.npmmirror.com/jsonfile/-/jsonfile-6.1.0.tgz", @@ -2643,6 +2819,12 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/jsonify": { + "version": "0.0.1", + "resolved": "https://registry.npmmirror.com/jsonify/-/jsonify-0.0.1.tgz", + "integrity": "sha512-2/Ki0GcmuqSrgFyelQq9M05y7PS0mEwuIzrf3f1fPqkVDVRvZrPZtVSMHxdgo8Aq0sxAOb/cr2aqqA3LeWHVPg==", + "dev": true + }, "node_modules/kind-of": { "version": "6.0.3", "resolved": "https://registry.npmmirror.com/kind-of/-/kind-of-6.0.3.tgz", @@ -2652,6 +2834,15 @@ "node": ">=0.10.0" } }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmmirror.com/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "dev": true, + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, "node_modules/lefthook": { "version": "1.4.10", "resolved": "https://registry.npmmirror.com/lefthook/-/lefthook-1.4.10.tgz", @@ -2957,6 +3148,24 @@ "node": ">=12" } }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmmirror.com/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmmirror.com/ms/-/ms-2.1.2.tgz", @@ -3035,6 +3244,15 @@ "boolbase": "^1.0.0" } }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmmirror.com/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "dependencies": { + "wrappy": "1" + } + }, "node_modules/onetime": { "version": "6.0.0", "resolved": "https://registry.npmmirror.com/onetime/-/onetime-6.0.0.tgz", @@ -3047,6 +3265,19 @@ "node": ">=12" } }, + "node_modules/open": { + "version": "7.4.2", + "resolved": "https://registry.npmmirror.com/open/-/open-7.4.2.tgz", + "integrity": "sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q==", + "dev": true, + "dependencies": { + "is-docker": "^2.0.0", + "is-wsl": "^2.1.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/ora": { "version": "7.0.1", "resolved": "https://registry.npmmirror.com/ora/-/ora-7.0.1.tgz", @@ -3067,6 +3298,15 @@ "node": ">=16" } }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/parse5": { "version": "7.1.2", "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.1.2.tgz", @@ -3095,6 +3335,94 @@ "node": ">=0.12" } }, + "node_modules/patch-package": { + "version": "8.0.0", + "resolved": "https://registry.npmmirror.com/patch-package/-/patch-package-8.0.0.tgz", + "integrity": "sha512-da8BVIhzjtgScwDJ2TtKsfT5JFWz1hYoBl9rUQ1f38MC2HwnEIkK8VN3dKMKcP7P7bvvgzNDbfNHtx3MsQb5vA==", + "dev": true, + "dependencies": { + "@yarnpkg/lockfile": "^1.1.0", + "chalk": "^4.1.2", + "ci-info": "^3.7.0", + "cross-spawn": "^7.0.3", + "find-yarn-workspace-root": "^2.0.0", + "fs-extra": "^9.0.0", + "json-stable-stringify": "^1.0.2", + "klaw-sync": "^6.0.0", + "minimist": "^1.2.6", + "open": "^7.4.2", + "rimraf": "^2.6.3", + "semver": "^7.5.3", + "slash": "^2.0.0", + "tmp": "^0.0.33", + "yaml": "^2.2.2" + }, + "bin": { + "patch-package": "index.js" + }, + "engines": { + "node": ">=14", + "npm": ">5" + } + }, + "node_modules/patch-package/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/patch-package/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmmirror.com/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dev": true, + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/patch-package/node_modules/slash": { + "version": "2.0.0", + "resolved": "https://registry.npmmirror.com/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/patch-package/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmmirror.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmmirror.com/path-key/-/path-key-3.1.1.tgz", @@ -3302,6 +3630,18 @@ "node": ">=0.10.0" } }, + "node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmmirror.com/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "dev": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, "node_modules/rollup": { "version": "3.29.0", "resolved": "https://registry.npmmirror.com/rollup/-/rollup-3.29.0.tgz", @@ -3470,6 +3810,18 @@ "node": ">=8" } }, + "node_modules/shiki": { + "version": "0.14.4", + "resolved": "https://registry.npmmirror.com/shiki/-/shiki-0.14.4.tgz", + "integrity": "sha512-IXCRip2IQzKwxArNNq1S+On4KPML3Yyn8Zzs/xRgcgOWIr8ntIK3IKzjFPfjy/7kt9ZMjc+FItfqHRBg8b6tNQ==", + "dev": true, + "dependencies": { + "ansi-sequence-parser": "^1.1.0", + "jsonc-parser": "^3.2.0", + "vscode-oniguruma": "^1.7.0", + "vscode-textmate": "^8.0.0" + } + }, "node_modules/signal-exit": { "version": "4.1.0", "resolved": "https://registry.npmmirror.com/signal-exit/-/signal-exit-4.1.0.tgz", @@ -3693,6 +4045,18 @@ } } }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmmirror.com/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "dev": true, + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmmirror.com/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -3820,6 +4184,18 @@ } } }, + "node_modules/vscode-oniguruma": { + "version": "1.7.0", + "resolved": "https://registry.npmmirror.com/vscode-oniguruma/-/vscode-oniguruma-1.7.0.tgz", + "integrity": "sha512-L9WMGRfrjOhgHSdOYgCt/yRMsXzLDJSL7BPrOZt73gU0iWO4mpqzqQzOz5srxqTvMBaR0XZTSrVWo4j55Rc6cA==", + "dev": true + }, + "node_modules/vscode-textmate": { + "version": "8.0.0", + "resolved": "https://registry.npmmirror.com/vscode-textmate/-/vscode-textmate-8.0.0.tgz", + "integrity": "sha512-AFbieoL7a5LMqcnOF04ji+rpXadgOXnZsxQr//r83kLPr7biP7am3g9zbaZIaBGwBRWeSvoMD4mgPdX3e4NWBg==", + "dev": true + }, "node_modules/vue": { "version": "3.3.4", "resolved": "https://registry.npmmirror.com/vue/-/vue-3.3.4.tgz", @@ -4076,6 +4452,12 @@ "node": ">= 8" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true + }, "node_modules/xml-js": { "version": "1.6.11", "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", diff --git a/package.json b/package.json index 9b74a5ae6c3..4cc8e46586d 100755 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "update": "nu make_docs.nu", "dev": "vuepress dev", "build": "vuepress build", + "postinstall": "patch-package", "prepare": "git config --unset core.hooksPath && rm -rf .husky || true; lefthook install", "pretty": "prettier --write ." }, @@ -17,15 +18,18 @@ "@vuepress/plugin-docsearch": "2.0.0-beta.67", "@vuepress/plugin-git": "2.0.0-beta.67", "@vuepress/plugin-medium-zoom": "2.0.0-beta.67", + "@vuepress/plugin-shiki": "^2.0.0-beta.67", "@vuepress/theme-default": "2.0.0-beta.67", "lefthook": "^1.4.10", + "patch-package": "^8.0.0", "prettier": "^3.0.3", + "shiki": "^0.14.4", "vuepress": "2.0.0-beta.67", "vuepress-plugin-feed2": "2.0.0-beta.237", "vuepress-plugin-sitemap2": "2.0.0-beta.237" }, - "engines" : { - "npm" : ">=9.0.0", - "node" : ">=18.12.0" + "engines": { + "npm": ">=9.0.0", + "node": ">=18.12.0" } } diff --git a/patches/shiki+0.14.4.patch b/patches/shiki+0.14.4.patch new file mode 100644 index 00000000000..40def208df0 --- /dev/null +++ b/patches/shiki+0.14.4.patch @@ -0,0 +1,966 @@ +diff --git a/node_modules/shiki/dist/index.js b/node_modules/shiki/dist/index.js +index 7ea80d5..54441e1 100644 +--- a/node_modules/shiki/dist/index.js ++++ b/node_modules/shiki/dist/index.js +@@ -797,6 +797,14 @@ const languages = [ + displayName: "Nix", + samplePath: "nix.sample" + }, ++ { ++ id: 'nushell', ++ scopeName: 'source.nushell', ++ path: 'nushell.tmLanguage.json', ++ displayName: 'nushell', ++ samplePath: 'nushell.sample', ++ aliases: ['nu'] ++ }, + { + id: "objective-c", + scopeName: "source.objc", +diff --git a/node_modules/shiki/languages/nushell.tmLanguage.json b/node_modules/shiki/languages/nushell.tmLanguage.json +new file mode 100644 +index 0000000..b1ac5be +--- /dev/null ++++ b/node_modules/shiki/languages/nushell.tmLanguage.json +@@ -0,0 +1,941 @@ ++{ ++ "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", ++ "name": "nushell", ++ "scopeName": "source.nushell", ++ "patterns": [ ++ { ++ "include": "#define-variable" ++ }, ++ { ++ "include": "#define-alias" ++ }, ++ { ++ "include": "#function" ++ }, ++ { ++ "include": "#extern" ++ }, ++ { ++ "include": "#module" ++ }, ++ { ++ "include": "#use-module" ++ }, ++ { ++ "include": "#expression" ++ }, ++ { ++ "include": "#comment" ++ } ++ ], ++ "repository": { ++ "string": { ++ "patterns": [ ++ { ++ "include": "#string-single-quote" ++ }, ++ { ++ "include": "#string-backtick" ++ }, ++ { ++ "include": "#string-double-quote" ++ }, ++ { ++ "include": "#string-interpolated-double" ++ }, ++ { ++ "include": "#string-interpolated-single" ++ }, ++ { ++ "include": "#string-bare" ++ } ++ ] ++ }, ++ "string-escape": { ++ "match": "\\\\(?:[bfrnt\\\\'\"/]|u[0-9a-fA-F]{4})", ++ "name": "constant.character.escape.nushell" ++ }, ++ "string-bare": { ++ "match": "[^$\\[{(\"',|#\\s|][^\\[\\]{}()\"'\\s#,|]*", ++ "name": "string.bare.nushell" ++ }, ++ "string-single-quote": { ++ "begin": "'", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.begin.nushell" ++ } ++ }, ++ "end": "'", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.end.nushell" ++ } ++ }, ++ "name": "string.quoted.single.nushell" ++ }, ++ "string-backtick": { ++ "begin": "`", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.begin.nushell" ++ } ++ }, ++ "end": "`", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.end.nushell" ++ } ++ }, ++ "name": "string.quoted.single.nushell" ++ }, ++ "string-double-quote": { ++ "begin": "\"", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.begin.nushell" ++ } ++ }, ++ "end": "\"", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.end.nushell" ++ } ++ }, ++ "name": "string.quoted.double.nushell", ++ "patterns": [ ++ { ++ "match": "\\w+" ++ }, ++ { ++ "include": "#string-escape" ++ } ++ ] ++ }, ++ "string-interpolated-double": { ++ "begin": "\\$\"", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.begin.nushell" ++ } ++ }, ++ "end": "\"", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.end.nushell" ++ } ++ }, ++ "name": "string.interpolated.double.nushell", ++ "patterns": [ ++ { ++ "match": "\\\\[()]", ++ "name": "constant.character.escape.nushell" ++ }, ++ { ++ "include": "#string-escape" ++ }, ++ { ++ "include": "#paren-expression" ++ } ++ ] ++ }, ++ "string-interpolated-single": { ++ "begin": "\\$'", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.begin.nushell" ++ } ++ }, ++ "end": "'", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.string.end.nushell" ++ } ++ }, ++ "name": "string.interpolated.single.nushell", ++ "patterns": [ ++ { ++ "include": "#paren-expression" ++ } ++ ] ++ }, ++ "control-keywords": { ++ "comment": "Regex generated with list-to-tree (https://github.com/glcraft/list-to-tree)", ++ "match": "(?=]=?|[!=]~|&&|\\|\\||\\||\\+\\+=?)(?= |$)", ++ "name": "keyword.control.nushell" ++ }, ++ "operators": { ++ "patterns": [ ++ { ++ "include": "#operators-word" ++ }, ++ { ++ "include": "#operators-symbols" ++ }, ++ { ++ "include": "#ranges" ++ } ++ ] ++ }, ++ "table": { ++ "begin": "\\[", ++ "beginCaptures": { ++ "0": { ++ "name": "meta.brace.square.begin.nushell" ++ } ++ }, ++ "end": "\\]", ++ "endCaptures": { ++ "0": { ++ "name": "meta.brace.square.end.nushell" ++ } ++ }, ++ "name": "meta.table.nushell", ++ "patterns": [ ++ { ++ "include": "#value" ++ }, ++ { ++ "match": ",", ++ "name": "punctuation.separator.nushell" ++ }, ++ { ++ "include": "#comment" ++ } ++ ] ++ }, ++ "function-parameter-default-value": { ++ "begin": "=\\s*", ++ "captures": { ++ "1": { ++ "name": "variable.parameter.nushell" ++ }, ++ "2": { ++ "name": "variable.parameter.nushell" ++ }, ++ "3": { ++ "name": "keyword.operator.nushell" ++ }, ++ "4": { ++ "name": "entity.name.type.nushell" ++ } ++ }, ++ "end": "(?=\\])|,|$", ++ "patterns": [ ++ { ++ "include": "#value" ++ } ++ ] ++ }, ++ "function-parameter-declare": { ++ "match": "(-{0,2}[\\w-]+|\\.{3})(?:\\((-[\\w?])\\))?(?:\\s*(\\??:)\\s*(\\w+)(?:@((?:\"[^\"]+\")|(?:'[^']+')))?)?", ++ "captures": { ++ "1": { ++ "name": "variable.parameter.nushell" ++ }, ++ "2": { ++ "name": "variable.parameter.nushell" ++ }, ++ "3": { ++ "name": "keyword.operator.nushell" ++ }, ++ "4": { ++ "name": "entity.name.type.nushell" ++ }, ++ "5": { ++ "name": "string.quoted.nushell" ++ } ++ } ++ }, ++ "function-parameter": { ++ "patterns": [ ++ { ++ "include": "#function-parameter-declare" ++ }, ++ { ++ "include": "#function-parameter-default-value" ++ } ++ ] ++ }, ++ "function-parameters": { ++ "begin": "\\[", ++ "beginCaptures": { ++ "0": { ++ "name": "meta.brace.square.begin.nushell" ++ } ++ }, ++ "end": "\\]", ++ "endCaptures": { ++ "0": { ++ "name": "meta.brace.square.end.nushell" ++ } ++ }, ++ "patterns": [ ++ { ++ "include": "#function-parameter" ++ }, ++ { ++ "include": "#comment" ++ } ++ ], ++ "name": "meta.function.parameters.nushell" ++ }, ++ "define-function": { ++ "match": "((?:export\\s+)?def(?:-env)?)\\s+([\\w\\-!]+|\"[\\w\\-! ]+\")", ++ "captures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.type.nushell" ++ } ++ } ++ }, ++ "define-extern": { ++ "match": "((?:export\\s+)?extern)\\s+([\\w\\-!]+|\"[\\w\\-! ]+\")", ++ "captures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.type.nushell" ++ } ++ } ++ }, ++ "function-body": { ++ "begin": "\\{", ++ "beginCaptures": { ++ "0": { ++ "name": "punctuation.definition.function.begin.nushell" ++ } ++ }, ++ "end": "\\}", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.function.end.nushell" ++ } ++ }, ++ "name": "meta.function.body.nushell", ++ "patterns": [ ++ { ++ "include": "source.nushell" ++ } ++ ] ++ }, ++ "function": { ++ "begin": "((?:export\\s+)?def(?:-env)?)\\s+([\\w\\-]+|\"[\\w\\- ]+\")", ++ "beginCaptures": { ++ "0": { ++ "patterns": [ ++ { ++ "include": "#define-function" ++ }, ++ { ++ "include": "#define-extern" ++ } ++ ] ++ } ++ }, ++ "end": "(?<=\\})", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.function.end.nushell" ++ } ++ }, ++ "patterns": [ ++ { ++ "include": "#function-parameters" ++ }, ++ { ++ "include": "#function-body" ++ } ++ ] ++ }, ++ "extern": { ++ "begin": "((?:export\\s+)?extern)\\s+([\\w\\-]+|\"[\\w\\- ]+\")", ++ "beginCaptures": { ++ "0": { ++ "patterns": [ ++ { ++ "include": "#define-extern" ++ } ++ ] ++ } ++ }, ++ "end": "(?<=\\])", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.function.end.nushell" ++ } ++ }, ++ "patterns": [ ++ { ++ "include": "#function-parameters" ++ } ++ ] ++ }, ++ "module": { ++ "begin": "(module)\\s+([\\w\\-]+)\\s*\\{", ++ "beginCaptures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.namespace.nushell" ++ } ++ }, ++ "end": "\\}", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.definition.module.end.nushell" ++ } ++ }, ++ "name": "meta.module.nushell", ++ "patterns": [ ++ { ++ "include": "source.nushell" ++ } ++ ] ++ }, ++ "use-module": { ++ "patterns": [ ++ { ++ "match": "^\\s*((?:export )?use)\\s+([\\w\\-]+|\"[\\w\\- ]+\"|'[\\w\\- ]+')(?:\\s+([\\w\\-]+|\"[\\w\\- ]+\"|'[\\w\\- ]+'|\\*))?\\s*;?$", ++ "captures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.namespace.nushell" ++ }, ++ "3": { ++ "name": "keyword.other.nushell" ++ } ++ } ++ }, ++ { ++ "begin": "^\\s*((?:export )?use)\\s+([\\w\\-]+|\"[\\w\\- ]+\"|'[\\w\\- ]+')\\s*\\[", ++ "beginCaptures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.namespace.nushell" ++ } ++ }, ++ "end": "(\\])\\s*;?\\s*$", ++ "endCaptures": { ++ "1": { ++ "name": "meta.brace.square.end.nushell" ++ } ++ }, ++ "patterns": [ ++ { ++ "match": "([\\w\\-]+|\"[\\w\\- ]+\"|'[\\w\\- ]+'|\\*),?", ++ "captures": { ++ "1": { ++ "name": "keyword.other.nushell" ++ } ++ } ++ }, ++ { ++ "include": "#comment" ++ } ++ ] ++ }, ++ { ++ "match": "(?(?:/|\\\\|~[\\/\\\\]|\\.\\.?[\\/\\\\])?(?:[^\\/\\\\]+[\\/\\\\])*[\\w\\- ]+(?:\\.nu)?){0}^\\s*((?:export )?use)\\s+(\"\\g\"|'\\g\\'|(?![\"'])\\g)(?:\\s+([\\w\\-]+|\"[\\w\\- ]+\"|'[^']+'|\\*))?\\s*;?$", ++ "captures": { ++ "2": { ++ "name": "entity.name.function.nushell" ++ }, ++ "3": { ++ "name": "string.bare.nushell", ++ "patterns": [ ++ { ++ "match": "([\\w\\- ]+)(?:\\.nu)?(?=$|\"|')", ++ "captures": { ++ "1": { ++ "name": "entity.name.namespace.nushell" ++ } ++ } ++ } ++ ] ++ }, ++ "4": { ++ "name": "keyword.other.nushell" ++ } ++ } ++ }, ++ { ++ "begin": "(?(?:/|\\\\|~[\\/\\\\]|\\.\\.?[\\/\\\\])?(?:[^\\/\\\\]+[\\/\\\\])*[\\w\\- ]+(?:\\.nu)?){0}^\\s*((?:export )?use)\\s+(\"\\g\"|'\\g\\'|(?![\"'])\\g)\\s+\\[", ++ "beginCaptures": { ++ "2": { ++ "name": "entity.name.function.nushell" ++ }, ++ "3": { ++ "name": "string.bare.nushell", ++ "patterns": [ ++ { ++ "match": "([\\w\\- ]+)(?:\\.nu)?(?=$|\"|')", ++ "captures": { ++ "1": { ++ "name": "entity.name.namespace.nushell" ++ } ++ } ++ } ++ ] ++ } ++ }, ++ "end": "(\\])\\s*;?\\s*$", ++ "endCaptures": { ++ "1": { ++ "name": "meta.brace.square.end.nushell" ++ } ++ }, ++ "patterns": [ ++ { ++ "match": "([\\w\\-]+|\"[\\w\\- ]+\"|'[\\w\\- ]+'|\\*),?", ++ "captures": { ++ "0": { ++ "name": "keyword.other.nushell" ++ } ++ } ++ }, ++ { ++ "include": "#comment" ++ } ++ ] ++ }, ++ { ++ "match": "^\\s*(?:export )?use\\b", ++ "captures": { ++ "0": { ++ "name": "entity.name.function.nushell" ++ } ++ } ++ } ++ ] ++ }, ++ "for-loop": { ++ "begin": "(for)\\s+(\\$?\\w+)\\s+(in)\\s+(.+)\\s*(\\{)", ++ "beginCaptures": { ++ "1": { ++ "name": "keyword.other.nushell" ++ }, ++ "2": { ++ "name": "variable.other.nushell" ++ }, ++ "3": { ++ "name": "keyword.other.nushell" ++ }, ++ "4": { ++ "patterns": [ ++ { ++ "include": "#value" ++ } ++ ] ++ }, ++ "5": { ++ "name": "punctuation.section.block.begin.bracket.curly.nushell" ++ } ++ }, ++ "end": "\\}", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.section.block.end.bracket.curly.nushell" ++ } ++ }, ++ "name": "meta.for-loop.nushell", ++ "patterns": [ ++ { ++ "include": "source.nushell" ++ } ++ ] ++ }, ++ "paren-expression": { ++ "begin": "\\(", ++ "beginCaptures": { ++ "0": { ++ "name": "meta.brace.round.begin.nushell" ++ } ++ }, ++ "end": "\\)", ++ "endCaptures": { ++ "0": { ++ "name": "meta.brace.round.end.nushell" ++ } ++ }, ++ "name": "meta.expression.parenthesis.nushell", ++ "patterns": [ ++ { ++ "include": "#expression" ++ } ++ ] ++ }, ++ "braced-expression": { ++ "begin": "(\\{)(?:\\s*\\|([\\w, ]*)\\|)?", ++ "beginCaptures": { ++ "1": { ++ "name": "punctuation.section.block.begin.bracket.curly.nushell" ++ }, ++ "2": { ++ "patterns": [ ++ { ++ "include": "#function-parameter" ++ }, ++ { ++ "match": ",", ++ "name": "punctuation.separator.nushell" ++ } ++ ] ++ } ++ }, ++ "end": "\\}", ++ "endCaptures": { ++ "0": { ++ "name": "punctuation.section.block.end.bracket.curly.nushell" ++ } ++ }, ++ "name": "meta.expression.braced.nushell", ++ "patterns": [ ++ { ++ "begin": "((?:(?:[^$\\(\\{\\[\"'#\\s][^\\(\\{\\[\"'#\\s]*)|\\$?(?:\"[^\"]+\"|'[^']+')))\\s*(:)\\s*", ++ "beginCaptures": { ++ "1": { ++ "name": "variable.other.nushell", ++ "patterns": [ ++ { ++ "include": "#paren-expression" ++ } ++ ] ++ }, ++ "2": { ++ "patterns": [ ++ { ++ "include": "#operators" ++ } ++ ] ++ } ++ }, ++ "end": "(?=,|\\s|\\})", ++ "name": "meta.record-entry.nushell", ++ "patterns": [ ++ { ++ "include": "#value" ++ } ++ ] ++ }, ++ { ++ "include": "source.nushell" ++ } ++ ] ++ }, ++ "define-variable": { ++ "match": "(let(?:-env)?|mut|const)\\s+(\\w+)\\s*(=)", ++ "captures": { ++ "1": { ++ "name": "keyword.other.nushell" ++ }, ++ "2": { ++ "name": "variable.other.nushell" ++ }, ++ "3": { ++ "patterns": [ ++ { ++ "include": "#operators" ++ } ++ ] ++ } ++ } ++ }, ++ "define-alias": { ++ "match": "((?:export )?alias)\\s+([\\w\\-!]+)\\s*(=)", ++ "captures": { ++ "1": { ++ "name": "entity.name.function.nushell" ++ }, ++ "2": { ++ "name": "entity.name.type.nushell" ++ }, ++ "3": { ++ "patterns": [ ++ { ++ "include": "#operators" ++ } ++ ] ++ } ++ } ++ }, ++ "pre-command": { ++ "begin": "(\\w+)(=)", ++ "beginCaptures": { ++ "1": { ++ "name": "variable.other.nushell" ++ }, ++ "2": { ++ "patterns": [ ++ { ++ "include": "#operators" ++ } ++ ] ++ } ++ }, ++ "end": "(?=\\s+)", ++ "patterns": [ ++ { ++ "include": "#value" ++ } ++ ] ++ }, ++ "command": { ++ "begin": "(? open editors/vscode/package.json ------+----------+----------+---------+---------+----------+----------+----------+----------+----------+----------+----------+----------+----------+---------- name | descript | author | license | version | reposito | publishe | categori | keywords | engines | activati | main | contribu | scripts | devDepen @@ -23,7 +23,7 @@ De um jeito similar ao comando `ls`, abrir um tipo de arquivo que o Nu entende v Se quisermos checar a versão do projeto que estamos olhando, podemos usar o comando `get`. -```shell +```nu > open editors/vscode/package.json | get version 1.0.0 ``` @@ -39,7 +39,7 @@ O Nu atualmente suporta carregar dados diretamente para tabelas a partir dos seg Mas o que acontece se você carregar um arquivo texto cujo formato não é um desses? Vamos tentar: -```shell +```nu > open README.md ``` @@ -53,7 +53,7 @@ Uma parte importante de se trabalhar com dados vindos de fora do Nu é que eles Vamos imaginar que obtivemos esse arquivo de dados: -```shell +```nu > open people.txt Octavia | Butler | Writer Bob | Ross | Painter @@ -64,7 +64,7 @@ Cada pedacinho de dado que queremos está separado pelo símbolo de pipe ('|') e A primeira coisa que queremos fazer ao carregar o arquivo é trabalhar com ele linha a linha: -```shell +```nu > open people.txt | lines ---+------------------------------ # | value @@ -77,7 +77,7 @@ A primeira coisa que queremos fazer ao carregar o arquivo é trabalhar com ele l Podemos notar que estamos lidando com linhas porque voltamos a ver uma lista. Nosso próximo passo é tentar dividir as linhas em algo um pouco mais útil. Para isso, vamos usar o comando `split column`. Como o nome implica, esse comando nos dá uma forma de dividir em colunas uma string delimitada. Informamos qual é o delimitador e o comando faz o resto: -```shell +```nu > open people.txt | lines | split column "|" ---+----------+-----------+----------- # | Column1 | Column2 | Column3 @@ -90,7 +90,7 @@ Podemos notar que estamos lidando com linhas porque voltamos a ver uma lista. No Está quase certo. Parece que tem um espaço extra ali. Vamos mudar nosso delimitador: -```shell +```nu > open people.txt | lines | split column " | " ---+---------+---------+---------- # | Column1 | Column2 | Column3 @@ -103,7 +103,7 @@ Está quase certo. Parece que tem um espaço extra ali. Vamos mudar nosso delimi Nada mal. O comando `split column` retorna dados que podemos usar. Ele também vai além e nos dá nomes de coluna padrão: -```shell +```nu > open people.txt | lines | split column " | " | get Column1 ---+--------- # | value @@ -116,7 +116,7 @@ Nada mal. O comando `split column` retorna dados que podemos usar. Ele também v Podemos também nomear nossas colunas ao invés de usar os nomes padrão: -```shell +```nu > open people.txt | lines | split column " | " first_name last_name job ---+------------+-----------+---------- # | first_name | last_name | job @@ -129,7 +129,7 @@ Podemos também nomear nossas colunas ao invés de usar os nomes padrão: Agora que nossos dados estão em uma tabela, podemos usar todos os comandos que já usávamos antes em tabelas: -```shell +```nu > open people.txt | lines | split column " | " first_name last_name job | sort-by first_name ---+------------+-----------+---------- # | first_name | last_name | job @@ -148,7 +148,7 @@ Há outros comandos que você pode usar para trabalhar com strings: Há também um conjunto de comandos auxiliares que podemos chamar se soubermos que os dados têm uma estrutura que o Nu deve ser capaz de entender. Por exemplo, vamos abrir um arquivo de lock do Rust: -```shell +```nu > open Cargo.lock # This file is automatically @generated by Cargo. # It is not intended for manual editing. @@ -159,7 +159,7 @@ version = "0.1.2" O arquivo "Cargo.lock" é na verdade um arquivo .toml, mas a extensão do arquivo não é .toml. Tudo bem, podemos usar o comando `from toml`: -```shell +```nu > open Cargo.lock | from toml ----------+------------- metadata | package @@ -174,7 +174,7 @@ Há um comando `from` para cada formato de dados estruturados em texto que o Nu Embora seja útil poder abrir um arquivo e trabalhar imediatamente com uma tabela dos seus dados, nem sempre é isso o que queremos fazer. Para ter acesso ao texto subjacente, o comando `open` pode receber um modificador opcional `--raw`: -```shell +```nu > open Cargo.toml --raw [package] name = "nu" version = "0.1.3" @@ -187,7 +187,7 @@ license = "MIT" Além de carregar dados a partir do sistema de arquivos, você também pode passar uma URL para o comando `open`. Ele trará da internet o conteúdo dessa URL e o retornará para você: -```shell +```nu > open https://www.jonathanturner.org/feed.xml ---------- rss diff --git a/pt-BR/book/escapando.md b/pt-BR/book/escapando.md index 7e14915633d..ec3f44d4752 100644 --- a/pt-BR/book/escapando.md +++ b/pt-BR/book/escapando.md @@ -4,12 +4,12 @@ O Nu fornece um conjunto de comandos que você pode usar entre diferentes SOs e Comando Nu: -```shell +```nu > ls ``` Escapando para o comando local: -```shell +```nu > ^ls ``` diff --git a/pt-BR/book/explorando.md b/pt-BR/book/explorando.md index 7c0ffc759ad..a4e23160bd6 100644 --- a/pt-BR/book/explorando.md +++ b/pt-BR/book/explorando.md @@ -10,7 +10,7 @@ Como vimos em outros capítulos, `ls` é um comando para visualizar o conteúdo O comando `ls` também recebe um parâmetro opcional para mudar o que você gostaria de ver. Por exemplo, podemos listar os arquivos cujo nome termina em ".txt". -```shell +```nu > ls *.txt ---+--------------+------+----------+---------+--------------+-------------- # | name | type | readonly | size | accessed | modified @@ -24,7 +24,7 @@ O asterisco (\*) usado no parâmetro opcional acima "\*.txt" é chamado de corin Nu também usa coringas modernos, que permitem acesso a diretórios mais profundos. -```shell +```nu > ls **/*.rs -----+-----------------------------------------------------+------+----------+----------+----------------+---------------- # | name | type | readonly | size | accessed | modified @@ -41,7 +41,7 @@ Aqui estamos procurando qualquer arquivo cujo nome termine com ".rs" e os dois a ## Mudando o diretório atual -```shell +```nu > cd new_directory ``` @@ -53,19 +53,19 @@ Nu também fornece alguns comandos básicos de sistemas de arquivos que funciona Podemos mover um item de um lugar para outro usando o comando `mv`. -```shell +```nu > mv item location ``` Podemos copiar um item de um local para outro: -```shell +```nu > cp item location ``` Podemos remover um item: -```shell +```nu > rm item ``` @@ -73,6 +73,6 @@ Os três comandos também podem usar os coringas que vimos anteriormente com `ls Por fim, podemos criar um novo diretório usando o comando `mkdir`: -```shell +```nu > mkdir new_directory ``` diff --git a/pt-BR/book/instalacao.md b/pt-BR/book/instalacao.md index 26875ee4500..587d3702414 100644 --- a/pt-BR/book/instalacao.md +++ b/pt-BR/book/instalacao.md @@ -16,7 +16,7 @@ Se ainda não tivermos o Rust instalado no sistema, a melhor maneira de instalar O Nu atualmente requer a versão **nightly** do Rust. Quando você abrir o "rustup" pela primeira vez, ele vai perguntar qual versão do Rust você quer instalar: -```shell +```nu Current installation options: default host triple: x86_64-unknown-linux-gnu @@ -30,25 +30,25 @@ Current installation options: Selecione a opção #2 para customizar a instalação. -```shell +```nu Default host triple? ``` Aperte enter aqui para selecionar o default. -```shell +```nu Default toolchain? (stable/beta/nightly/none) ``` Certifique-se de digitar "nightly" aqui e pressionar enter. Isso vai levar à configuração seguinte: -```shell +```nu Modify PATH variable? (y/n) ``` Você pode opcionalmente atualizar o seu _path_. Normalmente é uma boa ideia, pois torna os passos seguintes mais fáceis. -```shell +```nu Current installation options: default host triple: x86_64-unknown-linux-gnu @@ -94,7 +94,7 @@ brew install openssl cmake Quando tivermos todas as dependências de que o Nu precisa, podemos instalá-lo usando o comando `cargo`, que vem junto com o compilador Rust. -```shell +```nu > cargo install nu ``` @@ -102,7 +102,7 @@ Pronto! A ferramenta cargo fará o download do Nu e das dependências do fonte, Se quiser instalar todas as funcionalidades, inclusive algumas opcionais divertidas, você pode usar: -```shell +```nu > cargo install nu --features=stable ``` @@ -119,7 +119,7 @@ $ nu Também podemos fazer o build do código fonte diretamente do GitHub. Isso nos dá acesso imediato às últimas funcionalidades e correções do Nu. -```shell +```nu > git clone https://github.com/nushell/nushell.git ``` diff --git a/pt-BR/book/introducao.md b/pt-BR/book/introducao.md index 4d0e4a33d00..d3bab60e393 100644 --- a/pt-BR/book/introducao.md +++ b/pt-BR/book/introducao.md @@ -12,7 +12,7 @@ O jeito mais fácil de ver o que o Nu pode fazer é começar com alguns exemplos A primeira coisa que você vai perceber quando rodar um comando como `ls` é que ao invés de um bloco de texto, você recebe de volta uma tabela estruturada. -```shell +```nu > ls ----+------------------+-----------+----------+----------+----------------+---------------- # | name | type | readonly | size | accessed | modified @@ -30,7 +30,7 @@ Essa tabela faz mais do que somente mostrar o diretório de um jeito diferente. A primeira coisa que vamos fazer é ordenar a tabela por nome. Para isso, vamos direcionar a saída do `ls` para um comando capaz de ordenar tabelas com base no conteúdo de uma coluna. -```shell +```nu > ls | sort-by name ----+------------------+-----------+----------+----------+----------------+---------------- # | name | type | readonly | size | accessed | modified @@ -48,7 +48,7 @@ Você pode ver que, para fazer isso funcionar, não passamos parâmetros de linh O Nu fornece muitos comandos que trabalham com tabelas. Por exemplo, podemos filtrar o conteúdo da tabela do `ls` para que ela mostre apenas os arquivos com mais de 4 kilobytes: -```shell +```nu > ls | where size > 4kb ----+----------------+------+----------+----------+----------------+---------------- # | name | type | readonly | size | accessed | modified @@ -63,7 +63,7 @@ O Nu fornece muitos comandos que trabalham com tabelas. Por exemplo, podemos fil Assim como na filosofia Unix, fazer os comandos conversarem uns com os outros nos permite combiná-los de muitas maneiras diferentes. Vamos ver outro comando: -```shell +```nu > ps -----+-------+----------+------+-------------------------------------------------------------------------------- # | pid | status | cpu | name @@ -80,7 +80,7 @@ Você deve conhecer o comando `ps` se já usou Linux. Com ele, vemos uma lista c E se quiséssemos mostrar somente os processos que estão usando a CPU de fato? Exatamente como fizemos com o comando `ls` anteriormente, podemos também manipular a tabela que o comando `ps` nos retorna: -```shell +```nu > ps | where cpu > 10 ---+-------+----------+-------+----------------------------- # | pid | status | cpu | name @@ -95,7 +95,7 @@ Até agora vimos como usar `ls` e `ps` para listar arquivos e processos. O Nu ta Ao executar `date` obtemos informações sobre a data e hora correntes: -```shell +```nu > date ------+-------+-----+------+--------+--------+---------- year | month | day | hour | minute | second | timezone @@ -106,7 +106,7 @@ Ao executar `date` obtemos informações sobre a data e hora correntes: E ao executar `sys` obtemos informações sobre o sistema em que o Nu está rodando: -```shell +```nu > sys ----------+----------+-----------+----------+-----------+----------- host | cpu | disks | mem | temp | net @@ -117,7 +117,7 @@ E ao executar `sys` obtemos informações sobre o sistema em que o Nu está roda Essa tabela é um pouco diferente das que vimos antes. O comando `sys` retorna uma tabela que contém tabelas estruturadas em suas células, ao invés de valores simples. Para dar uma olhada nesses dados, precisamos selecionar a coluna que queremos ver: -```shell +```nu > sys | get host -------+------------------+----------+--------+----------+---------- name | release | hostname | arch | uptime | users @@ -128,7 +128,7 @@ Essa tabela é um pouco diferente das que vimos antes. O comando `sys` retorna u O comando `get` permite que tenhamos acesso ao conteúdo de uma coluna da tabela. Aqui, estamos olhando para dentro da coluna `host`, que contém informações a respeito da máquina host em que o Nu está rodando, como nome do SO (sistema operacional), o nome de host, a CPU e outros dados mais. Vamos ver os nomes dos usuários do sistema: -```shell +```nu > sys | get host.users jonathan ``` @@ -139,7 +139,7 @@ Talvez você tenha notado mais alguma coisa de diferente. Ao invés de uma tabel Vejamos como as strings funcionam fora do Nu. Vamos usar nosso exemplo anterior e executar o comando externo `echo`, presente na maioria dos SOs: -```shell +```nu > sys | get host.users | echo $it jonathan ``` @@ -148,7 +148,7 @@ Se isso lhe parece bastante similar ao que tínhamos anteriormente, você tem um _Nota: você pode obter um texto de ajuda para quaisquer comandos embutidos do Nu usando o comando `help`_: -```shell +```nu > help config Configuration management. Usage: diff --git a/pt-BR/book/metadados.md b/pt-BR/book/metadados.md index 5b6705a5f95..5f762c5d334 100644 --- a/pt-BR/book/metadados.md +++ b/pt-BR/book/metadados.md @@ -2,7 +2,7 @@ Usando o Nu vocë pode se deparar com momentos em que sente como se houvesse algo a mais acontecendo nos bastidores. Por exemplo, digamos que vocë vai tentar abrir um arquivo mas se esquece que ele é suportado pelo Nu e tenta convertê-lo novamente: -```shell +```nu > open Cargo.toml | from toml error: Expected a string from pipeline - shell:1:18 @@ -19,7 +19,7 @@ Valores que fluem pelo pipeline do Nu normalmente trazem consigo um conjunto adi Vamos executar o comando `open` de novo, mas, dessa vez, vamos olhar as tags que ele retorna: -```shell +```nu > open Cargo.toml | tags ----------+------------------------------------------ span | origin @@ -32,7 +32,7 @@ Atualmente, rastreamos dois pedaços de metadados dos valores no pipeline. Você Há também um coluna intervalo (span). Vamos ver mais de perto: -```shell +```nu > open Cargo.toml | tags | get span -------+----- start | end diff --git a/pt-BR/book/pipeline.md b/pt-BR/book/pipeline.md index cb4638adf5f..be4de8c2750 100644 --- a/pt-BR/book/pipeline.md +++ b/pt-BR/book/pipeline.md @@ -6,7 +6,7 @@ Um dos principais designs do Nu é o pipeline, uma ideia de design que tem suas Um pipeline é construído com três partes: a entrada, o filtro e a saída. -```shell +```nu > open "Cargo.toml" | inc package.version | save "Cargo_new.toml" ``` @@ -38,13 +38,13 @@ Você pode ter se perguntado como vemos uma tabela se o `ls` é uma entrada e n Com efeito, o comando: -```shell +```nu > ls ``` E o pipeline: -```shell +```nu > ls | autoview ``` diff --git a/pt-BR/book/shells_em_shells.md b/pt-BR/book/shells_em_shells.md index 3700e416d82..e9fc43a2e89 100644 --- a/pt-BR/book/shells_em_shells.md +++ b/pt-BR/book/shells_em_shells.md @@ -6,7 +6,7 @@ Embora seja comum trabalhar em um único diretório, pode ser útil trabalhar em Para começar, vamos entrar num diretório: -```shell +```nu /home/jonathan/Source/nushell(master)> enter ../lark /home/jonathan/Source/lark(master)> ls ----+----------------+-----------+----------+---------+---------------+--------------- @@ -19,7 +19,7 @@ Para começar, vamos entrar num diretório: Entrar é semlhante a mudar de diretório (como vimos com o comando `cd`), permitindo que você salte para o diretório dentro do qual vai trabalhar. Ao invés de mudar de diretório, nós agora estamos em dois diretórios. Para ver isso mais claramente, podemos usar o comando `shells` para listar os diretórios ativos agora: -```shell +```nu /home/jonathan/Source/lark(master)> shells ---+---+------------+------------------------------- # | | name | path @@ -55,7 +55,7 @@ Para ver como isso funciona, vamos fazer o seguinte exercício. Atualmente, list Vamos entrar no arquivo "Cargo.toml" do código fonte do Nu: -```shell +```nu /Users/andresrobalino/Code/nushell(master)> enter Cargo.toml /> ls ------------+--------------+------------------+----------+---------- @@ -69,7 +69,7 @@ Até o momento, apenas entramos no arquivo (usando o comando `enter`) e podemos Antes de continuarmos, vamos checar os shells ativos: -```shell +```nu /> shells ---+---+-------------------------------------------------+------------------------------------ # | | name | path @@ -82,7 +82,7 @@ Antes de continuarmos, vamos checar os shells ativos: Podemos observar que temos dois shells ativos e que estamos agora dentro do arquivo "Cargo.toml" com um caminho raíz padrão "/". Vamos ver seu contéudo novamente: -```shell +```nu /> ls ------------+--------------+------------------+----------+---------- bin | dependencies | dev-dependencies | lib | package @@ -93,7 +93,7 @@ Podemos observar que temos dois shells ativos e que estamos agora dentro do arqu O que estamos procurando pode estar dentro da coluna "bin", então vamos entrar lá: -```shell +```nu > cd bin /bin> ls ----+----------------------+--------------------------- @@ -115,13 +115,13 @@ O que estamos procurando pode estar dentro da coluna "bin", então vamos entrar Daqui, sempre podemos voltar para o diretório em que estávamos trabalhando antes usando p (de prévio, anterior). -```shell +```nu /bin> p ``` Vamos verificar os shells de novo: -```shell +```nu /Users/andresrobalino/Code/nushell(master)> shells ---+---+-------------------------------------------------+------------------------------------ # | | name | path @@ -134,7 +134,7 @@ Vamos verificar os shells de novo: Estamos de volta ao diretório onde estávamos trabalhando antes de entrar no arquivo "Cargo.toml". Agora vamos mudar para o diretório onde então os códigos fonte dos plugins e rastreá-los: -```shell +```nu /Users/andresrobalino/Code/nushell(master)> cd src/plugins/ /Users/andresrobalino/Code/nushell/src/plugins(master)> ls ----+---------------+------+----------+---------+------------+------------ diff --git a/pt-BR/book/trabalhando_com_tabelas.md b/pt-BR/book/trabalhando_com_tabelas.md index ee1393d392d..e05e8f6d81b 100644 --- a/pt-BR/book/trabalhando_com_tabelas.md +++ b/pt-BR/book/trabalhando_com_tabelas.md @@ -4,7 +4,7 @@ Uma forma comum de ver os dados no Nu é por meio de uma tabela. O Nu traz um co Para começar, vamos usar a seguinte tabela: -```shell +```nu > ls ---+---------------+------+----------+---------+------------+------------ # | name | type | readonly | size | accessed | modified @@ -26,7 +26,7 @@ Para começar, vamos usar a seguinte tabela: Podemos ordenar uma tabela chamando o comando `sort-by` e informando quais colunas queremos usar na ordenação. Digamos que queremos ordenar nossa tabela pelo tamanho do arquivo: -```shell +```nu > ls | sort-by size ---+---------------+------+----------+---------+------------+------------ # | name | type | readonly | size | accessed | modified @@ -50,7 +50,7 @@ Podemos ordenar uma tabela por qualquer coluna que possa ser comparada. Por exem Podemos selecionar dados de uma tabela escolhendo colunas ou linhas específicas. Vamos escolher algumas colunas da nossa tabela: -```shell +```nu > ls | select name size ---+---------------+--------- # | name | size @@ -70,7 +70,7 @@ Podemos selecionar dados de uma tabela escolhendo colunas ou linhas específicas Isso ajuda a criar uma tabela mais focada no que precisamos. A seguir, digamos que queremos ver apenas os 5 menores arquivos do diretório: -```shell +```nu > ls | sort-by size | first 5 ---+---------+------+----------+--------+------------+------------ # | name | type | readonly | size | accessed | modified @@ -87,7 +87,7 @@ Note que primeiro ordenamos a tabela por tamanho e depois usamos o `first 5` par Você também pode usar `skip` para pular as linhas que não quiser. Vamos pular as duas primeiras das 5 linhas que retornamos acima: -```shell +```nu > ls | sort-by size | first 5 | skip 2 ---+---------+------+----------+--------+------------+------------ # | name | type | readonly | size | accessed | modified @@ -102,7 +102,7 @@ Restringimos os dados às 3 linhas que nos interessam. Vamos examinar alguns outros comandos para selecionar dados. Você pode ter se perguntado por que as linhas da tabela são numeradas. Isso serve como uma maneira prática de acessar uma linha específica. Vamos ordenar nossa tabela pelo nome do arquivo e então escolher uma das linhas com o comando `nth`, usando o número da linha: -```shell +```nu > ls | sort-by name ---+---------------+------+----------+---------+------------+------------ # | name | type | readonly | size | accessed | modified @@ -131,7 +131,7 @@ Vamos examinar alguns outros comandos para selecionar dados. Você pode ter se p Até agora, trabalhamos as tabelas reduzindo-as para somente o que precisamos. Às vezes queremos ir um passo além e só ver os valores das células e não de uma coluna toda. Digamos, por exemplo, que queremos somente uma lista com os nomes do arquivos. Para isso, usamos o comando `get`: -```shell +```nu > ls | get name ---+--------------- # | value @@ -153,7 +153,7 @@ Agora temos os valores para cada um dos nomes de arquivo. Parece muito com o comando `select` que vimos antes, então vamos colocá-lo aqui de novo para compararmos os dois: -```shell +```nu > ls | select name ---+--------------- # | name @@ -188,7 +188,7 @@ Além de selecionar dados de uma tabela, podemos também alterar o que a tabela Podemos usar o comando `add` para adicionar uma nova coluna na tabela. Vejamos um exemplo: -```shell +```nu > open rustfmt.toml --------- edition @@ -199,7 +199,7 @@ Podemos usar o comando `add` para adicionar uma nova coluna na tabela. Vejamos u Vamos adicionar uma coluna chamada "next_edition" com o valor 2021: -```shell +```nu > open rustfmt.toml | add next_edition 2021 ---------+-------------- edition | next_edition @@ -210,7 +210,7 @@ Vamos adicionar uma coluna chamada "next_edition" com o valor 2021: Note que, se abrirmos o arquivo original, seu conteúdo permanece o mesmo: -```shell +```nu > open rustfmt.toml --------- edition @@ -221,7 +221,7 @@ Note que, se abrirmos o arquivo original, seu conteúdo permanece o mesmo: Alterações no Nu são alterações funcionais, isto é, atuam sobre os valores em si ao invés de tentar causar uma alteração permanente, o que nos permite executar muitos tipos diferentes de ações no nosso pipeline até que estejamos prontos para escrever o resultado com quaisquer mudanças, se assim quisermos. Aqui poderíamos salvar o resultado usando o comando `save`: -```shell +```nu > open rustfmt.toml | add next_edition 2021 | save rustfmt2.toml > open rustfmt2.toml ---------+-------------- @@ -235,7 +235,7 @@ Alterações no Nu são alterações funcionais, isto é, atuam sobre os valores Semelhante ao comando `add`, podemos usar o comando `edit` para alterar o conteúdo de uma coluna para um novo valor. Para ver isso funcionando, vamos abrir o mesmo arquivo: -```shell +```nu open rustfmt.toml --------- edition @@ -246,7 +246,7 @@ open rustfmt.toml E agora vamos alterar a coluna `edition` para mostrar a próxima edição à qual esperamos dar suporte: -```shell +```nu > open rustfmt.toml | edit edition 2021 --------- edition @@ -259,7 +259,7 @@ E agora vamos alterar a coluna `edition` para mostrar a próxima edição à qua Existe mais um comando do Nu que nos ajudará a trabalhar com números e versões: `inc`. -```shell +```nu > open rustfmt.toml --------- edition @@ -276,7 +276,7 @@ Existe mais um comando do Nu que nos ajudará a trabalhar com números e versõe Como o valor em "edition" é um número, podemos usar `inc` para alterá-lo. Onde `inc` realmente se destaca é trabalhando com versões: -```shell +```nu > open Cargo.toml | get package.version 0.1.3 > open Cargo.toml | inc package.version --minor | get package.version diff --git a/zh-CN/book/3rdpartyprompts.md b/zh-CN/book/3rdpartyprompts.md index e1e99a41975..669aadd30e9 100644 --- a/zh-CN/book/3rdpartyprompts.md +++ b/zh-CN/book/3rdpartyprompts.md @@ -20,7 +20,7 @@ Nerdfonts 并不是必需的,但它们能使呈现效果更好。 2. 下载并安装一个 [Nerdfonts 字体](https://github.com/ryanoasis/nerd-fonts)。 3. 在`~/.config/nushell/config.nu`(或由`$nu.config-path`输出的路径)中设置`PROMPT_COMMAND`,将`M365Princess.mp.json`改为你喜欢的任何 [主题](https://ohmyposh.dev/docs/themes)。 -```shell +```nu > $env.PROMPT_COMMAND = { oh-my-posh --config ~/.poshthemes/M365Princess.omp.json } ``` @@ -30,7 +30,7 @@ MacOS 用户配置步骤: 2. 下载并安装一个 [Nerdfonts 字体](https://github.com/ryanoasis/nerd-fonts); 3. 在`$nu.config-path`输出的文件中设置`PROMPT_COMMAND`,可以参考下面的代码片段: -```shell +```nu let posh_dir = (brew --prefix oh-my-posh | str trim) let posh_theme = $'($posh_dir)/share/oh-my-posh/themes/' # Change the theme names to: zash/space/robbyrussel/powerline/powerlevel10k_lean/ diff --git a/zh-CN/book/aliases.md b/zh-CN/book/aliases.md index ccb23559a06..edfe5efda8a 100644 --- a/zh-CN/book/aliases.md +++ b/zh-CN/book/aliases.md @@ -26,13 +26,13 @@ Nushell 中的别名提供了一种简单的文本替换方式,这允许你为 如果你想在别名中添加管道,你必须用小括号把它括起来,小括号是一对圆括号`()`,用来标记你的一组带有管道命令: -```shell +```nu alias lsname = (ls | get name) ``` 下面是一个带有多个管道的别名: -```shell +```nu alias lt = (ls | sort-by modified -r | sort-by type) ``` diff --git a/zh-CN/book/coloring_and_theming.md b/zh-CN/book/coloring_and_theming.md index 85c4c5b2411..c9f3289bff4 100644 --- a/zh-CN/book/coloring_and_theming.md +++ b/zh-CN/book/coloring_and_theming.md @@ -14,7 +14,7 @@ Nushell 界面的许多部分都可以定制它们的颜色,所有这些都可 表的边框由`config.nu`中的`table_mode`设置来控制。下面是一个例子: -```shell +```nu > $env.config = { table_mode: rounded } @@ -268,7 +268,7 @@ Nushell 界面的许多部分都可以定制它们的颜色,所有这些都可 下面是一个改变其中一些数值的小例子。 -```shell +```nu > let config = { color_config: { separator: purple @@ -293,7 +293,7 @@ Nushell 界面的许多部分都可以定制它们的颜色,所有这些都可 下面是另一个使用多种颜色语法的小例子,其中有一些注释: -```shell +```nu > let config = { color_config: { separator: "#88b719" # this sets only the foreground color like PR #486 @@ -347,7 +347,7 @@ Nushell 界面的许多部分都可以定制它们的颜色,所有这些都可 这里有一个小例子,说明如何对这些项目应用颜色。任何没有显示指定的都会被设置为默认的颜色。 -```shell +```nu > $env.config = { color_config: { shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b} @@ -370,13 +370,13 @@ Nushell 的提示符可以通过这些环境变量进行配置: 例如:对于一个简单的提示,我们可以这样做。注意`PROMPT_COMMAND`需要一个`block`而其他的需要一个`string`。 -```shell +```nu > $env.PROMPT_COMMAND = { build-string (date now | date format '%m/%d/%Y %I:%M:%S%.3f') ': ' (pwd | path basename) } ``` 如果你不喜欢默认的`PROMPT_INDICATOR`,你可以这样改变它: -```shell +```nu > $env.PROMPT_INDICATOR = "> " ``` @@ -402,7 +402,7 @@ Nushell 将尊重并使用 Mac、Linux 和 Windows 上的 `LS_COLORS` 环境变 使主题生效的关键是确保你在声明 `let config =` 行 _之前_,在`config.nu`文件中指定你要使用的所有主题和颜色: -```shell +```nu # let's define some colors let base00 = "#181818" # Default Background @@ -488,7 +488,7 @@ let config = { Nushell 的默认配置文件包含一个浅色主题定义,如果你在浅色背景的终端上工作,你可以很容易地应用浅色主题: -```shell +```nu # in $nu.config-file $env.config = { ... @@ -499,7 +499,7 @@ $env.config = { 你只需要将 `$dark_theme` 替换为 `$light_theme` 就可以切换到浅色主题了: -```shell +```nu # in $nu.config-file $env.config = { ... diff --git a/zh-CN/book/configuration.md b/zh-CN/book/configuration.md index df45d7c23b7..dc84374bf58 100644 --- a/zh-CN/book/configuration.md +++ b/zh-CN/book/configuration.md @@ -117,7 +117,7 @@ alias open = ^open 要在 [PATH 变量]() 中添加一个路径,你可以在 `env.nu` 中使用 `$env. = ` 和 [`append`](/commands/docs/append.md) 完成,如下: -```shell +```nu $env.PATH = ($env.PATH | split row (char esep) | append '/some/path') ``` diff --git a/zh-CN/book/custom_commands.md b/zh-CN/book/custom_commands.md index 2c4294e00cb..32331583af7 100644 --- a/zh-CN/book/custom_commands.md +++ b/zh-CN/book/custom_commands.md @@ -32,7 +32,7 @@ def greet [name] { ::: tip `echo`将其参数分别返回给管道。如果你想用它来生成一个单一的字符串,请在管道中添加` | str join`: -```shell +```nu def greet [name] { echo "hello " $name | str join } @@ -128,7 +128,7 @@ error: Type Error 若要使一个参数成为可选的,并具有默认值,你可以在命令定义中指定该默认值: -```shell +```nu def greet [name = "nushell"] { echo "hello " $name | str join } @@ -255,7 +255,7 @@ _注意:_ 标志是以其全称命名的,所以上面的例子的命令体 标志也可以作为基本开关使用,这意味着它们的存在或不存在被当作定义的参数。延伸前面的例子: -```shell +```nu def greet [ name: string --age (-a): int @@ -427,7 +427,7 @@ def double [] { 我们还可以使用`$in`变量来存储输入,以便在后面使用: -```shell +```nu def nullify [...cols] { let start = $in $cols | reduce --fold $start { |col, df| diff --git a/zh-CN/book/dataframes.md b/zh-CN/book/dataframes.md index 6b906b6b6d4..4174e9c1b19 100644 --- a/zh-CN/book/dataframes.md +++ b/zh-CN/book/dataframes.md @@ -26,7 +26,7 @@ DataFrame 相关命令从 0.33.1 版本开始支持 该数据集有 5 列,5,429,252 行。我们可以通过使用`dfr ls`命令来检查: -```shell +```nu > let df = (dfr open .\Data7602DescendingYearOrder.csv) > dfr ls @@ -39,7 +39,7 @@ DataFrame 相关命令从 0.33.1 版本开始支持 我们可以用 `first` 看一下文件的第一行: -```shell +```nu > $df | first ───┬──────────┬─────────┬──────┬───────────┬────────── @@ -55,7 +55,7 @@ DataFrame 相关命令从 0.33.1 版本开始支持 ...最后,我们可以了解一下推断出的数据类型: -```shell +```nu > $df | dtypes ───┬───────────┬─────── @@ -73,7 +73,7 @@ DataFrame 相关命令从 0.33.1 版本开始支持 让我们先来比较一下各种方法的加载时间。首先,我们将使用 Nushell 的[`open`](/commands/docs/open.md)命令加载数据: -```shell +```nu > benchmark {open .\Data7602DescendingYearOrder.csv} ───┬───────────────────────── @@ -95,7 +95,7 @@ df = pd.read_csv("Data7602DescendingYearOrder.csv") 而它的性能测试结果是: -```shell +```nu > benchmark {python load.py} ───┬─────────────────────── @@ -109,7 +109,7 @@ df = pd.read_csv("Data7602DescendingYearOrder.csv") 也许我们加载数据可以再快一点,这一次我们将使用 Nushell 的 `dfr open` 命令: -```shell +```nu > benchmark {dfr open .\Data7602DescendingYearOrder.csv} ───┬─────────────────── @@ -131,7 +131,7 @@ df = pd.read_csv("Data7602DescendingYearOrder.csv") 如果你想运行这个例子,请注意接下来的命令将使用大量的内存,在该命令执行期间可能会影响你的系统性能。 ::: -```shell +```nu > benchmark { open .\Data7602DescendingYearOrder.csv | group-by year @@ -161,7 +161,7 @@ print(res) 而性能测试的结果是: -```shell +```nu > benchmark {python .\load.py} ───┬──────────────────────── @@ -175,7 +175,7 @@ print(res) 为了进行比较,让我们试试 Nushell DataFrames。我们要把所有的操作放在一个`nu`文件中,以确保我们做的是类似的操作: -```shell +```nu let df = (dfr open Data7602DescendingYearOrder.csv) let res = ($df | group-by year | agg (col geo_count | sum)) $res @@ -183,7 +183,7 @@ $res 当使用 DataFrames 时的性能测试结果是: -```shell +```nu > benchmark {source load.nu} ───┬─────────────────── @@ -201,7 +201,7 @@ $res 在看到了可以用`DataFrame`命令完成的事情之后,现在是时候开始测试它们了。首先,让我们创建一个样本 CSV 文件,该文件将成为我们的样本 DataFrame,并与示例一起使用。在你喜欢的编辑器中粘贴下面几行来创建样本 csv 文件: -```csv +``` int_1,int_2,float_1,float_2,first,second,third,word 1,11,0.1,1.0,a,b,c,first 2,12,0.2,1.0,a,b,c,second @@ -219,7 +219,7 @@ int_1,int_2,float_1,float_2,first,second,third,word 现在,要将该文件作为 DataFrame 进行读取,请使用 `dfr open` 命令,如下所示: -```shell +```nu > let df = (dfr open test_small.csv) ``` @@ -231,7 +231,7 @@ int_1,int_2,float_1,float_2,first,second,third,word 要查看存储在内存中的所有 DataFrames,你可以使用: -```shell +```nu > dfr ls ───┬──────┬──────┬───────── @@ -245,7 +245,7 @@ int_1,int_2,float_1,float_2,first,second,third,word 如果你想看到加载的 DataFrame 的预览,你可以将 DataFrame 变量发送到流中: -```shell +```nu > $df ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬──────── @@ -274,7 +274,7 @@ int_1,int_2,float_1,float_2,first,second,third,word 让我们从 DataFrame 的基本聚合开始,通过使用`aggregate`命令对`df`中存在的所有列进行求和: -```shell +```nu > $df | sum ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬────── @@ -286,7 +286,7 @@ int_1,int_2,float_1,float_2,first,second,third,word 正如你所看到的,聚合函数(`aggregate`)为那些有意义的列计算出了总和。如果你想过滤掉文本列,你可以使用`select`命令来选择你想要的列。 -```shell +```nu $df | sum | select int_1 int_2 float_1 float_2 ───┬───────┬───────┬─────────┬───────── @@ -298,7 +298,7 @@ $df | sum | select int_1 int_2 float_1 float_2 你甚至可以像存储任何其他 Nushell 变量一样存储这个聚合的结果: -```shell +```nu > let res = ($df | sum | select int_1 int_2 float_1 float_2) ``` @@ -308,7 +308,7 @@ $df | sum | select int_1 int_2 float_1 float_2 现在我们有两个 DataFrame 存储在内存中: -```shell +```nu > dfr ls ───┬──────┬──────┬───────── @@ -337,13 +337,13 @@ int_1,int_2,float_1,float_2,first 我们使用 `dfr open` 命令来创建新的变量: -```shell +```nu > let df_a = (dfr open test_small_a.csv) ``` 现在,当第二个 DataFrame 加载到内存中时,我们可以使用左边 DataFrame 的`int_1`列和右边 DataFrame 的`int_1`列来连接它们。 -```shell +```nu > $df | join $df_a int_1 int_1 ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬─────────┬─────────────┬───────────────┬───────────────┬───────────── @@ -368,7 +368,7 @@ int_1,int_2,float_1,float_2,first 要创建一个`GroupBy`对象,你只需要使用`group-by`命令: -```shell +```nu > let group = ($df | group-by first) > $group @@ -377,7 +377,7 @@ int_1,int_2,float_1,float_2,first 当打印 `GroupBy` 对象时,我们可以看到它在后台是一个懒惰的操作,等待着通过添加一个聚合来完成。使用 `GroupBy` 我们可以在一个列上创建聚合 -```shell +```nu $group | agg (col int_1 | sum) ───┬───────┬───────────┬ @@ -391,7 +391,7 @@ $group | agg (col int_1 | sum) 或者我们可以在相同或不同的列上定义多个聚合: -```shell +```nu $group | agg [ (col int_1 | n-unique) (col int_2 | min) @@ -414,7 +414,7 @@ $group | agg [ 也可以从基本的 Nushell 基础类型,如整数、小数或字符串,来构建 DataFrames。让我们使用 `into df` 命令来创建一个小的 DataFrame: -```shell +```nu > let a = ([[a b]; [1 2] [3 4] [5 6]] | into df) > $a @@ -433,7 +433,7 @@ $group | agg [ 我们可以在一个 DataFrame 中添加列,以创建一个新的变量。作为一个例子,让我们在迷你 DataFrame `$a` 上添加两列: -```shell +```nu > let a2 = ($a | with-column $a.a --name a2 | with-column $a.a --name a3) ───┬───┬───┬────┬──── @@ -447,7 +447,7 @@ $group | agg [ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数据并将其附加到这些 DataFrame 中来创建新的 DataFrame。现在,如果你列出你的 DataFrame,你会看到总共有四个: -```shell +```nu > dfr ls ───┬───────┬──────┬───────── @@ -468,7 +468,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 让我们通过使用 `into df` 命令创建一个系列,来开始我们对系列的探索: -```shell +```nu > let new = ([9 8 4] | into df) > $new @@ -485,7 +485,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 系列已经定义了自己的基本操作,它们可以用来创建其他系列。让我们通过对先前创建的列进行一些运算来创建一个新的系列: -```shell +```nu > let new_2 = ($new * 3 + 10) > $new_2 @@ -506,7 +506,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 让我们重新命名我们之前的系列为 `memorable` -```shell +```nu > let new_2 = ($new_2 | rename "0" memorable) > $new_2 @@ -521,7 +521,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 只要两个系列的数据类型相同,我们也可以对它们进行基本操作: -```shell +```nu > $new - $new_2 ───┬────────── @@ -535,7 +535,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 而且我们可以将它们添加到先前定义的 DataFrames 中: -```shell +```nu > let new_df = ($a | with-column $new --name new_col) > $new_df @@ -550,7 +550,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 存储在 DataFrame 中的系列也可以直接使用,例如,我们可以将列`a`和`b`相乘来创建一个新系列: -```shell +```nu > $new_df.a * $new_df.b ───┬───────── @@ -564,7 +564,7 @@ Nushell 强大的管道语法允许我们通过从其他 DataFrame 中获取数 我们可以开始使用管道,以创建新的列和 DataFrames: -```shell +```nu > let $new_df = ($new_df | with-column ($new_df.a * $new_df.b / $new_df.new_col) --name my_sum) > let $new_df @@ -583,7 +583,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 在使用 DataFrames 时,系列还有另一个关键用途,那就是我们可以用它们来建立布尔掩码(Mask)。让我们先用等于运算符创建一个简单的掩码: -```shell +```nu > let mask = ($new == 8) > $mask @@ -598,7 +598,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 有了这个掩码,我们现在可以过滤一个 DataFrame,像这样: -```shell +```nu > $new_df | filter-with $mask ───┬───┬───┬─────────┬──────── @@ -612,7 +612,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 掩码也可以从 Nushell 列表中创建,比如: -```shell +```nu > let mask1 = ([true true false] | into df) > $new_df | filter-with $mask1 @@ -626,7 +626,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 为了创建复杂的掩码,我们可以使用`AND`: -```shell +```nu > $mask and $mask1 ───┬────────────────── @@ -640,7 +640,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 或者 `OR` 操作: -```shell +```nu > $mask or $mask1 ───┬───────────────── @@ -654,7 +654,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 我们也可以通过检查某些值是否存在于其他系列来创建一个掩码。使用我们创建的第一个 DataFrame,我们可以这样做: -```shell +```nu > let mask3 = ($df.first | is-in ([b c] | into df)) ───┬────── @@ -675,7 +675,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 而这个新的掩码可以用来过滤 DataFrame -```shell +```nu > $df | filter-with $mask3 ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬───────── @@ -693,7 +693,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 另一个可以用掩码进行的操作是设置或替换一个系列的值。例如,我们可以改变列`first`中的值,如果该值包含`a`: -```shell +```nu > $df.first | set new --mask ($df.first =~ a) ───┬──────── @@ -716,7 +716,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 系列也可以作为过滤 DataFrame 的一种方式,将它们作为索引列表使用。例如,假设我们想从原始 DataFrame 中获取第1、4和6行。针对这一点,我们可以使用以下命令来提取这些信息: -```shell +```nu > let indices = ([1 4 6] | into df) > $df | take $indices @@ -732,7 +732,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 命令 `take` 非常方便,特别是当我们把它与其他命令混合使用时。 假设我们想提取 `first` 列中含有第一个重复的元素的的所有记录。为了做到这一点,我们可以使用 `arg-unique` 命令,如下例所示: -```shell +```nu > let indices = ($df.first | arg-unique) > $df | take $indices @@ -751,7 +751,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 同样的结果也可以用`sort`命令来完成。 ::: -```shell +```nu > let indices = ($df.word | arg-sort) > $df | take $indices @@ -773,7 +773,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 最后,我们可以通过在标记的索引中设置一个新值来创建新的系列。请看下一条命令: -```shell +```nu > let indices = ([0 2] | into df); > $df.int_1 | set-with-idx 123 --indices $indices @@ -799,7 +799,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 第一个也是最常见的操作是`value_counts`。这个命令计算出一个系列中存在的唯一值的数量。例如,我们可以用它来计算 `first` 列各值的出现次数: -```shell +```nu > $df.first | value-counts ───┬───────┬──────── @@ -815,7 +815,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 继续我们对 `Series` 的探索,我们要做的下一件事是只从一个系列中获得唯一值,像这样: -```shell +```nu > $df.first | unique ───┬─────── @@ -829,7 +829,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 或者我们可以得到一个掩码,用来过滤出数据唯一或重复的行。例如,我们可以选择列 `word` 中含唯一值的行: -```shell +```nu > $df | filter-with ($df.word | is-unique) ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬─────── @@ -842,7 +842,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 或所有含重复值的行: -```shell +```nu > $df | filter-with ($df.word | is-duplicated) ───┬───────┬───────┬─────────┬─────────┬───────┬────────┬───────┬──────── @@ -866,7 +866,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 让我们创建一个惰性 Dataframe 的小例子: -```shell +```nu > let a = ([[a b]; [1 a] [2 b] [3 c] [4 d]] | into lazy) > $a ────────────────┬──────────────────────────────────────────────── @@ -882,7 +882,7 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 正如你所看到的,产生的 Dataframe 还没有被评估,它以一组可以对数据进行操作的指令的形式存在。 如果你要收集这个 Dataframe,你会得到如下结果: -```shell +```nu > $a | collect ───┬───┬─── # │ a │ b @@ -901,13 +901,13 @@ Nushell 的管道系统可以帮助你创建非常有趣的工作流程。 要找到所有惰性 Dataframe 操作,你可以使用: -```shell +```nu $nu.scope.commands | where category =~ lazyframe ``` 在定义了你的惰性 Dataframe 后,我们可以开始对它进行链式操作。例如: -```shell +```nu > $a ::: | reverse ::: | with-column [ @@ -933,26 +933,26 @@ $nu.scope.commands | where category =~ lazyframe `expression` 用于定义在惰性 Dataframe 上执行的操作。当它们组合在一起时,就形成了整个由惰性命令来查询数据的 指令集。要列出所有产生表达式的命令,你可以使用: -```shell +```nu $nu.scope.commands | where category =~ expression ``` 在我们前面的例子中,我们使用 `col` 命令来表示列 `a` 将被乘以2,然后它将被命名为 `double_a`。 在某些情况下,可以推断出 `col` 命令的使用,例如,使用 `select` 命令,我们可以只使用一个字符串: -```shell +```nu > $a | select a | collect ``` 或者使用 `col` 命令: -```shell +```nu > $a | select (col a) | collect ``` 让我们尝试更复杂的东西,从一个惰性 Dataframe 中创建聚合: -```shell +```nu > let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | into lazy ) > $a ::: | group-by name @@ -971,7 +971,7 @@ $nu.scope.commands | where category =~ expression 我们可以在一个还没有被收集的惰性 Dataframe 上进行连接操作。让我们把产生的分组连接到原来的惰性 Dataframe 中去吧 -```shell +```nu > let a = ( [[name value]; [one 1] [two 2] [one 1] [two 3]] | into lazy ) > let group = ($a ::: | group-by name diff --git a/zh-CN/book/hooks.md b/zh-CN/book/hooks.md index 025ac301436..8ffa9657ddb 100644 --- a/zh-CN/book/hooks.md +++ b/zh-CN/book/hooks.md @@ -23,7 +23,7 @@ 要想使用钩子需要先在 [配置](configuration.md) 中定义它们: -```shell +```nu $env.config = { # ...other config... @@ -42,7 +42,7 @@ $env.config = { 可以为每个触发器只定义一个钩子,也可以定义一个**钩子列表**,让其依次运行: -```shell +```nu $env.config = { ...other config... @@ -67,7 +67,7 @@ $env.config = { 另外,用新的钩子更新现有的配置,而不是从头开始定义整个配置可能更实用: -```shell +```nu $env.config = ($env.config | upsert hooks { pre_prompt: ... pre_execution: ... @@ -83,7 +83,7 @@ $env.config = ($env.config | upsert hooks { 在钩子**代码块**内定义的环境变量将以类似于 [`def-env`](environment.md#从自定义命令中定义环境变量) 的方式被保留下来。 你可以用下面的例子测试一下: -```shell +```nu > $env.config = ($env.config | upsert hooks { pre_prompt: { $env.SPAM = "eggs" } }) @@ -117,7 +117,7 @@ $env.config = ($env.config | upsert hooks { 为了处理上述问题,我们引入了另一种定义钩子的方式 -- **记录**: -```shell +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: [ @@ -145,7 +145,7 @@ $env.config = ($env.config | upsert hooks { 你可以把它想成是你在 REPL 中输入字符串并点击回车键。 所以,上一节中的钩子也可以写成: -```shell +```nu > $env.config = ($env.config | upsert hooks { pre_prompt: '$env.SPAM = "eggs"' }) @@ -156,7 +156,7 @@ eggs 这个功能可以用来,例如,根据当前目录有条件地引入定义: -```shell +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: [ @@ -175,7 +175,7 @@ $env.config = ($env.config | upsert hooks { 当把钩子定义为字符串时,`$before` 和 `$after` 变量分别被设置为之前和当前的环境变量值,这与前面的例子类似: -```shell +```nu $env.config = ($env.config | upsert hooks { env_change: { PWD: { @@ -191,7 +191,7 @@ $env.config = ($env.config | upsert hooks { 一个关于 `PWD` 环境变化的例子: -```shell +```nu $env.config = ($env.config | upsert hooks.env_change.PWD {|config| let val = ($config | get -i hooks.env_change.PWD) @@ -209,7 +209,7 @@ $env.config = ($env.config | upsert hooks.env_change.PWD {|config| 以下代码将在进入一个目录('/path/to/target/dir')后寻找 `test-env.nu` 并加载,而在离开该目录的时候移除相关定义(除了 `PWD` 环境变量): -```shell +```nu $env.config = ($env.config | upsert hooks.env_change.PWD { [ { diff --git a/zh-CN/book/overlays.md b/zh-CN/book/overlays.md index 54289bbd429..74fee642f69 100644 --- a/zh-CN/book/overlays.md +++ b/zh-CN/book/overlays.md @@ -13,7 +13,7 @@ _注意:要了解覆层,请确保先查看 [模块](modules.md),因为覆 要创建一个新的覆层,你首先需要一个模块: -```shell +```nu > module spam { export def foo [] { "foo" @@ -31,7 +31,7 @@ _注意:要了解覆层,请确保先查看 [模块](modules.md),因为覆 要创建覆层,请调用 [`overlay use`](/commands/docs/overlay_add.md)。 -```shell +```nu > overlay use spam > foo @@ -57,7 +57,7 @@ baz 如果你不再需要叠加定义,请调用 [`overlay hide`](/commands/docs/overlay_remove.md): -```shell +```nu (spam)> overlay hide spam (zero)> foo @@ -72,7 +72,7 @@ Error: Can't run executable... 覆层也是有作用域的。 任何添加的覆层都会在作用域结束时被移除: -```shell +```nu (zero)> do { overlay use spam; foo } foo @@ -88,7 +88,7 @@ foo 任何新的定义(命令、别名、环境变量)都会被记录到最后一个活动的覆层: -```shell +```nu (zero)> overlay use spam (spam)> def eggs [] { "eggs" } @@ -97,7 +97,7 @@ foo 现在,`eggs` 命令属于 `spam` 覆层。 如果我们删除该覆层,我们就不能再调用它: -```shell +```nu (spam)> overlay hide spam (zero)> eggs @@ -106,7 +106,7 @@ Error: Can't run executable... 但是,我们可以把它找回来! -```shell +```nu (zero)> overlay use spam (spam)> eggs @@ -120,7 +120,7 @@ eggs 有时,在添加一个覆层后,你可能不希望自定义对象被添加到其中。 解决的办法是创建一个新的空的覆层,只用来记录自定义的变化: -```shell +```nu (zero)> overlay use spam (spam)> module scratchpad { } @@ -135,7 +135,7 @@ eggs _0.64 版本新增:_ 为了让上述步骤不那么冗长,你可以使用 [`overlay new`](/commands/docs/overlay_new.md) 命令: -```shell +```nu (zero)> overlay use spam (spam)> overlay new scratchpad @@ -149,7 +149,7 @@ _0.64 版本新增:_ 有时,你可能想删除一个覆层,但保留所有你添加的自定义定义,而不必在下一个活动覆层中重新定义它们: -```shell +```nu (zero)> overlay use spam (spam)> def eggs [] { "eggs" } @@ -168,7 +168,7 @@ eggs 如果多个覆层包含相同的定义,比如 `foo`,最后一个活动的覆层将优先。 要把某个覆层放到堆栈的顶部,你可以再次调用 `overlay use`: -```shell +```nu (zero)> def foo [] { "foo-in-zero" } (zero)> overlay use spam diff --git a/zh-CN/book/pipelines.md b/zh-CN/book/pipelines.md index 105a2fa34b6..c886e789473 100644 --- a/zh-CN/book/pipelines.md +++ b/zh-CN/book/pipelines.md @@ -18,7 +18,7 @@ Nu 的核心设计之一是管道,这个设计思想可以追溯到几十年 `$in` 变量可以将管道收集成一个值,允许你将整个流作为一个参数访问,比如: -```shell +```nu > echo 1 2 3 | $in.1 * $in.2 6 ``` diff --git a/zh-CN/book/types_of_data.md b/zh-CN/book/types_of_data.md index d1e599a5460..dc788827d74 100644 --- a/zh-CN/book/types_of_data.md +++ b/zh-CN/book/types_of_data.md @@ -19,7 +19,7 @@ Nu 在其命令中采用了这种方法,并将其扩展到包括其他类型 整数(或整形)数字:例子包括 1、5 和 100。 你可以用 `into int` 命令将一个字符串转换成一个整数: -```shell +```nu > "1" | into int ``` @@ -28,7 +28,7 @@ Nu 在其命令中采用了这种方法,并将其扩展到包括其他类型 小数是指带有一些小数成分的数字,例如,1.5,2.0,和 15.333。 你可以用 `into decimal` 命令将一个字符串转换成一个小数: -```shell +```nu > "1.2" | into decimal ``` @@ -86,7 +86,7 @@ Nushell 的一个独特特征是,你也可以创建一个没有任何引号的 通过 `into ` 命令将一个字符串转换为另一种类型: -```shell +```nu > "1" | into int > "1.2" | into decimal ``` diff --git a/zh-CN/book/working_with_strings.md b/zh-CN/book/working_with_strings.md index 66fe61fd855..54c9d3aba75 100644 --- a/zh-CN/book/working_with_strings.md +++ b/zh-CN/book/working_with_strings.md @@ -6,7 +6,7 @@ Nushell 中的字符串用于保存文本数据以便后续使用,其中可以 Nushell 中最简单的字符串是单引号字符串。这种字符串使用`'`字符来包裹文本。下面是作为单引号字符串的`hello world`示例: -```sh +```nu > 'hello world' hello world ``` @@ -19,7 +19,7 @@ hello world 例如,我们可以用转义字符和双引号字符串写出文字 hello,然后换行,再写上 world: -```sh +```nu > "hello\nworld" hello world @@ -48,7 +48,7 @@ Nushell 目前支持以下转义字符: 例如,假设我们有一个叫做`$name`的变量,我们想问候这个变量中所包含的人: -```sh +```nu > let name = "Alice" > $"greetings, ($name)" greetings, Alice @@ -60,7 +60,7 @@ greetings, Alice 从 0.61 版开始,字符串插值支持转义小括号,所以`(`和`)`字符可以在一个字符串中使用,而 Nushell 不会试图计算它们之间出现的内容: -```sh +```nu > $"2 + 2 is (2 + 2) \(you guessed it!)" 2 + 2 is 4 (you guessed it!) ``` @@ -80,7 +80,7 @@ greetings, Alice 例如, 你可以使用`str contains`来检查一个字符串是否包含某个特定的字符: -```sh +```nu > "hello world" | str contains "w" true ``` @@ -89,7 +89,7 @@ true 你可以用 [`str trim`](/commands/docs/str_trim.md) 命令修剪字符串的两侧。默认情况下,[`str trim`](/commands/docs/str_trim.md) 命令会修剪字符串两边的空白。比如: -```sh +```nu > ' My string ' | str trim My string ``` @@ -100,7 +100,7 @@ My string 下面是一个传入了所有选项的例子: -```sh +```nu > '=== Nu shell ===' | str trim -r -c '=' === Nu shell ``` @@ -109,7 +109,7 @@ My string 子字符串是一个字符串的切片,它们有起始点和结束点。下面是一个使用子串的例子: -```sh +```nu > 'Hello World!' | str index-of 'o' 4 > 'Hello World!' | str index-of 'r' @@ -122,7 +122,7 @@ o Wo 使用 [`str lpad`](/commands/docs/str_lpad.md) 和 [`str rpad`](/commands/docs/str_rpad.md) 命令,你可以给字符串添加填充。填充会给字符串添加字符,直到它达到一定的长度。比如: -```sh +```nu > '1234' | str lpad -l 10 -c '0' 0000001234 > '1234' | str rpad -l 10 -c '0' | str length @@ -133,7 +133,7 @@ o Wo 反转字符串可以通过 [`str reverse`](/commands/docs/str_reverse.md) 命令轻松完成: -```sh +```nu > 'Nushell' | str reverse llehsuN > ['Nushell' 'is' 'cool'] | str reverse @@ -148,7 +148,7 @@ llehsuN 通过 [`parse`](/commands/docs/parse.md) 命令,你可以将一个字符串解析成若干列。比如: -```sh +```nu > 'Nushell is the best' | parse '{shell} is {type}' ╭───┬─────────┬──────────╮ │ # │ shell │ type │ @@ -181,7 +181,7 @@ llehsuN 你可以通过 [`ansi`](/commands/docs/ansi.md) 命令给字符串着色。例如: -```sh +```nu > $'(ansi purple_bold)This text is a bold purple!(ansi reset)' ``` diff --git a/zh-CN/book/working_with_tables.md b/zh-CN/book/working_with_tables.md index 193eab19825..47d2201a427 100644 --- a/zh-CN/book/working_with_tables.md +++ b/zh-CN/book/working_with_tables.md @@ -184,7 +184,7 @@ 我们可以使用[`merge`](/commands/docs/merge.md)命令将两个(或多个)表格合并在一起: -```shell +```nu > let $first = [[a b]; [1 2]] > let $second = [[c d]; [3 4]] > $first | merge { $second } @@ -197,13 +197,13 @@ 让我们再加一个表格吧: -```shell +```nu > let $third = [[e f]; [5 6]] ``` 我们可以将以上三个表格合并在一起,操作如下: -```shell +```nu > $first | merge { $second } | merge { $third } ───┬───┬───┬───┬───┬───┬─── # │ a │ b │ c │ d │ e │ f @@ -214,7 +214,7 @@ 或者我们可以使用[`reduce`](/commands/docs/reduce.md)命令来动态地合并所有的表格: -```shell +```nu > [$first $second $third] | reduce {|it, acc| $acc | merge { $it }} ───┬───┬───┬───┬───┬───┬─── # │ a │ b │ c │ d │ e │ f