diff --git a/3rdpartyprompts.md b/3rdpartyprompts.md new file mode 100644 index 0000000000000000000000000000000000000000..cadc623c660877eff0f26c09a0bc241ddfd19f90 --- /dev/null +++ b/3rdpartyprompts.md @@ -0,0 +1,99 @@ +# How to configure 3rd party prompts + +## nerdfonts + +nerdfonts are not required but they make the presentation much better. + +[site](https://www.nerdfonts.com) + +[repo](https://github.com/ryanoasis/nerd-fonts) + +## oh-my-posh + +[site](https://ohmyposh.dev/) + +[repo](https://github.com/JanDeDobbeleer/oh-my-posh) + +If you like [oh-my-posh](https://ohmyposh.dev/), you can use oh-my-posh with Nushell with a few steps. It works great with Nushell. How to setup oh-my-posh with Nushell: + +1. Install Oh My Posh and download oh-my-posh's themes following [guide](https://ohmyposh.dev/docs/installation/linux). +2. Download and install a [nerd font](https://github.com/ryanoasis/nerd-fonts). +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. + +```nu +# Generate the .oh-my-posh.nu file +> 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 +``` + +For MacOS users: + +1. You can install oh-my-posh by `brew`, just following the [guide here](https://ohmyposh.dev/docs/installation/macos) +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: + +```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/ +# material/half-life/lambda Or double lines theme: amro/pure/spaceship, etc. +# For more [Themes demo](https://ohmyposh.dev/docs/themes) +$env.PROMPT_COMMAND = { || oh-my-posh prompt print primary --config $'($posh_theme)/zash.omp.json' } +# Optional +$env.PROMPT_INDICATOR = $"(ansi y)$> (ansi reset)" +``` + +## Starship + +[site](https://starship.rs/) + +[repo](https://github.com/starship/starship) + +1. Follow the links above and install Starship. +2. Install nerdfonts depending on your preferences. +3. Use the config example below. Make sure to set the `STARSHIP_SHELL` environment variable. + +::: tip +An alternate way to enable Starship is described in the [Starship Quick Install](https://starship.rs/#nushell) instructions. + +The link above is the official integration of Starship and Nushell and is the simplest way to get +Starship running without doing anything manual: + +- Starship will create its own configuration / environment setup script +- you simply have to create it in `env.nu` and `use` it in `config.nu` + ::: + +Here's an example config section for Starship: + +```nu +$env.STARSHIP_SHELL = "nu" + +def create_left_prompt [] { + starship prompt --cmd-duration $env.CMD_DURATION_MS $'--status=($env.LAST_EXIT_CODE)' +} + +# Use nushell functions to define your right and left prompt +$env.PROMPT_COMMAND = { || create_left_prompt } +$env.PROMPT_COMMAND_RIGHT = "" + +# The prompt indicators are environmental variables that represent +# the state of the prompt +$env.PROMPT_INDICATOR = "" +$env.PROMPT_INDICATOR_VI_INSERT = ": " +$env.PROMPT_INDICATOR_VI_NORMAL = "ใ" +$env.PROMPT_MULTILINE_INDICATOR = "::: " +``` + +Now restart Nu. + +``` +nushell on ๐ main is ๐ฆ v0.60.0 via ๐ฆ v1.59.0 +โฏ +``` + +## Purs + +[repo](https://github.com/xcambar/purs) diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ecf96b0b1bda96912bca402fa09b797280de000a --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# Introduction + +Hello, and welcome to the Nushell project. +The goal of this project is to take the Unix philosophy of shells, where pipes connect simple commands together, and bring it to the modern style of development. +Thus, rather than being either a shell, or a programming language, Nushell connects both by bringing a rich programming language and a full-featured shell together into one package. + +Nu takes cues from a lot of familiar territory: traditional shells like bash, object based shells like PowerShell, gradually typed languages like TypeScript, functional programming, systems programming, and more. But rather than trying to be a jack of all trades, Nu focuses its energy on doing a few things well: + +- Being a flexible cross-platform shell with a modern feel +- Solving problems as a modern programming language that works with the structure of your data +- Giving clear error messages and clean IDE support + +## This Book + +The book is split into chapters which are further broken down into sections. +You can click on the chapter headers to get more information about it. + +- [Getting Started](getting_started.md) teaches you how to install Nushell and shows you the ropes. It also explains some of the design principles where Nushell differs from typical shells, such as bash. +- [Nu Fundamentals](nu_fundamentals.md) explains basic concepts of the Nushell language. +- [Programming in Nu](programming_in_nu.md) dives more deeply into the language features and shows several ways how to organize and structure your code. +- [Nu as a Shell](nu_as_a_shell.md) focuses on the shell features, most notably the configuration and environment. +- [Coming to Nu](coming_to_nu.md) is intended to give a quick start for users coming from other shells or languages. +- [Design Notes](design_notes.md) has in-depth explanation of some of the Nushell's design choices. +- [(Not So) Advanced](advanced.md) includes some more advanced topics (they are not _so_ advanced, make sure to check them out, too!). + +## The Many Parts of Nushell + +The Nushell project consists of multiple different repositories and subprojects. +You can find all of them under [our organization on GitHub](https://github.com/nushell). + +- The main Nushell repository can be found [here](https://github.com/nushell/nushell). It is broken into multiple crates that can be used as independent libraries in your own project, if you wish so. +- The repository of our [nushell.sh](https://www.nushell.sh) page, including this book, can be found [here](https://github.com/nushell/nushell.github.io). +- Nushell has its own line editor which [has its own repository](https://github.com/nushell/reedline) +- [`nu_scripts`](https://github.com/nushell/nu_scripts) is a place to share scripts and modules with other users until we have some sort of package manager. +- [Nana](https://github.com/nushell/nana) is an experimental effort to explore graphical user interface for Nushell. +- [Awesome Nu](https://github.com/nushell/awesome-nu) contains a list of tools that work with the Nushell ecosystem: plugins, scripts, editor extension, 3rd party integrations, etc. +- [Nu Showcase](https://github.com/nushell/showcase) is a place to share works about Nushell, be it blogs, artwork or something else. +- [Request for Comment (RFC)](https://github.com/nushell/rfcs) serves as a place to propose and discuss major design changes. While currently under-utilized, we expect to use it more as we get closer to and beyond 1.0. + +## Contributing + +We welcome contributions! +[As you can see](#the-many-parts-of-nushell), there are a lot of places to contribute to. +Most repositories contain `CONTRIBUTING.md` file with tips and details that should help you get started (if not, consider contributing a fix!). + +Nushell itself is written in [Rust](https://www.rust-lang.org). +However, you do not have to be a Rust programmer to help. +If you know some web development, you can contribute to improving this website or the Nana project. +[Dataframes](dataframes.md) can use your data processing expertise. + +If you wrote a cool script, plugin or integrated Nushell somewhere, we'd welcome your contribution to `nu_scripts` or Awesome Nu. +Discovering bugs with reproduction steps and filing GitHub issues for them is a valuable help, too! +You can contribute to Nushell just by using Nushell! + +Since Nushell evolves fast, this book is in a constant need of updating. +Contributing to this book does not require any special skills aside from a basic familiarity with Markdown. +Furthermore, you can consider translating parts of it to your language. + +## Community + +The main place to discuss anything Nushell is our [Discord](https://discord.com/invite/NtAbbGn). +You can also follow us on [Twitter](https://twitter.com/nu_shell) for news and updates. +Finally, you can use the GitHub discussions or file GitHub issues. diff --git a/advanced.md b/advanced.md new file mode 100644 index 0000000000000000000000000000000000000000..566ec9c963aaf2db9037f47fbbd57034d7c0c9ff --- /dev/null +++ b/advanced.md @@ -0,0 +1,20 @@ +# (Not So) Advanced + +While the "Advanced" title might sound daunting and you might be tempted to skip this chapter, in fact, some of the most interesting and powerful features can be found here. + +Besides the built-in commands, Nushell has a [standard library](standard_library.md). + +Nushell operates on _structured data_. +You could say that Nushell is a "data-first" shell and a programming language. +To further explore the data-centric direction, Nushell includes a full-featured dataframe processing engine using [Polars](https://github.com/pola-rs/polars) as the backend. +Make sure to check the [Dataframes documentation](dataframes.md) if you want to process large data efficiently directly in your shell. + +Values in Nushell contain some extra [metadata](metadata.md). +This metadata can be used, for example, to [create custom errors](creating_errors.md). + +Thanks to Nushell's strict scoping rules, it is very easy to [iterate over collections in parallel](parallelism.md) which can help you speed up long-running scripts by just typing a few characters. + +You can [interactively explore data](explore.md) with the [`explore`](/commands/docs/explore.md) command. + +Finally, you can extend Nushell's functionality with [plugins](plugins.md). +Almost anything can be a plugin as long as it communicates with Nushell in a protocol that Nushell understands. diff --git a/aliases.md b/aliases.md new file mode 100644 index 0000000000000000000000000000000000000000..b372d3295c2a50f576bd85bf2df9c1d5b10b13b7 --- /dev/null +++ b/aliases.md @@ -0,0 +1,112 @@ +# Aliases + +Aliases in Nushell offer a way of doing a simple replacement of command calls (both external and internal commands). This allows you to create a shorthand name for a longer command, including its default arguments. + +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 +``` + +And get the equivalent to having typed `ls -l -a`. + +## List all loaded aliases + +Your useable aliases can be seen in `scope aliases` and `help aliases`. + +## Persisting + +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_ + +```nu +$env.config = { + # main configuration +} + +alias ll = ls -l + +# some other config and script loading +``` + +## Piping in aliases + +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 } +``` + +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 } +``` + +displaying all listed files and folders in a grid. + +## Replacing existing commands using aliases + +> Caution! When replacing commands it is best to "back up" the command first and avoid recursion error. + +How to back up a command like `ls`: +```nu +alias core-ls = ls # This will create a new alias core-ls for ls +``` +Now you can use `core-ls` as `ls` in your nu-programming. You will see further down how to use `core-ls`. + +The reason you need to use alias is because, unlike `def`, aliases are position-dependent. So, you need to "back up" the old command first with an alias, before re-defining it. +If you do not backup the command and you replace the command using `def` you get a recursion error. + +```nu +def ls [] { ls }; ls # Do *NOT* do this! This will throw a recursion error + +#output: +#Error: nu::shell::recursion_limit_reached +# +# ร Recursion limit (50) reached +# โญโ[C:\Users\zolodev\AppData\Roaming\nushell\config.nu:807:1] +# 807 โ +# 808 โ def ls [] { ls }; ls +# ยท โโโโฌโโ +# ยท โฐโโ This called itself too many times +# โฐโโโโ +``` + +The recommended way to replace an existing command is to shadow the command. +Here is an example shadowing the `ls` command. + +```nu +# An escape hatch to have access to the original ls command +alias core-ls = ls + +# Call the built-in ls command with a path parameter +def old-ls [path] { + core-ls $path | sort-by type name -i +} + +# Shadow the ls command so that you always have the sort type you want +def ls [path?] { + if $path == null { + old-ls . + } else { + old-ls $path + } +} +``` + diff --git a/background_task.md b/background_task.md new file mode 100644 index 0000000000000000000000000000000000000000..81cbf5fc1243fcb1eefe3ef432323b37bfea190f --- /dev/null +++ b/background_task.md @@ -0,0 +1,34 @@ +# Background tasks with Nu + +Currently, Nushell doesn't have built-in background task management feature, but you can make it "support" background task with some tools, here are some examples: + +1. Using a third-party task management tools, like [pueue](https://github.com/Nukesor/pueue) +2. Using a terminal multiplexer, like [tmux](https://github.com/tmux/tmux/wiki) or [zellij](https://zellij.dev/) + +## Using nu with pueue + +The module borrows the power of [pueue](https://github.com/Nukesor/pueue), it is possible to schedule background tasks to pueue, and manage those tasks (such as viewing logs, killing tasks, or getting the running status of all tasks, creating groups, pausing tasks etc etc) + +Unlike terminal multiplexer, you don't need to attach to multiple tmux sessions, and get task status easily. + +Here we provide a [nushell module](https://github.com/nushell/nu_scripts/tree/main/modules/background_task) to work with pueue easiler. + +Here is a setup example to make Nushell "support" background tasks: + +1. Install pueue +2. run `pueued`, you can refer to [start-the-daemon page](https://github.com/Nukesor/pueue/wiki/Get-started#start-the-daemon) for more information. +3. Put the [task.nu](https://github.com/nushell/nu_scripts/blob/main/modules/background_task/task.nu) file under `$env.NU_LIB_DIRS`. +4. Add a line to the `$nu.config-path` file: `use task.nu` +5. Restart Nushell. + +Then you will get some commands to schedule background tasks. (e.g: `task spawn`, `task status`, `task log`) + +Cons: It spawns a new Nushell interpreter to execute every single task, so it doesn't inherit current scope's variables, custom commands, alias definition. +It only inherits environment variables whose value can be converted to a string. +Therefore, if you want to use custom commands or variables, you have to [`use`](/commands/docs/use.md) or [`def`](/commands/docs/def.md) them within the given block. + +## Using nu with terminal multiplexer + +You can choose and install a terminal multiplexer and use it. + +It allows you to easily switch between multiple programs in one terminal, detach them (they continue to run in the background) and reconnect them to a different terminal. As a result, it is very flexible and usable. diff --git a/cheat_sheet.md b/cheat_sheet.md new file mode 100644 index 0000000000000000000000000000000000000000..def5666f897595d4de8bd4abbbe121dd4966124e --- /dev/null +++ b/cheat_sheet.md @@ -0,0 +1,549 @@ +# Nushell cheat sheet + +## Data types + +```nu + > "12" | into int +``` + +> **converts string to integer** + +--- + +```nu + > date now | date to-timezone "Europe/London" +``` + +> **converts present date to provided time zone** + +--- + +```nu + > {'name': 'nu', 'stars': 5, 'language': 'Python'} | upsert language 'Rust' +``` + +> **updates a record's language and if none is specified inserts provided value** + +--- + +```nu + > [one two three] | to yaml +``` + +> **converts list of strings to yaml** + +--- + +```nu + > [[framework, language]; [Django, Python] [Lavarel, PHP]] +``` + +> **prints the table** + +--- + +```nu + > [{name: 'Robert' age: 34 position: 'Designer'} + {name: 'Margaret' age: 30 position: 'Software Developer'} + {name: 'Natalie' age: 50 position: 'Accountant'} + ] | select name position +``` + +> **selects two columns from the table and prints their values** + +## Strings + +```nu + > let name = "Alice" + > $"greetings, ($name)!" +``` + +> **prints `greetings, Alice!`** + +--- + +```nu + > let string_list = "one,two,three" | split row "," + $string_list + + โญโโโโฌโโโโโโโโฎ + โ 0 โ one โ + โ 1 โ two โ + โ 2 โ three โ + โฐโโโโดโโโโโโโโฏ +``` + +> **splits the string with specified delimiter and saves the list to `string_list` variable** + +--- + +```nu + "Hello, world!" | str contains "o, w" +``` + +> **checks if a string contains a substring and returns `boolean`** + +--- + +```nu + let str_list = [zero one two] + $str_list | str join ',' +``` + +> **joins the list of strings using provided delimiter** + +--- + +```nu + > 'Hello World!' | str substring 4..8 +``` + +> **created a slice from a given string with start (4) and end (8) indices** + +--- + +```nu + > 'Nushell 0.80' | parse '{shell} {version}' + + โญโโโโฌโโโโโโโโโโฌโโโโโโโโโโฎ + โ # โ shell โ version โ + โโโโโผโโโโโโโโโโผโโโโโโโโโโค + โ 0 โ Nushell โ 0.80 โ + โฐโโโโดโโโโโโโโโโดโโโโโโโโโโฏ +``` + +> **parses the string to columns** + +```nu + > "acronym,long\nAPL,A Programming Language" | from csv +``` + +> **parses comma separated values (csv)** + +```nu + > $'(ansi purple_bold)This text is a bold purple!(ansi reset)' +``` + +> **ansi command colors the text (alsways end with `ansi reset` to reset color to default)** + +## Lists + +```nu + > [foo bar baz] | insert 1 'beeze' + + โญโโโโฌโโโโโโโโฎ + โ 0 โ foo โ + โ 1 โ beeze โ + โ 2 โ bar โ + โ 3 โ baz โ + โฐโโโโดโโโโโโโโฏ +``` + +> **inserts `beeze` value at st index in the list** + +--- + +```nu + > [1, 2, 3, 4] | update 1 10 +``` + +> **updates 2nd value to 10** + +--- + +```nu + > let numbers = [1, 2, 3, 4, 5] + > $numbers | prepend 0 +``` + +> **adds value at the beginning of the list** + +--- + +```nu + > let numbers = [1, 2, 3, 4, 5] + > $numbers | append 6 +``` + +> **adds value at the end of the list** + +--- + +```nu + > let flowers = [cammomile marigold rose forget-me-not] + > let flowers = ($flowers | first 2) + > $flowers +``` + +> **creates slice of first two values from `flowers` list** + +--- + +```nu + > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] + > $planets | each { |it| $"($it) is a planet of solar system" } +``` + +> **iterates over a list; `it` is current list value** + +--- + +```nu + > $planets | enumerate | each { |it| $"($it.index + 1) - ($it.item)" } +``` + +> **iterates over a list and provides index and value in `it`** + +--- + +```nu + > let scores = [3 8 4] + > $"total = ($scores | reduce { |it, acc| $acc + $it })" +``` + +> **reduces the list to a single value, `reduce` gives access to accumulator that is applied +> to each element in the list** + +--- + +```nu + > $"total = ($scores | reduce --fold 1 { |it, acc| $acc * $it })" +``` + +> **initial value for accumulator value can be set with `--fold`** + +--- + +```nu + > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] + > $planets.2 + > Earth +``` + +> **gives access to the 3rd item in the list** + +--- + +```nu + > let planets = [Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune] + > $planets | any {|it| $it | str starts-with "E" } + > true +``` + +> **checks if any string in the list starts with `E`** + +--- + +```nu + > let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond + โญโโโโฌโโโโโฎ + โ 0 โ -1 โ + โ 1 โ -2 โ + โฐโโโโดโโโโโฏ +``` + +> **creates slice of items that satisfy provided condition** + +## Tables + +```nu + > ls | sort-by size +``` + +> **sorting table by size of files** + +--- + +```nu + > ls | sort-by size | first 5 +``` + +> **sorting table by size of files and show first 5 entries** + +--- + +```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 + + โญโโโโฌโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโฎ + โ # โ first_column โ second_column โ third_column โ + โโโโโผโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโค + โ 0 โ foo โ bar โ snooze โ + โ 1 โ hex โ seeze โ feeze โ + โฐโโโโดโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโฏ +``` + +> **concatenate two tables with same columns** + +--- + +```nu + > let teams_scores = [[team score plays]; ['Boston Celtics' 311 3] ['Golden State Warriors', 245 2]] + > $teams_scores | drop column + + โญโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโฎ + โ # โ team โ score โ + โโโโโผโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโค + โ 0 โ Boston Celtics โ 311 โ + โ 1 โ Golden State Warriors โ 245 โ + โฐโโโโดโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโฏ +``` + +> **remove the last column of a table** + +## Files & Filesystem + +```nu + > start file.txt +``` + +> **opens a text file with the default text editor** + +--- + +```nu + > 'lorem ipsum ' | save file.txt +``` + +> **saves a string to text file** + +--- + +```nu + > 'dolor sit amet' | save --append file.txt +``` + +> **appends a string to the end of file.txt** + +--- + +```nu + > { a: 1, b: 2 } | save file.json +``` + +> **saves a record to file.json** + +--- + +```nu + > glob **/*.{rs,toml} --depth 2 +``` + +> **searches for `.rs` and `.toml` files recursively up to 2 folders deep** + +--- + +```nu + > watch . --glob=**/*.rs {|| cargo test } +``` + +> **runs cargo test whenever a Rust file changes** + +--- + +## Custom Commands + +```nu + def greet [name: string] { + $"hello ($nameยญ)" + } +``` + +> **custom command with parameter type set to string** + +--- + +```nu + def greet [name = "nushell"] { + $"hello ($nameยญ)" + } +``` + +> **custom command with default parameter set to nushell** + +--- + +```nu + def greet [ + name: string + --age: int + ] { + [$name $age] + } + + > greet world --age 10 +``` + +> **passing named parameter by defining flag for custom commands** + +--- + +```nu + def greet [ + name: string + --age (-a): int + --twice + ] { + if $twice { + [$name $age $name $age] + } else { + [$name $age] + } + } + > greet -a 10 --twice hello +``` + +> **using flag as a switch with a shorthand flag (-a) for the age** + +--- + +```nu + def greet [...name: string] { + print "ยญhello all:" + for $n in $name { + print $n + } + } + + > greet earth mars jupiter venus +``` + +> **custom command which takes any number of positional arguments using rest params** + +## Variables & Subexpressions + +```nu + > let val = 42 + > print $val + 42 +``` + +> **an immutable variable cannot change its value after declaration** + +--- + +```nu + > let val = 42 + > do { let val = 101; $val } + 101 + > $val + 42 +``` + +> **shadowing variable (declaring variable with the same name in a different scope)** + +--- + +```nu + > mut val = 42 + > $val += 27 + > $val + 69 +``` + +> **declaring a mutable variable with mut key word** + +--- + +```nu + > mut x = 0 + > [1 2 3] | each { $x += 1 } +``` + +> **closures and nested defs cannot capture mutable variables from their enviroยญnment. +> This expression results in error.** + +```nu + > const plugin = 'path/ยญto/ยญplugin' + > register $plugin +``` + +> **a constant variable is immutable value which is fully evaluated at parse-time** + +--- + +```nu + > let files = (ls) + > $files.naยญme?.0? +``` + +> **using question mark operator to return null instead of error if provided path is incorrect** + +--- + +```nu + > let big_files = (ls | where size > 10kb) + > $big_files +``` + +> **using subexpยญression by wrapping the expression with parentยญheses ()** + +--- + +## Modules + +```nu + > module greetings { + export def hello [name: string] { + $"hello ($nameยญ)!" + } + + export def hi [where: string] { + $"hi ($where)!ยญ" + } + } + + > use greetings hello + > hello "ยญworยญld" +``` + +> **using inline module** + +--- + +```nu + # greetiยญngs.nu + export-env { + $env.MยญYNAME = "ยญArthur, King of the Britonยญs" + } + export def hello [] { + $"hello ($env.MยญYNยญAMEยญ)" + } + + > use greetiยญngs.nu + > $env.MยญYNAME + Arthur, King of the Britons + > greetings hello + hello Arthur, King of the Britons! +``` + +> **importing module from file and using its enviroยญnment in current scope** + +--- + +```nu + # greetiยญngs.nu + export def hello [name: string] { + $"hello ($nameยญ)!" + } + + export def hi [where: string] { + $"hi ($where)!ยญ" + } + + export def main [] { + "ยญgreยญetings and salutations!" + } + + > use greetiยญngs.nu + > greetings + greetings and salutaยญtions! + > greetings hello world + hello world! +``` + +> **using main command in module** + +--- diff --git a/coloring_and_theming.md b/coloring_and_theming.md new file mode 100644 index 0000000000000000000000000000000000000000..fc7d417a5ec091ddcb068d9f6cee81927ad6105a --- /dev/null +++ b/coloring_and_theming.md @@ -0,0 +1,562 @@ +# Coloring and Theming in Nu + +Many parts of Nushell's interface can have their color customized. All of these can be set in the `config.nu` configuration file. If you see the hash/hashtag/pound mark `#` in the config file it means the text after it is commented out. + +1. table borders +2. primitive values +3. shapes (this is the command line syntax) +4. prompt +5. LS_COLORS + +## `Table borders` + +Table borders are controlled by the `$env.config.table.mode` setting in `config.nu`. Here is an example: + +```nu +> $env.config = { + table: { + mode: rounded + } +} +``` + +Here are the current options for `$env.config.table.mode`: + +- `rounded` # of course, this is the best one :) +- `basic` +- `compact` +- `compact_double` +- `light` +- `thin` +- `with_love` +- `reinforced` +- `heavy` +- `none` +- `other` + +### `Color symbologies` + +--- + +- `r` - normal color red's abbreviation +- `rb` - normal color red's abbreviation with bold attribute +- `red` - normal color red +- `red_bold` - normal color red with bold attribute +- `"#ff0000"` - "#hex" format foreground color red (quotes are required) +- `{ fg: "#ff0000" bg: "#0000ff" attr: b }` - "full #hex" format foreground red in "#hex" format with a background of blue in "#hex" format with an attribute of bold abbreviated. + +### `attributes` + +--- + +| code | meaning | +| ---- | ------------------- | +| l | blink | +| b | bold | +| d | dimmed | +| h | hidden | +| i | italic | +| r | reverse | +| s | strikethrough | +| u | underline | +| n | nothing | +| | defaults to nothing | + +### `normal colors` and `abbreviations` + +| code | name | +| ------ | ---------------------- | +| g | green | +| gb | green_bold | +| gu | green_underline | +| gi | green_italic | +| gd | green_dimmed | +| gr | green_reverse | +| gbl | green_blink | +| gst | green_strike | +| lg | light_green | +| lgb | light_green_bold | +| lgu | light_green_underline | +| lgi | light_green_italic | +| lgd | light_green_dimmed | +| lgr | light_green_reverse | +| lgbl | light_green_blink | +| lgst | light_green_strike | +| r | red | +| rb | red_bold | +| ru | red_underline | +| ri | red_italic | +| rd | red_dimmed | +| rr | red_reverse | +| rbl | red_blink | +| rst | red_strike | +| lr | light_red | +| lrb | light_red_bold | +| lru | light_red_underline | +| lri | light_red_italic | +| lrd | light_red_dimmed | +| lrr | light_red_reverse | +| lrbl | light_red_blink | +| lrst | light_red_strike | +| u | blue | +| ub | blue_bold | +| uu | blue_underline | +| ui | blue_italic | +| ud | blue_dimmed | +| ur | blue_reverse | +| ubl | blue_blink | +| ust | blue_strike | +| lu | light_blue | +| lub | light_blue_bold | +| luu | light_blue_underline | +| lui | light_blue_italic | +| lud | light_blue_dimmed | +| lur | light_blue_reverse | +| lubl | light_blue_blink | +| lust | light_blue_strike | +| b | black | +| bb | black_bold | +| bu | black_underline | +| bi | black_italic | +| bd | black_dimmed | +| br | black_reverse | +| bbl | black_blink | +| bst | black_strike | +| ligr | light_gray | +| ligrb | light_gray_bold | +| ligru | light_gray_underline | +| ligri | light_gray_italic | +| ligrd | light_gray_dimmed | +| ligrr | light_gray_reverse | +| ligrbl | light_gray_blink | +| ligrst | light_gray_strike | +| y | yellow | +| yb | yellow_bold | +| yu | yellow_underline | +| yi | yellow_italic | +| yd | yellow_dimmed | +| yr | yellow_reverse | +| ybl | yellow_blink | +| yst | yellow_strike | +| ly | light_yellow | +| lyb | light_yellow_bold | +| lyu | light_yellow_underline | +| lyi | light_yellow_italic | +| lyd | light_yellow_dimmed | +| lyr | light_yellow_reverse | +| lybl | light_yellow_blink | +| lyst | light_yellow_strike | +| p | purple | +| pb | purple_bold | +| pu | purple_underline | +| pi | purple_italic | +| pd | purple_dimmed | +| pr | purple_reverse | +| pbl | purple_blink | +| pst | purple_strike | +| lp | light_purple | +| lpb | light_purple_bold | +| lpu | light_purple_underline | +| lpi | light_purple_italic | +| lpd | light_purple_dimmed | +| lpr | light_purple_reverse | +| lpbl | light_purple_blink | +| lpst | light_purple_strike | +| c | cyan | +| cb | cyan_bold | +| cu | cyan_underline | +| ci | cyan_italic | +| cd | cyan_dimmed | +| cr | cyan_reverse | +| cbl | cyan_blink | +| cst | cyan_strike | +| lc | light_cyan | +| lcb | light_cyan_bold | +| lcu | light_cyan_underline | +| lci | light_cyan_italic | +| lcd | light_cyan_dimmed | +| lcr | light_cyan_reverse | +| lcbl | light_cyan_blink | +| lcst | light_cyan_strike | +| w | white | +| wb | white_bold | +| wu | white_underline | +| wi | white_italic | +| wd | white_dimmed | +| wr | white_reverse | +| wbl | white_blink | +| wst | white_strike | +| dgr | dark_gray | +| dgrb | dark_gray_bold | +| dgru | dark_gray_underline | +| dgri | dark_gray_italic | +| dgrd | dark_gray_dimmed | +| dgrr | dark_gray_reverse | +| dgrbl | dark_gray_blink | +| dgrst | dark_gray_strike | + +### `"#hex"` format + +--- + +The "#hex" format is one way you typically see colors represented. It's simply the `#` character followed by 6 characters. The first two are for `red`, the second two are for `green`, and the third two are for `blue`. It's important that this string be surrounded in quotes, otherwise Nushell thinks it's a commented out string. + +Example: The primary `red` color is `"#ff0000"` or `"#FF0000"`. Upper and lower case in letters shouldn't make a difference. + +This `"#hex"` format allows us to specify 24-bit truecolor tones to different parts of Nushell. + +## `full "#hex"` format + +--- + +The `full "#hex"` format is a take on the `"#hex"` format but allows one to specify the foreground, background, and attributes in one line. + +Example: `{ fg: "#ff0000" bg: "#0000ff" attr: b }` + +- foreground of red in "#hex" format +- background of blue in "#hex" format +- attribute of bold abbreviated + +## `Primitive values` + +--- + +Primitive values are things like `int` and `string`. Primitive values and shapes can be set with a variety of color symbologies seen above. + +This is the current list of primitives. Not all of these are configurable. The configurable ones are marked with \*. + +| primitive | default color | configurable | +| ------------ | --------------------- | ------------ | +| `any` | | | +| `binary` | Color::White.normal() | \* | +| `block` | Color::White.normal() | \* | +| `bool` | Color::White.normal() | \* | +| `cellpath` | Color::White.normal() | \* | +| `condition` | | | +| `custom` | | | +| `date` | Color::White.normal() | \* | +| `duration` | Color::White.normal() | \* | +| `expression` | | | +| `filesize` | Color::White.normal() | \* | +| `float` | Color::White.normal() | \* | +| `glob` | | | +| `import` | | | +| `int` | Color::White.normal() | \* | +| `list` | Color::White.normal() | \* | +| `nothing` | Color::White.normal() | \* | +| `number` | | | +| `operator` | | | +| `path` | | | +| `range` | Color::White.normal() | \* | +| `record` | Color::White.normal() | \* | +| `signature` | | | +| `string` | Color::White.normal() | \* | +| `table` | | | +| `var` | | | +| `vardecl` | | | +| `variable` | | | + +#### special "primitives" (not really primitives but they exist solely for coloring) + +| primitive | default color | configurable | +| --------------------------- | -------------------------- | ------------ | +| `leading_trailing_space_bg` | Color::Rgb(128, 128, 128)) | \* | +| `header` | Color::Green.bold() | \* | +| `empty` | Color::Blue.normal() | \* | +| `row_index` | Color::Green.bold() | \* | +| `hints` | Color::DarkGray.normal() | \* | + +Here's a small example of changing some of these values. + +```nu +> let config = { + color_config: { + separator: purple + leading_trailing_space_bg: "#ffffff" + header: gb + date: wd + filesize: c + row_index: cb + bool: red + int: green + duration: blue_bold + range: purple + float: red + string: white + nothing: red + binary: red + cellpath: cyan + hints: dark_gray + } +} +``` + +Here's another small example using multiple color syntaxes with some comments. + +```nu +> let config = { + color_config: { + separator: "#88b719" # this sets only the foreground color like PR #486 + leading_trailing_space_bg: white # this sets only the foreground color in the original style + header: { # this is like PR #489 + fg: "#B01455", # note, quotes are required on the values with hex colors + bg: "#ffb900", # note, commas are not required, it could also be all on one line + attr: bli # note, there are no quotes around this value. it works with or without quotes + } + date: "#75507B" + filesize: "#729fcf" + row_index: { + # note, that this is another way to set only the foreground, no need to specify bg and attr + fg: "#e50914" + } + } +} +``` + +## `Shape` values + +As mentioned above, `shape` is a term used to indicate the syntax coloring. + +Here's the current list of flat shapes. + +| shape | default style | configurable | +| ---------------------------- | -------------------------------------- | ------------ | +| `shape_block` | fg(Color::Blue).bold() | \* | +| `shape_bool` | fg(Color::LightCyan) | \* | +| `shape_custom` | bold() | \* | +| `shape_external` | fg(Color::Cyan) | \* | +| `shape_externalarg` | fg(Color::Green).bold() | \* | +| `shape_filepath` | fg(Color::Cyan) | \* | +| `shape_flag` | fg(Color::Blue).bold() | \* | +| `shape_float` | fg(Color::Purple).bold() | \* | +| `shape_garbage` | fg(Color::White).on(Color::Red).bold() | \* | +| `shape_globpattern` | fg(Color::Cyan).bold() | \* | +| `shape_int` | fg(Color::Purple).bold() | \* | +| `shape_internalcall` | fg(Color::Cyan).bold() | \* | +| `shape_list` | fg(Color::Cyan).bold() | \* | +| `shape_literal` | fg(Color::Blue) | \* | +| `shape_nothing` | fg(Color::LightCyan) | \* | +| `shape_operator` | fg(Color::Yellow) | \* | +| `shape_range` | fg(Color::Yellow).bold() | \* | +| `shape_record` | fg(Color::Cyan).bold() | \* | +| `shape_signature` | fg(Color::Green).bold() | \* | +| `shape_string` | fg(Color::Green) | \* | +| `shape_string_interpolation` | fg(Color::Cyan).bold() | \* | +| `shape_table` | fg(Color::Blue).bold() | \* | +| `shape_variable` | fg(Color::Purple) | \* | + +Here's a small example of how to apply color to these items. Anything not specified will receive the default color. + +```nu +> $env.config = { + color_config: { + shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b} + shape_bool: green + shape_int: { fg: "#0000ff" attr: b} + } +} +``` + +## `Prompt` configuration and coloring + +The Nushell prompt is configurable through these environment variables and config items: + +- `PROMPT_COMMAND`: Code to execute for setting up the prompt (block) +- `PROMPT_COMMAND_RIGHT`: Code to execute for setting up the _RIGHT_ prompt (block) (see oh-my.nu in nu_scripts) +- `PROMPT_INDICATOR` = "ใ": The indicator printed after the prompt (by default ">"-like Unicode symbol) +- `PROMPT_INDICATOR_VI_INSERT` = ": " +- `PROMPT_INDICATOR_VI_NORMAL` = "v " +- `PROMPT_MULTILINE_INDICATOR` = "::: " +- `render_right_prompt_on_last_line`: Bool value to enable or disable the right prompt to be rendered on the last line of the prompt + +Example: For a simple prompt one could do this. Note that `PROMPT_COMMAND` requires a `block` whereas the others require a `string`. + +```nu +> $env.PROMPT_COMMAND = { build-string (date now | format date '%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. + +```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 + ... +} +``` + +Coloring of the prompt is controlled by the `block` in `PROMPT_COMMAND` where you can write your own custom prompt. We've written a slightly fancy one that has git statuses located in the [nu_scripts repo](https://github.com/nushell/nu_scripts/blob/main/modules/prompt/oh-my.nu). + +### Transient prompt + +If you want a different prompt displayed for previously entered commands, you can use Nushell's transient prompt feature. This can be useful if your prompt has lots of information that is unnecessary to show for previous lines (e.g. time and Git status), since you can make it so that previous lines show with a shorter prompt. + +Each of the `PROMPT_*` variables has a corresponding `TRANSIENT_PROMPT_*` variable to be used for changing that segment when displaying past prompts: `TRANSIENT_PROMPT_COMMAND`, `TRANSIENT_PROMPT_COMMAND_RIGHT`, `TRANSIENT_PROMPT_INDICATOR`, `TRANSIENT_PROMPT_INDICATOR_VI_INSERT`, `TRANSIENT_PROMPT_INDICATOR_VI_NORMAL`, `TRANSIENT_PROMPT_MULTILINE_INDICATOR`. By default, the `PROMPT_*` variables are used for displaying past prompts. + +For example, if you want to make past prompts show up without a left prompt entirely and leave only the indicator, you can use: + +```nu +> $env.TRANSIENT_PROMPT_COMMAND = "" +``` + +If you want to go back to the normal left prompt, you'll have to unset `TRANSIENT_PROMPT_COMMAND`: + +```nu +> hide-env TRANSIENT_PROMPT_COMMAND +``` + +## `LS_COLORS` colors for the [`ls`](/commands/docs/ls.md) command + +Nushell will respect and use the `LS_COLORS` environment variable setting on Mac, Linux, and Windows. This setting allows you to define the color of file types when you do a [`ls`](/commands/docs/ls.md). For instance, you can make directories one color, _.md markdown files another color, _.toml files yet another color, etc. There are a variety of ways to color your file types. + +There's an exhaustive list [here](https://github.com/trapd00r/LS_COLORS), which is overkill, but gives you an rudimentary understanding of how to create a ls_colors file that `dircolors` can turn into a `LS_COLORS` environment variable. + +[This](https://www.linuxhowto.net/how-to-set-colors-for-ls-command/) is a pretty good introduction to `LS_COLORS`. I'm sure you can find many more tutorials on the web. + +I like the `vivid` application and currently have it configured in my `config.nu` like this. You can find `vivid` [here](https://github.com/sharkdp/vivid). + +`$env.LS_COLORS = (vivid generate molokai | str trim)` + +If `LS_COLORS` is not set, nushell will default to a built-in `LS_COLORS` setting, based on 8-bit (extended) ANSI colors. + +## Theming + +Theming combines all the coloring above. Here's a quick example of one we put together quickly to demonstrate the ability to theme. This is a spin on the `base16` themes that we see so widespread on the web. + +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. + +```nu +# let's define some colors + +let base00 = "#181818" # Default Background +let base01 = "#282828" # Lighter Background (Used for status bars, line number and folding marks) +let base02 = "#383838" # Selection Background +let base03 = "#585858" # Comments, Invisibles, Line Highlighting +let base04 = "#b8b8b8" # Dark Foreground (Used for status bars) +let base05 = "#d8d8d8" # Default Foreground, Caret, Delimiters, Operators +let base06 = "#e8e8e8" # Light Foreground (Not often used) +let base07 = "#f8f8f8" # Light Background (Not often used) +let base08 = "#ab4642" # Variables, XML Tags, Markup Link Text, Markup Lists, Diff Deleted +let base09 = "#dc9656" # Integers, Boolean, Constants, XML Attributes, Markup Link Url +let base0a = "#f7ca88" # Classes, Markup Bold, Search Text Background +let base0b = "#a1b56c" # Strings, Inherited Class, Markup Code, Diff Inserted +let base0c = "#86c1b9" # Support, Regular Expressions, Escape Characters, Markup Quotes +let base0d = "#7cafc2" # Functions, Methods, Attribute IDs, Headings +let base0e = "#ba8baf" # Keywords, Storage, Selector, Markup Italic, Diff Changed +let base0f = "#a16946" # Deprecated, Opening/Closing Embedded Language Tags, e.g. + +# we're creating a theme here that uses the colors we defined above. + +let base16_theme = { + separator: $base03 + leading_trailing_space_bg: $base04 + header: $base0b + date: $base0e + filesize: $base0d + row_index: $base0c + bool: $base08 + int: $base0b + duration: $base08 + range: $base08 + float: $base08 + string: $base04 + nothing: $base08 + binary: $base08 + cellpath: $base08 + hints: dark_gray + + # shape_garbage: { fg: $base07 bg: $base08 attr: b} # base16 white on red + # but i like the regular white on red for parse errors + shape_garbage: { fg: "#FFFFFF" bg: "#FF0000" attr: b} + shape_bool: $base0d + shape_int: { fg: $base0e attr: b} + shape_float: { fg: $base0e attr: b} + shape_range: { fg: $base0a attr: b} + shape_internalcall: { fg: $base0c attr: b} + shape_external: $base0c + shape_externalarg: { fg: $base0b attr: b} + shape_literal: $base0d + shape_operator: $base0a + shape_signature: { fg: $base0b attr: b} + shape_string: $base0b + shape_filepath: $base0d + shape_globpattern: { fg: $base0d attr: b} + shape_variable: $base0e + shape_flag: { fg: $base0d attr: b} + shape_custom: {attr: b} +} + +# now let's apply our regular config settings but also apply the "color_config:" theme that we specified above. + +let config = { + filesize_metric: true + table_mode: rounded # basic, compact, compact_double, light, thin, with_love, rounded, reinforced, heavy, none, other + use_ls_colors: true + color_config: $base16_theme # <-- this is the theme + use_grid_icons: true + footer_mode: always #always, never, number_of_rows, auto + animate_prompt: false + float_precision: 2 + use_ansi_coloring: true + filesize_format: "b" # b, kb, kib, mb, mib, gb, gib, tb, tib, pb, pib, eb, eib, auto + edit_mode: emacs # vi + max_history_size: 10000 + log_level: error +} +``` + +if you want to go full-tilt on theming, you'll want to theme all the items I mentioned at the very beginning, including LS_COLORS, and the prompt. Good luck! + +### Working on light background terminal + +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. + +```nu +# in $nu.config-path +$env.config = { + ... + color_config: $dark_theme # if you want a light theme, replace `$dark_theme` to `$light_theme` + ... +} +``` + +You can just change it to light theme by replacing `$dark_theme` to `$light_theme` + +```nu +# in $nu.config-path +$env.config = { + ... + color_config: $light_theme # if you want a light theme, replace `$dark_theme` to `$light_theme` + ... +} +``` + +## Accessibility + +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: + +```nu +# in $nu.config-path +$env.config = { + ... + table: { + ... + mode: "none" + ... + } + error_style: "plain" + ... +} + +``` + +## Line editor menus (completion, history, helpโฆ) + +Reedline (Nuโs line editor) style is not using the `color_config` key. +Instead, each menu has its own style to be configured separately. +See the [section dedicated to Reedlineโs menus configuration](line_editor.md#menus) to learn more on this. diff --git a/coming_from_bash.md b/coming_from_bash.md new file mode 100644 index 0000000000000000000000000000000000000000..7237ab4baa87e86def023fef198da75ef9341d0f --- /dev/null +++ b/coming_from_bash.md @@ -0,0 +1,68 @@ +# Coming from Bash + +If you're coming from `Git Bash` on Windows, then the external commands you're used to (bash, grep, etc) will not be available in `nu` by default (unless you had explicitly made them available in the Windows Path environment variable). +To make these commands available in `nu` as well, add the following line to your `config.nu` with either `append` or `prepend`. + +``` +$env.Path = ($env.Path | prepend 'C:\Program Files\Git\usr\bin') +``` + +Note: this table assumes Nu 0.60.0 or later. + +| Bash | Nu | Task | +| ------------------------------------ | ------------------------------------------------------------- | ----------------------------------------------------------------- | +| `ls` | `ls` | Lists the files in the current directory | +| `ls